Export to CSV via PHP

前端 未结 7 2528
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 06:14

Let\'s say I have a database.... is there a way I can export what I have from the database to a CSV file (and text file [if possible]) via PHP?

7条回答
  •  野性不改
    2020-11-22 06:50

    Just for the record, concatenation is waaaaaay faster (I mean it) than fputcsv or even implode; And the file size is smaller:

    // The data from Eternal Oblivion is an object, always
    $values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000);
    
    // ----- fputcsv (slow)
    // The code of @Alain Tiemblo is the best implementation
    ob_start();
    $csv = fopen("php://output", 'w');
    fputcsv($csv, array_keys(reset($values)));
    foreach ($values as $row) {
        fputcsv($csv, $row);
    }
    fclose($csv);
    return ob_get_clean();
    
    // ----- implode (slow, but file size is smaller)
    $csv = implode(",", array_keys(reset($values))) . PHP_EOL;
    foreach ($values as $row) {
        $csv .= '"' . implode('","', $row) . '"' . PHP_EOL;
    }
    return $csv;
    // ----- concatenation (fast, file size is smaller)
    // We can use one implode for the headers =D
    $csv = implode(",", array_keys(reset($values))) . PHP_EOL;
    $i = 1;
    // This is less flexible, but we have more control over the formatting
    foreach ($values as $row) {
        $csv .= '"' . $row['id'] . '",';
        $csv .= '"' . $row['name'] . '",';
        $csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",';
        $csv .= '"' . ($row['pet_name'] ?: '-' ) . '",';
        $csv .= PHP_EOL;
    }
    return $csv;
    

    This is the conclusion of the optimization of several reports, from ten to thousands rows. The three examples worked fine under 1000 rows, but fails when the data was bigger.

提交回复
热议问题