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.
<?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();
<?xml version="1.0"?>
<root>
<blub>bla</blub>
<bar>foo</bar>
<overflow>stack</overflow>
</root>
// 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);
<?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.
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
How to Set or Unset a Cookie with jQuery
Use the JS document.cookie Property Y...How to add or remove rows inside a table dynamically using jQuery
Use the jQuery .append() or .remove() Me...How to Strip All Spaces Out of a String in PHP
Use the PHP str_replace() Function Yo...How to Create REST API in Laravel7 using Passport
Hey Artisan Hope you are doing well....How to fix Target class does not exist in Laravel 8
Laravel 8 has many new features and chan...