2014-10-20 41 views
2
 $xml = '<?xml version="1.0" encoding="UTF-8"?> 
<stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stwresponse.xsd"> 
    <stw:Response> 
     <stw:ThumbnailResult> 
      <stw:Thumbnail Exists="true">http://imagelink.com</stw:Thumbnail> 
      <stw:Thumbnail Verified="false">delivered</stw:Thumbnail> 
     </stw:ThumbnailResult> 
     <stw:ResponseStatus> 
      <stw:StatusCode>refresh</stw:StatusCode> 
     </stw:ResponseStatus> 
     <stw:ResponseTimestamp> 
      <stw:StatusCode>1413812009</stw:StatusCode> 
     </stw:ResponseTimestamp> 
     <stw:ResponseCode> 
      <stw:StatusCode>HTTP:200</stw:StatusCode> 
     </stw:ResponseCode> 
     <stw:CategoryCode> 
      <stw:StatusCode></stw:StatusCode> 
     </stw:CategoryCode> 
     <stw:Quota_Remaining> 
      <stw:StatusCode>132</stw:StatusCode> 
     </stw:Quota_Remaining> 
     <stw:Bandwidth_Remaining> 
      <stw:StatusCode>999791</stw:StatusCode> 
     </stw:Bandwidth_Remaining> 
    </stw:Response> 
</stw:ThumbnailResponse>'; 

     $dom = new DOMDocument; 
     $dom->loadXML($xml); 


     $result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; 
     $status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; 

     echo $result; 

具有上面的代碼應該輸出http://imagelink.com和$狀態應持有「交付」 - 這一點,但沒有這些工作,而不是我留下了錯誤的通知:DOMDocument簡單GetElementsByTagName不會工作?

Trying to get property of non-object 

我已經嘗試了不同的XML解析方案像simplexml(但是當標籤名稱有:在它裏面時不起作用),我嘗試循環遍歷xml中的每個範圍(ThumbNailresponse,response和thumbnailresult),但沒有運氣。

如何獲得stw中的值:Thumbnail?

+1

你確定這就是你的XML?它有一個命名空間。那些'xmlns =「http://www.yahoo.com」'值? – Ghost 2014-10-20 14:07:29

+0

@Ghost確實是我需要從webservice shrinktheweb.com中使用的xml響應。我確實刪除了xmlns =「」,因爲我不想將問題鏈接到web服務。但是我現在添加了它,如果這有幫助的話? – Karem 2014-10-20 14:15:46

+0

那就是爲什麼我想知道,反正名稱空間在哪裏,你可以使用簡單的XML在那個特定的情況下,檢查我的回答 – Ghost 2014-10-20 14:17:05

回答

0

利用簡單的XML,你可以在這一個使用->children()方法:

$xml = simplexml_load_string($xml_string); 
$stw = $xml->children('stw', 'http://www.shrinktheweb.com/doc/stwresponse.xsd'); 
echo '<pre>'; 
foreach($stw as $e) { 
    print_r($e); 
    // do what you have to do here 
} 
0

此代碼實際運行對我蠻好---

通常情況下,這一類的錯誤意味着你may've您$dom對象上做了一個錯字 - 仔細檢查,然後再試一次。

此外,值得注意的是,當您設置$status變量時,您需要將item(0)更改爲item(1)

$result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; 
    $status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; 
1

你需要指定一個命名空間和方法的DOMDocument ::的getElementsByTagName不能處理它。在manual

本地名稱(不命名空間)標籤的匹配上。

您可以使用DOMDocument::getElementsByTagNameNS代替:

$dom = new DOMDocument; 
$dom->loadXML($xml); 

$namespaceURI = 'http://www.shrinktheweb.com/doc/stwresponse.xsd'; 
$result = $dom->getElementsByTagNameNS($namespaceURI, 'Thumbnail')->item(0)->nodeValue;