Last updated on December 4, 2023
In PHP, you can convert an array to XML using various methods. One common approach is using the SimpleXMLElement
class to create an XML structure and then populate it with data from the array. Here’s an example
<?php
// Sample array
$data = array(
'book' => array(
'title' => 'The Great Gatsby',
'author' => 'F. Scott Fitzgerald',
'published_year' => 1925
)
);
// Create a new XML element
$xml = new SimpleXMLElement('<root></root>');
// Function to convert array to XML
function arrayToXml($data, &$xml) {
foreach ($data as $key => $value) {
// If the value is an array, create a child node and call the function recursively
if (is_array($value)) {
$subNode = $xml->addChild($key);
arrayToXml($value, $subNode);
} else {
// If the value is not an array, add it as a child element
$xml->addChild($key, htmlspecialchars($value));
}
}
}
// Call the function to convert the array to XML
arrayToXml($data, $xml);
// Format the XML output
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->formatOutput = true;
echo $dom->saveXML();
?>
This example takes a sample array ($data
) representing a book and converts it into an XML structure using SimpleXMLElement
. The arrayToXml
function iterates through the array and creates XML nodes accordingly. If the value is an array, it creates child nodes recursively.
Remember to handle special characters properly by using htmlspecialchars
when adding values to the XML to prevent XML syntax errors.
Adjust the array structure and keys to match your data. This method is suitable for simple arrays, but for more complex or nested arrays, you might need to tailor the conversion process accordingly.