fputcsv
$ids = json_decode($_POST['jsonarray']); // array sent with ajax
$start = $_POST['start']; // date sent with ajax
$end = $_POST['end']; // date sent with ajax
$start_date = date('yyyy-mm-dd', strtotime($start)); // format dates to sql firendly
$end_date = date('yyyy-mm-dd', strtotime($end));
$toZip = array(); // Prepare array to files for zip
if(is_array($ids)) {
foreach ($ids as $key => $qr)
{
// Get labels first
// Here we prepare the first line in the .CSV file
$tb = $qr . '_labels';
$sql = $user_pdo->query("SELECT * FROM $tb");
$head_array = array('Log ID', 'Timestamp');
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
// This array is the first line in the .CSV file
$head_array[] = $row['label'];
}
// Get ready for looping through the database
$table = $qr . '_data';
$results = $user_pdo->prepare("SELECT * FROM $table WHERE timestamp BETWEEN :start_date AND :end_date;");
$results->bindParam(':start_date', $start_date, PDO::PARAM_STR);
$results->bindParam(':end_date', $$end_date, PDO::PARAM_STR);
$results->execute();
// Pick a filename and destination directory for the file
$filename = "temp/db_user_export_".time().".csv";
// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'w+');
// Write the spreadsheet column titles/labels
fputcsv($handle, $head_array);
// Write all the user records to the spreadsheet
foreach($results as $row)
{
// amount of rows is unknown
$rows = $row->rowCount();
$insert_array = array();
for ($i=0; $i<=$rows; $i++)
{
// function goes here
$insert_array[] = $row[$i];
}
fputcsv($handle, $insert_array);
}
// Finish writing the file
fclose($handle);
$toZip[] = $filename;
}
}
實施例僅輸出一次一條線。更改此:
for ($i=0; $i<=$rows; $i++)
{
// function goes here
$insert_array[] = $row[$i];
}
fputcsv($handle, $insert_array);
要這樣:
for ($i=0; $i<=$rows; $i++)
{
// function goes here
fputcsv($handle, $row[$i]);
}
'$ ids'的值是多少? 'var_dump($ ids);' – showdev
根據PHP.net的文檔,json_decode的返回值是「混合的」。有時json_decode會返回一個對象。 – SamA
什麼可能是你的文件沒有被寫入的問題是'$ filename =「temp/db_user_export _」中的'temp /'文件夾聲明。time()。「。csv」;' - 嘗試將它設置爲'$ filename =「db_user_export _」。time()。「。csv」;'用於測試目的。 –