note 37342 modified in ref.domxml by didou
| From: | didou@php.net | Date: | Sun, 29 Aug 2004 21:46:52 +0000 |
| Subject: | note 37342 modified in ref.domxml by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-75597@lists.php.net to get a copy of this message | ||
This recursive function will iterate over a DOM object and display it as a nicely formatted XML
structure. I used intuitive variable names to help learn more about the DOM functions and their
return values.
<<?php
function PrintDomTree($DomNode)
{
if ($ChildDomNode = $DomNode->first_child()) {
static $depth = 0;
$whitespace = "\n<br>".str_repeat(" ", ($depth * 2));
while ($ChildDomNode) {
if ($ChildDomNode->node_type() == XML_TEXT_NODE) {
echo trim($ChildDomNode->node_value());
} elseif ($ChildDomNode->node_type() == XML_ELEMENT_NODE) {
$HasTag = 1;
echo $whitespace;
echo "<", $ChildDomNode->node_name();
if ($ChildDomNode->has_attributes()) {
$Array = $ChildDomNode->attributes();
foreach ($Array AS $DomAttribute) {
echo " ", $DomAttribute->name(), "=\"", $DomAttribute->value(),
"\"";
}
}
echo ">";
if ($ChildDomNode->has_child_nodes()) {
$depth++;
if (PrintDomTree($ChildDomNode)) {
echo $whitespace;
}
$depth--;
}
echo "</", $ChildDomNode->node_name(), ">";
}
$ChildDomNode = $ChildDomNode->next_sibling();
}
return $HasTag;
}
}
?>
--was--
This recursive function will iterate over a DOM object and display it as a nicely formatted XML
structure. I used intuitive variable names to help learn more about the DOM functions and their
return values.
<?php
function PrintDomTree($DomNode) {
if ($ChildDomNode = $DomNode->first_child()):
static $depth = 0;
$whitespace = "\n<br>".str_repeat(" ", ($depth * 2));
while($ChildDomNode):
if ($ChildDomNode->node_type() == XML_TEXT_NODE):
echo trim($ChildDomNode->node_value());
elseif ($ChildDomNode->node_type() == XML_ELEMENT_NODE):
$HasTag = 1;
echo $whitespace;
echo '<', $ChildDomNode->node_name();
if ($ChildDomNode->has_attributes()):
$Array = $ChildDomNode->attributes();
foreach ($Array AS $DomAttribute):
echo ' ', $DomAttribute->name(), '="', $DomAttribute->value(),
'"';
endforeach;
endif;
echo '>';
if ($ChildDomNode->has_child_nodes()):
$depth++;
if (PrintDomTree($ChildDomNode)):
echo $whitespace;
endif;
$depth--;
endif;
echo '</', $ChildDomNode->node_name(), '>';
endif;
$ChildDomNode = $ChildDomNode->next_sibling();
endwhile;
return $HasTag;
endif;
}
$DomDocument = domxml_open_mem($xmlstr);
$RootDomNode = $DomDocument->document_element();
PrintDomTree($RootDomNode);
?>
http://php.net/manual/en/ref.domxml.php