Pecorating XML with php

3

Colleagues.

I have the following XML.

<gabarito>
   <avaliacao tipo="Prova" codigo="01" segmento="Ensino Médio" serie="Pré-Vestibular" questoes="20">
      <disciplina nome="Matemática">
         <questao numero="1" alternativas="A,B,C,D,E">
            <resposta>C</resposta>
         </questao>
         <questao numero="2" alternativas="A,B,C,D,E">
            <resposta>D</resposta>
         </questao>
         <questao numero="3" alternativas="A,B,C,D,E">
            <resposta>A</resposta>
         </questao>
      </disciplina>

      <disciplina nome="Física">
         <questao numero="1" alternativas="A,B,C,D,E">
            <resposta>C</resposta>
         </questao>
         <questao numero="2" alternativas="A,B,C,D,E">
            <resposta>D</resposta>
         </questao>
         <questao numero="3" alternativas="A,B,C,D,E">
            <resposta>A</resposta>
         </questao>
      </disciplina>
   </avaliacao>
</gabarito>

How do I get the answer? I'm doing the following:

$xml = simplexml_load_file($arquivoXML);
 foreach($xml as $notasGabarito){  
  $resXML = $xml->avaliacao->disciplina->questao->resposta;
  echo "Res => " .$resXML."<br>";
 } 
}

But it's only returning me the first C.

    
asked by anonymous 20.04.2016 / 18:31

1 answer

2

You are getting the index direct, by the way you have set the xml will have to go through the question to get the answer.

Detail, I do not know if you have put the xml wrong but it has some syntactic errors.

Example:

Foo.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<gabarito>
   <avaliacao tipo="Prova" codigo="01" segmento="Ensino Médio" serie="Pré-Vestibular" questoes="20">
      <disciplina nome="Matemática">
         <questao numero="1" alternativas="A,B,C,D,E">
            <resposta>C</resposta>
         </questao>
         <questao numero="2" alternativas="A,B,C,D,E">
            <resposta>D</resposta>
         </questao>
         <questao numero="3" alternativas="A,B,C,D,E">
            <resposta>A</resposta>
         </questao>
      </disciplina>
   </avaliacao>
</gabarito>

Reading the foo.xml file

$xml = simplexml_load_file('foo.xml');
$questoes = count($xml->avaliacao->disciplina->questao);
for ($i = 0; $i < $questoes; $i++):
   print($xml->avaliacao->disciplina->questao[$i]->resposta);
endfor;

Output:

SimpleXMLElement Object ( [0] => C ) SimpleXMLElement Object ( [0] => D ) SimpleXMLElement Object ( [0] => A ) 

To read xml attributes:

$disciplina= count($xml->avaliacao->disciplina);
for ($i = 0; $i < $disciplina; $i++):
   print_r($xml->avaliacao->disciplina[$i]->attributes()['nome']);
endfor;
    
20.04.2016 / 19:58