Reputation: 169
I have the following being returned as XML from source:
<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>
I am retrieving this via file_get_contents then creating via SIMPLEXMLElement. However I am unable to access the content->properties fields (ie. ID, Name, ProfileImageUrl, etc). All I see from the SIMPLEXMLElement is the following:
[content] => SimpleXMLElement Object ( [@attributes] => Array ( [type] => application/xml ) )
Any thoughts on how I get this data?
Thanks!
Upvotes: 2
Views: 2257
Reputation: 51960
Accessing namespaced elements is easy with SimpleXML, you just tell the children()
method which namespace to look in.
A super basic example would look like:
$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;
Upvotes: 5