Problems with XPath in PHP 5

Album Cover: Plans

"And it came to me then that every plan is a tiny prayer to Father Time."
Death Cab / What Sarah Said

Posted on April 22, 2004 6:38 PM in XML
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

I finally got PHP 5 up and running on my Windows machine last night. It wasn't easy, but at least I got it working, which is more than I can say about my last attempt. For some reason whenever I would start up Apache the application would crash. After a bunch of trial and error testing, I eventually came to the conclusion that it had something to do with specifying a doc_root in my php.ini file. All is well that ends well, though, I suppose.

The bad news (there's always bad news when it comes to computers) is that I can't get XPath to work for the life of me. XPath is the sole reason I installed PHP 5 and Apache in the first place, so I'm slightly bummed to say the least. I tried using the sample code from Zend with several XPath queries against my Atom XML feed. The only one that did anything was $titles = $xp->query("*");, which essentially printed out all the nodes in the document.

After several attempts in vain, I scrolled down to the user comments and noticed XPath doesnt seem to work. In a self-reply to that comment, I found a "solution" that I modified to fit my needs as follows:

$xml = simplexml_load_file("atom.xml");
$items = $xml->xpath("/feed/entry");
foreach($items as $item) {
 print $item->title . "<br />";

That didn't work either, though, as it returned Warning: Invalid argument supplied for foreach() in sample.php on line 4.

So, next I went directly to the source to find out exactly what the xpath method does and how it is used. This led me to trying:

$xml = simplexml_load_file("atom.xml");
$result = $xml->xpath("/feed/entry/title");
while(list( , $node) = each($result)) {
 print($node."<br />");

Which, in turn, returned Warning: Variable passed to each() is not an array or object in sample.php on line 4. It should be noted here again, though, if I use a * as the XPath query, I get some results (although somewhat strange) back.

So what did I try next? Nothing. I'm giving up. I'll either wait for some more real-life examples to come out or I'll wait until I gather up enough patience to give it another go. At least next time I won't have to worry about setting up PHP 5 and's all sitting there ready to go.

I may, however, play around with libxml2 (which PHP 5 apparently uses for its XML handling) and C++, but that is another story for another day...


No one has added any comments.

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.


Email Address:



Check this box if you hate spam.