使用php解析XML数据

时间:2012-04-10 13:27:21

标签: php xml dom

这是我从外部xml文件加载的xml示例 $ data = file_get_contents($ filename); $ dom-> loadXML的($数据);

使用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";

    }

我能够得到标题和问题,但不是选择!

1 个答案:

答案 0 :(得分:0)

在检查每条记录时,您需要使用内部循环来获取choices集:

<?php

$dom->loadXML($data);

$all_records = $dom->getElementsByTagName("record");
foreach($all_records as $record) {
    $question = $record->getElementsByTagName("question")->item(0)->nodeValue;
    $title = $record->getElementsByTagName("title")->item(0)->nodeValue;
    $choices = $record->getElementsByTagName('choice');

    echo "<h2> Title=$title</h2>";
    echo "<h5><em>Question=$question</em></h5>";

    echo '<ol class="choices">';
    foreach ( $choices as $choice ) {
        echo "<li>" . $choice->nodeValue . "</li>\n";
    }
    echo "</ol>";

    echo "</div>\n";
}