使用PHP XPath我在xml文件中搜索客户:
$this->xpath->query(/custumer/new[id="222"])->item(0)->nodeValue;
Run Code Online (Sandbox Code Playgroud)
但是如果这个客户在xml文件中不存在,我会收到错误:
Notice: Trying to get property of non-object in D:\www\test.php on line 17
Run Code Online (Sandbox Code Playgroud)
如何避免这个错误?
首先检查XPATH-> query返回的nodeList 的长度.如果它不是0,则有一个对象.
$nodelist = $this->xpath->query('/custumer/new[@id="222"]');
if($nodelist->length)//a DOMNodelist has a length-property
{
$result = $nodelist->item(0)->nodeValue;
}
Run Code Online (Sandbox Code Playgroud)