tags:

views:

827

answers:

2

I am loading HTML into DOM and then querying it using XPath in PHP. My current problem is how do I find out how many matches have been made, and once that is ascertained, how do I access them?

I currently have this dirty solution:

$i = 0;
foreach($nodes as $node) {
echo $dom->savexml($nodes->item($i));
$i++; }

Is there a cleaner solution to find the number of nodes, I have tried count(), but that does not work.

+4  A: 

You haven't posted any code related to $nodes so I assume you are using DOMXPath and query(), or at the very least, you have a DOMNodeList.
DOMXPath::query() returns a DOMNodeList, which has a length member. You can access it via (given your code):

$nodes->length
Nick Presta
What a plum, it took me so long to investigate other elements of the DOMXPath and Query, that I failed to see if there was something like this. Thank you very much for your answer :)
esryl
A: 

If you just want to know the count, you can also use DOMXPath::evaluate.

Example from PHP Manual:

$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';
$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";
Gordon