How can PHP be used to output data from a MySQL query in XML format?

To output data from a MySQL query in XML format using PHP, you can fetch the data from the database using MySQL queries and then format the results into an XML structure. This can be achieved by looping through the query results and constructing an XML document with the data.

<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Perform a query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Create XML document
$xml = new SimpleXMLElement('<data/>');

// Loop through query results and add to XML
while ($row = mysqli_fetch_assoc($result)) {
    $item = $xml->addChild('item');
    foreach ($row as $key => $value) {
        $item->addChild($key, $value);
    }
}

// Output XML
header('Content-type: text/xml');
echo $xml->asXML();

// Close connection
mysqli_close($connection);
?>