Share your knowledge and create a knowledgebase.
Every website has ‘em. Forms. Places for users to enter data into your website. Whether it be a search box, a “Contact Us” form, or variables in the website address, at some point in the flow of your script these suckers are going to touch your database. Oh, that’s no problem — We’ll just take what they type in and run a query in MySQL on it!
WHOA, there! Are you sure you want to do that? Any input from a user should be treated like a nuclear fuel rod. You can handle it, but you’ve got to make sure you do it right. You wouldn’t just pick it up with your bare hands, would you?
Why? Just what are MySQL Injection attacks anyway?
Lets say your database has a table inside called ‘tbl_Users’. Inside ‘tbl_Users’ are a list of your users, which all have usernames, passwords, first names, last names, addresses, etc. If these users are presented with a login box somewhere on your site, your php user verification query might be something like this:
SELECT * FROM `tbl_Users` WHERE `username`=’”.$_POST['username'].”‘ AND `password`=’”.md5($_POST['password']).”‘”The problem is that unscrupulous users (read: bad ones) could enter this into your form:
username: no_onepassword: ‘ OR ”=”Which would make your query look something like this:
SELECT * FROM `tbl_Users` WHERE `username`=’no_one’ AND `password`=” OR ”=”Which, if you read that correctly, would allow that user access to whatever it was you wanted hidden by logging them in. There are a multitude of other ways this can be dangerous, but this is by far the easiest example. Even more unscrupulous users (read: the real jackasses) could send in multiple queries including DELETE queries.
In which case, when you wake up the morning after the attack you are most likely to be heard saying:”Hey, where did all my users go?”
Wow. Okay so I’ve got a friend… and his website isn’t secure. What can I do to help him out?
The good news is that with a few easy precautions, your “friend’s” website will be pretty secure against these types of attacks. I say pretty secure because there is no way to prevent every attack. We can only do our best to increase security to a point to take every realistic precaution to prevent these attacks.
#1: Escape your variables!
Using the php function ‘mysql_real_escape_string’ you can “escape” the single quote character from user input. This is probably the easiest method to prevent MySQL injection attacks. It works by adding a backslash (”\”) before each quote that the user enters into their input. So, to use our example from before:
username: hey’therebecomes
username: hey\’thereThis effectively stops MySQL injection in its tracks since it not only escapes the single quote (”‘”) character but also all other characters that the baddies can use to hijack your queries.
If you’ve got an array of data coming in, you can use this neat function that I found on the PHP mysql_real_escape_string page (code by “brian dot folts at gmail dot com”). It escapes all of the values in your array with ease.
To escape an array, use this function:
function mysql_real_escape_array($t){
return array_map(”mysql_real_escape_string”,$t);
}
Then you can call that function easily by passing your array to it:
$your_array = mysql_real_escape_array($your_array);
#2: Check the variable type of your input.
This is done by using the php functions “is_numeric()“, “is_string()“, “is_float()“, and “is_int()” to determine if the input the user is sending in is the same type that you were asking for. It’s not perfect, but if you were asking for a number and they sent in a word you know to discard it straight away and return an error thereby entirely avoiding any change of a MySQL injection attack.
#3: Always use proper MySQL syntax, including “`” and “‘” characters.
If your queries look something like this:
SELECT * FROM tbl_Users WHERE username=$value; Rewrite it so that it looks more like this:
$value = mysql_real_escape_string($value);mysql_query(SELECT * FROM `tbl_Users` WHERE `username`=’”.$value.”‘”); Proper MySQL syntax requires that all table and field names are surrounded by the reverse apostraphe (”`”) and values surrounded with single quotes / apostraphe (”‘”).
I hope this gives you a better indication of what you can do to help secure your websites. Keep in mind that this is in no way a complete list. Be ever vigilant in your efforts to prevent attacks of any kind on your code. Leave a comment or two if this helped you at all or if you have different suggestions on how to secure your code from injection attacks!
PHP comes with an extensive catalog of date and time functions, all designed to let you easily retrieve temporal information, massage it into a format you require, and either use it in a calculation or display it to the user. However, if you’d like to do something more complicated, things get much, much hairier.
A simple example of this involves displaying the time on a Web page. With PHP, you can easily use the date() function to read the server’s clock and display the required information in a specific format. But what if you’d like to display the time in a different location - for example, if your company is located in a different country from your server and you want to see “home” time instead of local time? Well, then you have to figure out the difference between the two places and perform some date arithmetic to adjust for the different time zones. If the time difference is significant, you need to take account of whether the new time is on the day before or after, worry about daylight savings time, and keep track of end-of-the-month and leap year constraints.
As you can imagine, the math to perform such time zone conversions can quickly get very complicated if you do it manually. To be fair, PHP has built-in time zone functions to help with this, but these aren’t particularly intuitive and require a fair amount of time to get used to. A quicker alternative is to use the PEAR Date class, which comes with built-in support for time zones and is, by far, the simplest way to perform these conversions.
This tutorial will teach you how to convert temporal values between time zones with the PEAR Date class. It assumes that you have a working Apache and PHP installation and that the PEAR Date class has been correctly installed.
Note: You can install the PEAR Date package directly from the Web, either by downloading it or by using the instructions provided.
Let’s begin with the basics - initialising and using a Date object. Create a PHP script with the following lines of code:
<?php // include class include ("Date.php"); // initialize object $d = new Date("2006-06-21 15:45:27"); // retrieve date echo $d->getDate(); ?> |
This is fairly simple - include the class code, initialise a Date() object with a date/time string, and then use the getDate() method to display the value you just inserted. Here’s the output:
2006-06-21 15:45:27
What if you want the date in a different format? If the format is a standard one, such as the ISO format, simply pass getDate() a modifier indicating this:
<?php // include class include ("Date.php"); // initialize object $d = new Date("2006-06-21 15:45:27"); // retrieve date as timestamp echo $d->getDate(DATE_FORMAT_ISO_BASIC); ?> |
The output in this case conforms to the standard ISO format.
20060621T154527Z
If you’d like a custom format, you can do that too, with the format() method. Like PHP’s native date() function, this method accepts a series of format specifiers that indicate how each component of the date is to be formatted. Below is an example (look in the class documentation for a complete list of modifiers):
<?php // include class include ("Date.php"); // initialize object $d = new Date("2006-06-21 15:45:27"); // retrieve date as formatted string echo $d->format("%A, %d %B %Y %T"); ?> |
And here’s the output:
Wednesday, 21 June 2006 15:45:27
Converting between time zones
Now that you’ve got the basics, let’s talk about time zones. Once you have a Date() object initialised, converting from one time zone to another is a simple two-step process:
1. Tell the Date class which time zone you’re converting from, with the setTZByID() method.
2. Then, tell the Date class which time zone you wish to convert to, with the convertTZByID() method.
<?php // include class include ("Date.php"); // initialize object $d = new Date("2006-06-21 10:36:27"); // set local time zone $d->setTZByID("GMT"); // convert to foreign time zone $d->convertTZByID("IST"); // retrieve converted date/time echo $d->format("%A, %d %B %Y %T"); ?> |
In this case, I’m attempting to convert from Greenwich Mean Time (GMT) to Indian Standard Time (IST). India is about 5.5 hours ahead of Greenwich, which is why the output of the script is:
Wednesday, 21 June 2006 16:06:27
Simple, isn’t it? Here’s another example, this one demonstrating how the class handles leap years and month end values.
<?php> // include class include ("Date.php"); // initialize object $d = new Date("2008-03-01 06:36:27"); // set local time zone $d->setTZByID("GMT"); // print local time echo "Local time is " . $d->format("%A, %d %B %Y %T") . "\n"; // convert to foreign time zone $d->convertTZByID("PST"); // retrieve converted date/time echo "Destination time is " . $d->format("%A, %d %B %Y %T"); ?> |
And the output is:
Local time is Saturday, 01 March 2008 06:36:27
Destination time is Friday, 29 February 2008 22:36:27
Note: In case you’re wondering where the time zone IDs come from, you can find a complete list within the class documentation.
Calculating GMT offsets
Another piece of information that’s sometimes useful when working with time zones is the GMT offset — that is, the difference between the specified time zone and standard GMT. The PEAR Date class lets you get this information easily, via its getRawOffset() method. Here’s an example:
<?php // include class include ("Date.php"); // initialize object $d = new Date("2006-06-21 10:36:27"); // set local time zone $d->setTZByID("PST"); // get raw offset from GMT, in msec echo $d->tz->getRawOffset(); ?> |
Here, the getRawOffset() method calculates the time difference between the local time and GMT. Here’s the output:
-28800000
Note that this offset value is expressed in milliseconds, so you will need to divide it by 3600000 (the number of milliseconds in one hour) to calculate the time zone difference in hours.
Tip: You can use the inDaylightTime() method to see if the destination is currently observing daylight savings time. Look in the class documentation for details on this method.
Adding and subtracting timespans
The Date class also lets you perform sophisticated date arithmetic on temporal values, adding or subtracting durations to a date/time value. These durations (or timespans) are expressed as a string containing day, hour, minute and/or second components.
<?php // include class include ("Date.php"); // initialize object $d = new Date("2006-06-21 15:45:27"); // add 01:20 to it $d->addSpan(new Date_Span("0,1,20,0")); // retrieve date as formatted string echo $d->format("%A, %d %B %Y %T"); ?> |
In this case, I’ve added an hour and twenty minutes to the initial timestamp, by calling the Date class’ addSpan() method and supplying it with a Date_Span() object initialised to that duration. The output is fairly easy to guess:
Wednesday, 21 June 2006 17:05:27
Just as you can add timespans, so too can you subtract them. That, in fact, is the purpose of the subtractSpan() method, which is illustrated below.
<?php // include class include ("Date.php"); // initialize object $d = new Date("2006-06-21 15:45:27"); // add 01:20 to it $d->addSpan(new Date_Span("0,1,20,0")); // subtract 00:05 from it $d->subtractSpan(new Date_Span("0,0,5,0")); // retrieve date as formatted string echo $d->format("%A, %d %B %Y %T"); ?> |
Here, I’ve first added an hour and twenty minutes, and then subtracted a further five minutes. The net effect is an addition of an hour and fifteen minutes, and the output reflects this:
Wednesday, 21 June 2006 17:00:27
As the examples above illustrate, the PEAR Date class provides methods to intuitively and efficiently perform fairly complex date math. If you’re looking for a stress-free way to convert timestamps between different locations, I’d heartily recommend it to you.
When working with XML-based applications, developers often find themselves facing the requirement to generate XML-encoded data structures on the fly. Examples of this include an XML order template based on user input in a Web form, or an XML representation of a server request or client response based on run-time parameters.
Although this task might seem intimidating, it’s actually quite simple when one takes into account PHP’s sophisticated DOM API for dynamic node construction and manipulation. Over the course of this article, I’ll be introducing you to the main functions in this API, showing you how to programmatically generate a complete well-formed XML document from scratch and save it to disk.
Note: This article assumes a working Apache/PHP5 installation with the DOM functions enabled, and a working knowledge of basic XML constructs such as elements, attributes and CDATA blocks. You can obtain an introduction to these topics from the introductory material at Melonfire (http://melonfire.com/community/columns/trog/article.php?id=78 and http://melonfire.com/community/columns/trog/article.php?id=79)
Creating the Doctype declaration
Let’s start right at the top, with the XML declaration. In PHP, this is fairly simple; it only requires you to instantiate an object of the DOMDocument class and supply it with a version number. To see it in action type out the example script in Listing A.
Listing A
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // save and display tree echo $dom->saveXML(); ?> |
Notice the saveXML() method of the DOMDocument object — I’ll come back to this later, but for the moment simply realise that this is the method used to output a current snapshot of the XML tree, either to a file or to the browser. In this case, I’ve sent the output directly to the browser as ASCII text for readability purposes; in real-world applications, you would probably send this with a Content-Type: text/xml header.
When you view the output in your browser, you should see something like this:
<?xml version="1.0"?> |
Adding elements and text nodes
Now that’s all very pretty and fine, but the real power of XML comes from its elements and the content they enclose. Fortunately, once you’ve got the basic DOMDocument initialised, this becomes extremely simple. There are two steps to the process:
1. For each element or text node you wish to add, call the DOMDocument object’s createElement() or createTextNode() method with the element name or text content. This will result in the creation of a new object corresponding to the element or text node.
2. Append the element or text node to a parent node in the XML tree by calling that node’s appendChild() method and passing it the object produced in the previous step.
An example will make this clearer. Consider the script in Listing B.
Listing B
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // save and display tree echo $dom->saveXML(); ?> |
Here, I’ve first created a root element named
<?xml version="1.0"?> <toppings> <item>pepperoni</item> </toppings> |
If you’d like to add another topping, simply create another
Listing C
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create another text node $text = $dom->createTextNode("tomato"); $item->appendChild($text); // save and display tree echo $dom->saveXML(); ?> |
And here’s the revised output:
<?xml version="1.0"?> <toppings> <item>pepperoni</item> <item>tomato</item> </toppings> |
Adding attributes
You can also add qualifying information to your elements, through the thoughtful use of attributes. With the PHP DOM API, attributes are added in a two-step process: first create an attribute node holding the name of the attribute with the DOMDocument object’s createAttribute() method, and then append a text node to it holding the attribute value. Listing D is an example.
Listing D
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create attribute node $price = $dom->createAttribute("price"); $item->appendChild($price); // create attribute value node $priceValue = $dom->createTextNode("4"); $price->appendChild($priceValue); // save and display tree echo $dom->saveXML(); ?> |
And here’s what the output will look like:
<?xml version="1.0"?> <toppings> <item price="4">pepperoni</item> </toppings> |
Adding CDATA blocks and processing instructions
While not used quite as often, CDATA blocks and processing instructions (PI) are also well-supported by the PHP API, through the DOMDocument object’s createCDATASection() and createProcessingInstruction() methods. Listing E shows you an example.
Listing E
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create attribute node $price = $dom->createAttribute("price"); $item->appendChild($price); // create attribute value node $priceValue = $dom->createTextNode("4"); $price->appendChild($priceValue); // create CDATA section $cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n"); $root->appendChild($cdata); // create PI $pi = $dom->createProcessingInstruction("pizza", "bake()"); $root->appendChild($pi); // save and display tree echo $dom->saveXML(); ?> |
And here’s the output:
<?xml version="1.0"?> <toppings> <item price="4">pepperoni</item> <![CDATA[ Customer requests that pizza be sliced into 16 square pieces ]]> <?pizza bake()?> </toppings> |
Saving the results
Once you’ve got the tree the way you want it, you can either save it to a file or store it in a PHP variable. The former function is performed by calling the save() method with a file name, while the latter is performed by calling the saveXML() method and assigning the result to a string. Here’s an example (Listing F).
Listing F
<?php // create doctype $dom = new DOMDocument("1.0"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); $dom->formatOutput=true; // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create attribute node $price = $dom->createAttribute("price"); $item->appendChild($price); // create attribute value node $priceValue = $dom->createTextNode("4"); $price->appendChild($priceValue); // create CDATA section $cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n"); $root->appendChild($cdata); // create PI $pi = $dom->createProcessingInstruction("pizza", "bake()"); $root->appendChild($pi); // save tree to file $dom->save("order.xml"); // save tree to string $order = $dom->save("order.xml"); ?> |
And that’s about it. Hopefully you found this article interesting, and will be able to use these techniques in your daily work with XML. Happy coding!
Most PHP Web developers have heard of PEAR, the PHP Extension and Application Repository, but very few of them actually use it on a regular basis. Here are 10 reasons to get started today.
Most PHP Web developers have heard of PEAR, the PHP Extension and Application Repository, but very few of them actually use it on a regular basis. This is an oversight that should be corrected, because PEAR is actually a rich treasure trove of PHP widgets that can significantly simplify the average Web developer’s workday.
If you think I’m overstating the benefits, ask yourself if you’ve ever written custom code to (a) create HTML e-mail, (b) generate Web forms on the fly, or (c) validate email addresses. PEAR has pre-built PHP packages for all these tasks, and a few hundred more besides. These packages provide a robust, well-tested code base that can save you the time and effort you would otherwise spend on “rolling your own” code. You can’t beat the price either…they’re free!
PEAR classes cover a wide range of tasks, and so this document will focus specifically on classes of interest to developers working with Web pages and form input. If there are other categories you’d like to see addressed, send in your suggestions and we will examine those areas too…and until then, here’s to easier coding!
Note: You can install PEAR packages directly from the Web, by following the provided instructions.
Package Name: Validate
Description: This package provides validation routines for common input types: email addresses, credit card numbers, URLs, dates and times, string and number classes, and more.
Use this package to test user input entered in Web forms and ensure it is valid before using it in a calculation/saving it to a file or database.
URL: http://pear.php.net/package/Validate
Calendar
This package creates calendar data structures for one or more months. These data structures can then be combined with HTML formatting or a template to create a calendar display, complete with forward/backward navigation links.
Use this package to quickly integrate a pop-up Web calendar into a Web site.
http://pear.php.net/package/Calendar
Mail_Mime
This package provides routines to create a MIME-compliant multi-part message. Such a message can contain embedded HTML, images, file attachments, or other parts. The package also provides functions to decode received multi-part messages into their constituent parts.
Use this package to create HTML email with embedded images, or messages with one or more attachments. You can also use this class to decode multi-part messages - for example, as an attachment browser in a Web mail client.
http://pear.php.net/package/Mail_Mime
Cache
This package provides a simple caching framework for a Web site. It allows you to cache the output of PHP scripts as well as function calls, and reduce response times by rendering the cached pages to clients. Cached pages may be stored as files on disk, in a database, or using a custom storage engine.
If your site receives a lot of traffic, use this package to reduce server load and page processing time by occasionally providing clients with snapshots from the page cache instead of the “live” page. You can also reduce the load on your database server by caching the output of frequently-used SQL queries.
http://pear.php.net/package/Cache
Image_Graph
This package makes it possible to automatically convert numerical data into a graph suitable for display on a Web page. Bar, graph, pie, radar and scatter graphs are just some of the supported graph types. X and Y axis customisations are supported, as are many different output formats.
Use this package to display numerical data in a visual manner for easier comprehension - for example, when calculating Web site traffic or ad clicks.
http://pear.php.net/package/Image_Graph
HTML_QuickForm
This package provides routines to generate, validate, and process Web forms programmatically. It supports all the HTML form input types, and comes with built-in validation routines for most common input types. It also provides built-in functionality for multi-page forms and file upload forms.
Use this package to significantly simplify the task of generating Web forms at run-time, or to efficiently validate and process form input.
http://pear.php.net/package/HTML_QuickForm
Auth
This package provides a framework for a basic login/authentication system using PHP. It can verify user credentials against a variety of data sources, including MySQL databases, ASCII files, LDAP servers and POP3 servers.
Use this package to quickly create a login system for a Web application. Because it has “out of the box” support for so many authentication sources, it can also be used to implement Web-based “single login” infrastructure.
http://pear.php.net/package/Auth
XML_RSS
This package is designed to parse RSS documents. It extracts information from an RSS feed as PHP data structures, which can be processed and formatted for display.
Use this package to integrate RSS feeds from other sites into your Web pages.
http://pear.php.net/package/XML_RSS
HTML_Progress
This package provides a framework for a progress bar on a Web site. It uses PHP, JavaScript and CSS to display and dynamically update a progress bar with visual notification of a task’s progress.
Use this package to display progress bars for time-consuming Web tasks — for example a file upload or a long-running loop.
http://pear.php.net/package/HTML_Progress
Translation
This package provides a framework for multi-lingual Web sites. It contains routines to retrieve a translation for each string value from a database and insert it into the appropriate location on each translation-enabled page.
Use this package to efficiently handle multi-language versions of a Web site.
http://pear.php.net/package/Translation/
XPath is a language that allows you to address parts of an XML document, making XSLT transformations practically necessary. It also makes it an invaluable tool for managing XML data in applications such as Web applications.
Microsoft provides XPath functionality through the selectSingleNode() and selectNodes() methods on DOM nodes and documents. However, PHP uses functions that provide XPath functionality through contexts. In the following example, I’ll show sample XML data and PHP code to grab different parts of the XML document. I’ll also explain how the PHP code works.
In the example code, I use the following XML data to provide the functionality. (Note: This code was developed and run successfully using PHP 4.3.4, Windows XP, and IIS 5.1.)
<?xml version="1.0"?> <x:root xmlns:x="http://www.someplace.com"> <x:row> <x:dog color="yellow">Marmaduke</x:dog> <x:cat>Garfield</x:cat> </x:row> <x:row> <x:dog color="white">Snoopy</x:dog> <x:cat>Heathcliff</x:cat> </x:row> <x:row> <x:dog color="gray">Spike</x:dog> <x:cat>Sylvester</x:cat> </x:row> </x:root> |
This XML data contains a few elements and some attributes including a namespace declaration — some basic XML. This results in varied queries for me to test.
<?php $sxml = '<?xml version="1.0"?> <x:root xmlns:x="http://www.someplace.com"> <x:row> <x:dog color="yellow">Marmaduke</x:dog> <x:cat>Garfield</x:cat> </x:row> <x:row> <x:dog color="white">Snoopy</x:dog> <x:cat>Heathcliff</x:cat> </x:row> <x:row> <x:dog color="gray">Spike</x:dog> <x:cat>Sylvester</x:cat> </x:row> </x:root>'; $xml = domxml_open_mem($sxml); $xpc = xpath_new_context($xml); xpath_register_ns($xpc, "x", "http://www.someplace.com"); $nodes = xpath_eval($xpc, "//x:row/x:dog[@color='yellow']/text()"); foreach ($nodes->nodeset as $node) { print $node->content . "\n"; } $nodes = xpath_eval($xpc, "//x:row/x:dog"); foreach ($nodes->nodeset as $node) { print $xml->dump_node($node) . "\n"; } $nodes = xpath_eval($xpc, "//x:cat/child::text()|//x:dog[@color='white' or @color='gray']/text()"); foreach ($nodes->nodeset as $node) { print $node->content . "\n"; } $xml->free(); ?> |
First, I create a local variable to hold the XML string. This information could have been passed in as part of a POST HTTP request. However, for this example, I’m going to include it in the code. The next step is to create a DOM Document by using the domxml_open_mem() function. This function creates a DOM Document object in memory from a valid XML string. It accepts one parameter: the XML string. Another way to accomplish this is to store the XML in a separate file and use the domxml_open_file() function to load the XML from a file. This function takes one parameter: the filename of the XML file.
Once I create the DOM Document object, I can create an XPath context with this object through the xpath_new_context() function, which takes one parameter: the current DOM Document object. This context is used to evaluate the XPath expression and is also used to register namespaces, if needed. Since my XML includes a namespace, I register the namespace with the xpath_register_ns() function. This makes it possible to create XPath queries using prefixes. The xpath_register_ns() function takes three parameters: the XPath context, the prefix, and the namespace, respectively.
Now I can run XPath queries. This is done with the xpath_eval() function, whose first parameter is the XPath context and second parameter is the XPath expression. The function returns an array of DOM Nodes. In my code, I step through the nodeset and produce some form of output.
In the first XPath example, I grab all the x:dog text elements under the x:row nodes, where the ‘color’ attribute equals ‘yellow’. This is where the XPath expression in PHP differs slightly from an XPath expression using MSXML. I include the ‘/text()’ part of the expression to return the text nodes only. With MSXML, you access the text node with the ‘text’ property. Using the ‘content’ property on the returned text node, I can get the content of the text node.
In the second example, I grab all the x:dog elements under the x:row nodes. However, I use the dump_node() method on the DOM Document object to print out the complete XML of the appropriate node. The dump_node() method accepts one parameter: the DOM Node of which you wish to dump the contents.
In the last example, I grab all the x:cat text nodes and all the x:dog text nodes where the ‘color’ attribute is ‘white’ or ‘gray’. Once again, I step through the nodeset and print out the content of each text node. Finally, I free up the DOM Document object.