PHP Simple XML Parsers

PHP Simple XML Parsers


The SimpleXML Parser :
  • PHP SimpleXML extension lets you access and work with XML data.
  • This parser is tree-based and provides an efficient method of getting the name of a specific element, attributes or text content. However, you have to be aware of the layout or structure of the XML document you're working with.
  • Using Simple XML, you can convert documents written in PHP XML to arrays or objects.
  • It takes fewer lines of code than its alternatives, Expat and DOM.
  • The SimpleXML functions are part of the PHP core. No installation is required to use these functions.
PHP SimpleXML - Read From String :

Whenever our work requires PHP reading XML document data from string, we use a function called simplexml_load_string().

Imagine we have a variable $my_data that contains XML data. The following code example shows how it would look first declared:

Now, in the example below, simplexml_load_string() is used to PHP read XML data straight from previously mentioned variable :

Here is the output we get in XML:

 

Error Handling Tip: Use the libxml functionality to retrieve all XML errors when loading the document and then iterate over the errors. The following example tries to load a broken XML string:

 

Now, this is the output we would get in XML in such case:

 
PHP SimpleXML - Read From File

The PHP simplexml_load_file() function is used to read XML data from a file.

Assume we have an XML file called "Hello.html", that looks like this:

The example below shows how to use the simplexml_load_file() function to read XML data from a file:

Output :

SimpleXML: Summary

  • SimpleXML is a very convenient choice since it is inbuilt in PHP since version 5 and available in all PHP supporting servers.
  • It is a tree-based parser. Therefore, you need to understand the structure of the document you're going to parse. An element in an XML document is classed as SimpleXMLElement.
  • SimpleXML lets you treat XML files as usable data structures: you can easily fetch certain content, attributes or names of elements. Basically, it turns PHP XML into an array.
  • Compared to Expat or DOM parsers, it requires less code lines to PHP parse XML data properly.