note 70240 deleted from ref.xml by betz
| From: | betz@php.net | Date: | Sun, 08 Oct 2006 12:54:19 +0000 |
| Subject: | note 70240 deleted from ref.xml by betz | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-118209@lists.php.net to get a copy of this message | ||
Note Submitter: Rattus
----
This is a re-write of the "xml2array" function last posted by aerik at wikidweb dot
com" on "26-Nov-2005 02:24".
It fixes some bugs and produces a more compact output.
The only outstanding issue first noted by "sander at gameqube dot nl" on "25-Dec-2005
10:07", is that child elements with the same name as the parent will go wrong.
EXAMPLE:
--------
<?php
print_r(xml2array('afile.xml'));
?>
FUNCTION DEFINITION:
--------------------
<?php
function xml2array ($xml)
{
$xmlary = array ();
if (is_file($xml)) // load file and remove unneccessary white-space
{
$xml = file_get_contents($xml);
$xml = preg_replace('@[\t\r\n]+@', '', $xml);
$xml = preg_replace('@>\s+@', '>', $xml);
$xml = preg_replace('@\s+<@', '<', $xml);
}
$ReElements =
'/<\s*(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*?)<(\/\s*\1\s*)>)/s';
$ReAttributes = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';
preg_match_all($ReElements, $xml, $elements);
foreach($elements[1] as $ie => $xx)
{
if ($attributes = trim($elements[2][$ie]))
{
preg_match_all ($ReAttributes, $attributes, $att);
foreach ($att[1] as $ia => $yy) $xmlary["attributes"][$att[1][$ia]] = $att[2][$ia];
// all the attributes for current element are added here
}
$cdend = strpos($elements[3][$ie], "<"); // get text if it's combined with
sub elements
if ($cdend > 0) $xmlary["text"] = substr($elements[3][$ie], 0, $cdend);
if (preg_match($ReElements, $elements[3][$ie])) $xmlary[$elements[1][$ie]][$index++] = xml2array
($elements[3][$ie]);
else if (isset($elements[3][$ie])) $xmlary[$elements[1][$ie]] = $elements[3][$ie];
}
return $xmlary;
}
?>