下载csv但使用逗号的行是空白的

时间:2017-08-27 07:19:41

标签: php mysql

我知道这些代码确实有效但数据库中的某些行有值,逗号这些行的下载空白。对此有什么解决方法?

这是我的php

<?php

require_once('config.php');

$y = $_REQUEST['y'];
$m = $_REQUEST['m'];
$date = "$y-$m";
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Data-Backup-' . $date . '.csv');
$select_table = mysql_query("SELECT * FROM records WHERE DATE_FORMAT(data_submitted, '%Y-%m') = '$date'  ORDER BY ID DESC");
$rows = mysql_fetch_assoc($select_table);

if ($rows) {
    getcsv(array_keys($rows));
}

while ($rows) {
    getcsv($rows);
    $rows = mysql_fetch_assoc($select_table);
}

function getcsv($no_of_field_names)
{
    $separate = '';
    foreach ($no_of_field_names as $field_name) {
        if (preg_match('/\\r|\\n|,|"/', $field_name)) {
            $field_name = '' . str_replace('', $field_name) . '';
        }
        echo $separate . $field_name;
        $separate = ',';
    }
    echo "\r\n";
}

?>

1 个答案:

答案 0 :(得分:1)

您可以使用fputcsv

$output = fopen('php://output', 'w');

$count = 0;
while($row = mysql_fetch_assoc($select_table)) {
    if ($count == 0) {
        // header
        fputcsv($output, array_keys($row));
    }

    fputcsv($output, array_values($row));

    $count++;
}

fpassthru($output);