2014-03-01 32 views
-1
<?xml version="1.0" encoding="UTF-8"?> 
<AddProduct> 
<auth><id>vendor123</id><auth_code>abc123</auth_code></auth> 
</AddProduct> 

我在做什麼錯誤可以得到:致命錯誤:調用未定義的方法的DOMNodeList ::的getElementsByTagName()XML Xpath的失敗上的getElementsByTagName

$xml = $_GET['xmlRequest']; 
$dom = new DOMDocument(); 
@$dom->loadXML($xml); 

$xpath = new DOMXPath($dom); 

$auth = $xpath->query('*/auth'); 
$id = $auth->getElementsByTagName('id')->item(0)->nodeValue; 
$code = $auth->getElementsByTagName('auth_code')->item(0)->nodeValue; 
+2

如果我可以提出建議,不要在調試時使用'@'來抑制錯誤警告。 – Ohgodwhy

+0

嘗試將XPath更改爲'// auth'或'/ AddProduct/auth' – helderdarocha

+1

實際上,經過進一步的審查,'DOMXpath'沒有'getElementsByTagName'屬性,但是'DOMDocument'確實有它。 – Ohgodwhy

回答

1

你可以檢索數據(在XML您發佈)你想只使用XPath:

$id = $xpath->query('//auth/id')->item(0)->nodeValue; 
$code = $xpath->query('//auth/auth_code')->item(0)->nodeValue; 

您還呼籲$authDOMXPathgetElementsByTagName()),作爲@Ohgodwhy在評論中指出,這是中國農業大學唱錯誤。如果你想使用它,你應該打電話給$dom

您的XPath表達式返回當前(上下文)節點的auth子節點。除非你的XML文件不同的是,它更清晰使用的一個:

/*/auth   # returns auth nodes two levels below root 
/AddProduct/auth # returns auth nodes in below /AddProduct 
//auth   # returns all auth nodes 
+2

如果用evaluate()替換query(),則可以通過在Xpath中投射結果列表直接獲取值。 '$ id = $ xpath-> evaluate('string(// auth/id)');' – ThW

+0

謝謝!這很好。因爲這是我在我的代碼中使用的獎勵。 –

1

這是我想出了審查php的文件(http://us1.php.net/manual/en/class.domdocument.phphttp://us1.php.net/manual/en/domdocument.loadxml.phphttp://us3.php.net/manual/en/domxpath.query.phphttp://us3.php.net/domxpath

$dom = new DOMDocument(); 
$dom->loadXML($xml); 
$id = $dom->getElementsByTagName("id")->item(0)->nodeValue; 
$code = $dom->getElementsByTagName("auth_code")->item(0)->nodeValue; 

由於helderdarocha後Ohgodwhy指出,getElementByTagName是一個不是DOMXPath方法的DOMDocument方法。我喜歡helderdarocha的解決方案,只使用XPath,我發佈的解決方案完成同樣的事情,但只使用DOMDocument。