How to convert array to SimpleXML in PHP
Many times need to store the data as a XML format into the database or into the file for later use. To fulfill this requirement need to convert data to XML and save XML file. The SimpleXML extension functions provides the tool set to convert XML to an object. Those objects deals with normal property selectors and array iterators.
Example 1:
php
<?php
function arrayToXml( $array , $rootElement = null, $xml = null) {
$_xml = $xml ;
if ( $_xml === null) {
$_xml = new SimpleXMLElement( $rootElement !== null ? $rootElement : '<root/>' );
}
foreach ( $array as $k => $v ) {
if ( is_array ( $v )) {
arrayToXml( $v , $k , $_xml ->addChild( $k ));
}
else {
$_xml ->addChild( $k , $v );
}
}
return $_xml ->asXML();
}
$my_array = array (
'name' => 'GFG' ,
'subject' => 'CS' ,
'contact_info' => array (
'city' => 'Noida' ,
'state' => 'UP' ,
'email' => 'feedback@geeksforgeeks.org'
),
);
echo arrayToXml( $my_array );
?>
|
Output:
<?xml version="1.0"?>
<root>
<name> GFG </name>
<subject> CS </subject>
<contact_info >
<city > Noida < /city >
<state > UP < /state >
<email > feedback@geeksforgeeks.org </email>
<contact_info>
<root>
The above problem can be solved using array_walk_recursive() function. This function converts array to xml document where keys of array are converted into values and values of array are converted into element of XML.
Example 2:
php
<?php
$my_array = array (
'a' => 'x' ,
'b' => 'y' ,
'another_array' => array (
'c' => 'z' ,
),
);
$xml = new SimpleXMLElement( '<root/>' );
array_walk_recursive ( $my_array , array ( $xml , 'addChild' ));
print $xml ->asXML();
?>
|
Output:
<?xml version="1.0"? >
<root >
<x> a </x >
<y> b </y >
<z> c </z >
</root >
Note: If the system generate error of type :PHP Fatal error: Uncaught Error: Class ‘SimpleXMLElement’ not found in /home/6bc5567266b35ae3e76d84307e5bdc78.php:24 then simply install php-xml, php-simplexml packages.
Last Updated :
10 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...