by MT Shahzad on March 17th, 2008, 11:32 am
The below code takes the XML data in a php variable and will parse it and generate an Array.
- Code: Select all
<?
function xml2array ($xml)
{
$xmlary = array ();
$ReElements = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s';
$ReAttributes = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';
preg_match_all ($ReElements, $xml, $elements);
foreach ($elements[1] as $ie => $xx)
{
$xmlary[$ie]["name"] = $elements[1][$ie];
if ( $attributes = trim($elements[2][$ie]))
{
preg_match_all ($ReAttributes, $attributes, $att);
foreach ($att[1] as $ia => $xx) // all the attributes for current element are added here
$xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
}
// if $attributes
// get text if it's combined with sub elements
$cdend = strpos($elements[3][$ie],"<");
if ($cdend > 0)
{
$xmlary[$ie]["text"] = substr($elements[3][$ie],0,$cdend -1);
} // if cdend
if (preg_match ($ReElements, $elements[3][$ie]))
$xmlary[$ie]["elements"] = xml2array ($elements[3][$ie]);
else if ($elements[3][$ie])
{
$xmlary[$ie]["text"] = $elements[3][$ie];
}
}
return $xmlary;
}
?>