note 96281 added to simplexmlelement.children
| From: | php at shiinaringo dot se | Date: | Thu, 18 Feb 2010 10:42:39 +0000 |
| Subject: | note 96281 added to simplexmlelement.children | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-166115@lists.php.net to get a copy of this message | ||
Most examples on this page do not take namespaces into account, rendering them useless in many
cases. Here is a function to convert xml to array. You have to feed it the list of namespaces to
use. Watch the example at the bottom.
<?php
function xml2phpArray($xml, $namespaces, $arr) {
$iter = 0;
foreach ($namespaces as $namespace => $namespaceUrl) {
foreach ($xml->children($namespaceUrl) as $b) {
$a = $b->getName();
if ($b->children($namespaceUrl)) {
$arr[$a][$iter] = array();
$arr[$a][$iter] = xml2phpArray($b, $namespaces, $arr[$a][$iter]);
}
else {
$arr[$a] = trim($b[0]);
}
$iter++;
}
}
return $arr;
}
$xml = simplexml_load_file('http://urltosomexmlfile.xml');
$namespaces = array_merge(array('' => ''), $xml->getDocNamespaces(true));
$myArray = array();
$myArray = xml2phpArray($xml, $namespaces, $myArray);
?>
----
Server IP: 61.195.146.164
Probable Submitter: 61.214.154.89
----
Manual Page -- http://www.php.net/manual/en/simplexmlelement.children.php
Edit -- https://master.php.net/note/edit/96281
Del: integrated -- https://master.php.net/note/delete/96281/integrated
Del: useless -- https://master.php.net/note/delete/96281/useless
Del: bad code -- https://master.php.net/note/delete/96281/bad+code
Del: spam -- https://master.php.net/note/delete/96281/spam
Del: non-english -- https://master.php.net/note/delete/96281/non-english
Del: in docs -- https://master.php.net/note/delete/96281/in+docs
Del: other reasons-- https://master.php.net/note/delete/96281
Reject -- https://master.php.net/note/reject/96281
Search -- https://master.php.net/manage/user-notes.php