Last updated on October 4th, 2022 at 02:20 pm

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 version="1.0" encoding="ISO-8859-1"?><cars><make name="Ford"><model>Mustang</model></make><make name="Honda"><model>Accord</model></make></cars>

Load XML 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
// 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.

Load XML Using simplexml_load_string

<?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.

Load XML Using SimpleXMLElement

<?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.

Load XML Using simplexml_import_dom

This function takes a node of a DOM document and makes it into a SimpleXML node.

<?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

Leave a Reply

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