nomaki
nomaki

Reputation: 84

How to access XML data via SImpleXML in PHP

I have an XML source which appears to be using some d2LogicalModel markup, and I'm really struggling to figure out how to extract any data from it using PHP's SimpleXML.

I've included a cut-down version of the XML below: How do I extract the carParkIdentity? How to I access a specific 's id?

Then I can figure out the rest of the data myself!

Thanks a bunch!

<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>

Upvotes: 0

Views: 136

Answers (1)

Artyom Sokolov
Artyom Sokolov

Reputation: 2405

As simple as this piece of code:

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

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

    echo $child;

}

Also, you are more than welcome to take a look on XPath syntax here.

Upvotes: 1

Related Questions