CRM和数据平台
PHP 和 MySQL:将查询导出到制表符分隔文件或 CSV 文件
这个周末,我想建一个 PHP 可以备份任何内容的页面 MySQL的 查询或表放入制表符分隔文件中。 网上的大多数示例都对列进行了硬编码。
就我而言,我希望列是动态的,因此我必须首先循环遍历所有表字段名称以构建具有列名称的标题行,然后循环遍历剩余数据行的所有记录。 我还设置了标头,以便浏览器将以文件类型 (txt) 启动文件下载,并带有文件日期和时间戳的名称。
在 PHP 中从 MySQL 制表符分隔导出
<?php
$today = date("YmdHi");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$today."_Backup.txt\"");
$conn = new mysqli("hostname", "username", "password", "database_name"); // Replace with your database credentials
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM `mytable` ORDER BY `myorder`";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$fields = $result->fetch_fields();
// Prepare the header row
$header = [];
foreach ($fields as $field) {
$header[] = $field->name;
}
$data = implode("\t", $header) . "\n";
// Fetch and process the data rows
while ($row = $result->fetch_assoc()) {
$rowValues = [];
foreach ($fields as $field) {
$rowValues[] = $row[$field->name];
}
$data .= implode("\t", $rowValues) . "\n";
}
// Output the data
echo $data;
} else {
echo "No data found";
}
// Close the database connection
$conn->close();
?>
让我们逐步浏览一下代码,并对每个部分进行解释:
<?php
// Get the current date and time in a specific format
$today = date("YmdHi");
// Set HTTP headers for file download
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$today."_Backup.txt\"");
// Create a MySQL database connection
$conn = new mysqli("hostname", "username", "password", "database_name"); // Replace with your database credentials
// Check if the database connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
- 我们以“YmdHi”格式生成当前日期和时间并将其存储在
$today
变量。 - HTTP 标头设置为指定应将内容视为八位字节流(二进制数据)并触发具有指定文件名的文件下载。
- 使用该扩展,我们创建一个 MySQL 数据库连接,用您的实际数据库凭据替换占位符。
- 我们检查数据库连接是否成功。 如果出现错误,我们将终止脚本并显示错误消息。
// Define the SQL query to select data from the `mytable` table
$query = "SELECT * FROM `mytable` ORDER BY `myorder`";
// Execute the SQL query
$result = $conn->query($query);
// Check if there are any rows returned
if ($result->num_rows > 0) {
// Fetch the field (column) names
$fields = $result->fetch_fields();
// Prepare the header row for the export file
$header = [];
foreach ($fields as $field) {
$header[] = $field->name;
}
$data = implode("\t", $header) . "\n";
- 我们定义 SQL 查询来选择所有数据
mytable
表,按顺序排序myorder
列。 - 执行查询,并将结果存储在
$result
变量。 - 我们通过检查是否有任何行返回
num_rows
结果对象的属性。 - 我们使用
fetch_fields()
检索字段(列)名称并将它们存储在$fields
数组。 - 导出文件的标题行是通过循环字段名称并将它们与制表符连接起来准备的。
// Fetch and process the data rows
while ($row = $result->fetch_assoc()) {
$rowValues = [];
foreach ($fields as $field) {
$rowValues[] = $row[$field->name];
}
$data .= implode("\t", $rowValues) . "\n";
}
- 我们使用一个
while
循环从结果集中获取每个数据行fetch_assoc()
. - 在循环内,我们通过迭代字段并收集相应的数据来准备每行的值。
- 每行的值都用制表符连接起来以创建制表符分隔的行,并将该行添加到
$data
变量。
// Output the data to the browser
echo $data;
} else {
// If no data is found, display a message
echo "No data found";
}
// Close the MySQL database connection
$conn->close();
?>
- 如果找到数据(检查
num_rows
),我们回显连接的数据,这是导出文件的内容。 这会触发用户浏览器中的文件下载。 - 如果未找到数据,我们会显示一条消息,指示没有可用数据。
- 我们使用以下命令关闭 MySQL 数据库连接
$conn->close()
以释放资源。
此代码有效地将数据从 MySQL 数据库表导出到制表符分隔的文本文件中,并处理各种情况,例如数据库连接错误和空结果集。
在 PHP 中从 MySQL 导出逗号分隔值
我可以修改代码以将数据导出为 CSV 文件。 以下是针对 CSV 导出进行更新的代码:
<?php
// Get the current date and time in a specific format
$today = date("YmdHi");
// Set HTTP headers for file download
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"".$today."_Backup.csv\"");
// Create a MySQL database connection
$conn = new mysqli("hostname", "username", "password", "database_name"); // Replace with your database credentials
// Check if the database connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Define the SQL query to select data from the `mytable` table
$query = "SELECT * FROM `mytable` ORDER BY `myorder`";
// Execute the SQL query
$result = $conn->query($query);
// Check if there are any rows returned
if ($result->num_rows > 0) {
// Prepare the output file handle for writing
$output = fopen('php://output', 'w');
// Fetch and process the data rows
while ($row = $result->fetch_assoc()) {
// Output each row as a CSV line
fputcsv($output, $row);
}
// Close the output file handle
fclose($output);
} else {
// If no data is found, display a message
echo "No data found";
}
// Close the MySQL database connection
$conn->close();
?>
在这个修改后的代码中:
- HTTP 响应的标头已更新以指定
text/csv
内容类型,文件名具有“.csv”扩展名。 - 我们不使用手动创建 CSV 内容,而是使用
fputcsv
函数将 MySQL 结果集中的每一行输出为 CSV 行。 此函数为您处理 CSV 格式,包括处理特殊字符以及在必要时用双引号将字段括起来。 - 我们使用打开输出文件句柄
fopen
以“php://output”作为文件名。 这允许我们直接写入 HTTP 响应输出流。 - 该代码的结构可以有效地处理 CSV 导出,并在完成后关闭文件句柄。
此代码将从 MySQL 表中将数据导出为 CSV 文件,使用户可以轻松在 Excel 等电子表格应用程序中打开和使用。 不要忘记用您自己的数据库凭据替换数据库凭据。