我想从我的数据库中使用php中提取数据并将其导出到可下载的CSV文件中,该文件可以用excel打开。我能够做到这一点,当我使用MySQL,但是,许多人建议在我的代码中不包括mysql语法,因为它被弃用,而应该使用mysqli。我改变了我的代码,但现在我的代码无法正常工作。有谁知道这是为什么?PHP不能创建可下载的CSV文件
MySQL版本(工作版本)`
mysql_connect('localhost', 'xxxxx', 'xxxxx') or die('connect');
mysql_select_db('db') or die('select');
$result = mysql_query('SELECT * bodyshops_master_network') or die('query');
if(mysql_num_rows($result) == 0)
{
die('no data');
}
$fh = tmpfile() or die('tmpfile');
$cols = array_keys(mysql_fetch_assoc($result));
fputcsv($fh, $cols);
mysql_data_seek($result, 0); // set result row pointer back to first row
while($row = mysql_fetch_assoc($result))
{
fputcsv($fh, $row);
}
rewind($fh);
$text = fread($fh, 999999);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="download.csv"');
header('Content-Length: ' . strlen($text));
echo $text;
exit;
mysqli的版本(不工作):
$mysqli = new mysqli("localhost", "xxxxx", "xxxxx", "db");
if (mysqli_connect_errno())
{
printf("Connect failed: ", mysqli_connect_error());
exit();
} else
{
$result = "SELECT * FROM bodyshops_master_network";
if(mysqli_num_rows($result) == 0)
{
die('no data');
}
$fh = tmpfile() or die('tmpfile');
$cols = array_keys($result->fetch_assoc());
fputcsv($fh, $cols);
$result->data_seek(0); // set result row pointer back to first row
while($row = $result->fetch_assoc())
{
fputcsv($fh, $row);
}
rewind($fh);
$text = fread($fh, 999999);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="download.csv"');
header('Content-Length: ' . strlen($text));
echo $text;
exit;
我已经注释掉了标题调用,并且当我运行我的代码时什么也没有发生,即没有数据显示 – user3009232
也检查您的服务器日志。除非你忘记粘贴上面的代码,否则你的代码在结尾处缺少一个}(关闭else if(mysqli_connect_errno())。 –