使用PHP列将数据库导出为CSV

时间:2014-10-09 15:31:22

标签: php csv

这是我的php脚本,用于将数据库信息导出为CSV文件。

我没有到达任何结构来正确整理我的CSV文件中的信息。

例如,将所有名称放在名称列中,将所有电子邮件放在电子邮件列中......等等

include_once('conf.php');
include_once('BDD.php');

header('charset=UTF-8');
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");


$bdd = new BDD($conf['bddhost'], $conf['bddport'], $conf['bddname'], $conf['bdduser'], $conf['bddpass']);
$sql = "SELECT * FROM user";
$qry = $bdd->prepare($sql);

// Execute the statement
$qry->execute();

$data = fopen('/tmp/db_user_export_".time().".csv', 'w');


while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
    // Export every row to a file
    fputcsv($data, $row);
    echo ''.$row['prenom'].' '
                .$row['nom'].' '
                .$row['email'].' '
                .$row['cp'].' '
                .$row['information'].'  
                ';
}
fclose($data);

3 个答案:

答案 0 :(得分:0)

您在使用echo

创建文件时不想使用fputcsv
while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
    // Export every row to a file
    fputcsv($data, $row);
}

// reset the file pointer to the beginning of the file
rewind($data);

// dump the csv file and stop the script
fpassthru($data);
exit;

答案 1 :(得分:0)

语法错误:

$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
              ^--                  ^--      ^--  ^---

您正在混合字符串引用样式,因此您的文件名实际上将包含字符".t等等。

尝试

$data = fopen('/tmp/db_user_export_' .time() .'.csv', 'w');
                                   ^----------^---

代替。请注意" - >的更改'

答案 2 :(得分:-2)

由于您的结果是数组,这可能会帮助您: Convert php array to csv string

if(!function_exists('str_putcsv'))
{
    function str_putcsv($input, $delimiter = ',', $enclosure = '"')
    {
        // Open a memory "file" for read/write...
        $fp = fopen('php://temp', 'r+');
        // ... write the $input array to the "file" using fputcsv()...
        fputcsv($fp, $input, $delimiter, $enclosure);
        // ... rewind the "file" so we can read what we just wrote...
        rewind($fp);
        // ... read the entire line into a variable...
        $data = fread($fp, 1048576);
        // ... close the "file"...
        fclose($fp);
        // ... and return the $data to the caller, with the trailing newline from fgets() removed.
        return rtrim($data, "\n");
    }
 }

 $csvString = '';
 foreach ($list as $fields) {
     $csvString .= str_putcsv($fp, $fields);
 }

关于GitHub的更多信息,这是由@johanmeiring创建的函数。