How to Convert Array to XML in PHP - TechvBlogs
PHP

How to Convert Array to XML in PHP

In this article, You will learn How to Convert Array to XML in PHP.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

4 months ago

TechvBlogs - Google News

If you're looking for an example of how to convert an array to XML in PHP, you're in the right place. I'll walk you through the process of transforming an array into XML using PHP. Additionally, I'll demonstrate how to convert an XML response back into an array in PHP. This example will guide you through using the SimpleXMLElement class for seamless conversion between PHP arrays and XML structures.

How to Convert Array to XML in PHP

In PHP, the conversion of an array into XML is easily accomplished using the SimpleXMLElement class.

Convert Array to XML in PHP Example

<?php

/* Sample array */

$data = array(
    'person' => array(
        'name' => 'John Doe',
        'age' => 30,
        'city' => 'Canada'
    )
);

/* 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>John Doe</name>
        <age>30</age>
        <city>Canada</city>
    </user>
</root>

This example showcases a basic array containing person-related information. The arrayToXml function employs recursive logic to convert the array into XML, leveraging the SimpleXMLElement class. The resulting XML is then echoed. If you prefer to save the XML to a file, you can utilize the $xml->asXML('output.xml'); line in place of echo.

Thank you for reading this guide!

 
PHP

Comments (0)

Comment


Note: All Input Fields are required.