I was curious to know how a SimpleXMLElement object was formed in PHP from an XML document, but I think there might be something in this process that is unknown to me.
When we loop through an object in PHP, the public properties are iterated over. So if the first property is an array, then we should need another loop inside our first loop to iterate over it, however, it doesn't seem to be the case about a SimpleXMLElement object. Look at this object for instance:
object(SimpleXMLElement)#1 (1) {
["user"]=>
array(5) {
[0]=>
object(SimpleXMLElement)#2 (3) {
["firstname"]=>
string(6) "Sheila"
["surname"]=>
string(5) "Green"
["contact"]=>
object(SimpleXMLElement)#7 (3) {
["phone"]=>
string(9) "1234 1234"
["url"]=>
string(18) "http://example.com"
["email"]=>
string(18) "[email protected]"
}
}
[1]=>
object(SimpleXMLElement)#3 (3) {
["firstname"]=>
string(5) "Bruce"
["surname"]=>
string(5) "Smith"
.
.
.
It contains a "user" property in which there's an array(of 5 elements). So when we loop through this object, we should get this error:
Notice: Array to string conversion in ...
I've tested this in this snippet:
$var = (object)array(
'user'=>['joe','mia'],
);
Now this loop gives the error I just mentioned above:
foreach ($test as $property => $val){
echo $property.':'.$val.'<br>';
}
$val
in the loop is an array, so you can not echo it. Use print_r($val)
to show its value.
foreach ($test as $property => $val){
echo $property.':';
print_r($val);
echo '<br>';
}