Finding number of nodes in PHP, DOM, XPath

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

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


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):


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

Example from PHP Manual:

$doc = new DOMDocument;
$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";

Need Your Help

Convert base64 string to ArrayBuffer

javascript base64 arraybuffer

I need to convert a base64 encode string into an ArrayBuffer.

Removing right bar button item from navigation item

iphone objective-c cocoa-touch uibarbuttonitem

I have added a right bar button item in my navigation item and want to remove this on some condition. This is what I am doing: