Home > Web Development > PHP SimpleXML Rules!

PHP SimpleXML Rules!

August 1st, 2009

Last week I was debugging an xml parsing utility in PHP. Debugging can be enjoyable when it goes well but in my case it just wasn’t happening. It felt like chewing mud. The issue was actually a bug within the libxml library which is a native PHP extension. Apparently it was a bug that was introduced in PHP version 5.2.6 and was addressed in version 5.2.8 or 5.2.9. The bug presented itself when using the xml_parser methods which are built into the PHP. It is the old way of parsing XML with PHP, the new way is using SimpleXML, SimpleXMLElement, or XMLReader objects.

Now, once I read over the documentation I realized how easy it is to use the new SimpleXML. Additionally, I reduced my XML related code size from 100+ lines to less than 20. Fun!

Here is a short example of how to use it, let’s say we have the following XML structure:

<webservers>
 <webserver>
 <hostname>dev1</hostname>
 <purpose>eCommerce LAMP Development</purpose>
 <os>CentOS</os>
 <applications>
 <application isInstalled="1">Apache</application>
 <application isInstalled="1">MySQL</application>
 <application isInstalled="1">PHP</application>
 </applications>
 </webserver>
</webservers>

Now lets observe how to use the SimpleXML class:

//We'll assume that the above xml is represented as a string and located inside $xmlDoc
//Here we create the SimpleXML object named $xml from the xmlDoc shown above
$xml = simplexml_load_string($xmlDoc);

//Now we can loop through the nodes 
//Notice how the node translates to a property of the object)
foreach($xml->webservers->webserver as $webserver)
{
  //Here we can use $webserver as a sub-node
  echo "My Web Server Info:\n";
  echo "Hostname: " . $webserver->hostname . "\n";
  echo "Purpose: " . $webserver->purpose . "\n";
  echo "OS: ". $webserver->os . "\n";
  //Now we'll see how we can use the xml node attributes
  foreach($webserver->applications as $application)
  {
    echo "Application: ". $application;
    echo ($application['isInstalled'] == 1 ? " is installed" : " is not installed");
    echo "\n";
  }
}

That is it! easy right? I thought so. At least it is much easier than working directly with the old xml_parser methods which turns to be buggy in recent versions of PHP.

A word of caution: I found it is necessary to join the values of the SimpleXML object to a string, sometimes even to an empty string in case that I am sending it to a function. In other words, i had to use:

myFunction($webserver->hostname."");

instead of simply:

myFunction($webserver->hostname);

and the reason is that otherwise PHP would pass a copy of the object instead of triggering the toString() method. By adding the empty string we force PHP to first convert it to string and then send it to the function or method.

Web Development ,

Comments are closed.