PHP代码将MySQL查询转换为CSV [英] PHP code to convert a MySQL query to CSV

查看:159
本文介绍了PHP代码将MySQL查询转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中将MySQL查询转换为CSV的最有效方式是什么?

What is the most efficient way to convert a MySQL query to CSV in PHP please?

最好避免使用临时文件,因为这会降低可移植性并设置需要的文件系统权限。)

It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).

CSV还应包括一行字段名称。

The CSV should also include one top line of field names.

推荐答案

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;

此处的文档位于: http://dev.mysql.com/ doc / refman / 5.0 / en / select.html

(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)

或:

$select = "SELECT * FROM table_name";

$export = mysql_query ( $select ) 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";

这篇关于PHP代码将MySQL查询转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆