Creating a CSV File Using PHP

In PHP, there are functions defined to create a CSV file. There are several advantages to using these functions instead of libraries like PhpExcel. It consumes less resources and is faster.

First, let’s create a function that will create our CSV file.

<?php

function array_to_csv_function($array, $filename = "export.csv", $delimiter=";") {
    // Instead of opening a temp file, we use memory space.
    $f = fopen('php://memory', 'w');
    // We're making a loop with an array which contains our data
    foreach ($array as $line) {
        // Each array in our array is a line in our CSV file.
        fputcsv($f, $line, $delimiter);
    }
    // File initialization is reset
    fseek($f, 0);
    // Php tells the browser that it is a csv file
    header('Content-Type: application/csv');
    // Php tells the browser not to display, to save. 
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // The generated CSV is transferred to the browser.
    fpassthru($f);
}

With this function, we can create a CSV file and output it to the browser by sending a series of file names to the function. I have explained each line in the code with comments. I made this function use memory space instead of using a temporary temp file. If you want to use a temporary temp file, replace $f = fopen(‘php: // memory’, ‘w’); with $f = fopen(‘php: // output’, ‘w’); command.

We then create an array that will be an array of lines, either by pulling it from the database or from a json data, and send it to our function. That’s all. As an example, I wrote the code below;

<?php

$titles = array("Name", "Surname");
$row1 = array("Erhan", "Kılıç");
$row2 = array("Onur", "Bakır");
$content = array($titles, $row1, $row1);

array_to_csv_function($content, "export.csv");
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments