2014-10-09 87 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'); 
            ^----------^--- 

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