Search code examples
domxpath

DOMXPath - Select only a few items


Let's say we have this html and the following DOMXPath code:

<div>
    <div>
        <p>1</p>
    </div>
    <div>
        <p>2</p>
    </div>
    <div>
        <p>3</p>
    </div>
    <div>
        <p>4</p>
    </div>
    <div>
        <p>5</p>
    </div>
    <div>
        <p>6</p>
    </div>
</div>

$doc = new DOMDocument();
$doc->loadHtml($strhtml);
$doc->preserveWhiteSpace = false;

$xpath = new DOMXPath( $doc );

$nodelist = $xpath->query('//div/div[2]/p');

foreach( $nodelist as $node ) {
    $result = $node->nodeValue."\n";
}

echo $result;

Obviously, $result = '2', since we asked for the value of 'p' from the second 'div' node.

Now, how can I get the values for, say, from 'div[2]' to 'div[4]' and sum them?

To be precise, I would like to know how to get "from # to #" and also how to get "this #, that #, also # and #". So two questions, for two different problems.

Thanks in advance.


Solution

  • You are able to select range of elements with DOMXPath:

    • as for the first problem to get "from # to #" use the following approach:

      // select nodes within specified range of positions
      $nodelist = $xpath->query('//div/div[position()>1 and position()<5]');
      
    • as for the second problem to get "this #, that #, also # and #" try the following (with | union operator):

      // extracts the 2nd, 4th and 6th elements respectively
      $nodelist = $xpath->query('//div/div[2] | //div/div[4] | //div/div[6]);