PHP export array data into column of data in CSV - php

I'm trying to export nationality data into CSV. My nationality data are stored in an array. However, when i export it out, my CSV output show this error "Warning: fputcsv() expects parameter 2 to be array". Can I know how i can show my nationality data in a csv column?
my code:
$filename = "nationality_list.csv"; // Create file name
$array_nat = array('BANGLADESH','CAMBODIA','CHINESE','DUTCH','FILIPINO','FRENCH','GERMAN','INDIAN','INDONESIA','ITALY','JAPANESE','KOREAN','LITHUANIAN','MALAYSIA','MYANMAR','NEW ZEALAND','RUSSIAN','SINGAPOREAN','SRI LANKAN','THAILAND','UK','USA');
$f = fopen('php://memory', 'w');
$fields = array('Nationality_list');
fputcsv($f, $fields);
foreach($array_nat as $nat){
fputcsv($f, $nat);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f)
Desired output in CSV

Try this:
fputcsv($f, [$nat]);
fputcsv expects an array because a row consists of n columns. 1 in your case :)

Related

PHP 7: Query output to Text File Questions (FIeld Headers and Skipping a Comma after last column)

I've very new to PHP and trying to re-create some code I had in another language. The current version of PHP I'm working with is 7.17.
Right now, I'm trying to re-create a simple function of opening a MySQL query as a comma deliminated text file where there is no comma after the last column (just a line break). I'm trying to figure out two things right now to finish this piece of code.
How do I insert the query column headers at the top of the data output (right now only the data is output, not the column headers).
At the line "fwrite($output, $value.',');", I'm trying to figure out how to not add the comma after the last field (how to skip adding the comma after the last column of data).
PHP:
if (isset($_POST['download'])) {
header('Content-Type: text/plain');
header('Content-Disposition: attachment;filename=cars.txt');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$output = fopen('php://output', 'w');
while ($row = getRow($result)) {
foreach ($row as $key => $value) {
fwrite($output, $value.',');
}
fwrite($output, "\r\n");
}
fclose($output);
exit;
}
Thank You!
It sounds like you are trying to create a CSV file, so why not use PHP's built in CSV handling functionality (fputcsv), like so:
$output = fopen('php://output', 'w');
while ($row = getRow($result)) {
fputcsv($output, $row);
}
fclose($output);
This way PHP does all the heavy lifting for you.
Edited based upon comment.
You could try using the answer from here to handle the encoding of the values before converting to CSV and then set the file encoding in the HTTP header to header('Content-Type: text/plain; charset=utf-8');.
Also fputcsv allows you to change the delimiter, enclosure and escape characters if they were causing you issues.
Otherwise just do:
$output = fopen('php://output', 'w');
while ($row = getRow($result)) {
$line = implode(', ', $row);
fwrite($output, $line);
}
fclose($output);

Content-type: text/csv output html into the csv file

I can't seem to output only specific information, into a csv or any file. The following, e.g., output the html from the page, rather than the data that I'm trying to send to the Applicants.csv:
(the $a_Lines array has already been populated):
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="Applicants.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$file = fopen('php://output', 'w');
foreach ( $a_Lines as $row ) {
fputcsv($file, $row);
}
fclose($file);
Make sure that in expression
fputcsv($file, $row);
$row is always array. If you want to create from $a_Lines csv file, then you don't need foreach loop (of course, I presume that $a_Lines is array). In case that you want selected data from $a_Lines array, then run through $a_Lines, create new array or transform existing one and after the loop add prepared array into fputcsv function.

How to deal with unicode while exporting data in csv format using fputcsv in php?

I have following code to export data in csv format. It works fine in normal text, but didnot work if unicode exists means exported text are illegible even with the option of charset=utf-8, what should i do right here
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;
filename=magazine_subscribers'.date('Y-m-d').'.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Customer Id', 'Name', 'Company','Subscription Type','Address 1','Postal Code','City','Email','mobile','note','Invoice Receiver','Invoice Email','Invoice address','Invoice city','Invoice Postal Code'));
foreach($subscribers as $subscriber)
{
fputcsv($output,array($subscriber->customer_id,$subscriber->name,$subscriber->company,$subscriber->subscription_type,$subscriber->address_1,$subscriber->postal_code,$subscriber->city,$subscriber->email,$subscriber->mobile,$subscriber->note,$subscriber->invoice_receiver,$subscriber->invoice_email,$subscriber->invoice_address,$subscriber->invoice_city,$subscriber->invoice_zip));
}
thanks in advance

How to add data (which includes commas) to CSV file through php form

I have created a form and able to add data to CSV on submit. But my code is such that the csv file is delimited by commas and so when I add comma in the form data, the php code separates it as another entry (column).
Here is my php code:
<?php
$filename = "data.csv";
$string = $_POST['element_1'].",".$_POST['element_2'].",".$_POST['element_3'].",".$_POST['element_4_1']."-".$_POST['element_4_2']."-".$_POST['element_4_3'].",".$_POST['element_5']."\n";
if (file_exists($filename)) {
$file = fopen($filename, "a");
fwrite($file, $string);
} else {
$file = fopen($filename, "a");
fwrite($file, '"Name","Phone","No. of persons","Date","Venue"\n');
fwrite($file, $string);
}
fclose($file);
?>
In the above code, Venue sometimes, takes 'commas'. But the code separates the Venue data into new columns.
So, is there any other way to enter data into excel sheet other that CSV or any code gimmick.
You can make your life easier by using fputcsv and fgetcsv.
fputcsv lets you specify the delimiter and enclosure you need. The big difference is that you must pass the fields as an array: each value of the array is a column value in the csv line.
So given a $fields array that contains your CSV line values:
$file = fopen( 'data.csv', 'a' );
fputcsv( $file, $fields, ',', '"' );
fclose( $file );
Important: the flag on fopen must be a in order to append to the file. If you use w you will overwrite the previous content.

unserializing multiple attachments data

I have stored some multiple attachments in my database, in one column by serializing the Attachments data through code:
$files = array(
'file1' => base64_encode(file_get_contents('back.jpg')),
'file2' => base64_encode(file_get_contents('email.jpg')),
'file3' => base64_encode(file_get_contents('web.jpg')),
);
// serialize
$filesData = serialize($files);
Now, in another php page, i am getting the files to download , in that i m UNserializing the above files data, getting them from the database column "Data"
Using the following code to unserialize data, but it seems that the data is not unserailized, I have saved three pics, and when i retrive them, i get a .txt file downloaded, in which written there "Array"
if($result->num_rows == 1) {
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
$files = unserialize($row['data']);
echo $files;
}
$files is an array containing the three files, what do you expect?
"Array" is the result of the string cast from echo.
try echo $files['file1'] etc..

Categories