Home >Backend Development >PHP Tutorial >How to Efficiently Export MySQL Query Results to CSV in PHP?

How to Efficiently Export MySQL Query Results to CSV in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-05 10:46:101030browse

How to Efficiently Export MySQL Query Results to CSV in PHP?

Efficient MySQL Query Conversion to CSV in PHP

To convert a MySQL query to CSV in PHP, a popular method is to leverage SQL's INTO OUTFILE command. With this approach, you can specify the output destination and formatting options:

SELECT * INTO OUTFILE "/path/to/file.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;

Another efficient option is to programmatically fetch the query results and build the CSV manually:

$select = "SELECT * FROM my_table";
$export = mysql_query($select);
$fields = mysql_num_fields($export);

$header = '';
for ($i = 0; $i < $fields; $i++) {
    $header .= mysql_field_name($export, $i) . "\t";
}

$data = '';
while ($row = mysql_fetch_row($export)) {
    $line = '';
    foreach ($row as $value) {
        $value = str_replace('"', '""', $value);
        $line .= '"' . $value . '"' . "\t";
    }
    $data .= trim($line) . "\n";
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=my_file.csv");
print "$header\n$data";

This approach allows you to customize the field delimiters and quote characters to suit your specific requirements.

The above is the detailed content of How to Efficiently Export MySQL Query Results to CSV in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn