当我遍历下面的树:http://tuningcode.com/math/temp/library.xml时,一些结果会加倍。也就是说,例如,它打印了两次“集理论”主题部分,它的所有内容。您可以在这里看到有问题的结果:http://tuningcode.com/math/temp/simple-parse.php。
问题的截图

PHP
<?php
$library = simplexml_load_file('library.xml');
if($library == null){
echo "uh oh, null library";
}
function traverseObject($object)
{
foreach ($object as $key => $value ){
if($key == "title"){
echo "<b>" . $object->title . "</b>";
} else if ($key == "topic"){
// traverse child elements, if any
echo "<ul>";
foreach ( $object->topic as $num => $thatTopic ){
echo "<li>";
traverseObject($thatTopic);
echo "</li>";
}
echo "</ul>";
} else { // skip the rest for now
}
}
}
traverseObject($library);
?>XML
<?xml version="1.0" encoding="UTF-8"?>
<library userid="095209376">
<title>UserID095209376's Library</title>
<topic>
<title>Set Theory</title>
<topic>
<title>Axioms</title>
<topic>
<title>Axiom of Separation</title>
<id>axiom-of-separation</id>
</topic>
<topic>
<title>Axiom of Infinity</title>
<id>axiom-of-infinity</id>
<entry>
<title>Axiom of Infinity</title>
<section>
<title>History</title>
<body>
Long ago, in a galaxy far far away...
</body>
</section>
</entry>
</topic>
</topic>
</topic>
<topic>
<title>Analysis</title>
<topic>
<title>Normed Vector Spaces</title>
<id>normed-vector-spaces</id>
<topic>
<title>Vector space</title>
<id>vector-space</id>
<entry>
<section>
<title>Definition</title>
<body>A vector space is a...</body>
</section>
</entry>
</topic>
</topic>
</topic>
</library>发布于 2014-04-20 23:56:48
所以我的算法错了。很难分析到底是什么不起作用,但这里有一个修正:
输出

PHP
<?php
error_reporting(E_ALL);
$library = simplexml_load_file('library.xml');
if($library == null){
echo "uh oh, null library";
}
function traverseObject($object)
{
echo "<ul>";
foreach ($object as $key => $value ){
if($key == "title"){
echo "<li><b>" . $object->title . "</b></li>";
} else if ($key == "topic"){
// traverse child elements, if any
traverseObject($value);
} else if($key == "id"){
echo "<i>id: " . $value . "</i>";
} else { // skip the rest for now
}
}
echo "</ul>";
}
traverseObject($library);
?>https://stackoverflow.com/questions/23188701
复制相似问题