Reading XML file

I’m trying to read an XML file and have got so far but need some advice.

My XML file is

<?xml version="1.0"?><!DOCTYPE quiz [
    <!ELEMENT quiz (title, items)>
    <!ELEMENT title (#PCDATA)>
    <!ELEMENT items (item)+>    
    <!ELEMENT item (question, answer, answer+)>
    <!ELEMENT question (#PCDATA)>
    <!ELEMENT answer (#PCDATA)>
    <!ATTLIST answer correct (y) #IMPLIED>
    <title>Alberta Sparrow</title>
            <question>What type of bird is Alberta and her family?</question>
            <answer>a robin</answer>
            <answer>a duck</answer>
            <answer correct="y">a sparrow</answer>
            <answer>a blue jay</answer>

with several <item>s

My PHP is

$doc = new DOMDocument();
$items = $doc->getElementsByTagName("item");
foreach ( $items as $item ) {
  $questions = $item->getElementsByTagName("question");
  $question = $questions->item(0)->nodeValue;
 $answers = $item->getElementsByTagName("answer");
  $answer1 = $answers->item(0)->nodeValue;
  $answer2 = $answers->item(1)->nodeValue;
  $answer3 = $answers->item(2)->nodeValue;
  $answer4 = $answers->item(3)->nodeValue;
  echo "<p>$question<br \\> 1. $answer1<br \\> 2. $answer2<br \\> 3. $answer3<br \\> 4. $answer4</p>\

What I want is (a) to print the <title> and (b) to be able to tell which <answer> has the correct=“y” attribute.

Many thanks

For the title after

$items = $doc->getElementsByTagName("item");


$title = $doc->getElementsByTagName("title");

Here is a great read for some more information. There are several parts and a prefence of mine is XML Reader

Also, if you’d rather work with the XML as an array, a very simple way to convert it is using the json_encode/decode functions.

$array = json_decode(json_encode(file_get_contents('filename.xml')), true);

Thanks Onle.

Funnily enough it was an IBM article that got me as far as I got. I tried

$title = $doc->getElementsByTagName("title");

but couldn’t do anything with $title. Then I found I could print it if I used

$title = $doc->getElementsByTagName('title')->item(0)->nodeValue;

Thanks, kduv. I’ll have a play with that too.

Good catch gandalf, glad you got it working.

I fathomed out the 2nd part of my query too. To get the ‘correct’ attribute:

$correct1 = $answers->item(0)->getAttribute('correct');

G :slight_smile: