Search code examples
phpxmlsimplexml

how get indexed value from PHP object output of simplexml_load_file


From the output1 below we can see that PHP simplexml_load_file translates the same index tags as indexed array [0,1,2,3,4].

I would like to find out how can I get the index from the output of simplexml_load_file? I tired to do that with example 'php2', and I got 'output2' in return. Is it possible or how can I get my output as shown on 'desired output2'? Thank you in advance

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Report>
    <index><value>h</value></index>
    <index><value>e</value></index>
    <index><value>l</value></index>
    <index><value>l</value></index>
    <index><value>o</value></index>
</Report>

php1:

<?php
    $oFile = simplexml_load_file("test.xml") or die("error: Cannot create object");
    var_dump($oFile);
?>

output1:

object(SimpleXMLElement)#1 (1) 
{ 
    ["index"]=> array(5) 
    { 
        [0]=> object(SimpleXMLElement)#2 (1) { ["value"]=> string(1) "h" } 
        [1]=> object(SimpleXMLElement)#3 (1) { ["value"]=> string(1) "e" } 
        [2]=> object(SimpleXMLElement)#4 (1) { ["value"]=> string(1) "l" } 
        [3]=> object(SimpleXMLElement)#5 (1) { ["value"]=> string(1) "l" } 
        [4]=> object(SimpleXMLElement)#6 (1) { ["value"]=> string(1) "o" } 
    } 
}

php2:

<?php
    $oFile = simplexml_load_file("test.xml") or die("error: Cannot create object");
    foreach ($oFile->index as $key=>$value) {
        echo $key.': '.$value->value.'<br>';
    }
?>

output2:

index: h
index: e
index: l
index: l
index: o

desired output2:

0: h
1: e
2: l
3: l
4: o

Solution

  • Simple XML is painful to work with:

    $oFile = simplexml_load_file("test.xml");
    
    foreach($oFile->xpath("index") as $key => $value) {
            echo "{$key}: {$value->value}<br>";
    }