SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpathExécute une requête Xpath sur des données XML

Description

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

La méthode xpath cherche dans le nœud SimpleXML des enfants qui correspondent au expression Xpath.

Liste de paramètres

expression

Un chemin XPath

Valeurs de retour

Retourne un tableau d'objets SimpleXMLElement en cas de succès ou null ou false si une erreur survient.

Exemples

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

/* On cherche <a><b><c> */
$result $xml->xpath('/a/b/c');

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

/* Les chemins relatifs fonctionnent aussi... */
$result $xml->xpath('b/c');

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

L'exemple ci-dessus va afficher :

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

Notez que les deux résultats sont égaux.

Voir aussi