Creating a CSV File Using PHP
PHP'also, CSV There are functions defined to create files with the extension . PhpExcel There are several advantages to using these functions instead of libraries like: It consumes fewer resources and is therefore faster.
Firstly CSV Let's create our function that will create our file.
function array_to_csv_function($array, $filename = "export.csv", $delimiter=";") { // We're using memory space instead of opening a temp file. $f = fopen('php://memory', 'w'); // We're looping through the array containing our data foreach ($array as $line) { // Each array in our array becomes a line in our CSV file. fputcsv($f, $line, $delimiter); } // Reset the file start mark fseek($f, 0); // Indicates to the browser that it's a csv file header('Content-Type: application/csv'); // Indicates to the browser that it's not for displaying, but for saving. header('Content-Disposition: attachment; filename="'.$filename.'";'); // The generated CSV is sent to the browser. fpassthru($f); }
With this function, we can send a string and a file name to it. CSV We're creating the file and outputting it to the browser. I've explained each line of code with comments. I've made this function use memory space instead of a temporary temp file. If you want it to use a temporary temp file, $f = fopen('php://memory', 'w'); in its place $f = fopen('php://output', 'w'); use the command.
Then, we create an array, either from the database or as JSON data, with each row as an array, and send it to our function. That's it. Here's the code example.
$titles = array("Name", "Surname"); $line1 = array("Erhan", "Kılıç"); $line2 = array("Onur", "Bakır"); $content = array($titles, $line1, $line2); array_to_csv_function($content, "export.csv"); // Alternatively used array_to_csv_function(array($titles, $line1, $line2), "export.csv");