PHP code example of andrewfenn / xmlreader

1. Go to this page and download the library: Download andrewfenn/xmlreader library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

andrewfenn / xmlreader example snippets


$input = <<<XML
<?xml version="1.0" encoding="UTF-8"

// Start accessing the data you want
var_dump($data);

/* Returns...
object(Sabre\Xml\XMLReaderElement)#68 (4) {
  ["name"]=>
  string(12) "HotelMessage"
  ["namespace"]=>
  string(0) ""
  ["attributes"]=>
  object(stdClass)#69 (2) {
    ["Version"]=>
    string(3) "1.0"
    ["TimeStamp"]=>
    string(19) "2016-05-26T11:11:50"
  }
  ["children"]=>
  string(19) "Message,Hotel,Hotel"
}
*/

echo "Message: ".$data->Message->value."\n";
echo "Message Type: ".$data->Message->attributes->Type."\n";

/* Returns...
Message: Hello
Message Type: Info
*/

echo "Hotel ID: ".$data->Hotel->attributes->HotelCode."\n";
/* Returns...
Hotel ID: 3
*/


foreach($data->find('Hotel') as $hotel) {
    // Find a specific element's attribute
    echo "Hotel ID: ".$hotel->attributes->HotelCode."\n";
}

foreach($data->children() as $tag) {
    if ($tag->name == 'Hotel') {
        echo "Hotel ID: ".$tag->attributes->HotelCode."\n";
    }
}

/* Returns...
Hotel ID: 3
Hotel ID: 7
Hotel ID: 3
Hotel ID: 7
*/

// You can search for any tag attribute by prepending an @ infront of the attribute's name like so...
foreach($data->find('@HotelCode') as $hotel_code) {
    echo "Hotel Code: ".$hotel_code."\n";
}

// You can search for any tag like so...
foreach($data->find('LengthsOfStay') as $los) {
    echo "Length of Stay: ".$los->findFirst('@Time')." Days\n";
}

/* Returns...
Hotel Code: 3
Hotel Code: 4
Length of Stay: 3 Days
Length of Stay: 7 Days
*/

echo $data->findFirst('@TimeStamp')."\n";
echo $data->findFirst('@HotelCode')."\n";
echo $data->findFirst('Hotel')->findFirst('@RatePlanCode')."\n";

/* Returns...
2016-05-26T11:11:50
3
888
*/