Tuesday, December 12, 2017

Using XML with PHP (Example 2)

In this example, you will see using foreach function twice. Ok, let's start write codes. We will write the following xml codes and save it as file name 'example.xml'.

<producer>

      <producer>
             <food>
                   <foodname>banana</foodname>
                   <foodprice>100 kyats</foodprice>
             </food>
       </producer>

       <producer>
             <food>
                   <foodname>lime</foodname>
                   <foodprice>200 kyats</foodprice>
             </food>
        </producer>

       <producer>
             <food>
                   <foodname>milk</foodname>
                   <foodprice>300 kyats</foodprice>
             </food>
       </producer>

</producer>



And then we will write the following php codes and save it as filename 'xml.php'.

<?php

$xml = simplexml_load_file('example.xml');

foreach($xml -> producer as $producer){
  
  foreach($producer as $food){
    echo $food -> foodname.' = '.$food -> foodprice.'.</br>';
  }
}

?>

To test the codes, open your browser and write xml.php in your browser. Then, you will see all data in .xml file.


No comments:

Post a Comment