我有一个像这样构造的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
?
您需要检查从XPath调用返回的元素数。所以
$xpath = $xml->xpath('/sitename/listing[@ItemID=' . '"' . $itemid[$i] .'"' . ']');
if (count($xpath) > 0) {
$prices[] = (string)$xpath[0]->attributes()->Price;
}