Friday, 14 December 2012

PHP - XML: Retrieving Attribute Values

PHP XML Tips - Part 4: Below, sample how to retrieve attribute value.

First, create xml document like this:
01    <?xml version="1.0"?>
02    <datas>
03      <cars>
04        <car>
05          <manufacture country="japan">Honda</manufacture>
06          <type>Honda Jazz</type>
07        </car>
08        <car>
09          <manufacture country="korea">Nissan</manufacture>
10          <type>Nissan Livina</type>
11        </car>  
12      </cars>
13    </datas>

Save as "cars.xml" within www/test/xml. Then create reader like this:
01    <?php
02    $xml = simplexml_load_file("cars.xml")
03           or die("Error: Cannot create object");
04           
05    foreach($xml->children() as $cars){
06        foreach($cars->children() as $car => $data){
07          echo $data->manufacture['country'];
08          echo "<br />";
09        }
10    }
11   
12    ?>

As you see, to read attribute value, we can use such as $data->manufacture['country'].

No comments:

Post a Comment