- Create rich and interactive web applications with PHP and jQuery
- Debug and execute jQuery code on a live site
- Design interactive forms and menus
- Another title in the Packt Cookbook range, which will help you get to grips with PHP as well as jQuery
Extensible Markup Language—also known as XML—is a structure for representation of data in human readable format. Contrary to its name, it’s actually not a language but a markup which focuses on data and its structure. XML is a lot like HTML in syntax except that where HTML is used for presentation of data, XML is used for storing and data interchange.
Moreover, all the tags in an XML are user-defined and can be formatted according to one’s will. But an XML must follow the specification recommended by W3C.
With a large increase in distributed applications over the internet, XML is the most widely used method of data interchange between applications. Web services use XML to carry and exchange data between applications. Since XML is platform-independent and is stored in string format, applications using different server-side technologies can communicate with each other using XML.
Consider the following XML document:
From the above document, we can infer that it is a list of websites containing data about the name, URL, and some information about each website.
PHP has several classes and functions available for working with XML documents. You can read, write, modify, and query documents easily using these functions.
In this article, we will discuss SimpleXML functions and DOMDocument class of PHP for manipulating XML documents. You will learn how to read and modify XML files, using SimpleXML as well as DOM API. We will also explore the XPath method, which makes traversing documents a lot easier.
Note that an XML must be well-formed and valid before we can do anything with it. There are many rules that define well-formedness of XML out of which a few are given below:
- An XML document must have a single root element.
- There cannot be special characters like , and soon.
- Each XML tag must have a corresponding closing tag.
- Tags are case sensitive
To know more about validity of an XML, you can refer to this link:
For most of the recipes in this article, we will use an already created XML file. Create a new file, save it as common.xml in the Article3 directory. Put the following contents in this file.
You see, but you do not observe. The distinction
It is quite a three pipe problem, and I beg that you
won’t speak to me for fifty minutes.
It is, of course, a trifle, but there is nothing so
important as trifles.
I am not the law, but I represent justice so far as
my feeble powers go.
We must look for consistency. Where there is a want
of it we must suspect deception.
Dogs don’t make mistakes.
Any truth is better than indefinite doubt.
Results without causes are much more impressive.
If I were assured of your eventual destruction I would,
in the interests of the public, cheerfully accept my
Loading XML from files and strings using SimpleXML
True to its name, SimpleXML functions provide an easy way to access data from XML documents. XML files or strings can be converted into objects, and data can be read from them.
We will see how to load an XML from a file or string using SimpleXML functions. You will also learn how to handle errors in XML documents.
Create a new directory named Article3. This article will contain sub-folders for each recipe. So, create another folder named Recipe1 inside it.
How to do it…
- Create a file named index.php in Recipe1 folder. In this file, write the PHP code that will try to load the common.xml file. On loading it successfully, it will display a list of book names. We have also used the libxml functions that will detect any error and will show its detailed description on the screen.
$objXML = simplexml_load_file(‘../common.xml’);
$errors = libxml_get_errors();
foreach($errors as $error)
foreach($objXML->book as $book)
- Open your browser and point it to the index.php file. Because we have already validated the XML file, you will see the following output on the screen:
The Adventures of Sherlock Holmes
The Case-book of Sherlock Holmes
The Memoirs of Sherlock Holmes
- Let us corrupt the XML file now. For this, open the common.xml file and delete any node name. Save this file and reload index.php on your browser. You will see a detailed error description on your screen:
How it works…
In the first line, passing a true value to the libxml_use_internal_errors function will suppress any XML errors and will allow us to handle errors from the code itself. The second line tries to load the specified XML using the simplexml_load_file function. If the XML is loaded successfully, it is converted into a SimpleXMLElement object otherwise a false value is returned.
We then check for the return value. If it is false, we use the libxml_get_errors() function to get all the errors in the form of an array. This array contains objects of type LibXMLError. Each of these objects has several properties. In the previous code, we iterated over the errors array and echoed the message property of each object which contains a detailed error message.
If there are no errors in XML, we get a SimpleXMLElement object which has all the XML data loaded in it.
Parameters for simplexml_load_file
More parameters are available for the simplexml_load_file method, which are as follows:
- filename: This is the first parameter that is mandatory. It can be a path to a local XML file or a URL.
- class_name: You can extend the SimpleXMLElement class. In that case, you can specify that class name here and it will return the object of that class. This parameter is optional.
- options: This third parameter allows you to specify libxml parameters for more control over how the XML is handled while loading. This is also optional.
Similar to simplexml_load_file is simplexml_load_string, which also creates a SimpleXMLElement on successful execution. If a valid XML string is passed to it we get a SimpleXMLElement object or a false value otherwise.
$objXML = simplexml_load_string(‘
The above code will return a SimpleXMLElement object with data loaded from the XML string. The second and third parameters of this function are same as that of simplexml_load_file.
Using SimpleXMLElement to create an object
You can also use the constructor of the SimpleXMLElement class to create a new object.
$objXML = new SimpleXMLElement(‘