【问题标题】:PHP ODATA XML parsing with SimpleXMLElement使用 SimpleXMLElement 解析 PHP ODATA XML
【发布时间】:2012-02-29 21:07:41
【问题描述】:

我将以下内容作为 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 ) )

对我如何获取这些数据有任何想法吗?

谢谢!

【问题讨论】:

标签: php xml simplexml odata


【解决方案1】:

使用 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多