Search

How to convert php array to simple xml

PHP
post-title

In this article, i will share with you how to convert PHP array to simple XML formate with example. as you know we need to many times convert PHP array to XML in PHP application. like when we integrate some third-party API in our application and that API only allows post data payload in XML format then we need to convert out array data payload in XML data payload.

Example - 1 :

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

Output :

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

Example - 2 :

// Define a function that converts array to xml. 
function arrayToXml($array, $rootElement = null, $xml = null) { 
    $_xml = $xml; 
      
    // If there is no Root Element then insert root 
    if ($_xml === null) { 
        $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>'); 
    } 
      
    // Visit all key value pair 
    foreach ($array as $k => $v) { 
          
        // If there is nested array then 
        if (is_array($v)) {  
              
            // Call function for nested array 
            arrayToXml($v, $k, $_xml->addChild($k)); 
            } 
              
        else { 
              
            // Simply add child element.  
            $_xml->addChild($k, $v); 
        } 
    } 
      
    return $_xml->asXML(); 
} 
  
// Creating an array for demo 
$my_array = array ( 
'name' => 'Harsukh Makwana', 
'subject' => 'CS',   
    // Creating nested array. 
    'contact_info' => array ( 
    'city' => 'Ahmedabad', 
    'state' => 'Gujrat', 
    'email' => 'contact@laravelcode.com'
    ), 
); 
  
// Calling arrayToxml Function and printing the result 
echo arrayToXml($my_array); 

Output :

<?xml version="1.0"?>
<root>
    <name> Harsukh Makwana </name>
    <subject> CS </subject>
    <contact_info >
        <city> Ahmedabad </city>
        <state> Gujrat </state>
        <email> contact@laravelcode.com </email>
    <contact_info>
<root>

Note : if the SimpleXMLElement not found then install "php-xml, php-simplexml" in your local.

i hope you like this solution.