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() — Executa uma consulta XPath em dados XML
Descrição
SimpleXMLElement
array xpath
( string $path
)
O método xpath vasculha o nó SimpleXML em busca de nós filhos que fechem com XPath path .
Parâmetros
- path
-
Um caminho XPath
Valor Retornado
Retorna uma array de um objeto SimpleXMLElement ou FALSE em caso de erro.
Exemplos
Exemplo #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";
}
?>
O exemplo acima irá imprimir:
/a/b/c: text /a/b/c: stuff b/c: text b/c: stuff
Note que os dois resultados são iguais.
User Contributed Notes
SimpleXMLElement->xpath()
SimpleXMLElement->xpath()
paul at pmtlogic dot com
18-Jun-2008 04:17
18-Jun-2008 04:17

SimpleXMLElement->registerXPathNamespace()