How to convert an array to SimpleXML in PHP?

PHPProgrammingServer Side Programming

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.

raja
Published on 26-Jun-2019 13:40:33
Advertisements