Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export query result as CSV through PHP

Say I have stored a query in a variable called $query. I want to create small hyper link called "export as CSV" on the results page. How do i do this?

like image 899
Arc Avatar asked Oct 29 '09 07:10

Arc


2 Answers

$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";
like image 58
Arthur Halma Avatar answered Nov 08 '22 01:11

Arthur Halma


ehm ?

<a href="yourexport.php" title="export as csv">Export as CSV</a>

and if you are looking for script wich can do this:

$myArray = array ();

$fp = fopen('export.csv', 'w');

foreach ($myArray as $line) {
    fputcsv($fp, split(',', $line));
}

fclose($fp);
like image 39
opHASnoNAME Avatar answered Nov 08 '22 00:11

opHASnoNAME