我如何使用PHP SimpleXML Parser回应John和Mike?如果两者都有不同的项目
<DATA>
<KEY>
<item0>
<RTS>John</RTS>
</item0>
<item1>
<RTS>Mike</RTS>
</item1>
</KEY>
</DATA>
这样可行,但是如果你尝试使用$ xml = simplexml_load_file(“example.xml”)或者死掉(“错误:对象创建失败”);
它不适用于simple_load_file
<?php
$xml =
"<?xml version='1.0' encoding='UTF-8'?>
<DATA>
<KEY>
<item0>
<RTS>John</RTS>
</item0>
<item1>
<RTS>Mike</RTS>
</item1>
</KEY>
</DATA>";
function xml2array($xml)
{
$arr = array();
foreach ($xml as $element)
{
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e))
{
$arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
}
else
{
$arr[$tag] = trim($element);
}
}
return $arr;
}
$xml = new SimpleXMLElement($xml);
$data = xml2array($xml);
foreach ($data as $key => $value) {
foreach ($value as $key1 => $val1) {
echo $val1['RTS']; echo "<br/>";
}
}
?>
答案 0 :(得分:0)
<?php
/// load your external xml file here////
if (file_exists('file.xml')) {
$xml = simplexml_load_file('file.xml');
// $xml = new SimpleXMLElement($xml);
$data = xml2array($xml);
foreach ($data as $key => $value) {
foreach ($value as $key1 => $val1) {
echo $val1['RTS']; echo "<br/>";
}
}
} else {
exit('Failed to open test.xml.');
}
function xml2array($xml)
{
$arr = array();
foreach ($xml as $element)
{
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e))
{
$arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
}
else
{
$arr[$tag] = trim($element);
}
}
return $arr;
}
?>