Convert PHP array to XML

Conversion function
//******************************************
//******************************************
//********** CONVERT ARRAY TO XML **********
//******************************************
//******************************************
//We use our own function as array_walk_recursive() adds array items the wrong way round (<value>name</value>)
function ArrayToXml($Array, &$XmlData)
{
  foreach ($Array as $key => $value)
  {
    //If there is nested array
    if (is_array($value))
    {
      if (is_numeric($key))
      {
        $key = 'item'.$key; //deal with <0/>..<n/> issues
      }
      $subnode = $XmlData->addChild($key);
      ArrayToXml($value, $subnode);
    }
    else
    {
      $XmlData->addChild("$key",htmlspecialchars("$value"));
    }
   }
}
Using it
    //Make sure simplexml is installed (it should be there by default with php, but it seems to be omitted in some installs.
    if (!function_exists('simplexml_load_file'))
      die('Server config issue - simpleXML functions are not available.');    //You can install this on ubuntu using: sudo apt-get install php-xml

    $test_array = array (
      'abc' => 'Field1',
      'def' => 'Field2'
    );

    $xml = new SimpleXMLElement('<root/>');
    ArrayToXml($test_array, $xml);
    print $xml->asXML();
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *