Php SimpleXML检查元素是否有子元素并获取子值
我有以下XML:Php SimpleXML检查元素是否有子元素并获取子值,php,simplexml,Php,Simplexml,我有以下XML: <?xml version="1.0" encoding="UTF-8"?> <data> <header> <export_time>2012-08-28 08:13:36</export_time> <file_name>nameasd</file_name> </header> <shipping>
<?xml version="1.0" encoding="UTF-8"?>
<data>
<header>
<export_time>2012-08-28 08:13:36</export_time>
<file_name>nameasd</file_name>
</header>
<shipping>
<shipping_number>some data</shipping_number>
<location_id>some data</location_id>
<status>DONE</status>
<shipping_line>
<article id="1257" />
<article id="1177" >
<product>5500070000126273</product>
<product>5500070000126264</product>
<product>5500070000126255</product>
<product>5500070000126246</product>
<product>5500070000126237</product>
</article>
</shipping_line>
</shipping>
</data>
现在我想检查article
元素是否有子元素,如果有,则将它们放入数组中
这似乎不起作用,我得到一个错误:对非对象调用成员函数hasChildren()
if ($article_array->hasChildren()) {
error_log('has children');
}
您可以使用xpath的
child::
位置路径选择文章节点child,并为文章节点备份一个,如下所示:
$shipping_number_array = $xml->xpath('/data/shipping/shipping_number');
$location_id_array = $xml->xpath('/data/shipping/location_id');
$shipping_status_array = $xml->xpath('/data/shipping/status');
$shipping_number = $shipping_number_array[0];
$location_id = $location_id_array[0];
$status = $shipping_status_array[0];
$article_array = $xml->xpath('//article/child::*/..');
这应该只返回包含child的文章节点(在您的示例中为id 1177)。您可以使用xpath的
子节点::
位置路径来选择文章节点child并为文章节点备份一个,如下所示:
$shipping_number_array = $xml->xpath('/data/shipping/shipping_number');
$location_id_array = $xml->xpath('/data/shipping/location_id');
$shipping_status_array = $xml->xpath('/data/shipping/status');
$shipping_number = $shipping_number_array[0];
$location_id = $location_id_array[0];
$status = $shipping_status_array[0];
$article_array = $xml->xpath('//article/child::*/..');
这应该只返回包含child的文章节点(在您的示例中为id 1177)。为
$article\u数组
变量分配了什么?我怀疑它是一个simplexml::xpath
返回值,您可以简单地使用empty()
$article\u array=$xml->xpath('/data/shipping/shipping\u line/article')代码>这个。为了解释错误:对非对象调用成员函数hasChildren()。您可能尝试在SimpleXMLElement对象上使用它,而不是在SimpleXMLIterator对象上使用它。分配给$article\u数组的变量是什么?我怀疑它是一个simplexml::xpath
返回值,您可以简单地使用empty()
$article\u array=$xml->xpath('/data/shipping/shipping\u line/article')代码>这个。为了解释错误:对非对象调用成员函数hasChildren()。您可能尝试在SimpleXMLElement对象上使用它,而不是在SimpleXMLIterator对象上使用它