8 min read

PHP jQuery Cookbook

PHP jQuery Cookbook

Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery

  • 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

Introduction

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:
http://en.wikipedia.org/wiki/XML#Schemas_and_validation

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.




The Adventures of Sherlock Holmes

A Scandal in Bohemia
You see, but you do not observe. The distinction
is clear.



The Red-headed League
It is quite a three pipe problem, and I beg that you
won’t speak to me for fifty minutes.



The Man with the Twisted Lip
It is, of course, a trifle, but there is nothing so
important as trifles.




The Case-book of Sherlock Holmes

The Adventure of the Three Gables
I am not the law, but I represent justice so far as
my feeble powers go.



The Problem of Thor Bridge
We must look for consistency. Where there is a want
of it we must suspect deception.



The Adventure of Shoscombe Old Place
Dogs don’t make mistakes.



The Memoirs of Sherlock Holmes

The Yellow Face
Any truth is better than indefinite doubt.


The Stockbroker’s Clerk
Results without causes are much more impressive.


The Final Problem
If I were assured of your eventual destruction I would,
in the interests of the public, cheerfully accept my
own.




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.

Getting ready

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…

  1. 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.

    libxml_use_internal_errors(true);
    $objXML = simplexml_load_file(‘../common.xml’);

    if (!$objXML)
    {
    $errors = libxml_get_errors();
    foreach($errors as $error)
    {
    echo $error->message,'
    ’;
    }
    }
    else
    {
    foreach($objXML->book as $book)
    {
    echo $book->name.'
    ’;
    }
    }
    ?>

    
    
  2. 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
  3. 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.

There’s more…

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.

simplexml_load_string

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(‘
Myfavourite book
’);


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(‘
Myfavourite book
’);


More info about SimpleXML and libxml

You can read about SimpleXML in more detail on the PHP site at http://php.net/manual/en/book.simplexml.php and about libxml at http://php.net/manual/en/book.libxml.php.


Subscribe to the weekly Packt Hub newsletter

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here