What best practices should be followed when exporting data from a database to a text file in PHP?

When exporting data from a database to a text file in PHP, it is important to properly handle encoding, formatting, and security to ensure the integrity and safety of the data. Use PHP's file handling functions to open a file for writing, fetch the data from the database, format it as needed, and then write it to the file securely.

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

// Open a file for writing
$file = fopen("exported_data.txt", "w");

// Fetch data from the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Write data to the file
while($row = mysqli_fetch_assoc($result)) {
    fwrite($file, implode(",", $row) . "\n");
}

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