How to convert php array to simple xml

  75 views   4 weeks ago PHP

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles