简体   繁体   中英

Parse XML data using php

Here is an xml example that I load from an external xml file $data = file_get_contents($filename); $dom->loadXML($data);

Using php, I want to walk through this xml to get the title, question, and each question's choices.

<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>

I want my result to be like this:

Title = Centipede

Question = How many shots does it take to destroy a mushroom?

I. 1
II. 2
III. 3
IV. 4

here is my try:

$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";

    }

I'm able to get the title and the question, but not the choices!

You need to fetch the choices set using an inner loop as you inspect each record:

<?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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM