我的php简单xml对象出了问题。
我的日志中有以下xml数据
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
)
)
我的php varible $xmlObj = SimpleXMLElement Object
但是当我有以下
if (is_array($xmlObj->subpod)){
echo 'is array';
}else {
echo 'not array';
}
输出总是'不是数组',我希望我的代码回显'是数组'
我以为$xmlObj->subpod
是一个数组。
当我测试$xmlObj->subpod[0]->plaintext
时,它实际上会返回字符串。
我不知道如何解决这个问题。有人可以帮忙吗?
答案 0 :(得分:2)
如果你去var_dump($xmlObj->subpod)
,你会发现它仍然是SimpleXMLElement
个对象。但是,仍然可以将其称为数组。 (请参阅this example之后的注释,该注释暗示该类实现了ArrayAccess,即使类文档没有这样做。)
检查此结构的正确方法是使用SimpleXMLElement::count():
if ($xmlObj->subpod->count() > 0) { ... }
编辑:您问题中的输出可能来自print_r
,有时在输出中无用(例如,当它不是时告诉您某个数组是某个数组)。请尝试使用var_dump
,因为它通常对调试更有用。这里唯一需要注意的是,您无法看到SimpleXMLElement对象的整个嵌套对象结构!
答案 1 :(得分:2)
在SimpleXMLElement Object
内部,一切都是SimpleXMLElement Object
,print_r和var_dump有时候是关于数组的 - 它们是可遍历的对象,但你可以对它们执行大多数操作,就好像它们是数组一样。如果您坚持使用纯数组,则可以将此节点强制转换为数组:
$subpod = (array)$xmlObj->subpod;