Creating a CSV File Using PHP
PHP has built-in functions for creating CSV files. Using these functions instead of libraries like PHPExcel offers several advantages. It consumes fewer 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 passing it a series of file names. I've commented each line of code. I've configured this function to use memory space instead of a temporary temporary file. If you want to use a temporary temporary file, replace $f = fopen('php: // memory', 'w'); with $f = fopen('php: // output', 'w');
Next, we create an array of rows, either from the database or from JSON data, and send it to our function. That's all. As an example, I wrote the following code:
<?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");