假设我在一个名为 $query 的变量中存储了一个查询。我想在结果页面上创建名为“导出为 CSV”的小型超链接。我该怎么做呢?
问问题
11067 次
3 回答
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";
于 2009-10-29T08:24:56.123 回答
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);
于 2009-10-29T08:23:15.387 回答
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 是资源句柄。
要让浏览器弹出一个下载框,你必须在文件的开头设置header(假设你的文件名是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");
就是这样!
ps 此方法不会在服务器中留下物理文件。如果您打算在服务器中生成文件,请使用传统的 fopen 和 fwrite 函数。
于 2009-10-29T08:23:53.433 回答