I have this SimpleXML object:
object(SimpleXMLElement)#176 (1) {
["record"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#39 (2) {
["f"]=>
array(2) {
[0]=>
string(13) "stuff"
[1]=>
string(1) "1"
}
}
[1]=>
object(SimpleXMLElement)#37 (2) {
["f"]=>
array(2) {
[0]=>
string(13) "more stuff"
[1]=>
string(3) "90"
}
}
}
Why does is_array($object->record) return false? It clearly says it's an array. Why can't I detect it using is_array?
Also, I am unable to cast it as an array using (array) $object->record. I get this error:
Warning: It is not yet possible to assign complex types to properties
SimpleXML nodes are objects that can contain other SimpleXML nodes. Use iterator_to_array().
It's not an array. The var_dump
output is misleading. Consider:
<?php
$string = <<<XML
<?xml version='1.0'?>
<foo>
<bar>a</bar>
<bar>b</bar>
</foo>
XML;
$xml = simplexml_load_string($string);
var_dump($xml);
var_dump($xml->bar);
?>
Output:
object(SimpleXMLElement)#1 (1) {
["bar"]=>
array(2) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
}
}
object(SimpleXMLElement)#2 (1) {
[0]=>
string(1) "a"
}
As you can see by the second var_dump
, it is actually a SimpleXMLElement
.
I solved the problem using count()
function:
if( count( $xml ) > 1 ) {
// $xml is an array...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With