Home  >  Article  >  Backend Development  >  PHP exports tens of thousands of data

PHP exports tens of thousands of data

不言
不言Original
2018-04-13 09:27:442490browse

This article introduces the content of PHP exporting tens of thousands of data. Friends in need can refer to it

php uses buffering to achieve dynamic output (ob_flush)

The following is an example of exporting tens of thousands of pieces of data from PHP. The above code is:

// 导出测试
    function explode() {
    	ob_end_clean();
    	header("Content-type:text/csv");
		header('Content-Disposition: attachment;filename=test_' . time() . '.csv');


		$fp = fopen('php://output', 'a');
		// 输出Excel列头信息
		$head = array('平台', '名称', '本金','时间');
		// foreach($head as $i => $v) {
		//     // CSV的Excel支持GBK编码,一定要转换,否则乱码
		//     $head[$i] = iconv('utf-8', 'GB2312//IGNORE', $v);
		// }
		fputcsv($fp, $head);

		$limit = 1000;
		$count = 1;
		$sql = 'select * from assets limit 0,1000';
		$rows = Db::table('表名')->query($sql);
		while(count($rows)>0 && $count<21) {
			$offset = $count*$limit;
		    $count++;

		    foreach ($rows as $key => $row) {
		    	if($key%2000 == 0) {
		    		if(ob_get_level()>0){
    					ob_flush() ;
		    		}
		    	}

		    	$val = array($row[&#39;platform&#39;],$row[&#39;name&#39;],$row[&#39;principal&#39;],$row[&#39;create_time&#39;]);

		    	// foreach($val as $k => $v) {
		     //        $val[$k] = iconv(&#39;utf-8&#39;, &#39;GB2312//IGNORE&#39;, $v);
		     //    }

		        fputcsv($fp, $val);
		    }

		    $sql = "select * from assets limit {$offset},{$limit}";
			$rows = Db::table(&#39;表名&#39;)->query($sql);
		}
	}

Related recommendations:

php methods for exporting HTML content files in Excel

PHP exports csv instance sharing with leading 0

Native implementation method of PHP exporting and downloading excel

The above is the detailed content of PHP exports tens of thousands of data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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