note 101010 modified in class.domdocument by danbrown
| From: | danbrown@php.net | Date: | Fri, 19 Nov 2010 20:55:13 +0000 |
| Subject: | note 101010 modified in class.domdocument by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-174213@lists.php.net to get a copy of this message | ||
A nice and simple node 2 array I wrote, worth a try ;)
<?php
$dom = new DOMDocument();
$dom->loadXML("test.xml");
echo "<PRE>";
print_r(getArray($dom->documentElement));
function getArray($node)
{
$array = false;
if ($node->hasAttributes())
{
foreach ($node->attributes as $attr)
{
$array[$attr->nodeName] = $attr->nodeValue;
}
}
if ($node->hasChildNodes())
{
if ($node->childNodes->length == 1)
{
$array[$node->firstChild->nodeName] = $this->getArray($node->firstChild);
}
else
{
foreach ($node->childNodes as $childNode)
{
if ($childNode->nodeType != XML_TEXT_NODE)
{
$array[$childNode->nodeName][] = $this->getArray($childNode);
}
}
}
}
else
{
return $node->nodeValue;
}
return $array;
}
?>
--was--
A nice and simple node 2 array I wrote, worth a try ;)
$dom = new DOMDocument();
$dom->loadXML("test.xml");
echo "<PRE>";
print_r(getArray($dom->documentElement));
function getArray($node)
{
$array = false;
if ($node->hasAttributes())
{
foreach ($node->attributes as $attr)
{
$array[$attr->nodeName] = $attr->nodeValue;
}
}
if ($node->hasChildNodes())
{
if ($node->childNodes->length == 1)
{
$array[$node->firstChild->nodeName] = $this->getArray($node->firstChild);
}
else
{
foreach ($node->childNodes as $childNode)
{
if ($childNode->nodeType != XML_TEXT_NODE)
{
$array[$childNode->nodeName][] = $this->getArray($childNode);
}
}
}
}
else
{
return $node->nodeValue;
}
return $array;
}
http://php.net/manual/en/class.domdocument.php