0
這是一個xml示例,我從外部xml文件加載 $ data = file_get_contents($ filename); $ dom-> loadXML($ data);使用php解析XML數據
使用PHP,我想通過這個XML來獲得標題,問題和每個問題的選擇。
<questions>
<record topic = "classic video games">
<title>Centipede</title>
<question>How many shots does it take to destroy a mushroom?</question>
<choices>
<choice correct="no" votes="0">1</choice>
<choice correct="no" votes="0">2</choice>
<choice correct="no" votes="0">3</choice>
<choice correct="yes" votes="0">4</choice>
</choices>
</record>
<record topic = "classic video games">
<title>Quake</title>
<question>What is the name of the most powerful weapon in Quake?</question>
<choices>
<choice correct="no" votes="0">gauntlet</choice>
<choice correct="no" votes="0">machine gun</choice>
<choice correct="yes" votes="0">BFG2000</choice>
<choice correct="no" votes="0">rocket launcher</choice>
<choice correct="no" votes="0">railgun</choice>
</choices>
</record>
</questions>
我希望我的結果是這樣的:
Title = Centipede
Question = How many shots does it take to destroy a mushroom?
I. 1
II. 2
III. 3
IV. 4
這裏是我的嘗試:
$dom->loadXML($data);
$all_records = $dom->getElementsByTagName("record");
$all_choices = $dom->getElementsByTagName("choices");
foreach($all_records as $record){
$question = $record->getElementsByTagName("question")->item(0)->nodeValue;
$title = $record->getElementsByTagName("title")->item(0)->nodeValue;
echo "<h2> Title=$title</h2>";
echo "<h5><em>Question=$question</em></h5>";
echo "<li>". $all_choices->getElementsByTagName("choice")->nodeValue."</li>\n";
echo "</ul>\n";
echo "</div>\n";
}
我能夠拿到冠軍和問題,而不是選擇!
我固定它,回來到把答案,但我發現你的。非常感謝! – Timmy 2012-04-10 14:24:42
嘿,對不起,我沒有早點回答:) – 2012-04-10 17:02:46