Create a CSV File For a User in PHP

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;
}

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);

Export a CSV File for a 'username' in PHP

$filename = "testing-exports.csv";

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

$insquery = "SELECT username FROM r_institution where status=1";
//$exportstmt = $conn->query($insquery);
$insresults = $conn->query($insquery);
//$insresults = mysqli_fetch_assoc($exportstmt);
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$content = array();
$title = array("Institution Emails");
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}

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);
}
}

How do I prompt the user to download a PHP-generated .CSV file, and how should I handle deleting it?

no need to store anything on the server (and thus no need to delete ...). Just write the results back to the browser and set the headers accordingly:

<?php
require_once "../assets/repository/mysql.php";

$query = "SELECT * FROM datashep_AMS.COMPLETE_APPLICATIONS";
$results = mysql_query($query);

$first = true;

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="export.csv"');
header('Cache-Control: max-age=0');

$out = fopen('php://output', 'w');

while($row = mysql_fetch_assoc($results)){
if($first){
$titles = array();
foreach($row as $key=>$val){
$titles[] = $key;
}
fputcsv($out, $titles);
$first = false;
}
fputcsv($out, $row);
}

fclose($out);
?>

PHP script to create new csv from another csv after rearranging the data

A much more compact method would be to read the input and write out the target file in one loop.

This code reads in each line, combines it with the header and then extracts the sku (and removes it from the details). Then loops over the remaining details, and if there is a value to output it writes the output to the result file.

As each value may also be a comma separated list, this uses explode() to split them into individual items and writes them out as separate parts...

$inputFile = "a.csv";
$outputFile = "a1.csv";
$inputHandle = fopen($inputFile, 'r');
$outputHandle = fopen($outputFile, 'w');
$headers = fgetcsv($inputHandle);
fputcsv($outputHandle, ["sku", "feature", "value" ]);

while ( false !== $fields = fgetcsv($inputHandle) ) {
$fields = array_combine($headers, $fields);
$sku = $fields['sku'];
unset($fields['sku']);
foreach ( $fields as $name => $field ) {
if (!empty(trim($field))) {
$subFields = explode(",", $field );
foreach ( $subFields as $value ) {
fputcsv($outputHandle, [$sku, $name, $value]);
}
}
}
}
fclose($inputHandle);
fclose($outputHandle);

Create CSV file to the specific place on server in PHP with given HTML content

No chance, pal. CSV is plain text and you cannot format anything in plain text :-)



Related Topics



Leave a reply



Submit