How to convert an array to SimpleXML in PHP?


We can solved the above problem using array_walk_recursive() function.array_walk_recursive()   is an inbuilt PHP function. This function converts array to XML document where keys of the array are converted into values and values of the array are converted into the element of XML.

Let' demonstrate with a simple example.

Example

<?php
   $array = array (
   'name' => 'alex',
   'empdept' => 'account',
   'address' => array (
      'city' => 'michigan'
      ),
   );
   //This function create a xml object with element root.
   $xml = new SimpleXMLElement('');
   array_walk_recursive($array, array ($xml,'addChild'));
   print $xml->asXML();
?>

Output

<?xml version="1.0"?>
<root>
<name> alex </name>
<empdept> account </empdept>
<city> michigan </city >
</root>

Note

If errors message display like PHP Fatal error: Uncaught Error: Class 'SimpleXMLElement' not found in then simply install php-xml, php-simplexml packages.

Updated on: 29-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements