【问题标题】:Traversing XML in PHP在 PHP 中遍历 XML
【发布时间】:2011-06-10 01:30:30
【问题描述】:

我有以下要解析的 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 等内容的内部内容?

【问题讨论】:

  • 我假设您使用的是 DOM 解析器,命名空间 (m:) 的处理方式略有不同。
  • 那些是命名空间的。你必须做一些特别的事情来访问命名空间的笔记。你在用simplexml吗?
  • 啊,我明白了。我正在使用 SimpleXML。在快速搜索并查看迈克尔提供的链接后,我想我被困在如何深入两个级别(m:properties -> d:NEW_DATE)......

标签: php xml traversal


【解决方案1】:

在 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

【讨论】:

  • 谢谢,我想出了如何通过在 children() 中包含模式的 uri 来做到这一点,但也试图弄清楚如何在不必包含 uri 的情况下做到这一点!你知道这两种方法在速度上是否有区别吗?
【解决方案2】:

您可以使用 SimpleXml 的函数 SimpleXML

但我最喜欢的课程是DOMDocument

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2023-04-06
    • 2011-10-13
    • 1970-01-01
    相关资源
    最近更新 更多