我一直在使用 PHP 的简单 XML 函数来处理 XML 文件。
下面的代码适用于简单的 XML 层次结构:
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
假设 XML 文档的结构如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
但是,如果我的 XML 文档中有更复杂的结构 - 内容就不会输出。更复杂的 XML 示例如下所示:
<note>
<noteproperties>
<notetype>
TEST
</notetype>
</noteproperties>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
我需要处理深度不定的 XML 文件 - 谁能建议一种方法?
那是因为你需要再往下走一个层次<noteproperties>
检查一下,示例来自SimpleXMLElement::children http://www.php.net/manual/en/simplexmlelement.children.php:
$xml = new SimpleXMLElement(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');
foreach ($xml->children() as $second_gen) {
echo ' The person begot a ' . $second_gen['role'];
foreach ($second_gen->children() as $third_gen) {
echo ' who begot a ' . $third_gen['role'] . ';';
foreach ($third_gen->children() as $fourth_gen) {
echo ' and that ' . $third_gen['role'] .
' begot a ' . $fourth_gen['role'];
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)