How to Convert Array to XML in PHP?

By Hardik Savani December 4, 2023 Category : PHP

Hello Developer,

If you need to see an example of php convert array to xml. I’m going to show you about how to convert array to xml in php. you will learn how to convert xml response to array in php. This example will help you php array to xml SimpleXMLElement.

In PHP, you can use the `SimpleXMLElement` class to convert an array into XML. Here's a simple example:

index.php

<?php

/* Sample array */

$data = array(

'person' => array(

'name' => 'John Doe',

'age' => 30,

'city' => 'New York'

)

);

/* Function to convert array to XML */

function arrayToXml($data, &$xml) {

foreach ($data as $key => $value) {

if (is_array($value)) {

$subnode = $xml->addChild($key);

arrayToXml($value, $subnode);

} else {

$xml->addChild($key, htmlspecialchars($value));

}

}

}

/* Create XML element */

$xml = new SimpleXMLElement('<root/>');

/* Convert array to XML */

arrayToXml($data, $xml);

/* Print or save XML */

echo $xml->asXML();

/* If you want to save to a file, you can use: */

/* $xml->asXML('output.xml'); */

?>

Output

<?xml version="1.0"?>

<root>

<user>

<name>Hardik</name>

<age>30</age>

<city>Rajkot</city>

</user>

</root>

This example demonstrates a simple array containing information about a person. The "arrayToXml" function recursively converts the array to XML using the `SimpleXMLElement` class. Finally, it prints the XML using `echo`. If you want to save the XML to a file, you can use the `$xml->asXML('output.xml');` line instead of `echo`.

I hope it can help you...

Tags :
Shares