假设我在一个名为$ query的变量中存储了一个查询。我想在结果页面上创建一个名为“export as CSV”的小超链接。我该怎么做?
答案 0 :(得分:11)
$query = "SELECT * FROM table_name";
$export = mysql_query ($query ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
答案 1 :(得分:5)
嗯?
<a href="yourexport.php" title="export as csv">Export as CSV</a>
如果您正在寻找可以执行此操作的脚本:
$myArray = array ();
$fp = fopen('export.csv', 'w');
foreach ($myArray as $line) {
fputcsv($fp, split(',', $line));
}
fclose($fp);
答案 2 :(得分:3)
CSV =逗号分隔值=用逗号分隔您的值
你必须逐行回显/打印结果,用逗号(,)分隔。
我假设您的$ query是查询的结果集,它是一个关联数组:
while($query = mysql_fetch_assoc($rs)) {
// loop till the end of records
echo $query["field1"] . "," . $query["field2"] . "," . $query["field3"] . "\r\n";
}
其中$ rs是资源句柄。
要让浏览器弹出下载框,您必须在文件开头设置标题(假设您的文件名为export.csv):
header("Expires: 0");
header("Cache-control: private");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=export.csv");
就是这样!
P.S。此方法不会在服务器中保留物理文件。如果您打算在服务器中生成文件,请使用传统的fopen和fwrite函数。