views:

23

answers:

2

In my PHP script, I'm using XPATH to search nodes for text. Everything works swimmingly -except - when I search for a word with an apostrophe.

basically my code looks like this

$keyword = $_GET['keyword'];
...snip...
$xml = simplexml_load_file($data);


 $search = strtolower($keyword);
 $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 $lower = "abcdefghijklmnopqrstuvwxyz";

$nodes = $xml-xpath("//line[contains(translate(text(),'$upper','$lower'),'$search')]");

again, all the above code works great - I can search for strings inside nodes and I get the correct matches back.

However, if a node looks like this: <line number="23">Shall I compare thee to a summer's day?</line>

and I search for summer's day...I get errors on the above $nodes line. What's more, if I search for "...summers" (no apos) the above line does not match. The only way to get the above line to return would be a search for "...summer" - which would include summer's.

I've tried stripslashes, addslashes, tohellwithslashes, htmlspecialchars but nothing works. Also, According to Google, in XPATH 1.0 (which I'm forced to use since this is PHP) I will NEVER be able to escape an apostrophe. Seriously?

So I turn to the geniuses here, someone MUST have had to deal with an XML file that they needed to traverse with XPATH in PHP that had an apostraphe! If XPATH can't do this, what can I do in PHP to get XPATH to return this node?

+1  A: 

As Google shared with you, you cannot escape an apostrophe in XPath. The simplest workaround is to use a different quote character around the string parts of the query.

$nodes = $xml->xpath('//line[contains(translate(text(),"'.$upper.'","'.$lower.'"),"'.$search.'")]');

Of course, the above is only useful if you don't want to allow double-quotes in the search value. If that might be necessary, then you could move the searching/comparison into PHP-land using the method that Gordon pointed out in your previous question.

salathe
@salathe - thank you (again). One tiny typo in your code (should you wish to edit it for others' befefit) is `xml-xpath` should be `xml->xpath` (you forgot the > ). Also, in my case I needed to change one other thing to get the apostrophe to be recognized. From my above posted code I changed `$search = strtolower($keyword);` to `$search = stripslashes(strtolower($keyword)); otherwise entering `summer's` actually becomes `summer\'s`. Hopefully I didn't botch anything else up in doing this! thanks a million.
dijon
A: 

Hi dijon,

(which I'm forced to use since this is PHP)

perhaps http://basex.org/api might be worth a look/try. It allows you to use XQuery/XPath and communicates either via REST or sockets. Apart from that I'd recommend salathes solutions.

michael
This looks very cool, I have been reading about XQuery and wish I could use it, however, in my situation I am using a shared hosting platform and cannot install things like this.
dijon