Search code examples
phpxmlsimplexml

How do I get xml tag attributes in converted array using simplexml_load_string


I am having below xml data. There is the questions in <question> and all possible answers are in <answer>. The <answer> tag have attribute "correct" which is the correct answer of that question. So here I am trying to read this "Correct" attribute of <answer>. Here when I used "simplexml_load_string" function it converts xml to php array but it does not return this "Correct" attribute.

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<questions> <question type="1" text="Which one of the following addresses is associated with you?"> <answer correct="false">ABC</answer> <answer correct="false">PQR</answer> <answer correct="false">ASD</answer> <answer correct="false">5374 </answer> <answer correct="false">8288 SELKIRK</answer> <answer correct="false">1558 NICHOLS</answer> <answer correct="true">1400 AMERICAN LN</answer> <answer correct="false">None of the above</answer> </Question> </Questions>

How can i achieve this?


Solution

  • Xml is case sensitive. If turn </Question> and </Questions> into lowercase, all works fine:

    $xml = simplexml_load_string($str);
    foreach($xml->xpath('/questions/question/answer') as $ans)
       echo $ans['correct'] .' : ' . $ans . "\n"; 
    

    result:

    false : ABC
    false : PQR
    false : ASD
    false : 5374 
    false : 8288 SELKIRK
    false : 1558 NICHOLS
    true : 1400 AMERICAN LN
    false : None of the above
    

    demo