12

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.

2 Answers 2

28

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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"; 

Comments