What is the common issue faced when exporting an SQL table to a TXT file using PHP?
One common issue faced when exporting an SQL table to a TXT file using PHP is the encoding problem, where special characters may not be displayed correctly in the TXT file. To solve this issue, you can set the character encoding to UTF-8 before writing the data to the TXT file.
// Set character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Export SQL table to TXT file
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$file = fopen("export.txt", "w");
while($row = $result->fetch_assoc()) {
fwrite($file, implode("\t", $row) . "\n");
}
fclose($file);
} else {
echo "0 results";
}
$conn->close();