开发者

avoid error when xpath does not find namespace in xml

开发者 https://www.devze.com 2023-01-16 09:24 出处:网络
Could someone tell me how to avoid these errors? Testing for existance of namespace? It starts when I want to add geo information to an array

Could someone tell me how to avoid these errors? Testing for existance of namespace?

It starts when I want to add geo information to an array I thought it was enough to do this.

(from the picasa api feed)

foreach($feed->xpath('//gml:pos') as $pos)
{

$feed_arr['geo'][$i]['pos'] = (string)$pos[0];
$i++;
}

<b>Warning</b>:  SimpleXMLElement::xpath() [<a href='/phpmanual/simplexmlelement.xpath'>simplexmlelement.xpath</a>]: Undefined namespace prefix in <b>/home/woonbel/public_html/tsa.nl/applicatie/lib/gpicasa.class.php</b> on line <b>390</b><br />
<br />
<b>Warning</b>:  SimpleXMLElement::xpath() [<a href='/phpmanual/simplexmlelement.xpath'>simplexmlelement.xpath</a>]: xmlXPathEval: evaluation failed in <b>/home/woonbel/public_html/tsa.nl/applicatie/lib/gpicasa.class.php</b> on line <b>390</b><br />
<br />
<b>Warning</b>开发者_运维技巧:  Invalid argument supplied for foreach() in <b>/home/woonbel/public_html/tsa.nl/applicatie/lib/gpicasa.class.php</b> on line <b>390</b><br />

regards, Richard


Just don't query for it when it isn't in $element->getDocNamespaces();


The clean solution is the one posted by Wrikken, but you can try this


foreach( (($tmp = @$feed->xpath('//gml:pos')) ? $tmp : array()) as $pos ) {
    // body
}

$xml->xpath is called with '@' to suppress error messages (the first two warnings about xpath), the result is assigned to $tmp. Then the conditional statement is evaluated. $xml->xpath(...) ? $tmp : array() will return $tmp (the result of the xpath query) if it contains valid data, otherwise it will return an empty array. That will avoid the warning output for an invalid foreach argument.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号