简体   繁体   English

使用PHP导出到CSV文件

[英]Export to CSV file using PHP

I am using this code to export selected data from MySQL to CSV using PHP, I am facing a little problem that when data exported to the csv file it looks like below: 我正在使用此代码将选定的数据从MySQL导出到使用PHP的CSV文件,我面临一个小问题,当数据导出到csv文件时,它看起来如下所示:

First line in its correct place, but starting from the second row data shifts to the right one space, if I open the csv file in Excel, I can see the most left cell after the first row is empty. 第一行位于正确的位置,但是从第二行开始,数据会向右移动一个空格,如果我在Excel中打开csv文件,则可以看到第一行为空后最左边的单元格。

parts   destination 
===================     
1   9.71504E+11 
1   9.71504E+11
1   96656587662
1   9.71504E+11

This is my code : 这是我的代码:

$values =mysql_query( "SELECT parts,destination from log");

$rown = 0;
$row = array();
$row[] = 'parts';
$row[] = 'destination'."\n";
$data .= join(',', $row)."\n";

while( $row_select = mysql_fetch_assoc($values) ) {
  if($rown++==0)
    $row = array();

  $row[] = $row_select['parts'];
  $row[] = $row_select['destination']."\n";
}
$data .= join(',', $row)."\n";

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: text/csv");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $data;
exit();

Would you please help? 你能帮忙吗?

Regards, 问候,

First line in its correct place, but starting from the second row data shifts to the right one space, if I open the csv file in Excel, I can see the most left cell after the first row is empty. 第一行位于正确的位置,但是从第二行开始,数据会向右移动一个空格,如果我在Excel中打开csv文件,则可以看到第一行为空后最左边的单元格。

I've found out the hard way that writing CSV is more complex than one would imagine. 我发现写CSV的难度比人们想象的要复杂。 Take, for example, escaping the values so that the delimiter is properly escaped inside values. 以转义值为例,以便分隔符在值内部正确转义。 I've created a simple class that utilises fwritecsv( ) instead of trying to render CSV myself: 我创建了一个使用fwritecsv()的简单类,而不是尝试自己呈现CSV:

EDIT : I've changed the example to your usage scenario. 编辑 :我已将示例更改为您的使用方案。

<?php
/**
 * Simple class to write CSV files with.
 * 
 * @author Berry Langerak <berry@ayavo.nl>
 */
class CsvWriter {
    /**
     * The delimiter used. Default is semi-colon, because Microsoft Excel is an asshole.
     * 
     * @var string
     */
    protected $delimiter = ";";

    /**
     * Enclose values in the following character, if necessary.
     * 
     * @var string
     */
    protected $enclosure = '"';

    /**
     * Constructs the CsvWriter.
     */
    public function __construct( ) {
        $this->buffer = fopen( 'php://temp', 'w+' );
    }

    /**
     * Writes the values of $line to the CSV file.
     * 
     * @param array $line 
     * @return CsvWriter $this
     */
    public function write( array $line ) {
        fputcsv( $this->buffer, $line, $this->delimiter, $this->enclosure );
        return $this;
    }

    /**
     * Returns the parsed CSV.
     * 
     * @return string
     */
    public function output( ) {
        rewind( $this->buffer );
        $output = $this->readBuffer( );
        fclose( $this->buffer );

        return $output;
    }

    /**
     * Reads the buffer.
     * @return type 
     */
    protected function readBuffer( ) {
        $output = '';
        while( ( $line = fgets( $this->buffer ) ) !== false ) {
            $output .= $line;
        }
        return $output;
    }
}


/**
 * Example usage, in your scenario:
 */
$values = mysql_query( "SELECT parts,destination from log" );

$csv = new CsvWriter( );
$csv->write( array( 'parts', 'destination' ) ); // write header.

while( $line = mysql_fetch_assoc( $values ) ) {
    $csv->write( $line );
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: text/csv");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");

print $csv->output( );

exit();

Like @ChrisPatrick points out, the line 就像@ChrisPatrick指出的那样,

$data .= join(',', $row)."\n";

is causing the problem, you should move this to inside the while loop and then you'll get rid of the cell skipping. 导致此问题,您应该将其移至while循环内,然后摆脱单元格跳过的麻烦。

The problem is in the following line 问题在下面的行中

$data .= join(',', $row)."\\n";

You're concatenating all the elements in $row with commas. 您正在用逗号连接$row所有元素。 So the destination of one row is concatenated with the parts of the next row with a comma in between, so you get something like this: 因此,将一行的目标与下一行的各部分连接在一起,中间用逗号隔开,因此您将获得如下内容:

$data = $row_select['parts'] . ',' . $row_select['destination']."\n" . ',' . $row_select['parts'] etc...

The comma after the newline creates an empty cell at the beginning of the row. 换行符后的逗号在行的开头创建一个空单元格。

UPDATE It should work with the following 更新它应该与以下一起工作

while( $row_select = mysql_fetch_assoc($values)){
$row = array();
$row[] = $row_select['parts'];
$row[] = $row_select['destination']."\n";
$data .= join(',', $row);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM