在PHP中遍历XML

时间:2011-06-10 01:30:31

标签: php xml traversal

我有以下我正在尝试解析的XML代码,但我确定如何遍历PHP中的一些数据:

  <entry>
    <id>http://data.treasury.gov:8001/Feed.svc/DailyTreasuryYieldCurveRateData(5360)</id>
    <title type="text"></title>
    <updated>2011-06-09T20:15:18Z</updated>
    <author>
      <name />
    </author>
    <link rel="edit" title="DailyTreasuryYieldCurveRateDatum" href="DailyTreasuryYieldCurveRateData(5360)" />
    <category term="TreasuryDataWarehouseModel.DailyTreasuryYieldCurveRateDatum" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int32">5360</d:Id>
        <d:NEW_DATE m:type="Edm.DateTime">2011-06-01T00:00:00</d:NEW_DATE>
        <d:BC_1MONTH m:type="Edm.Double">0.04</d:BC_1MONTH>
        <d:BC_3MONTH m:type="Edm.Double">0.05</d:BC_3MONTH>
        <d:BC_6MONTH m:type="Edm.Double">0.11</d:BC_6MONTH>
        <d:BC_1YEAR m:type="Edm.Double">0.18</d:BC_1YEAR>
        <d:BC_2YEAR m:type="Edm.Double">0.44</d:BC_2YEAR>
        <d:BC_3YEAR m:type="Edm.Double">0.74</d:BC_3YEAR>
        <d:BC_5YEAR m:type="Edm.Double">1.6</d:BC_5YEAR>
        <d:BC_7YEAR m:type="Edm.Double">2.28</d:BC_7YEAR>
        <d:BC_10YEAR m:type="Edm.Double">2.96</d:BC_10YEAR>
        <d:BC_20YEAR m:type="Edm.Double">3.83</d:BC_20YEAR>
        <d:BC_30YEAR m:type="Edm.Double">4.15</d:BC_30YEAR>
        <d:BC_30YEARDISPLAY m:type="Edm.Double">4.15</d:BC_30YEARDISPLAY>
      </m:properties>
    </content>
  </entry>

我只能到目前为止

entry->content

由于以下内容因冒号而引发错误:

entry->content->m:properties 

如何访问内容,例如d:NEW_DATE?

2 个答案:

答案 0 :(得分:6)

在SimpleXML中,您可以使用children('prefix',true)和attributes('prefix',true)函数来访问命名空间内容。

entry->content->children('m', true)->properties

或访问d:NEW_DATE

entry->content->children('m', true)->properties->children('d', true)->NEW_DATE

或进一步访问m:type属性

entry->content->children('m', true)->properties->children('d', true)->NEW_DATE->attributes('m', true)->type

答案 1 :(得分:0)

您可以使用SimpleXml的功能 SimpleXML

但我最喜欢的课程是DOMDocument