Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert an array to SimpleXML in PHP?
In PHP, you can convert an array to SimpleXML using the array_walk_recursive() function combined with the SimpleXMLElement class. This approach transforms array keys into XML element names and array values into the element content.
Note: If you encounter "Class 'SimpleXMLElement' not found" error, install the required packages:
sudo apt-get install php-xml php-simplexml(Ubuntu/Debian)
yum install php-xml(CentOS/RHEL)
Basic Array to XML Conversion
Here's how to convert a simple array structure to XML using array_walk_recursive() ?
<?php
$array = array(
'name' => 'alex',
'empdept' => 'account',
'address' => array(
'city' => 'michigan'
),
);
// Create XML object with root element
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($array, array($xml, 'addChild'));
echo $xml->asXML();
?>
<?xml version="1.0"?> <root> <name>alex</name> <empdept>account</empdept> <city>michigan</city> </root>
Advanced Method with Custom Function
For better control over the XML structure, you can create a custom function ?
<?php
function arrayToXml($array, $xmlElement) {
foreach($array as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xmlElement->addChild("$key");
arrayToXml($value, $subnode);
} else {
arrayToXml($value, $xmlElement);
}
} else {
$xmlElement->addChild("$key", htmlspecialchars("$value"));
}
}
}
$array = array(
'employee' => array(
'name' => 'John Doe',
'position' => 'Developer',
'salary' => '50000'
)
);
$xml = new SimpleXMLElement('<company/>');
arrayToXml($array, $xml);
echo $xml->asXML();
?>
<?xml version="1.0"?> <company> <employee> <name>John Doe</name> <position>Developer</position> <salary>50000</salary> </employee> </company>
Key Differences
| Method | Structure Preservation | Complexity |
|---|---|---|
array_walk_recursive() |
Flattens nested arrays | Simple |
| Custom Function | Maintains hierarchy | More control |
Conclusion
Use array_walk_recursive() for simple conversions, but implement a custom recursive function when you need to preserve the array's hierarchical structure in the resulting XML.
