Home > Backend Development > PHP Tutorial > How to export csv file in php (code example)

How to export csv file in php (code example)

不言
Release: 2023-04-04 06:14:01
Original
5142 people have browsed it

The content of this article is about how to export csv files (code examples) in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

/**  如果大量数据导出 支持分页写入
	 * [DownloadDate 公共导出csv]
	 * @param  string                   $name   [文件名称]
	 * @param  array                   $header [表头]
	 * @param  array                    $data   [数据集]
	 * @param                      $is_header   [真 假 是否取表头 解决循环写入问题]
	 * @return array             name[文件名称]   filePath[文件路径]                               
	 */
	public static function DownloadData($name='',$header=array(),$data=array(),$is_header=true){
      	set_time_limit(0);
      	ini_set('memory_limit','2048M'); 
      	header("Content-type:application/vnd.ms-excel");
      	header("content-Disposition:filename=downloaded.pdf ");
      	try {
      		if (!$name || !$data) {
      			throw new BadRequestHttpException('参数不可为空');
      		}
	      	$filePath = "./temp/download/{$name}.csv";
	      	$header = implode(",",$header);
	      	$header = iconv('UTF-8', 'GBK//IGNORE', $header);
	      	$header = explode(",", $header);
	      	$fp = fopen($filePath, 'a+');   
	      	if (!empty($header) && is_array($header) && $is_header) {
	      		fputcsv($fp, $header);
	      	}
	      	foreach ($data as $row) {
	      		$str = implode("@@@@",$row);
	      		$str = iconv('UTF-8', 'GBK//IGNORE', $str);
	      		$str = str_replace(",","|",$str);
	      		$row = explode("@@@@", $str);
	      		fputcsv($fp, $row);
	      	}
	      	unset($data);  
	      	if(ob_get_level()>0){
	      		ob_flush();
	      	}  
	      	flush(); 	
      	} catch (Exception $e) {
      		 throw new BadRequestHttpException($e->getMessage());//抛出异常
      	}
      	return [
      	'filePath'=>ltrim($filePath,"./"),
      	'name'=>$name.'.csv',
      	];
 	}
Copy after login

Related recommendations:

php export csv file: specify encoding export and csv file import and export class

php implements CSV file import and export,

The above is the detailed content of How to export csv file in php (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template