Home > Software engineering >  Filter xml by node value in php
Filter xml by node value in php

Time:06-22

I have an xml that shows Arriving and departing flights, we have to sort this in different columns based on the "type" (arriving or departure) values in the xml file. How do i do this?

Xml looks like this:

<flights>
<flight>
<iata>ND812</iata>
<name>NDA812</name>
<type>arrival</type>
<airline>
<name>Nordica</name>
</airline>
<remark/>
 <airport>
   <name>Airport 1</name>
<localname/>
</airport>
<scheduleddate>2022-06-21</scheduleddate>
<scheduledtime>10:35</scheduledtime>
</flight>

<flight>
<iata>ND812</iata>
<name>NDA812</name>
<type>departure</type>
<airline>
<name>Nordica</name>
</airline>
<remark/>
 <airport>
   <name>Airport 2</name>
<localname/>
</airport>
<scheduleddate>2022-06-21</scheduleddate>
<scheduledtime>10:35</scheduledtime>
</flight>
</flights>

Were using PHPCode snippets plugin in WP

// load SimpleXML
$flight = new SimpleXMLElement('https://XXX/fids.xml', null, true);

echo $flight ->flight[0]->type."<br />";
echo $flight ->flight[1]->type."<br />";
echo $flight ->flight[2]->type."<br />";

This obviously shows all flights arriving and departure....

Grateful for quick help!! :)

CodePudding user response:

You can simply loop on each flight. Then you can test the flight type to do whatever you want. I'm not sure I understand: "we have to sort this in different columns based on the type".

<?php
$response = <<<XML
<?xml version="1.0"?>
<flights>
<flight>
<iata>ND812</iata>
<name>NDA812</name>
<type>arrival</type>
<airline>
<name>Nordica</name>
</airline>
<remark/>
 <airport>
   <name>Airport 1</name>
<localname/>
</airport>
<scheduleddate>2022-06-21</scheduleddate>
<scheduledtime>10:35</scheduledtime>
</flight>
<flight>
<iata>ND812</iata>
<name>NDA812</name>
<type>departure</type>
<airline>
<name>Nordica</name>
</airline>
<remark/>
 <airport>
   <name>Airport 2</name>
<localname/>
</airport>
<scheduleddate>2022-06-21</scheduleddate>
<scheduledtime>10:35</scheduledtime>
</flight>
</flights>
XML;

$xml = new SimpleXMLElement($response);

foreach ($xml->flight as $flight) {
   if($flight->type=='departure') {
    echo $flight->type, ' / ', $flight->name, ' / ', $flight->airport->name, ' / ', $flight->iata, ' / ', $flight->remark, ' / ', $flight->scheduleddate, PHP_EOL;
   }
}

Results

departure / NDA812 / Airport 2 / ND812 /  / 2022-06-21
  • Related