xref: /PHP-8.2/ext/dom/tests/domxpath.phpt (revision bd9f4fa6)
1--TEST--
2DOMXPath Tests
3--EXTENSIONS--
4dom
5--FILE--
6<?php
7require_once("dom_test.inc");
8
9function MyAverage($nodelist) {
10    $count = 0;
11    $val = 0;
12    foreach ($nodelist AS $node) {
13        $count++;
14        $val += $node->textContent;
15    }
16    if ($val > 0) {
17        return $val/$count;
18    } else {
19        return 0;
20    }
21}
22
23$dom = new DOMDocument;
24$dom->loadXML('<root xmlns="urn::default"><child>myval</child></root>');
25
26$xpath = new DOMXPath($dom);
27
28$xpath->registerPHPFunctions('MyAverage');
29$xpath->registerNamespace("php", "http://php.net/xpath");
30
31$xpath->registerNamespace("def", "urn::default");
32$nodelist = $xpath->query("//def:child");
33if ($node = $nodelist->item(0)) {
34    print $node->textContent."\n";
35}
36
37$count = $xpath->evaluate("count(//def:child)");
38
39var_dump($count);
40
41$xpathdoc = $xpath->document;
42
43var_dump($xpathdoc instanceof DOMDocument);
44
45$root = $dom->documentElement;
46$root->appendChild($dom->createElementNS("urn::default", "testnode", 3));
47$root->appendChild($dom->createElementNS("urn::default", "testnode", 4));
48$root->appendChild($dom->createElementNS("urn::default", "testnode", 4));
49$root->appendChild($dom->createElementNS("urn::default", "testnode", 5));
50
51$avg = $xpath->evaluate('number(php:function("MyAverage", //def:testnode))');
52var_dump($avg);
53
54try {
55    $xpath->registerPHPFunctions('non_existent');
56    $avg = $xpath->evaluate('number(php:function("non_existent", //def:testnode))');
57} catch (\Error $e) {
58    echo $e->getMessage() . \PHP_EOL;
59}
60try {
61    $xpath->registerPhpFunctions(['non_existant']);
62    $avg = $xpath->evaluate('number(php:function("non_existent", //def:testnode))');
63} catch (\Error $e) {
64    echo $e->getMessage() . \PHP_EOL;
65}
66?>
67--EXPECT--
68myval
69float(1)
70bool(true)
71float(4)
72Unable to call handler non_existent()
73Unable to call handler non_existent()
74