Create and download CSV in PHP

An example of creating a CSV with a line separator ";"

Разделитель CSV

The code:

// 1
$fp = fopen('./fileName.csv', 'w');
if ($fp === false) {
// 2
exit('Can not create file (No Rights) ./fileName.csv');
}

// 3
$models = [
[
'name' => 'Visa',
'type' => 'Card',
'balance' => '10.0'
],
[
'name' => 'Master',
'type' => 'Card',
'balance' => '0'
]
];

// 4
fwrite($fp, '"Имя";"Тип";"Баланс"' . "\n");
foreach ($models as $v) {
fwrite($fp, '"' . $v['name'] . '";"'
. $v['type'] . '";"'
. $v['balance'] . '"'
. "\n");
}

// 5
fseek($fp, 0);
fclose($fp);

// 6
$data = file_get_contents('./fileName.csv');

// 7
header('Content-Type: text/csv'); // 7.1
header('Content-Disposition: attachment; filename="fileName.csv"'); // 7.2
header("Content-Transfer-Encoding: binary"); // 7.3
header('Expires: 0'); // 7.4
header('Pragma: no-cache'); // 7.5
header("Content-Length: ".strlen($data)); // 7.6

// 8
exit($data);

Note :

For the header to fire, there must be no BOM and no output of information before the code fires.

1 - Create a file fileName.csv in the root of the site for writing.

2 - We warn about an error if there are no rights to write.

3 - An array of values that we will process

4 - Writing to a file. '"Name ";" Type";"Balance"' . "\n" (";" - line separator, "\n" - line break).

5 - Return the pointer to the beginning of the file and close the file (save).

6 - Read the file again.

7 - We give headers for the ability to download the file.

7.1 - Parameter defining file type.

7.2 - Pointer to file attachment.

7.3 - In what form to transfer (in this case, in binary).

7.4, 7.5 - Pointer not to cache the file and constantly give the current one.

7.6 - The size of the content part of the file.

8 - We display information that, in conjunction with the headers, will make it possible to download it to a CSV file.

Result:

Результат CSV

869 0

Comments

Be the first to review this item. Share your rating and review so that other customers can decide if this is the right item for them.
You have to log in to leave a comment. Sign in

Similar articles

Long-term storage of the basket in the online store

Consider options for popular options for storing goods in a shopping cart in an online store. Let's outline the pros and cons of such storage. Consider options for long-term storage of the basket.