loo9162 Posted April 5, 2013 Share Posted April 5, 2013 I'm trying to pick out items from an XML file by their titles using Xpath in DOM, but because some have apostrophes, it doesn't work. I've tried replacing the apostrophes using this $query1 = "channel/item[title=$p]/title"; but even that doesn't work. Any advice on how to do this, or alternatives for how to extract elements by their titles in DOM? Here's my code: <?php $q = $_GET["q"];$q = explode('|^', $q);$counts = count($q);unset($q[$counts-1]);$p = stripslashes($q);$q = stripslashes($p);$dom = new DOMDocument;$dom->preserveWhiteSpace = false;$dom->formatOutput = true;$dom->Load("../$userid.xml");$xpath = new DOMXPath($dom);foreach ($q as $r) {$p = preg_replace("/'/","",$r);$query1 = "channel/item[title=$p]/title";$query2 = "channel/item[title=$p]/url";$query3 = "channel/item[title=$p]";$entries = $xpath->query($query1);$entries2 = $xpath->query($query2);$entries3 = $xpath->query($query3);foreach ($entries as $entry) {foreach ($entries2 as $entry2) {foreach ($entries3 as $entry3) {$oldchapter = $entry->parentNode->removeChild($entry);$oldchapter2 = $entry2->parentNode->removeChild($entry2);$oldchapter3 = $entry3->parentNode->removeChild($entry3);$dom->preserveWhiteSpace = false;}}}}$dom->formatOutput = true;$dom->save("../$userid.xml") ?> Basically, my code extracts titles from a URL, separated by "|^" (For example title1|^title2|^title3|^). Because the "|^" is appended to the end of each title, I have to remove the empty value from the array. Then, because the titles with apostrophes come in like "Title\\'s", I have to strip slashes twice to get rid of them. Then I load a new DOMdocument, and find the titles from the URL in my existing XML document. Then I want the code to remove the whole items (titles, urls and the item itself) which have the same titles as the ones in the URL, and then save the document. Quote Link to comment https://forums.phpfreaks.com/topic/276586-apostrophes-in-php-xpath/ Share on other sites More sharing options...
waynew Posted April 5, 2013 Share Posted April 5, 2013 Swap your single quotes and double quotes around and see if it works. Example: Change: $query1 = "channel/item[title='$p']/title"; to $query1 = 'channel/item[title="'.$p.'"]/title'; You can't escape apostrophes in XPath, as far as I'm aware. Properly formed XML shouldn't contain apostrophes, by the way. The following characters should be escaped: " "' '< <> >& & In this case, ' should be used instead of ' Quote Link to comment https://forums.phpfreaks.com/topic/276586-apostrophes-in-php-xpath/#findComment-1423161 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.