来自 MySQL 的 CSV 文件,使用 PHP 和 OOP 方法(mysqli->connect 等) [英] CSV file from MySQL using PHP with a OOP aproach (mysqli->connect, etc.)
问题描述
我正在尝试使用 php 和 OOP 方法直接从 mysql 表创建一个 csv 文件.这是我的代码:
I'm trying to create a csv file direct from a mysql table using php with an OOP approach. Here is my code:
$mysqli = new mysqli($host, $user, $pass, $database);
// Checking connection.
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = 'SELECT * FROM table';
$result = $mysqli->query($query);
while ($row = $result->fetch_array()) {
$rows[] = $row;
}
$array = "";
foreach($rows as $row) {
$array .= "\"".$row["genus"].",".$row["species"]."\",";
}
$list = array($array);
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=export.csv');
$file = fopen("php://output","w");
foreach ($list as $line) {
fputcsv($file,explode(',',$line));
}
fclose($file);
// Free result set.
$result->close();
// Close connection.
$mysqli->close();
我的问题在于以下部分,在创建数组时:
My problem is with the following part, when creating the array:
$array = "";
foreach($rows as $row) {
$array .= "\"".$row["genus"].",".$row["species"]."\",";
}
因为当我做一个 print_r ($list);我没有收到预期的数组:数组 ( [0] => "homo,sapiens", [1] => "homo,erectus",[2] => "homo,ergaster", )
because when I do a print_r ($list); I don't receive the expected array: Array ( [0] => "homo,sapiens", [1] => "homo,erectus", [2] => "homo,ergaster", )
但是这个:数组 ( [0] => "homo,sapiens","homo,erectus","homo,ergaster", )
but this one: Array ( [0] => "homo,sapiens","homo,erectus","homo,ergaster", )
此外,当我手动创建数组时
and moreover when I create the array manually
$list = array("homo,sapiens","homo,erectus","homo,ergaster");
它工作得很好,我收到了正确的 csv 文件.
it works just fine and I receive the correct csv file.
如果有人能帮助我,向我解释我做错了什么以及我应该怎么做来修复代码,我将不胜感激.
I would appreciate if someone could help me, explain me what I'm doing wrong and what I should do to fix the code.
推荐答案
那是因为您将 $array
视为字符串,而不是数组.这应该有效:
That's because you're treating $array
as a string, not an array.
This should work:
$array = array();
foreach($rows as $row) {
$array[] = "\"".$row["genus"].",".$row["species"]."\",";
}
我认为您希望 $list = array($array);
行神奇地将逗号分隔的字符串转换为数组中的单个元素,但事实并非如此.
I think you're expecting the $list = array($array);
line to magically convert a comma separated string to individual elements in the array, but it doesn't.
这篇关于来自 MySQL 的 CSV 文件,使用 PHP 和 OOP 方法(mysqli->connect 等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!