What is the process for outputting MySQL result tables in TXT format using PHP?
To output MySQL result tables in TXT format using PHP, you can fetch the data from the database and then loop through the results to write them into a text file. You can use functions like fopen, fwrite, and fclose to create and write to the text file.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if ($connection === false) {
die("Error: Could not connect. " . mysqli_connect_error());
}
// Query to fetch data from MySQL
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Open a file for writing
$fp = fopen('output.txt', 'w');
// Loop through the results and write to the file
while ($row = mysqli_fetch_assoc($result)) {
fwrite($fp, implode("\t", $row) . "\n");
}
// Close the file and database connection
fclose($fp);
mysqli_close($connection);
echo "Data exported to output.txt successfully!";
?>
Keywords
Related Questions
- What function can be used to retrieve HTTP request headers in PHP?
- What is the significance of the __sleep and __wakeup methods in PHP when storing instances in sessions?
- What are the potential pitfalls of using the mail() function in PHP for email sending, especially when dealing with special characters like umlauts?