Press "Enter" to skip to content

Working with PHP and XML

This article gives you an understanding that how can we read a XML Document in PHP.
first we have an idea that what is XML? Xml is a data storage format. It makes a choice for user to define tags and attributes. A simple structure of an xml document is:

[xml]
<?xml version="1.0" ?>
<data>
<employee>
<name>abc</name>
<salary>10000</salary>
</employee>
</data>
OR
<?xml version="1.0" ?>
<data>
<employee name=”abc” salary=”10000” />
</data>
[/xml]

In this xml document parent tag is and its child tags , which has a set of information and tags. And in second example we can use attributes to an xml tags as key/value pair. Now to parse this xml document php has a SimpleXML extension tool.

[php]
// storing xml as a string variable
$xml_string = "<?xml version=’1.0′ ?>
<data>
<employee>
<name>abc</name>
<salary>10000</salary>
</employee>
</data>";
$xmlObj = simplexml_load_string($xml_string);
[/php]

simplexml_load_string() is a php function for parsing XML Document. From this xml object $xmlObj we can get employee name and salary

[php]
$name = $xmlObj->employee->name;
$salary = $xmlObj->employee->salary;
echo "Name is:".$name."<br /> Salary is:".$salary;
// OR
//If we want data from attributes use:
foreach($xmlObj->employee[0]->attributes() as $key => $value)
{
echo $key,’="’,$value,"\"\n";
}
[/php]

In this example $a print attribute name”abc” $b its value “10000”. This is a simple description how php interacts with xml. Last there are some illegal XML characters that cannot be parsed by xml are: [<, > &, ‘, “]. So keep in mind when creating xml document.

Leave a Reply

Your email address will not be published. Required fields are marked *