2016-04-26 62 views
1

在有人指出類似這樣的類似問題之前,請記住我已經嘗試並用盡了所有可以在堆疊中找到的方法。在使用simplexml之後訪問XML時遇到問題

我在使用simplexml從結構如下的響應中抽出我想要的數據時遇到了問題。

<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<soap:body> 
    <authenticateresponse xmlns="http://somesite.co.nz"> 
    <authenticateresult> 
     <username>Username</username> 
     <token>XXXXXXXXX</token> 
     <reference> 
     <message>Access Denied</message> 
     </reference> 
    </authenticateresult> 
    </authenticateresponse> 
</soap:body> 

在這種情況下,我想知道如何取出令牌和用戶名。

+1

很有可能,*默認命名空間*('的xmlns = 「http://somesite.co.nz」')使你的問題。閱讀:http://stackoverflow.com/a/2386706/2998271 – har07

回答

1

您的XML具有authenticateresponse元素聲明默認命名空間:

xmlns="http://somesite.co.nz" 

請注意,這裏的默認名稱空間與沒有前綴的後代元素一起申報的元素都在同一個命名空間。要在默認命名空間訪問元素,你需要映射的前綴命名空間URI和在XPath使用前綴,例如:

$raw = <<<XML 
<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<soap:body> 
    <authenticateresponse xmlns="http://somesite.co.nz"> 
    <authenticateresult> 
     <username>Username</username> 
     <token>XXXXXXXXX</token> 
     <reference> 
     <message>Access Denied</message> 
     </reference> 
    </authenticateresult> 
    </authenticateresponse> 
</soap:body> 
</soap:envelope> 
XML; 
$xml = new SimpleXMLElement($raw); 
$xml->registerXPathNamespace('d', 'http://somesite.co.nz'); 
$username = $xml->xpath('//d:username'); 
echo $username[0]; 

eval.in demo

輸出:

Username 

以前的幾個相關問題:

+0

謝謝你。我只是回顧一些其他問題。對於一些混亂的原因,甚至當我完全按照你所做的那樣重寫我的代碼時,它仍然失敗,我得到一個未定義的用戶名偏移量。 – Duncan

+0

您可以發佈簡短的演示,可能在eval.in中重現該問題?否則我不知道... – har07

+0

當我靜態寫入時,您的解決方案有效,錯誤必須位於某處的響應數據中,我只在此處張貼了一小部分。感謝非常感謝的幫助。 @ har07 – Duncan