2010-06-05 143 views
1

我使用PHP獲取請求,但解析器遇到問題。在下面的示例中,我正在尋找一種方法來檢索URL的值。響應xml看起來像這樣。PHP XML解析

<?xml version="1.0" encoding="iso-8859-1" standalone="no"?> 
<testtemplate JobName="test1"> 
<Sources> 
<Source xmlns="http://www.microsoft.com/test/schema/api"> 
    <System> 
     <SystemIdentifier>HTTPS</SystemIdentifier> 
     <URL>http://example.com</URL> 
    </System> 
</Source> 
</Sources> 
<testtemplate> 

和我的PHP代碼如下所示:

$xml = DOMDocument::LoadXML($response); 
$mypath = new DOMXPath($xml); 
$mypath->registerNamespace("a", "http://www.microsoft.com/test/schema/api"); 

$url = $mypath->evaluate("/testtemplate/Sources/Source/System/URL"); 
$message = $url->item(0)->value; 

print($message); 

任何幫助,將不勝感激。

感謝 阿希什

+1

它有什麼「問題」? – Amber 2010-06-05 21:13:45

回答

2

示例XML的格式不正確(該testtemplate未閉),假設只是一個錯字讓坐上去修理你的主要問題。

您需要使用已註冊的名稱空間才能訪問其中的元素,並且item(0)的DOMElement沒有value屬性(改用nodeValue)。

$xml = DOMDocument::LoadXML($response); 
$mypath = new DOMXPath($xml); 
$mypath->registerNamespace("a", "http://www.microsoft.com/test/schema/api"); 

// These two lines have changed, slightly. 
$url = $mypath->evaluate("/testtemplate/Sources/a:Source/a:System/a:URL"); 
$message = $url->item(0)->nodeValue; 

print($message);