Re: Replacing text of a DOM text node
| From: | Rob Richards | Date: | Wed, 07 Jun 2006 10:26:25 +0000 |
| Subject: | Re: Replacing text of a DOM text node | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-237546@lists.php.net to get a copy of this message | ||
Hi Frank,
Frank Arensmeier wrote:
Jochem, thank you for your input! So, right now I am able to access all text nodes by e.g. $nodeElement -> parentNode -> childNodes -> item(0); -> returns Lenght, Width and so on $nodeElement -> parentNode -> childNodes -> item(1); -> is empty $nodeElement -> parentNode -> childNodes -> item(2); -> returns mm, kg ...
and so on. Or is there an easier way? When trying to acces the items by ($nodeElement containing text nodes) $nodeElemtent -> item(0); I get the following error message: Call to undefined method DOMText::item()...Only a nodelist and namenodemap has the item() method. You could also do something like the following - note that manually walking the tree is much faster than iterating a nodelist - (there are also many different variations of this code depending upon what you need to do with the subtree): $node = $nodeElement->parentNode->firstChild; while ($node) { /* only process text or element nodes here */ if ($node->nodeType == XML_TEXT_NODE) {
$node->nodeValue = 'New text content'; /* modify text content */} else if ($node->nodeType == XML_ELEMENT_NODE) {
/* node is element - process its subtree or move on i.e.: */
if ($node->hasChildNodes()) {
foreach ($node->childNodes AS $child) {
/* process child nodes here */
}
}
}
$node = $node->nextSibling;
}
BTW, is there an easy way to get the total amount of items in a curent node? count ( $nodeElement -> parentNode -> childNodes ) always returns 1. For now the only solution I know of is looping through the nodeElements (e.g. foreach ( $nodeElement as $value ) and have a counter inside the loop.$count = $nodeElement->parentNode->childNodes->length; This property is only available from a nodelist or namednodemap.
Thank you so far. /frank ps. I am desperately looking for some good sites covering the PHP DOM functions. On www.php.net/dom there are barely some examples. And on www.zend.com I only found one article with very, very basic examples. Any ideas/suggestions are more than welcome. ds.You can pretty much search for examples from any DOM implementation since its a standard (not too difficult to go from one language to another when using DOM). For PHP specific ones, there are a number of tests in the CVS repository that demonstrate much of the functionality: http://cvs.php.net/viewcvs.cgi/php-src/ext/dom/tests/ One particular test that uses a good amount of the API (though the basic functions) is dom001.phpt: http://cvs.php.net/viewcvs.cgi/php-src/ext/dom/tests/dom001.phpt?view=markup&rev=1.4 Rob -- rrichards@ctindustries.net author of Pro PHP XML and Web Services from Apress