前端之家收集整理的这篇文章主要介绍了
通过PHP将查询结果导出为CSV,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我在一个名为$query的变量中存储了一个
查询.我想在结果
页面上创建一个名为“export as CSV”的小超
链接.我该怎么做呢?
$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";