How can an array be saved as an XML structure in PHP?
To save an array as an XML structure in PHP, you can use the SimpleXMLElement class to create an XML document from the array. You can loop through the array and add elements and attributes to the SimpleXMLElement object. Finally, you can save the XML structure to a file or output it as a string.
<?php
// Sample array
$data = array(
'name' => 'John Doe',
'age' => 30,
'email' => 'john.doe@example.com'
);
// Create a new XML document
$xml = new SimpleXMLElement('<data/>');
// Function to recursively convert array to XML
function array_to_xml($data, &$xml) {
foreach($data as $key => $value) {
if(is_array($value)) {
$subnode = $xml->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml->addChild("$key", htmlspecialchars("$value"));
}
}
}
// Call the function to convert array to XML
array_to_xml($data, $xml);
// Save XML to a file
$xml->asXML('data.xml');
?>