Creating CSV File with PHP

Creating csv file with php

Its blank because you are writing to file. you should write to output using php://output instead and also send header information to indicate that it's csv.

Example

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);

$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);

Create CSV File with PHP

Using fopen with w will create the file if does not exist:

$list = [
["Name" => "John", "Gender" => "M"],
["Name" => "Doe", "Gender" => "M"],
["Name" => "Sara", "Gender" => "F"]
];

$fp = fopen($filename, 'w');
//Write the header
fputcsv($fp, array_keys($list[0]));
//Write fields
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

If you don't like fputcsv and fopen you can use this alternative:

$list = [
["Name" => "John", "Gender" => "M"],
["Name" => "Doe", "Gender" => "M"],
["Name" => "Sara", "Gender" => "F"]
];

$csvArray = ["header" => implode (",", array_keys($list[0]))] + array_map(function($item) {
return implode (",", $item);
}, $list);

file_put_contents($filename, implode ("\n", $csvArray));

I hope this will help you.

How to create and download a csv file from php script?

You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
fputcsv($f, $line);
}

To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):

header('Content-Disposition: attachment; filename="filename.csv";');

Putting it all together:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: text/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}

And you can use it like this:

array_to_csv_download(array(
array(1,2,3,4), // this array is going to be the first row
array(1,2,3,4)), // this array is going to be the second row
"numbers.csv"
);

Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');

// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');

foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}

Create a CSV File for a user in PHP

Try:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";
die;

etc

Edit: Here's a snippet of code I use to optionally encode CSV fields:

function maybeEncodeCSVField($string) {
if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string;
}

Create CSV files and add data depending on condition php

May be you want line-by-line separation?

// creating dirty and clean file
$clean_emails = fopen(UPLOAD_DIRECTORY . '/clean/' . $file_name_new . '.' . $extension, 'w');
$dirty_emails = fopen(UPLOAD_DIRECTORY . '/dirty/' . $file_name_new . '.' . $extension, 'w');
$unknown_emails = null; // No file yet

// adding headers to them
fputcsv($clean_emails, $headers);
fputcsv($dirty_emails, $headers);

foreach ($results as $row) { // Scan each row
if ($row['result'] === 'valid') {
fputcsv($clean_emails, $row);
} elseif ($row['result'] === 'invalid') {
fputcsv($dirty_emails, $row);
} else { // found something else
if (!isset($unknown_emails)) { // Open file if it was not
$unknown_emails = fopen(UPLOAD_DIRECTORY . '/unknown/' . $file_name_new . '.' . $extension, 'w');
fputcsv($unknown_emails, $headers); // Add headers ?
}
fputcsv($unknown_emails, $row);
}
} // end loop
fclose($clean_emails);
fclose($dirty_emails);
if (isset($unknown_emails)) {
fclose($unknown_emails); // Close 'unknown' if it was opened
}

Generate CSV file on an external FTP server in PHP

If you have ftp:// URL wrappers enabled, just open the file directly on FTP server:

$fp = fopen('ftp://username:password@ftp.example.com/path/to/somefile', 'w');

If you do not have the wrapers enabled, see:

Creating and uploading a file in PHP to an FTP server without saving locally



Related Topics



Leave a reply



Submit