In this tutorial, I am going to show you how you can parse an XML into PHP.
An XML parser is a program that allows to translate an XML doc or code into XML Document Object Model(DOM) object.
In PHP, we have an extension called SimpleXML that allows us to manipulate and get XML data.
SimpleXML is a XML parser available in PHP.
SimpleXML allows an easy way of getting an element’s name, attributes and content.
In this process, I am going to use SimpleXML to parse XML in PHP.
Parse XML in PHP
Here I am using xml code in PHP, you can also parse XML with filename.
Suppose we have an xml data
<?xml version='1.0'?> <studentinfo> <student> <name>Akash</name> <gender>M</gender> <age>23</age> </student> <student> <name>Sameer</name> <gender>M</gender> <age>23</age> </student> <student> <name>Paras</name> <gender>M</gender> <age>20</age> </student> </studentinfo>
Now let’s see how to parse it. Either we can directly store XML data in PHP variable or save it into an XML file.
Here I am storing it in a variable.
<?php $xmlfile = "<?xml version='1.0'?> <studentinfo> <student> <name>Akash</name> <gender>M</gender> <age>23</age> </student> <student> <name>Sameer</name> <gender>M</gender> <age>23</age> </student> <student> <name>Paras</name> <gender>M</gender> <age>20</age> </student> </studentinfo>"; ?>
Now we use a method simplexml_load_string to covert XML string into an object.
<?php
//If you have xml file
/* $xml = simplexml_load_file('filename.xml'); */
// Convert xml string into an object
$xml = simplexml_load_string($xmlfile);
?>
So, we have converted a string into an object. Now we can easily get the value of elements.
Get Node Value
<?php $data= $xml->student->name; echo $data; ?>
Get Node Values of Specific Elements
<?php
$spdata= $xml->student[1]->name;
echo $spdata;
?>
Get Node Values – Loop
<?php
foreach($xml->children() as $xmldata)
{
echo $xmldata->name . ", ";
echo $xmldata->gender . ", ";
echo $xmldata->age . "<br>";
}
?>
I have used three different approach to get node value. Hope you have got how to parse an XML data in PHP.
Also Read:
How to POST JSON Data With PHP cURL
How to Receive JSON POST with PHP
If you have any query related to this tutorial, leave a comment below.