Reading xml with PHP

Two days back I was working on reading xml using php. And let me tell you it was really cool with php. Hence thought of sharing with you.

the source xml programs.xml is fallows,

<?xml version=”1.0″ ?>
<programs>

<program name=”cart”>
<price>250</price>
</program>

<program name=”survey”>
<price>500</price>
</program>

</programs>

the php script to populate data from the xml file (programs.xml),

<?php

$php_programs=simplexml_load_file(‘programs.xml’);

foreach($php_programs->program as $program_key => $program_val)
{

echo”the root element
is named <b>$program_key</b><br/>”;

foreach($program_val->children() as $child_of_program_key=>
$child_of_program_val)

{

if($child_of_program_key == “price”)
{

foreach($program_val->attributes() as $att=>$val)
{
foreach($program_val->price as $the_price)
{

echo “This <b>$program_key</b>
element has an ettribute named <b>$att</b> and is named
<b>$val</b>.<br/>”;

echo “This <b>$program_key</b>
element has a child element named <b>$child_of_program_key</b>
and the value is : <b>$the_price</b>.<br/><br/>”;

}
}
}
}

}
?>

And the output looks as follows,

the root element is named program
This program element has an ettribute named name and is named cart.
This program element has a child element named price and the value is : 250.

the root element is named program
This program element has an ettribute named name and is named survey.
This program element has a child element named price and the value is : 500.

Advertisements