10.4. SimpleXML

XML is everywhere these days, so it only makes sense that there should be an easy way to retrieve and interpret those files. Thankfully, PHP offers us an XML interface to utilize XML data, in a simple and easy-to-use extension: SimpleXML. SimpleXML is installed by default, but if you're not going to use it, it is recommended that you disable it in php.ini. It should be noted that SimpleXML also requires PHP5.

As the name suggests, the extension's purpose is to access XML documents on a very basic level. To illustrate the ease with which this can be implemented, create a fictitious XML file that contains information on beachfront rentals (this file will be used in all of the examples):

<?xml version="1.0"?>
  <rentals>
    <description>
     <name>The Bayfront</name>
     <type>condo</type>
     <view>oceanfront</view>
     <space>1200 square feet</space>
     <location>Wrightsville Beach</location>
     <price>1000 per week</price>
     <bed_bath>3 bedrooms, 2 bathrooms</bed_bath>
    </description>
    <description>
      <name>Paradise</name>
      <type>house</type>
      <view>oceanfront</view>
      <space>1000 square feet</space>
      <location>Wrightsville Beach</location>
      <price>900 per week</price>
      <bed_bath>2 bedrooms, 2 bathrooms</bed_bath>
     </description>
   </rentals>>

Now that you have the XML file, grab the information and put it into an object (using the simplexml_load_file() function) so you can manipulate it:

<?php
if (file_exists('beachfront.xml')) {
   $data = simplexml_load_file('beachfront.xml');

   print_r($data);
}
?>

You can ...

Get Professional LAMP: Linux®, Apache, MySQL®, and PHP5 Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.