The code bellow
<?php
$ans=<<<XML
<?xml version="1.0" encoding="utf-8"?>
<ResponseDoc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<response>
<index>1</index>
<statusCode>Success</statusCode>
</response>
<response>
<index>2</index>
<statusCode>Success</statusCode>
</response>
<response>
<index>3</index>
<statusCode>Success</statusCode>
</response>
<response>
<index>4</index>
<statusCode>Success</statusCode>
</response>
</ResponseDoc>
XML;
$r1= simplexml_load_string($ans);
print_r($r1);
echo '<br>---------------------------------<br>';
$r2=$r1->response;
print_r($r2);
echo '<br>---------------------------------<br>';
?>
gives the bellow output
SimpleXMLElement Object (
[response] =>
Array (
[0] => SimpleXMLElement Object ( [index] => 1 [statusCode] => Success )
[1] => SimpleXMLElement Object ( [index] => 2 [statusCode] => Success )
[2] => SimpleXMLElement Object ( [index] => 3 [statusCode] => Success )
[3] => SimpleXMLElement Object ( [index] => 4 [statusCode] => Success )
)
)
---------------------------------
SimpleXMLElement Object ( [index] => 1 [statusCode] => Success )
---------------------------------
I cannot understand why, as in my current mental model the $r2 should contain an array instead of the value of the array at index 0. If I loop
foreach($r1 as $i) echo "statusCode='{$i->statusCode}'<br>";
foreach($r1->response as $i) echo "statusCode='{$i->statusCode}'<br>";
the output in both cases (and I don't understand why it works in the first case) is:
statusCode='Success'
statusCode='Success'
statusCode='Success'
statusCode='Success'
probably I am missing some difference between objects and arrays or there is some special detail regarding SimpleXMLElement or print_r and var_dump work incorrectly.
The output is correct, because the simple xml parser gives you the first object automatically. But you can overcome this by using the xpath method. You also can use the
print_r($responses)to view the array of each item beeing a SimpleXMLElement.You also can directly use foreach, because the SimpleXml parser checks for array context.
Demo: https://3v4l.org/BXhC2
Demo: https://3v4l.org/5bJNZ (with print_r())
And the output with
print_r($responses)