PHP
Converting PHP Array to Simple XML String
Generate a basic XML string from a PHP array, perfect for simple data exchange or creating XML feeds directly from your application's data for APIs or legacy systems.
<?php
function arrayToXml(array $data, string $rootNodeName = 'data', SimpleXMLElement $xml = null): string
{
if ($xml === null) {
$xml = new SimpleXMLElement('<' . $rootNodeName . '/>');
}
foreach ($data as $key => $value) {
if (is_numeric($key)) {
$key = 'item' . $key; // Or a more descriptive tag like 'product' or 'entry'
}
if (is_array($value)) {
arrayToXml($value, $key, $xml->addChild($key));
} else {
$xml->addChild($key, htmlspecialchars((string) $value));
}
}
return $xml->asXML();
}
$productData = [
'product' => [
'id' => 101,
'name' => 'Wireless Headphones',
'price' => 199.99,
'currency' => 'USD',
'features' => [
'bluetooth',
'noise_cancelling',
'long_battery_life',
],
'description' => 'High-quality wireless headphones with excellent sound and comfort.',
'stock' => 50,
'available' => true,
]
];
$xmlOutput = arrayToXml($productData, 'products');
echo $xmlOutput;
/* Expected XML Output (simplified, formatting for readability):
<?xml version="1.0"?>
<products>
<product>
<id>101</id>
<name>Wireless Headphones</name>
<price>199.99</price>
<currency>USD</currency>
<features>
<item0>bluetooth</item0>
<item1>noise_cancelling</item1>
<item2>long_battery_life</item2>
</features>
<description>High-quality wireless headphones with excellent sound and comfort.</description>
<stock>50</stock>
<available>1</available>
</product>
</products>
*/
How it works: This `arrayToXml` function recursively converts a PHP associative array into a SimpleXML object, which can then be output as an XML string. It handles nested arrays by creating child XML elements and properly escapes special characters in element values using `htmlspecialchars` to prevent XML invalidity. Numeric array keys are automatically converted to a default tag name (e.g., 'item0', 'item1') for valid XML structure. This is highly useful for generating XML data feeds, API responses, or configuration files from your application's PHP arrays.