简体   繁体   English

用php将mysql表导出到csv(不选择到outfile中)

[英]export mysql table to csv with php (no select into outfile)

I am trying to export a MySQL table to a CSV file. 我正在尝试将MySQL表导出到CSV文件。 The code I have works fine: 我的代码工作正常:

$result = mysql_query('SELECT * FROM `TABLE`'); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
$headers[] = mysql_field_name($result , $i); 
} 
$fp = fopen('php://output', 'w'); 
if ($fp && $result) 
{     
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');    
header('Expires: 0');
fputcsv($fp, $headers); 
while ($row = mysql_fetch_row($result)) 
{
fputcsv($fp, array_values($row)); 
}
die; 
}

However I would like to have the csv file uploaded automatically to my web host server instead of being downloaded to my computer. 但是,我想将csv文件自动上传到我的Web主机服务器,而不是下载到我的计算机。
I can't use the "SELECT... INTO OUTFILE" query as my provider does not want to give me the FILE privilege. 我不能使用“ SELECT ... INTO OUTFILE”查询,因为我的提供者不想给我FILE特权。
Any way I can wright the csv output to my provider's server with php instead of downloading it to my computer? 以任何方式我可以使用php将csv输出输出到提供程序的服务器上,而不是将其下载到计算机上?

If you want to store on the server instead of offering the data to the browser, you need to do some changes with your (otherwise fine working) code: 如果要存储在服务器上而不是将数据提供给浏览器,则需要对您的(否则可以正常工作的)代码进行一些更改:

  1. The header function is not needed any longer. header功能不再需要。 Remove those. 删除那些。
  2. You don't want to output into php://output any longer, but instead use the path to the file where you want to store the CSV data into. 您不想再输出到php://output ,而是使用要将CSV数据存储到的文件的路径。

And that's it already. 就是这样。

Some example code with the outdated Mysql client library you're using as PHP 5.5 code: 您将一些过时的Mysql客户端库用作PHP 5.5代码的示例代码:

$file_name = '/path/to/file/on/server.csv';
$sql       = 'SELECT * FROM `TABLE`';

$query = function ($statement) {
    if (!$result = mysql_query($statement)) throw new RuntimeException(
        sprintf('Statement %s failed: #%s %s', var_export($statement, true), mysql_errno(), mysql_error())
    );
    return $result;
};

$names = function ($result) {
    for ($names = [], $i = mysql_num_fields($result); $i; $i--)
        $names[] = mysql_field_name($result, $i);
    return $names;
};

$rows = function($result) {while ($row = mysql_fetch_row($result)) yield $row;};

$result = $query($sql);

$lines = new AppendIterator();
$lines->append(new ArrayIterator([$names($result)]));
$lines->append($rows($result));

$csv = new SplFileObject($file_name, 'w');
foreach ($lines as $fields) {
    $csv->fputcsv($fields);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM