工作中經常會有遇到導入/導出的需求,下面是常用的方法。
讀取CSV檔案,可以分頁讀取,設定讀取行數,起始行數即可。
導出CSV檔案,用兩種方法進行實作。
/**
* 讀取CSV檔案
* @param string $csv_file csv檔案路徑
* @param int $lines 讀取行數
* @param int $offset 起始行數
* @return array|bool
*/
public function read_csv_lines($csv_file = '', $lines = 0, $offset = 0)
{
if (!$fp = fopen($csv_file, 'r')) {
return false;
}
$i = $j = 0;
while (false !== ($line = fgets($fp))) {
if ($i++ < $offset) {
continue;
}
break;
$data = array();
while (($j++ < $lines) && !feof($fp)) {
$data[] = fgetcsv($fp);
fclose($fp);
return $data;
}
* 導出CSV檔案
* @param array $data 資料
* @param array $header_data 首行資料
* @param string $file_name 檔案名稱
* @return string
public function export_csv_1($data = [], $header_data = [], $file_name = '')
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file_name);
if (!empty($header_data)) {
echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","',$header_data).'"'."\n");
foreach ($data as $key => $value) {
$output = array();
$output[] = $value['id'];
$output[] = $value['name'];
echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","', $output)."\"\n");
public function export_csv_2($data = [], $header_data = [], $file_name = '')
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='.$file_name);
header('Cache-Control: max-age=0');
$fp = fopen('php://output', 'a');
foreach ($header_data as $key => $value) {
$header_data[$key] = iconv('utf-8', 'gbk', $value);
fputcsv($fp, $header_data);
$num = 0;
//每隔$limit行,重新整理一下輸出buffer,不要太大,也不要太小
$limit = 100000;
//逐行取出資料,不浪費記憶體
$count = count($data);
if ($count > 0) {
for ($i = 0; $i < $count; $i++) {
$num++;
//重新整理一下輸出buffer,防止由于資料過多造成問題
if ($limit == $num) {
ob_flush();
flush();
$num = 0;
}
$row = $data[$i];
foreach ($row as $key => $value) {
$row[$key] = iconv('utf-8', 'gbk', $value);
fputcsv($fp, $row);
Thanks ~