小编典典

PHP代码将MySQL查询转换为CSV

mysql

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

最好避免使用临时文件,因为这会降低可移植性(需要目录路径和设置文件系统权限)。

CSV还应包括一列字段名。


阅读 300

收藏
2020-05-17

共1个答案

小编典典

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

要么:

$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";
2020-05-17