2016-04-26 4 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> 

この場合、トークンとユーザー名を引き出す方法を知りたいと思います。デフォルトの名前空間は、接頭辞なしの子孫要素と一緒に宣言された要素が同じ名前空間にあること

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

お知らせ:

+1

可能性が非常に高い、*デフォルトの名前空間(* 'のxmlnsは= "http://somesite.co.nzは、"')あなたに問題が発生します。読んでください:http://stackoverflow.com/a/2386706/2998271 – har07

答えて

1

あなたのXMLはauthenticateresponse要素で宣言されたデフォルトの名前空間を持っています。デフォルトの名前空間内の要素にアクセスするには、例えば、名前空間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

関連する問題