Home > Backend Development > PHP Tutorial > How Can I Efficiently Export MySQL Query Results to a CSV File Using PHP?

How Can I Efficiently Export MySQL Query Results to a CSV File Using PHP?

Mary-Kate Olsen
Release: 2024-12-14 01:03:24
Original
206 people have browsed it

How Can I Efficiently Export MySQL Query Results to a CSV File Using PHP?

Exporting MySQL Query Results to CSV in PHP

Question:

What's the best method for efficiently converting a MySQL query to a CSV file in PHP?

Answer:

There are multiple approaches to exporting MySQL query results to CSV using PHP:

1. Using MySQL's SELECT INTO OUTFILE:

This method allows you to directly output the query results to a CSV file, without using temp files:

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;
Copy after login

Refer to the MySQL documentation for more details.

2. Manual Export and Formatting:

You can perform the export and formatting manually using PHP:

$select = "SELECT * FROM table_name";

$export = mysql_query($select) or die("Sql error : " . mysql_error());

$fields = mysql_num_fields($export);

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

// Generate data
while ($row = mysql_fetch_row($export)) {
    $line = '';
    foreach ($row as $value) {
        // Handle empty values
        if (empty($value)) {
            $value = "\t";
        } else {
            // Escape double quotes
            $value = str_replace('"', '""', $value);
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim($line) . "\n";
}

// Remove leading/trailing whitespace
$data = str_replace("\r", "", $data);

// Send headers and output CSV
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";
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template