What are the best practices for ensuring data integrity when exporting data from a MySQL database to a CSV file using PHP?

When exporting data from a MySQL database to a CSV file using PHP, it is important to ensure data integrity by properly handling special characters, formatting, and encoding. One way to achieve this is by using PHP's built-in functions like `fputcsv` to properly format the data before writing it to the CSV file. Additionally, it is recommended to sanitize the data to prevent SQL injection attacks and other security vulnerabilities.

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

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

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

// Fetch data from MySQL database
$result = $mysqli->query("SELECT * FROM table");

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

// Write data rows to CSV file
while ($row = $result->fetch_assoc()) {
    fputcsv($file, $row);
}

// Close file handle
fclose($file);

// Close MySQL connection
$mysqli->close();
?>