(PHP >= 8.4.0)
DOMXPath::registerPhpFunctionNS — Enregistre une fonction PHP en tant que fonction XPath dans un espace de noms
$namespaceURI, string $name, callable $callable): voidCette méthode permet d'utiliser une fonction PHP en tant que fonction XPath dans les expressions XPath.
namespaceURInamecallableoptions contient une option invalide.
overrideEncoding utilise un encodage inconnu.
Aucune valeur n'est retournée.
Exemple #1 Enregistre une fonction XPath dans un espace de noms et l'appelle depuis l'expression XPath
<?php
$xml = <<<EOB
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
<author>Jane Smith</author>
</book>
<book>
<title>PHP Secrets</title>
<author>Jenny Smythe</author>
</book>
<book>
<title>XML basics</title>
<author>Joe Black</author>
</book>
</books>
EOB;
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
// Enregistre le namespace my: (obligatoire)
$xpath->registerNamespace("my", "urn:my.ns");
// Enregistre les fonctions PHP
$xpath->registerPhpFunctionNS(
'urn:my.ns',
'substring',
fn (array $arg1, int $start, int $length) => substr($arg1[0]->textContent, $start, $length)
);
// Appel de la fonction substr sur le titre du livre
$nodes = $xpath->query('//book[my:substring(title, 0, 3) = "PHP"]');
echo "{$nodes->length} livres trouvés dont le titre commence par 'PHP' :\n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title par $author\n";
}
?>Résultat de l'exemple ci-dessus est similaire à :
2 livres trouvés dont le titre commence par 'PHP' : PHP Basics par Jim Smith PHP Secrets par Jenny Smythe