SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpathEjecuta una consulta XPath sobre datos XML

Descripción

public SimpleXMLElement::xpath(string $expression): array|null|false

El método xpath busca en el nodo SimpleXML hijos que correspondan al expression Xpath.

Parámetros

expression

Una ruta XPath

Valores devueltos

Devuelve un array de objetos SimpleXMLElement en caso de éxito o null o false si ocurre un error.

Ejemplos

Ejemplo #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);

/* Se busca <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach (
$result as $node) {
echo
'/a/b/c: ',$node,"\n";
}

/* Las rutas relativas también funcionan... */
$result = $xml->xpath('b/c');

foreach (
$result as $node) {
echo
'b/c: ',$node,"\n";
}
?>

El resultado del ejemplo sería:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Observe que los dos resultados son iguales.

Ver también