Simple XML Reading Using PHP
Sample XML File Used
The following XML data will be contained in the referenced “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>
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
-
// Location of the XML file on the file system
-
$file = ‘test_file.xml’;
-
$xml = simplexml_load_file($file);
-
?>
That’s it. No need to clean anything up, PHP will take care of that for you.
Loading 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.
Loading XML Using the SimpleXMLElement Class
-
<?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);
-
?>
It’s your choice on using this method, or simplexml_load_string.
Loading XML Data Using simplexml_import_dom
-
<?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);
-
$xml = simplexml_import_dom($dom);
-
?>
This is handy when you are working with the advanced XML features of DOM. When you’re ready to move from those precocious features, just load the DOM object into simplexml_import_dom, and start programming the easy way!
Related posts:







