I am having trouble on my php simple xml object.
I have the following xml data in my log
SimpleXMLElement Object
(
[@attributes] => Array
(
[title] => test
[scanner] => Data
[id] => WordData
[position] => 1800
[error] => false
[num] => 6
)
[subpod] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[title] => Surnames
)
[plaintext] => Common (US population: 650 people, white: 63% | black: 35%)
[img] => SimpleXMLElement Object
(
[@attributes] => Array
(
[alt] => Common (US population: 650 people, white: 63% | black: 35%)
[title] => Common (US population: 650 people, white: 63% | black: 35%)
[width] => 349
[height] => 18
)
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[title] => Cities
)
[plaintext] => Littleton Common (Massachusetts, 2789 people)
[img] => SimpleXMLElement Object
(
[@attributes] => Array
(
[alt] => Littleton Common (Massachusetts, 2789 people)
[title] => Littleton Common (Massachusetts, 2789 people)
[width] => 287
[height] => 18
)
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[title] => Buildings
)
[plaintext] => Rotunda on Woolwich Common (London, Greater London)
[img] => SimpleXMLElement Object
(
[@attributes] => Array
(
[alt] => Rotunda on Woolwich Common (London, Greater London)
[title] => Rotunda on Woolwich Common (London, Greater London)
[width] => 356
[height] => 18
)
)
)
.....more simpleXmlElement object
)
)
my php varible $xmlObj = SimpleXMLElement Object but when I have the following
if (is_array($xmlObj->subpod)){
echo 'is array';
}else {
echo 'not array';
}
the output is always ‘not array’ and I want my codes to echo ‘is array’
I thought $xmlObj->subpod is an array.
When I test $xmlObj->subpod[0]->plaintext, it will actually return strings.
I am not sure how to solve this problem. Can anyone help?
If you were to
var_dump($xmlObj->subpod), you would see that it is still aSimpleXMLElementobject. However, it can still be called as if it were an array. (See the note after this example, which hints that the class implements ArrayAccess, even though the class documentation doesn’t.)The correct way to check for this structure would be using SimpleXMLElement::count():
Edit: The output in your question is presumably from
print_r, which is sometimes rather unhelpful in its output (e.g. telling you something is an array when it’s not). Try usingvar_dumpinstead, as it’s generally more useful for debugging. The only caveat here is that you don’t get to see the entire nested object structure for SimpleXMLElement objects!