Export a mysql table into CSV using PHP code

前端 未结 4 1212
猫巷女王i
猫巷女王i 2021-01-20 22:56

I have a my sql table called pvdata, I would like to export it to csv file.

But I\'m obtaining the following results instead of the normal looking table:



        
4条回答
  •  清酒与你
    2021-01-20 23:16

    Before for loop initialize $header to empty string.

    $header = '';//initialize header
    for ( $i = 0; $i < $fields; $i++ )
    {
        $header .= mysql_field_name( $export , $i ) . "\t";
    
        echo $header;//remove this line
    }
    

    EDIT

    Also initialize $data outside while loop.

    $data = '';
    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";
    }
    

提交回复
热议问题