How to Convert Array to XML in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- PHP array_merge() Function Example
- How to Remove String Values in PHP Array?
- How to Get First 10 Elements of Array in PHP?
- How to Get First Word from String in PHP?
- How to Install PHP XML Extension in Ubuntu?
- Laravel 9 Generate Sitemap XML File Tutorial Example
- How to Convert XML File to Array in PHP?
- How to Read XML File in Laravel?
- PHP CURL Post Request with Parameters Example
- How to install Adminer with PHP Laravel?
- How to Upload and Resize Image in PHP?
- How to Create Zip Folder and Download in PHP?
- PHP Paypal Payment Gateway Integration Example