2012-02-29 32 views
3

解析,我有以下被作爲XML返回從源:PHP ODATA XML用的SimpleXMLElement

<content type="application/xml"> 
    <m:properties> 
    <d:ID>30</d:ID> 
    <d:Name></d:Name> 
    <d:ProfileImageUrl>default.png</d:ProfileImageUrl> 
    <d:ThumbnailUrl>default.png</d:ThumbnailUrl> 
    <d:FavoriteCount m:type="Edm.Int64">0</d:FavoriteCount> 
    <d:ViewCount m:type="Edm.Int64">12030</d:ViewCount> 
    <d:LastMonthViewCount m:type="Edm.Int64">1104</d:LastMonthViewCount> 
    <d:LastWeekViewCount m:type="Edm.Int64">250</d:LastWeekViewCount> 
    <d:LastDayViewCount m:type="Edm.Int64">21</d:LastDayViewCount> 
    <d:CreationDate m:type="Edm.DateTime">2011-03-28T13:46:54.227</d:CreationDate> 
    <d:Enabled m:type="Edm.Boolean">true</d:Enabled> 
    <d:UrlSafeName>t-boz</d:UrlSafeName> 
    <d:LastDayFavoriteCount m:type="Edm.Int64">0</d:LastDayFavoriteCount> 
    <d:LastWeekFavoriteCount m:type="Edm.Int64">0</d:LastWeekFavoriteCount> 
    <d:LastMonthFavoriteCount m:type="Edm.Int64">0</d:LastMonthFavoriteCount> 
    <d:IsOnTour m:type="Edm.Boolean">false</d:IsOnTour> 
    <d:TodayRank m:type="Edm.Int32">6272</d:TodayRank> 
    <d:WeekRank m:type="Edm.Int32">6851</d:WeekRank> 
    <d:MonthRank m:type="Edm.Int32">6915</d:MonthRank> 
    <d:AllTimeRank m:type="Edm.Int32">7973</d:AllTimeRank> 
    </m:properties> 
</content> 

我通過的file_get_contents然後通過創建的SimpleXMLElement檢索此。但是我無法訪問content->屬性字段(即ID,名稱,ProfileImageUrl等)。我從SIMPLEXMLElement看到的所有內容如下:

[content] => SimpleXMLElement Object ([@attributes] => Array ([type] => application/xml)) 

有關如何獲取此數據的任何想法?

謝謝!

+0

你的XML無效,需要在文檔中定義'm'和'd'命名空間前綴。 – salathe 2012-02-29 21:12:48

+0

這是非常狡猾的XML。它在其元素上使用名稱空間前綴,但不綁定這些名稱空間前綴。 – 2012-02-29 21:13:51

+1

Feed在頂部有這個..很抱歉,我之前排除了它。 <?xml version =「1.0」encoding =「utf-8」standalone =「yes」?> Nikon0266 2012-02-29 22:19:56

回答

4

訪問命名空間的元素很容易與SimpleXML的,你只要告訴children()方法來看看其中的命名空間

一個超級基本例如會是什麼樣子:

$xml = <<<XML 
<content type="application/xml" xmlns:m="urn:m" xmlns:d="urn:d"> 
    <m:properties> 
    <d:ID>30</d:ID> 
    <d:ProfileImageUrl>default.png</d:ProfileImageUrl> 
    </m:properties> 
</content> 
XML; 

$content  = simplexml_load_string($xml); 

// Quick way 
// $properties = $content->children('m', TRUE)->properties->children('d', TRUE); 
// echo $properties->ProfileImageUrl; 

// Step by step 
$m_elements = $content->children('m', TRUE); 
$m_properties = $m_elements->properties; 
$d_elements = $m_properties->children('d', TRUE); 
echo $d_elements->ProfileImageUrl; 
+0

拯救了我的一天。謝謝 – 2017-03-20 12:29:27