2014-10-09 90 views
-1

这里是我的php脚本,用于将数据库信息导出到CSV文件。将数据库导出为带有列的CSV PHP

我没有达到把任何结构正确整理我的信息在我的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); 
+0

你的问题是什么?我意识到存在语言障碍,但很难理解你要问什么或者你的代码如何工作。 – David 2014-10-09 15:38:21

+0

'CSV - “逗号分隔值”'...你的逗号在哪里?你的报价在哪里?问题是什么? – charlietfl 2014-10-09 15:38:29

+0

您可能想要激活错误('error_reporting(E_ALL); ini_set('display_errors','On');')并检查应该返回所写字符串长度的fputcsv输出。也许试着去掉header()函数来帮助调试。也许这是/ tmp上的写入权限 – Asenar 2014-10-09 15:39:43

回答

-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创建。

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; 
0

语法错误的文件:

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

你混合串引用样式,让你的文件名是从字面上去包含字符".t等等。

尝试

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

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