0

We've got an XML file with this format:

<Quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <id>0</id>
  <title>Ganz Anderer Titel</title>
  <questions>
    <Question xsi:type="ChoiceQuestion">
      <title>Frage1</title>
      <id>0</id>
      <rightAnswer>1</rightAnswer>
    </Question>
    <Question xsi:type="ChoiceQuestion">
      <title>Frage2</title>
      <id>1</id>
      <rightAnswer>2</rightAnswer>
    </Question>
    <Question xsi:type="ChoiceQuestion">
      <title>Frage2</title>
      <id>2</id>
      <rightAnswer>3</rightAnswer>
    </Question>
  </questions>
  <expireDate>2018-06-06T00:00:00</expireDate>
</Quiz>

We now need to parse this XML file, but we are not able to access the content or attributes of the questions element.

We are using PHP 7 with the built in SimpleXML parser.

echo json_encode($xml->questions);

displays this

{"Question":[{"title":"Frage1","id":"0","rightAnswer":"1"},{"title":"Frage2","id":"1","rightAnswer":"2"},{"title":"Frage2","id":"2","rightAnswer":"3"}]}

but we have no idea how to get the data of each question individually.

miken32
  • 42,008
  • 16
  • 111
  • 154
Patrick S.
  • 33
  • 1
  • 5

1 Answers1

0

As suggested in the comments, a simple foreach loop will let you loop through each item in the list. To get namespaced attributes, use the SimpleXMLElement::attributes() method:

$xml = <<< XML
<Quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <id>0</id>
  <title>Ganz Anderer Titel</title>
  <questions>
    <Question xsi:type="ChoiceQuestion">
      <title>Frage1</title>
      <id>0</id>
      <rightAnswer>1</rightAnswer>
    </Question>
    <Question xsi:type="ChoiceQuestion">
      <title>Frage2</title>
      <id>1</id>
      <rightAnswer>2</rightAnswer>
    </Question>
    <Question xsi:type="ChoiceQuestion">
      <title>Frage2</title>
      <id>2</id>
      <rightAnswer>3</rightAnswer>
    </Question>
  </questions>
  <expireDate>2018-06-06T00:00:00</expireDate>
</Quiz>
XML;

$x = new SimpleXMLElement($xml);
foreach ($x->questions->Question as $q) {
    printf(
        "Question %d:\nType:%s\nTitle:%s\nRight answer:%s\n",
        $q->id,
        $q->attributes("xsi", true)->type,
        $q->title,
        $q->rightAnswer
    );
}
miken32
  • 42,008
  • 16
  • 111
  • 154