Parsing XML using PHP - XML2Array

This sections will contains code regarding different PHP & MySQL features and contains help about php/mysql issues.

Parsing XML using PHP - XML2Array

Postby 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;
   }
?>
MT Shahzad
Web/Software Developer
http://mts.sw3solutions.com
User avatar
MT Shahzad
Site Admin
 
Posts: 300
Joined: February 29th, 2008, 8:11 am
Location: Muridke, Pakistan

Return to PHP / MySQL / XML

Who is online

Users browsing this forum: No registered users and 0 guests

cron