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