我从源中以 XML 形式返回以下内容:
<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 创建。但是我无法访问内容->属性字段(即 ID、名称、ProfileImageUrl 等)。我从 SIMPLEXMLElement 中看到的所有内容如下:
[content] => SimpleXMLElement Object ( [@attributes] => Array ( [type] => application/xml ) )
关于如何获取这些数据有什么想法吗?
谢谢!
最佳答案
使用 SimpleXML 访问命名空间元素很容易,您只需告诉 children()
要查找哪个 namespace 的方法。
一个 super 基本示例如下所示:
$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;
关于使用 SimpleXMLElement 进行 PHP ODATA XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9506627/