How can PHP be used to sort and display only the latest 3 entries from a MySQL database in an XML file?

To sort and display only the latest 3 entries from a MySQL database in an XML file using PHP, you can first query the database to retrieve the latest entries, sort them by date in descending order, limit the results to 3 entries, and then format the data into an XML file.

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

// Query to retrieve the latest 3 entries sorted by date in descending order
$query = "SELECT * FROM table_name ORDER BY date_column DESC LIMIT 3";
$result = mysqli_query($connection, $query);

// Create XML file
$xml = new SimpleXMLElement('<entries></entries>');

// Loop through the retrieved entries and add them to the XML file
while($row = mysqli_fetch_assoc($result)) {
    $entry = $xml->addChild('entry');
    foreach($row as $key => $value) {
        $entry->addChild($key, $value);
    }
}

// Save the XML file
$xml->asXML('latest_entries.xml');

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