rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

Convert SimpleXML Object into PHP Array

Web Services are very useful when we need to send and receive information from third-party clients. These Web Services, generally, output or return the response in an XML format.

XML can be easily parsed in PHP using the simplexml_load_string or the SimpleXMLElement object. Now, manipulating this object can be sometime painful.

The solution: converting this object in an array. Here's two examples on how to convert this:

Let's say we have this xml:

<monitor>
  <manufacturer>Samsung</manufacturer>
  <model>XL30</model>
  <display>
    <screen_size>30</screen_size>
    <resolution>2560x1600</resolution>
    <brightness>200</brightness>
    <contrast_ratio>1000:1</contrast_ratio>
    <response_time>6</response_time>
    <viewing_angle_h>178</viewing_angle_h>
    <viewing_angle_v>178</viewing_angle_v>
    <colour_supported>16.7</colour_supported>
    <colour_supported_metric>M</colour_supported_metric>
  </display>
</monitor>

Solution #1

function xml2array($xml) {
  $arr = array();
  foreach ($xml as $element) {
    $tag = $element->getName();
    $e = get_object_vars($element);
    if (!empty($e)) {
      $arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
    }
    else {
      $arr[$tag] = trim($element);
    }
  }
  return $arr;
}

$xml = new SimpleXMLElement($string);

Solution #2

$xml = json_decode(json_encode((array) simplexml_load_string($string)), 1);

This will print out the following code using both solutions:

Array
(
 [manufacturer] => Samsung
 [model] => XL30
 [display] => Array
  (
   [screen_size] => 30
   [resolution] => 2560x1600
   [brightness] => 200
   [contrast_ratio] => 1000:1
   [response_time] => 6
   [viewing_angle_h] => 178
   [viewing_angle_v] => 178
   [colour_supported] => 16.7
   [colour_supported_metric] => M
  )
)