How can PHP be used to filter and select specific data from a MySQL database for inclusion in an XML output?

To filter and select specific data from a MySQL database for inclusion in an XML output using PHP, you can first establish a connection to the database, execute a query with the desired filters, fetch the results, and then format the data into an XML structure.

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

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Execute query to select specific data
$query = "SELECT column1, column2 FROM table WHERE condition";
$result = mysqli_query($connection, $query);

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

// Fetch and format results into XML
while ($row = mysqli_fetch_assoc($result)) {
    $item = $xml->addChild('item');
    $item->addChild('column1', $row['column1']);
    $item->addChild('column2', $row['column2']);
}

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

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