if条件检查XPath属性是否存在

问题描述 投票:0回答:1

我有一个像这样构造的xml文件

<listing ItemID="12345679" SKU="ABC123" Price="99.99" />

我在for loop里面有一个foreach loop

for ($i = 0; $i < $itemidcount; $i++) {
    $xpath = $xml->xpath('/sitename/listing[@ItemID=' . '"' . $itemid[$i] .'"' . ']');
    $prices[] = (string)$xpath[0]->attributes()->Price;
}

我的问题是,如果在ItemID中不存在attribute for loop,它会输出错误并停止我的脚本。

Notice: Undefined offset: 0 in /home/sitename/public_html/feeds/script.php on line 137

Fatal error: Uncaught Error: Call to a member function attributes() on null in /home/sitename/public_html/feeds/script.php:137 Stack trace: #0 {main} thrown in /home/sitename/public_html/feeds/script.php on line 137

我试过做一个count

$count = count((string)$xpath[0]->attributes()->Price);

并将其包裹在$prices[]

if ($count > 0) {
    $prices[] = (string)$xpath[0]->attributes()->Price;
}

但是会发生同样的错误。

如果找不到if $prices[],我如何创建一个跳过ItemID线的Attribute

php xml xpath
1个回答
1
投票

您需要检查从XPath调用返回的元素数。所以

$xpath = $xml->xpath('/sitename/listing[@ItemID=' . '"' . $itemid[$i] .'"' . ']');
if (count($xpath) > 0) {
   $prices[] = (string)$xpath[0]->attributes()->Price;
}
© www.soinside.com 2019 - 2024. All rights reserved.