duanjiangzhi6851 2014-05-04 06:16
浏览 44
已采纳

用php导出mysql表到csv(没有选择输出文件)

I am trying to export a MySQL table to a CSV file. 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.
I can't use the "SELECT... INTO OUTFILE" query as my provider does not want to give me the FILE privilege.
Any way I can wright the csv output to my provider's server with php instead of downloading it to my computer?

  • 写回答

1条回答 默认 最新

  • douken0530 2014-05-04 06:25
    关注

    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. 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.

    And that's it already.

    Some example code with the outdated Mysql client library you're using as PHP 5.5 code:

    $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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器