note 81860 added to ref.dom
| From: | SvenArduwie at osu1 dot php dot net | Date: | Mon, 17 Mar 2008 02:28:52 +0000 |
| Subject: | note 81860 added to ref.dom | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-137114@lists.php.net to get a copy of this message | ||
I needed a function that quickly converts an xml with key/value pairs to an array.
for example:
<?xml version="1.0" encoding="UTF-8"?>
<test>
<key id="Array key #1" value="Value #1"/>
<key id="Array key #2" value="Value #2"/>
<key id="Dupe" value="Duplicate keys"/>
<key id="Dupe" value="create numeric arrays"/>
<key id="And another key">
<![CDATA[
Multiline
data
works
just
as
well.
]]>
</key>
<nested>
<key id="Nested key" value="Nested data works as well, but it still results in a
1 dimensional array."/>
</nested>
</test>
Results in the following array:
array(5) {
["Array key #1"]=>
string(8) "Value #1"
["Array key #2"]=>
string(8) "Value #2"
["Dupe"]=>
array(2) {
[0]=>
string(14) "Duplicate keys"
[1]=>
string(21) "create numeric arrays"
}
["And another key"]=>
string(49) "Multiline
data
works
just
as
well."
["Nested key"]=>
string(73) "Nested data works as well, but it still results in a 1 dimensional array."
}
Here's the code:
<?php
function xml2array($xml) {
$domDocument = new DOMDocument;
$domDocument->loadXML($xml);
$domXPath = new DOMXPath($domDocument);
$array = array();
foreach ($domXPath->query('//key') as $keyDOM) {
$id = $keyDOM->getAttribute('id');
$value = $keyDOM->hasAttribute('value') ?
$keyDOM->getAttribute('value') : trim($keyDOM->textContent);
if (array_key_exists($id, $array)) {
if (is_array($array[$id])) {
$array[$id][] = $value;
} else {
$array[$id] = array($array[$id]);
$array[$id][] = $value;
}
} else {
$array[$id] = $value;
}
}
return $array;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 81.245.27.231
----
Manual Page -- http://www.php.net/manual/en/ref.dom.php
Edit -- https://master.php.net/note/edit/81860
Del: integrated -- https://master.php.net/note/delete/81860/integrated
Del: useless -- https://master.php.net/note/delete/81860/useless
Del: bad code -- https://master.php.net/note/delete/81860/bad+code
Del: spam -- https://master.php.net/note/delete/81860/spam
Del: non-english -- https://master.php.net/note/delete/81860/non-english
Del: in docs -- https://master.php.net/note/delete/81860/in+docs
Del: other reasons-- https://master.php.net/note/delete/81860
Reject -- https://master.php.net/note/reject/81860
Search -- https://master.php.net/manage/user-notes.php