我正在尝试通过simplexml_load_file创建的数组循环,当访问我的每个循环之外的数组时,我得到预期的结果,
print_r ($feedobject->Item[0]->attributes())`;
输出:SimpleXMLElement Object
(
[@attributes] => Array
(
[ID] => 202fnl
[TableID] => newitem
)
)
当通过my for每个循环访问
时foreach ($feedobject->Item[$x] as $value) {
print_r ($value->attributes());
$x++;
}
我得到了意想不到的结果(进一步进入数组)
SimpleXMLElement Object
(
[@attributes] => Array
(
[TableFieldID] => description
[Value] => Our 2-ounce plastic funnel is the perfect fit for our 8-ounce stainless steel flasks. It works!
)
)
Xml文件看起来像
<Item ID="202fnl" TableID="newitem">
<ItemField TableFieldID="description" Value="Our 2-ounce plastic funnel is the perfect fit for our 8-ounce stainless steel flasks. It works!"/>
为什么会发生这种情况,有没有人有更好的建议来循环遍历数组的特定元素?
您对元素选择感到困惑。要得到每个<Item>
,只需使用$feedobject->Item
。
// select each `<Item>`
foreach ($feedobject->Item as $value) {
echo $value->attributes()->ID;
}
当您使用$feedobject->Item[$x] as $value
时,这已经直接指向<Item>
中的元素,显示您的<ItemField>
。