note 19240 deleted from function.domxml-attributes by nlopess

From: Date: Mon, 28 Jun 2004 14:25:59 +0000
Subject: note 19240 deleted from function.domxml-attributes by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-72010@lists.php.net to get a copy of this message
Note Submitter: jon.sprague(at)itgco.com ---- Here's a little something to demonstrate the use of the domxml_attributes function as a method. It's recurcive and prints out the attributes and some other stuff for each node in an XML doc, but only content for a text node. $xmlstr= '<?xml version="1.0" encoding="iso-8859-1" ?> <acquaintance> <addresses> <address type="home" loc="1 1st st"/> <address type="office" loc="2 2nd ave"/> </addresses> <name>John Doe</name> </acquaintance>'; function print_data($nodes) { while($node = array_shift($nodes)) //cycle through each child node { if($node->type=='3') //if node is text print the text { //**** See bottom for comment **** if(ereg('^[[:space:]]*$', $node->content)) continue; print('NODE:\ntext node content: '.$node->content.'\n\n'); } else { print('NODE:\ntype: '.$node->type.'\n'); print('tagname: '.$node->tagname.'\n'); $many = $node->attributes(); while($attr = array_shift($many)) //cycle through each attribute of the child node print('attr('.$attr->name.'): '.$attr->value.'\n'); print('\n'); //if child node has children run this function on them if($sub_nodes = $node->children()) print_data($sub_nodes); } } } $doc = xmldoc($xmlstr); $root = $doc->root(); print('ROOT:\ntype :'.$root->type.'\n'); print('tagname: '.$root->tagname.'\n\n'); $nodes = $root->children(); print_data($nodes); COMMENT: The XML has line breaks and tabs to get the tags arranged in an organized fashion, so it is easier to read. But when DOM parses the XML, all the white space between tags is treated like a child node. So my function would output many "text node content:" lines. So I check for text nodes that have no content, other than white space (tabs, spaces, line returns), and skip them. I didn't show the output because this is getting pretty long, so copy and paste it and try it out!

« previous php.notes (#72010) next »