PHP 将MySQL查询结果导出为CSV

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 将MySQL查询结果导出为CSV相关的知识,希望对你有一定的参考价值。

// Export to CSV
if($_GET['action'] == 'export') {
	
	$rsSearchResults = mysql_query($sql, $db) or die(mysql_error());
	
	$out = '';
	$fields = mysql_list_fields('database','table',$db);
	$columns = mysql_num_fields($fields);
	
	// Put the name of all fields
	for ($i = 0; $i < $columns; $i++) {
	$l=mysql_field_name($fields, $i);
	$out .= '"'.$l.'",';
	}
	$out .="\n";
	
	// Add all values in the table
	while ($l = mysql_fetch_array($rsSearchResults)) {
	for ($i = 0; $i < $columns; $i++) {
	$out .='"'.$l["$i"].'",';
	}
	$out .="\n";
	}
	// Output to browser with appropriate mime type, you choose ;)
	header("Content-type: text/x-csv");
	//header("Content-type: text/csv");
	//header("Content-type: application/csv");
	header("Content-Disposition: attachment; filename=search_results.csv");
	echo $out;
	exit;
}

以上是关于PHP 将MySQL查询结果导出为CSV的主要内容,如果未能解决你的问题,请参考以下文章