note 98736 deleted from book.dom by danbrown
| From: | danbrown@php.net | Date: | Sat, 03 Jul 2010 16:05:51 +0000 |
| Subject: | note 98736 deleted from book.dom by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-170684@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
Thanks to sweisman at pobox dot com. I modified his function to convert a DOM into an array
structure, which works better for me:
function dom_to_array($root, $full_view=FALSE)
{
$result = array();
// process attributes
if ($root->hasAttributes())
{
$attrs = $root->attributes;
foreach ($attrs as $i => $attr)
{
$result['@attributes'][$attr->name] = $attr->value;
}
}
//process child nodes
$children = $root->childNodes;
for($i = 0; $i < $children->length; $i++)
{
$child = $children->item($i);
if ($child->nodeType == XML_TEXT_NODE)
{
$result['#text'][] = $child->nodeValue;
}
else
{
$result[$child->nodeName][] = dom_to_array($child);
}
}
// direct assignment of text nodes
if (
TRUE
and count($result) == 1
and isset($result['#text'])
and count($result['#text']) == 1
)
{
$result = $result['#text'][0];
}
// reduce array to am more minimalistic structure
if (is_array($result) and !$full_view)
{
foreach ( $result as $key => $value )
{
if ( count($result[$key]) == 1 )
{
$result[$key] = $result[$key][0];
}
}
}
return $result;
}