如果条件检查 XPath 属性是否存在



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

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

我在foreach loop里有for 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;
}

但同样的错误也发生了。

如何创建一个在找不到ItemID Attribute时跳过$prices[]行的if

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

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

最新更新