Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP将大数据导出到CSV_Php_Sql_Csv_Export To Csv - Fatal编程技术网

使用PHP将大数据导出到CSV

使用PHP将大数据导出到CSV,php,sql,csv,export-to-csv,Php,Sql,Csv,Export To Csv,我正在尝试使用PHP将一些数据导出到CSV 我的代码: function download_send_headers($filename) { // disable caching $now = gmdate("D, d M Y H:i:s"); header("Expires: Tue, 03 Jul 2001 06:00:00 GMT"); header("Cache-Control: max-age=0, no-cache, must-revalidate,

我正在尝试使用PHP将一些数据导出到CSV

我的代码:

function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

$givenTerm = $_POST['TextBoxList'];

$sql_query = "select * from some_table where key=".$givenTerm;
$result = sqlsrv_query($conn,$sql_query);
$r1 = array();
$file = fopen("php://output", 'w');
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)){
    $valuesArray=array();
    foreach($row as $name => $value)
    {
        $valuesArray[]=$value;
    }
    fputcsv($file,$valuesArray);
}
fclose($file);
download_send_headers("data_export_" . date("Y-m-d") . ".csv");

die();
在这里,我从另一个页面中的表单接收一个搜索值,然后根据它触发一个查询。对于较小的数据集(最多100个),该代码运行良好。但是当结果中的行数更多时(大约600-700行),代码就会崩溃。请告诉我如何解决这个问题


另外,我正在使用Sql Server 2012作为数据库

您也可以逐行获取结果并直接输出每一行,而不是先在单个数组中获取所有结果然后再输出。
这样,您就不需要大量内存来容纳整个数组。

您可能需要在php设置中增加
max\u execution\u time
memory\u limit
;循环浏览您的记录,将每个记录直接转换为csv,然后直接输出。。。。更快,使用更少的内存如果您使用的是SQL server,为什么不从那里导出CSV?@MarkBaker我也使用过这种方法。但是结果是一样的。@shanal-你可以使用ini_set()增加特定脚本的内存-这取决于你的主机:许多ISP禁用了这个功能,尽管我已经根据你的建议修改了我的代码。但问题依然存在。