To convert an array to XML in PHP, you can use the SimpleXMLElement
class.
Here’s an example of how to convert an array to an XML string:
$array = [
'item' => [
[
'name' => 'apple',
'price' => 0.5,
],
[
'name' => 'banana',
'price' => 0.25,
],
],
];
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($array, array ($xml, 'addChild'));
$xml_string = $xml->asXML();
// $xml_string is now:
// '<root><item><name>apple</name><price>0.5</price></item><item><name>banana</name><price>0.25</price></item></root>'
You can also use the array_to_xml
function from this library: https://github.com/spatie/array-to-xml
Here’s an example of how to use the array_to_xml
function:
$array = [
'item' => [
[
'name' => 'apple',
'price' => 0.5,
],
[
'name' => 'banana',
'price' => 0.25,
],
],
];
$xml = array_to_xml($array);
$xml_string = $xml->asXML();
// $xml_string is now:
// '<root><item><name>apple</name><price>0.5</price></item><item><name>banana</name><price>0.25</price></item></root>'
You can then use the $xml_string
variable to save the XML string to a file, or send it as an HTTP response, or do any other operation you need.
For example, to save the XML string to a file, you can use the file_put_contents
function:
$filename = 'items.xml';
file_put_contents($filename, $xml_string);
To send the XML string as an HTTP response, you can use the header
function and the echo
statement:
header('Content-Type: application/xml');
echo $xml_string;
exit;
Note that the SimpleXMLElement
class and the array_to_xml
function only support a limited subset of the XML specification. If you need to generate more complex or custom XML documents, you can use a different library such as DOM or XMLWriter.