Skip to content

Instantly share code, notes, and snippets.

@webarthur
Last active January 19, 2016 14:48
Show Gist options
  • Select an option

  • Save webarthur/c873414b314fa716ab9f to your computer and use it in GitHub Desktop.

Select an option

Save webarthur/c873414b314fa716ab9f to your computer and use it in GitHub Desktop.
How to create CVS content using PHP and write it to variable
<?php
$handle = fopen('php://memory', 'w');
$data = array('value 1', 20, 'text value', '0');
fputcsv($handle, $data, ';');
/* to be able to read from a handle, it is necessary to reset internal file pointer to the begining */
fseek($handle, 0);
$csv = stream_get_contents($handle);
/* converting CSV content encoding */
$csv = mb_convert_encoding($csv, 'iso-8859-2', 'utf-8');
/* writing content to a file locally */
file_put_contents('/pat/to/file.csv', $csv);
/* sending to browser */
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="file.csv";');
echo $csv;
exit;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment