note 101063 added to book.simplexml
| From: | philipp at strazny dot com | Date: | Wed, 24 Nov 2010 01:33:51 +0000 |
| Subject: | note 101063 added to book.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-174306@lists.php.net to get a copy of this message | ||
Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each
nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update
values externally (i.e. in code that doesn't know about the underlying xml). Then I use
DOMXPath to find the node containing the original value and update it.
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
$children = array();
if ($xml instanceof SimpleXMLElement) {
$children = $xml->children();
if ($root){ // we're at root
$path .= '/'.$xml->getName();
}
}
if ( count($children) == 0 ){
$return[$path] = (string)$xml;
return;
}
$seen=array();
foreach ($children as $child => $value) {
$childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
if ( !isset($seen[$childname])){
$seen[$childname]=0;
}
$seen[$childname]++;
XMLToArrayFlat($value, $return,
$path.'/'.$child.'['.$seen[$childname].']');
}
}
Use like this:
$xml = simplexml_load_string(...some xml string...);
$xmlarray = array(); // this will hold the flattened data
XMLToArrayFlat($xml, $xmlarray, '', true);
You can also pull multiple files in one array:
foreach($files as $file){
$xml = simplexml_load_file($file);
XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
The respective filename/path is thus prefixed to each key.
----
Server IP: 69.147.83.197
Probable Submitter: 76.230.213.149
----
Manual Page -- http://www.php.net/manual/en/book.simplexml.php
Edit -- https://master.php.net/note/edit/101063
Del: integrated -- https://master.php.net/note/delete/101063/integrated
Del: useless -- https://master.php.net/note/delete/101063/useless
Del: bad code -- https://master.php.net/note/delete/101063/bad+code
Del: spam -- https://master.php.net/note/delete/101063/spam
Del: non-english -- https://master.php.net/note/delete/101063/non-english
Del: in docs -- https://master.php.net/note/delete/101063/in+docs
Del: other reasons-- https://master.php.net/note/delete/101063
Reject -- https://master.php.net/note/reject/101063
Search -- https://master.php.net/manage/user-notes.php