Adding the headers when creating a csv file PhP, SQL - php

I have the following code:
PhP
function write_csv($filename, $rows) {
$file = fopen($filename, 'w');
while($row = mysqli_fetch_assoc($rows)) :
fputcsv($file, $row);
endwhile;
fclose($file);
}
// $db is a class I have and this function just returns a SQL result set
$result_set = $db->run_query("SELECT * FROM Users");
write_csv('../MOCK_USERS_DATA.csv', $result_set);
I am correctly getting a created CSV file with the the users information for example
1,greg,mason,407-356-3322,greg#gmail.com
2,derek,herd,407-234-4352,derek#gmail.com
etc...
My question is how do I get the headers from the table as the first row in my CSV file. I am new to creating CSV files and am stuck on getting that first row of headers in that file that match the name of the column in my database. Any suggestions?

Easy export to CSV
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
ob_start();
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings -> trim is used for lang translates
// or use SQL query to get table columns headers name
fputcsv($output, array(
trim('Product name'),
trim('Pellet number'),
trim('Quantity'),
trim('Date')
), ";");
// use foreach
***********
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header('Content-Disposition: attachment; filename=pelletlist-' . time() . '.csv');
header("Content-Transfer-Encoding: binary");
header("Cache-control: private"); //use this to open files directly
header('Expires: 0');
header("Pragma: no-cache");
header("Connection: close");
fclose($output);
exit();
for load column name from db use:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
or
SHOW COLUMNS FROM my_table;

Related

How do I get MySQL table entities in excel

What I have done is get the data from MySQL to excel in csv format but I am not getting the entities of that table like if I have a table member having these 3 entities
memberid membername memberemail
I am getting the data of these entities like
1 alishah test#test.com
What I want is when I download an excel it gets header with it like
memberid membername memberemail
1 alishah test#test.com
What I did for excel is
<?php
$selectUserData = "SELECT * FROM tbl_member";
$export = $conn->query($selectUserData);
$fp= fopen('php://output', 'w');
foreach ($export as $fields)
{
fputcsv($fp, $fields);
}
header("Content-Type: text/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename=member.csv");
header("Pragma: no-cache");
header("Expires: 0");
?>
Simply write a line with the column headers before writing the data to the csv.
<?php
$selectUserData = "SELECT * FROM tbl_member";
$export = $conn->query($selectUserData);
$fp = fopen('php://output', 'w');
fwrite($fp,'"memberid","membername","memberemail"'."\n");
foreach ($export as $fields)
{
fputcsv($fp, $fields);
}
header("Content-Type: text/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename=member.csv");
header("Pragma: no-cache");
header("Expires: 0");
?>

PHP MySQL csv export

I am trying to export MySQL data to csv file. Here is my code
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment;filename=data.csv");
header("Content-Transfer-Encoding: binary");
$output = fopen('php://output', 'w');
fputcsv($output, array('Id', 'Data 1', 'Data 2','Data 3'));
foreach ($data as $row)
{
fputcsv($output, $row, ',', '"'); //arabic data
}
fclose($output);
return chr(255) . chr(254) . mb_convert_encoding(ob_get_clean(), 'UTF-16LE', 'UTF-8');
The data contain Arabic and Hindi languages. The code results with all data with comma separated in one cell with new line.
I want to download this file with data in each cell. I tried this in last of code
return ob_get_clean();
it shows data in each row, but data expect English not loaded correctly.
How can solve this?
The mysqli_set_charset() function specifies the default character set to be used when sending data from and to the database server.
Please use before Mysql query.
mysqli_set_charset( $db, 'utf8');

Wordpress converting array to csv for download

I have the following function that takes an array of results from a database query. I populate the array as I loop through the query results. At the same time I create an html table. After outputting the html table I call the function download_csv($csvArray) but no downloading of the CSV happens, It just displays the contents of the the array as if I did a var_dump on the array. I can confirm that the contents of the array are correct.
Note: this is being done on an external web page not from the admin area.
Is there some wordpress function that needs to be called to allow the download or am I missing something?
function download_csv($csvArray) {
$file_name = 'report.csv';
//output headers so that the file is downloaded rather than displayed
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=$file_name");
//Disable caching - HTTP 1.1
header("Cache-Control: no-cache, no-store, must-revalidate");
//Disable caching - HTTP 1.0
header("Pragma: no-cache");
//Disable caching - Proxies
header("Expires: 0");
//Start the ouput
$output = fopen("php://output", "w");
//Then loop through the rows
foreach ($csvArray as $fields) {
fputcsv($output, $fields);
}
//Close the stream off
fclose($output);
die();
}
Following Code will help you to convert Array to CSV and Make it to automatically download Change the die(); function to exit(); And Use Implode function. It will work.
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=sample.csv');
header('Pragma: no-cache');
header('Expires: 0');
$fp = fopen('php://output', 'w');
//ex: $list={...};
foreach ($list as $fields)
{
fputcsv($fp,implode($fields, ','));
}
fclose($fp);
exit();

Read and write using fgetcsv and fputcsv

I have a 3rd party source from where I am getting "csv" file. I wrote it inside a quote because it says it's a csv file but basically it's not.
So I am taking that main source file then reading and putting the data in a "PROPER" csv file.
The read and write is fine but the problem is when it saves the properly quoted data is writing on the script file itself.For example if the my php file name is "fixcsv.php" then I am getting the downloadable file as "fixcsv.php".
My code
$headings = array('HID');
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0, ";",'"');
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $headings);
// Loop over the * to export
if (! empty($data)) {
foreach ($data as $item) {
// echo $item;
fputcsv($fh, array($item));
}
}
$string = ob_get_clean();
$filename = 'csv_' . date('Ymd') .'_' . date('His');
// Output CSV-specific headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment filename=\"$filename.csv\";" );
header("Content-Transfer-Encoding: binary");
exit($string);
Any help is highly appreciated. Thanks in advance.
Your Content-Disposition has a semi-colon in the wrong place (per the spec). Should be:
header("Content-Disposition: attachment; filename=\"$filename.csv\" );

File download for csv works in local host but not when live

I am creating a csv file from nested array and it works fine with a download link to the csv file in the localhost, but on live host it won't download. This is what is in my php file:
The headers declared:
/**
* Declare headers for CSV
*/
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=registration.csv");
header("Pragma: no-cache");
header("Expires: 0");
The Function that outputs the csv file:
/**
* Function will output the scsv file
* #param the csv $data in nested array form array(array("","",""),array("",""...)...)
*/
function outputCSV($data) {
$outstream = fopen("php://output", "w");
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals); // add parameters if you want
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}
The link that I used in local:
Download CSV
Won't work on Live site. Instead of downloading it just takes me to the csv.php page and outputs the array in a string like this.
...ID,"Coach One","Coach Two",Work,Cell,Email,...
Try hardcoding the csv into the code. Replace these lines with the ones you have to see if your data being passed has bad characters. Maybe specifying the charset will help.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
As described here:
http://code.stephenmorley.org/php/creating-downloadable-csv-files/
I'm not setup to really debug your code. You can try this though if you like. I know it works.
$out = fopen("php://temp", 'r+');
while (($row = $res->fetch(Zend_Db::FETCH_NUM)) != false) {
fputcsv($out, $row, ',', '"');
}
rewind($out);
$csv = stream_get_contents($out);
header("Content-Type: application/csv;");
header("Content-Disposition: attachment; filename=\"foo.csv\"");
header("Pragma: no-cache");
header("Expires: 0");
echo $csv;
exit(0);
Adjust the loop as needed to iterate on your results.

Categories