eval.in

Paste #4899

PHP — PHP 5.4.6, pasted 1 year ago

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php

$xml = <<<XML
<root>
<a class="title">Title One</a>
<a class="item">Item One</a>
<a class="item">Item Two</a>

<a class="title">Title Two</a>
<a class="item">Item Three</a>
<a class="item">Item Four</a>  
</root>
XML;

$doc = new DOMDocument;
$doc->loadXML($xml);
$xp = new DOMXPath($doc);

echo "Single Query:\n";
$query = '
    //a[@class="title"][1]
        /following-sibling::a
        [
          @class="item" 
          and preceding-sibling::a[@class="title"][1] 
              = //a[@class="title"][1]
        ]';
foreach($xp->query($query) as $item)
{
    echo " * ", $item->nodeValue, "\n";
}
echo "\nFull List:\n";
  
$titles = $xp->query('//a[@class="title"]');
foreach ($titles as $title)
{
    echo $title->nodeValue, ":\n";
    $query = './following-sibling::a[@class="item" and 
              preceding-sibling::a[@class="title"][1] = ' .
              $title->getNodePath() . ']';
    foreach ($xp->query($query, $title) as $item)
    {
        echo ' * ', $item->nodeValue, "\n";
    }    
}

Program Output

Single Query:
 * Item One
 * Item Two

Full List:
Title One:
 * Item One
 * Item Two
Title Two:
 * Item Three
 * Item Four

OK (0.004 sec real, 0.005 sec wall, 13 MB, 68 syscalls)

Fork