xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.
xml snippet:
<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>
The following code does not work:
<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");
foreach ( $result[0]->attributes() as $key => $val ) {
print "<div class='coords'>$key: $val</div>\n";
}
?>
I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.
In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:
<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
SimpleXMLElement::xpath
(PHP 5 >= 5.2.0)
SimpleXMLElement::xpath — Runs XPath query on XML data
Description
SimpleXMLElement
array xpath
( string $path
)
The xpath method searches the SimpleXML node for children matching the XPath path .
Parameters
- path
-
An XPath path
Return Values
Returns an array of SimpleXMLElement objects or FALSE in case of an error.
Examples
Example #1 Xpath
<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');
while(list( , $node) = each($result)) {
echo '/a/b/c: ',$node,"\n";
}
/* Relative paths also work... */
$result = $xml->xpath('b/c');
while(list( , $node) = each($result)) {
echo 'b/c: ',$node,"\n";
}
?>
The above example will output:
/a/b/c: text /a/b/c: stuff b/c: text b/c: stuff
Notice that the two results are equal.
SimpleXMLElement::xpath
paul at pmtlogic dot com
18-Jun-2008 09:17
18-Jun-2008 09:17
