Reputation: 70
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>';
}
Upvotes: 0
Views: 642
Reputation: 57121
It's worth trying to understand how the basic SimpleXML processing works, trying to hack around the internal structures of the objects isn't going to help. When trying to access elements, use ->elementName
A simple mock up of the data you probably has...
$data = "<base>
<user>
<firstname>Sheila</firstname>
<surname>Green</surname>
<contact>
<phone>1234 1234</phone>
</contact>
</user>
</base>";
If you wanted to print out all of the elements under <user>
, then you can use foreach()
and use ->user->children()
as in...
$xml = simplexml_load_string($data);
//print_r($xml);
foreach ( $xml->user->children() as $tag => $value ) {
echo $tag."-".$value.PHP_EOL;
}
Which outputs...
firstname-Sheila
surname-Green
contact-
As contact is a structure in itself, you could add
if ( $value->count() > 0 ) {
foreach ( $value->children() as $tag => $sub ) {
echo $tag."-".$sub.PHP_EOL;
}
}
To allow you to print that out.
Upvotes: 1
Reputation: 4850
$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>';
}
Upvotes: 1