Facebook Twitter Reset

This Tutorial Has Been Viewed 1,021 Times.

Simple XML Reading Using PHP

Sample XML File Used

The following XML data will be contained in the referenced “test_file.xml”:

XML
  1. <?xml version=“1.0″ encoding=“ISO-8859-1″?>
  2. <cars>
  3. <make name=“Ford”>
  4. <model>Mustang</model>
  5. </make>
  6. <make name=“Honda”>
  7. <model>Accord</model>
  8. </make>
  9. </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
  1. <?php
  2. // Location of the XML file on the file system
  3. $file = ‘test_file.xml’;
  4. $xml = simplexml_load_file($file);
  5. ?>

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

Loading XML Using simplexml_load_string

PHP
  1. <?php
  2. // XML String
  3. $xml =
  4. <?xml version=”1.0″ encoding=”ISO-8859-1″?>
  5. <cars>
  6. <make name=”Ford”>
  7. <model>Mustang</model>
  8. </make>
  9. <make name=”Honda”>
  10. <model>Accord</model>
  11. </make>
  12. </cars>
  13. ;
  14. $xml = simplexml_load_string($xml);
  15. ?>

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
  1. <?php
  2. $xml =
  3. <?xml version=”1.0″ encoding=”ISO-8859-1″?>
  4. <cars>
  5. <make name=”Ford”>
  6. <model>Mustang</model>
  7. </make>
  8. <make name=”Honda”>
  9. <model>Accord</model>
  10. </make>
  11. </cars>
  12. ;
  13. $xml = new SimpleXMLElement($xml);
  14. ?>

It’s your choice on using this method, or simplexml_load_string.

Loading XML Data Using simplexml_import_dom

PHP
  1. <?php
  2. $xml =
  3. <?xml version=”1.0″ encoding=”ISO-8859-1″?>
  4. <cars>
  5. <make name=”Ford”>
  6. <model>Mustang</model>
  7. </make>
  8. <make name=”Honda”>
  9. <model>Accord</model>
  10. </make>
  11. </cars>
  12. ;
  13. $dom = new DOMDocument;
  14. $dom->loadXML($xml);
  15. $xml = simplexml_import_dom($dom);
  16. ?>

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!

VN:F [1.9.13_1145]
Rating: 5.5/10 (2 votes cast)
VN:F [1.9.13_1145]
Rating: +1 (from 1 vote)
Simple XML Reading Using PHP, 5.5 out of 10 based on 2 ratings

Incoming search terms:




You will also be interested in ,

No comments yet.

Leave a Comment

Spam protection by WP Captcha-Free

Affordable Seo PackagesSeo BlogEdu Backlinks
More in Jquery (5 of 15 articles)