如何通过PHP中的SImpleXML访问XML数据

时间:2017-01-03 11:59:18

标签: php xml simplexml

我有一个XML源,似乎使用了一些d2LogicalModel标记,我真的很难弄清楚如何使用PHP的SimpleXML从中提取任何数据。

我在下面列出了XML的简化版本:如何提取carParkIdentity? 如何访问特定的ID?

然后我可以自己找出其余的数据!

非常感谢!

<d2lm:d2LogicalModel xmlns:d2lm="http://datex2.eu/schema/1_0/1_0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xalan="http://xml.apache.org/xslt" xmlns:java="http://xml.apache.org/xalan/java" modelBaseVersion="1.0" xsi:schemaLocation="http://datex2.eu/schema/1_0/1_0 http://datex2.eu/schema/1_0/1_0/DATEXIISchema_1_0_1_0.xsd">
  <d2lm:exchange>...</d2lm:exchange>
  <d2lm:payloadPublication lang="en" xsi:type="d2lm:SituationPublication">
    <d2lm:situation id="CPN0017">
      <d2lm:situationRecord id="CPN0017_1" xsi:type="d2lm:CarParks">
        <d2lm:situationRecordCreationTime>2017-01-03T10:47:41</d2lm:situationRecordCreationTime>
        <d2lm:situationRecordVersion>1</d2lm:situationRecordVersion>
        <d2lm:carParkIdentity>Chapelfield, Chapelfield Road, N:CPN0017</d2lm:carParkIdentity>
        <d2lm:carParkOccupancy>77.0</d2lm:carParkOccupancy>
        <d2lm:carParkStatus>enoughSpacesAvailable</d2lm:carParkStatus>
      </d2lm:situationRecord>
    </d2lm:situation>
  </d2lm:payloadPublication>
</d2lm:d2LogicalModel>

1 个答案:

答案 0 :(得分:1)

就像这段代码一样简单:

$xml = simplexml_load_file('/PATH/TO/YOUR/FILE.XML');

foreach ($xml->xpath('//d2lm:carParkIdentity') as $child) {

    echo $child;

}

另外,非常欢迎您查看XPath语法here

相关问题