Posted by: phillipnb | May 7, 2011

PHP and XML – Part 3


In the previous edition of this series about xml, we played with a few examples of xml using the SimpleXML library. In this edition we will work on examples to demonstrate the use of XPath. The name XPath stands for xml path language. As the name suggest it is language that is used for navigating through the nodes, attributes and elements of a xml document. XPath navigates through a xml document using path expressions. The path expression looks very similar to the directory structure of files and folders on our computer. for e.g. if we have a file called index.html in a folder called ‘Web’ on the C drive of our computer (Windows OS), we will write its path as C:\Web\index.html or \home\Web\index.html on a unix system. XPath uses the very same tree structure to access a node in the xml document. I am not going to describe anything more about the XPath syntax, you can read about the XPath syntax here.

To understand the power of XPath, let us play with a few examples. The xml file given below is mybook.xml:

Example:1

<?xml version="1.0" encoding="utf-8"?>
<catalog>
<book code="11">
    <id>1</id>
    <title value="a">One Last Paradise</title>
    <author age="56">George Milton</author>
    <price>9.99</price>
</book>
<book code="111">
    <id>2</id>
    <title value="b">Managing Time and Space</title>
    <author age="34">Kris Ben King</author>
    <price>12.99</price>
</book>
<book code="222">
    <id>3</id>
    <title value="c">Programming in PHP</title>
    <author age="39">Phillip N.B.</author>
    <price>39.99</price>
</book>
$dom = new DomDocument();
$dom->load("mybook.xml");

$xpath  = new DOMXPath($dom);
$result   = $xpath->query("/catalog/book/price");
foreach ($result as $element) {
    echo "\n".$element->nodeValue."\n";
}

The aim of this example is that we want to display the price of all the books in that xml document. To do that, we need to pick all the ‘price’ elements. We use XPath to pick the ‘price’ nodes. To achieve this, we first create an instance of the DomDocument and the load the xml file. We then use the dom handle to this xml document while creating an instance of DomXPath. Using the DomXPath object we navigate through the xml document for a given condition. The condition given here is to start navigating from the root element then its child element called ‘book’ and finally terminate at the ‘price’ node. Once we have gathered all the price elements, we pick one price element at a time and display the node value of that node. The same output can be achieved using a slightly different xpath query like: $xpath->query(“/catalog/book/price/text()”);

Example:2
In this example, we are going to pick the book whose title has an attribute value of ‘b’ (we are not going to write the entire code, we will write only the query part).

$result = $xpath->query("/catalog/book/title[@value='b']");
foreach ($result as $element) {
    echo "\n".$element->nodeValue."\n";
}

Example:3
Suppose we want to pick all the books that cost more than 10 dollars. To extract such books we will write a xpath query with the condition as price greater than 10.

$result = $xpath->query("/catalog/book[price>10]");
foreach ($result as $element) {
    echo "\n".$element->nodeValue."\n";
}

Example:4
In this example we are going to pick those books whose author has an attribute age greater than 40.

$result = $xpath->query("/catalog/book/author[@age>40]");
foreach ($result as $element) {
    echo "\n".$element->nodeValue."\n";
}

Example:5
In this example,we are going to pick the title of those books whose attribute ‘code’ has a value greater than 40.

$result = $xpath->query("/catalog/book[@code>40]/title");
foreach ($result as $element) {
    echo "\n".$element->nodeValue."\n";
}

Example:6
So far we used xpath to search a xml document and display the search results. That is not the only use of xpath. Let us use xpath to edit our xml document. Let us go through an example where we actually remove a node from a xml file. Here is book.xml used for this example:

<?xml version='1.0' encoding='utf-8'?>
<books>
    <book>
        <chapter num='1'>
            <lesson>1</lesson>
            <lesson>2</lesson>
            <lesson>3</lesson>
        </chapter>
        <chapter num='2'>
            <lesson>1</lesson>
        </chapter>
        <chapter num='3'>
            <lesson>1</lesson>
            <lesson>2</lesson>
            <lesson>3</lesson>
            <lesson>4</lesson>
            <lesson>5</lesson>
        </chapter>
    </book>
</books>
$doc = new DOMDocument();
$doc->load('book.xml');

$xpath = new DomXPath($doc);
$chapters = $xpath->query("/books/book/chapter[@num=3]");
foreach($chapters as $chapter) {
   $nodes  = $chapter->childNodes;
   $domRef = dom_import_simplexml($chapter);
   $domRef->parentNode->removeChild($domRef);
}
echo $doc->saveXML();

In this example, we can see that we are using xpath to pick the book whose chapter has an attribute of ‘num’ as 3. Once we have focussed on that node, we will use dom_import_simplexml() to import that node to dom and then use the method removeChild to delete that node.

Example:7
In this example we are going to replace one node with another. We are going to replace ‘chapter’ with attribute ‘num’ equal to 3 with ‘num’ equal to 0 with just zero as the content. We will use the same book.xml and here is the php code for replacing a node.

$doc = new DOMDocument();
$doc->load('book.xml');

$newelement = $doc->createElement("chapter","0");
$newelement->setAttribute('num','0');

$xpath = new DomXPath($doc);
$chapters = $xpath->query("/books/book/chapter[@num=3]");
foreach($chapters as $chapter) {
   $nodes = $chapter->childNodes;
   $domRef = dom_import_simplexml($chapter);
   $domRef->parentNode->replaceChild($newelement,$domRef);
}
echo $doc->saveXML();

By now you must have felt the power of xpath. In fact xml and xpath have been here for a long time and there are plenty of blogs, write-ups and tutorials about them. My aim was to revisit them with examples that are different from others but at the same time exposing the power of php and xml. So, till next time,

It is Happy PHPing.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

Join 25 other followers

%d bloggers like this: