export query result as CSV through PHP

蓝咒 提交于 2019-12-31 22:36:09

问题


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?


回答1:


$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";



回答2:


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);



回答3:


CSV = Comma Separated Values = Separate your Values with Commas

you have to echo / print your result line by line, separated with comma (,).

I assume your $query is the result set of your query, which is an associative array:

while($query = mysql_fetch_assoc($rs)) {
  // loop till the end of records
  echo $query["field1"] . "," . $query["field2"] . "," . $query["field3"] . "\r\n";
}

where $rs is the resource handle.

To let the browser pops up a download box, you must set the header at the beginning of the file (assume your file name is export.csv):

header("Expires: 0");
header("Cache-control: private");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=export.csv");

That's it!

p.s. This method won't leave a physical file in the server. If you intended to generate a file in the server, use traditional fopen and fwrite functions.



来源:https://stackoverflow.com/questions/1642136/export-query-result-as-csv-through-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!