Home >Database >Mysql Tutorial >How Can I Efficiently Export MySQL Data to CSV Using PHP?

How Can I Efficiently Export MySQL Data to CSV Using PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 15:24:15738browse

How Can I Efficiently Export MySQL Data to CSV Using PHP?

Converting MySQL Queries to CSV in PHP

Exporting data from MySQL databases into CSV format is a common task. PHP offers various methods to achieve this. One efficient approach that avoids intermediate file creation is using the SELECT * INTO OUTFILE statement:

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

Alternatively, you can use the following PHP code:

$select = "SELECT * FROM table_name";

$export = mysql_query($select) 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";

Both methods retrieve data from the MySQL database and convert it directly to CSV format without using temporary files.

The above is the detailed content of How Can I Efficiently Export MySQL Data to CSV Using 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