note 88264 added to class.xmlreader
| From: | boukeversteegh at gmail dot com | Date: | Sun, 18 Jan 2009 10:06:19 +0000 |
| Subject: | note 88264 added to class.xmlreader | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-149378@lists.php.net to get a copy of this message | ||
XML to ASSOCIATIVE ARRAY
Improved algorithm based on Sergey Aikinkulov's. The problem was that it would overwrite nodes
if they had the same tag name. Because of that <a><b/><b/><a> would be read
as if <a><b/><a/>. This algorithm handles it better and outputs an easy to
understand array:
<?
function xml2assoc($xml) {
$tree = null;
while($xml->read())
switch ($xml->nodeType) {
case XMLReader::END_ELEMENT: return $tree;
case XMLReader::ELEMENT:
$node = array('tag' => $xml->name, 'value' =>
$xml->isEmptyElement ? '' : xml2assoc($xml));
if($xml->hasAttributes)
while($xml->moveToNextAttribute())
$node['attributes'][$xml->name] = $xml->value;
$tree[] = $node;
break;
case XMLReader::TEXT:
case XMLReader::CDATA:
$tree .= $xml->value;
}
return $tree;
}
?>
Usage:
myxml.xml:
------
<PERSON>
<NAME>John</NAME>
<PHONE type="home">555-555-555</PHONE>
</PERSON>
----
<?
$xml = new XMLReader();
$xml->open('myxml.xml');
$assoc = xml2assoc($xml);
$xml->close();
print_r($assoc);
?>
Outputs:
Array
(
[0] => Array
(
[tag] => PERSON
[value] => Array
(
[0] => Array
(
[tag] => NAME
[value] => John
)
[1] => Array
(
[tag] => PHONE
[value] => 555-555-555
[attributes] => Array
(
[type] => home
)
)
)
)
)
For reasons that have to do with recursion, it returns an array with the ROOT xml node as the first
childNode, rather than to return only the ROOT node.
----
Server IP: 89.248.170.61
Probable Submitter: 87.212.170.64
----
Manual Page -- http://www.php.net/manual/en/class.xmlreader.php
Edit -- https://master.php.net/note/edit/88264
Del: integrated -- https://master.php.net/note/delete/88264/integrated
Del: useless -- https://master.php.net/note/delete/88264/useless
Del: bad code -- https://master.php.net/note/delete/88264/bad+code
Del: spam -- https://master.php.net/note/delete/88264/spam
Del: non-english -- https://master.php.net/note/delete/88264/non-english
Del: in docs -- https://master.php.net/note/delete/88264/in+docs
Del: other reasons-- https://master.php.net/note/delete/88264
Reject -- https://master.php.net/note/reject/88264
Search -- https://master.php.net/manage/user-notes.php