How can data be exported from a database in PHP to different file formats like XLS, CSV, or TXT?

To export data from a database in PHP to different file formats like XLS, CSV, or TXT, you can query the database to retrieve the data and then use PHP libraries like PHPExcel for XLS, fputcsv for CSV, or fwrite for TXT to write the data to the desired file format.

// Example code to export data from a MySQL database to CSV file

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

// Query to select data from database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Open file for writing
$file = fopen("data.csv", "w");

// Write column headers
$headers = array("Column1", "Column2", "Column3");
fputcsv($file, $headers);

// Write data rows
while($row = mysqli_fetch_assoc($result)){
    fputcsv($file, $row);
}

// Close file and database connection
fclose($file);
mysqli_close($connection);