Traversing XML in PHP

送分小仙女□ 提交于 2019-12-21 06:06:12

问题


I have the following XML code that I'm trying to parse, but I'm sure of how to traverse some of the data in 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>

I can only get so far as

entry->content

As the following throws an error for having a colon:

entry->content->m:properties 

How do I access what's inside content such as d:NEW_DATE?


回答1:


In SimpleXML you can use the children('prefix', true) and attributes('prefix', true) functions to access namespaced content.

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

or to access d:NEW_DATE

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

or one step further to access the m:type attribute

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



回答2:


You can use the SimpleXml's functions SimpleXML

But my fav class is DOMDocument



来源:https://stackoverflow.com/questions/6301084/traversing-xml-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!