使用php下载csv问题

时间:2014-03-30 23:11:48

标签: php csv

我正在尝试创建一个CSV文件,到目前为止,我的csv文件已下载,但它是空白的。

<?php
include('connect.php');

//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');

// Gets users information of who's logged in
$query = "SELECT * FROM expenses";
$result = mysqli_query($db_connection, $query);

while ($dbRow = mysqli_fetch_array($result))
{
    $id = $dbRow["id"];
    $user_id = $dbRow["user_id"];
    $amount = $dbRow["amount"];
    $currency = $dbRow["currency"];
    $type = $dbRow["type"];
    $description = $dbRow["description"];
    $project_id = $dbRow["project_id"];
    $submission = $dbRow["submission"];
    $status = $dbRow["status"];
}

if ($rows)
{
    getcsv(array_keys($rows));
}
while($rows)
{
    getcsv($rows);
    $rows = mysqli_fetch_assoc($query);
}

// get total number of fields present in the database
function getcsv($no_of_field_names)
{
    $separate = '';


// do the action for all field names as field name
    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;

//sepearte with the comma
        $separate = ',';
    }

//make new row and line
    echo "\r\n";
}
?>

1 个答案:

答案 0 :(得分:1)

<?php
include('connect.php');

//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');

// Gets users information of who's logged in
$query = "SELECT * FROM expenses";
$result = mysqli_query($db_connection, $query);

$first = true;
while ($dbRow = mysqli_fetch_array($result, MYSQL_ASSOC))
{
  if($first){
     $first = false;
     echo implode(',', array_keys($dbRow));
     echo "\r\n";
  }
  echo implode(',', $dbRow);
  echo "\r\n";
}
?>