ItSolutionStuff.com

How to Convert Array to XML in PHP?

By Hardik Savani • May 14, 2024
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: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

šŸ“ŗ Subscribe on YouTube

We Are Recommending You

ā˜…

PHP array_merge() Function Example

Read Now →
ā˜…

How to Remove String Values in PHP Array?

Read Now →
ā˜…

How to Get First 10 Elements of Array in PHP?

Read Now →
ā˜…

How to Get First Word from String in PHP?

Read Now →
ā˜…

How to Install PHP XML Extension in Ubuntu?

Read Now →
ā˜…

Laravel 9 Generate Sitemap XML File Tutorial Example

Read Now →
ā˜…

How to Convert XML File to Array in PHP?

Read Now →
ā˜…

How to Read XML File in Laravel?

Read Now →
ā˜…

PHP CURL Post Request with Parameters Example

Read Now →
ā˜…

How to install Adminer with PHP Laravel?

Read Now →
ā˜…

How to Upload and Resize Image in PHP?

Read Now →
ā˜…

How to Create Zip Folder and Download in PHP?

Read Now →
ā˜…

PHP Paypal Payment Gateway Integration Example

Read Now →