How to parse xml using PHP (Demo)

Last updated on February 4th, 2022 at 11:09 am

Click to rate this tutorial!
[Total: 2 Average: 3]

Read xml and parse it using php and we are using simple php functions named simplexml_load_file, simplexml_load_string & SimpleXMLElement

This is handy when you are working with the advanced XML features of DOM. When you are ready to move from those precocious features, just load the DOM object into simplexml_import_dom, and start programming the easy way!

Sample XML File Used ‘test_file.xml’:

XML

<?xml version="1.0" encoding="ISO-8859-1"?><cars><make name="Ford"><model>Mustang</model></make><make name="Honda"><model>Accord</model></make></cars>

Loading XML Data Using simplexml_load_file

This function is typically used for loading XML data either from a file, or a remote call. In this example, we will load a flat XML file:

PHP

<?php
// Location of the XML file on the file system
$file = 'test_file.xml';
$xml = simplexml_load_file($file);
?>

Thats it. No need to clean anything up, PHP will take care of that for you.

Loading XML Using simplexml_load_string

PHP

<?php
// XML String
$xml = '
<?xml version="1.0" encoding="ISO-8859-1"?>
<cars>
<make name="Ford">
<model>Mustang</model>
</make>
<make name="Honda">
<model>Accord</model>
</make>
</cars>
';
$xml = simplexml_load_string($xml);
?>

Pretty easy, huh? This function loads an XML string and returns and instance of SimpleXMLElement. You could also directly instantiate the SimpleXMLElement class a similar way, as demonstrated below.

Loading XML Using the SimpleXMLElement Class

PHP

<?php
$xml = '
<?xml version="1.0" encoding="ISO-8859-1"?>
<cars>
<make name="Ford">
<model>Mustang</model>
</make>
<make name="Honda">
<model>Accord</model>
</make>
</cars>
';
$xml = new SimpleXMLElement($xml);
?>

Its your choice on using this method, or simplexml_load_string.

Loading XML Data Using simplexml_import_dom

PHP

<?php
$xml='<?xml version="1.0" encoding="ISO-8859-1"?><cars><make name="Ford"><model>Mustang</model></make><make name="Honda"><model>Accord</model></make></cars>';
$dom = new DOMDocument;
$dom->loadXML($xml);
#$dom->loadXML($xml);
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}
$xml = simplexml_import_dom($dom);
var_dump($xml);
echo "<hr>";
echo $xml->make[0]->model;
echo "<hr>";
echo $xml->make[1]->model;
echo "<hr>";
?>

Demo

Click to rate this tutorial!
[Total: 2 Average: 3]

Leave a Reply

Your email address will not be published.