note 44266 modified in function.dom-domnodelist-item by didou

From: Date: Tue, 31 Aug 2004 18:14:59 +0000
Subject: note 44266 modified in function.dom-domnodelist-item by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-75760@lists.php.net to get a copy of this message
The use of the count() function stumped me for a bit in this context, things can be a little confusing if you are using both SimpleXML and DOM (and are perhaps working late through the night :). In SimpleXML the result of an XPath expression returns an array of simplexml_element objects, so you can use count() to determine if the expression returned any nodes. In DOM the result of an XPath expression is a DOMNodeList which always returns 1 when it is passed into count, instead we can use DOMNodeList->length to get the number of nodes returned. As a simple example we have some session data stored using WDDX, the root node of any WDDX packet is wddxPacket, so when looking for wddxPacketBAD our XPath query should return 0 nodes. SimpleXML: $sessionDOM = simplexml_load_string($sessionXML) if($sessionDOM) { $xpQuery = $sessionDOM->xpath("//wddxPacketBAD"); print(count($xpQuery)); // prints 0 - OK } DOM: $sessionDOM = new DOMDocument(); $sessionDOM->loadXML($sessionXML); if($sessionDOM) { $xpHandle = new domXPath($sessionDOM); $xpQuery = $xpHandle->query("//wddxPacketBAD"); print(count($xpQuery)); // prints 1 - NOT OK print($xpQuery->length); // prints 0 - OK } Hope this helps! --was-- The use of the count() function stumped me for a bit in this context, things can be a little confusing if you are using both SimpleXML and DOM XML (and are perhaps working late through the night :). In SimpleXML the result of an XPath expression returns an array of simplexml_element objects, so you can use count() to determine if the expression returned any nodes. In DOM XML the result of an XPath expression is a DOMNodeList which always returns 1 when it is passed into count, instead we can use DOMNodeList->length to get the number of nodes returned. As a simple example we have some session data stored using WDDX, the root node of any WDDX packet is wddxPacket, so when looking for wddxPacketBAD our XPath query should return 0 nodes. SimpleXML: $sessionDOM = simplexml_load_string($sessionXML) if($sessionDOM) { $xpQuery = $sessionDOM->xpath("//wddxPacketBAD"); print(count($xpQuery)); // prints 0 - OK } DOM XML: $sessionDOM = new DOMDocument(); $sessionDOM->loadXML($sessionXML); if($sessionDOM) { $xpHandle = new domXPath($sessionDOM); $xpQuery = $xpHandle->query("//wddxPacketBAD"); print(count($xpQuery)); // prints 1 - NOT OK print($xpQuery->length); // prints 0 - OK } Hope this helps! http://php.net/manual/en/function.dom-domnodelist-item.php

« previous php.notes (#75760) next »