How to convert an XML string to an array using PHP

You may come across a situation where you would need to convert an XML string to an array so you can manipulate it using your PHP code. There is no default PHP function which does this however you can build your own to accomplish this task. I use the following function to convert any XML string to an array.


// This function takes the XML string as input and returns an array
function xml2array($text) {
  $reg_exp = '/<(\w+)[^>]*>(.*?)<\/\\1>/s';
  preg_match_all($reg_exp, $text, $match);
  foreach ($match[1] as $key=>$val) {
  	if ( preg_match($reg_exp, $match[2][$key]) ) {
      $array[$val][] = xml2array($match[2][$key]);
    } else {
      $array[$val] = $match[2][$key];
    }
  }
  return $array;
} 


$strXml = '
				
					Adeel Sarfraz
					123 456 7890
					adeel@company.com
					Karachi
				
				
					Adam Sandler
					000 126 7890
					adam@company.com
					Los Angeles
				
				
					Betty Paige
					455 123 0000
					betty@company.com
					London
												
		   ';
		   
		   
print_r(xml2array($strXml));

If you run the above script you will receive the following output in array

Array
(
    [PEOPLE] => Array
        (
            [0] => Array
                (
                    [PERSON] => Array
                        (
                            [0] => Array
                                (
                                    [FULLNAME] => Adeel Sarfraz
                                    [PHONE] => 123 456 7890
                                    [EMAIL] => adeel@company.com
                                    [CITY] => Karachi
                                )

                            [1] => Array
                                (
                                    [FULLNAME] => Adam Sandler
                                    [PHONE] => 000 126 7890
                                    [EMAIL] => adam@company.com
                                    [CITY] => Los Angeles
                                )

                            [2] => Array
                                (
                                    [FULLNAME] => Betty Paige
                                    [PHONE] => 455 123 0000
                                    [EMAIL] => betty@company.com
                                    [CITY] => London
                                )

                        )

                )

        )

)

Hope the above helped!

Please follow and like us:
error

Be the first to comment

Leave a Reply

Your email address will not be published.