Output to excel.csv gives weird æøå - php

I just can't seem to make ÆØÅ give me right chars.
If I open Excel and then import from data and choice UTF-8 it will show correctly. but I can't ask my users to open excel and do this, so how do I make Excel open the file correctly the first time?
//Give our CSV file a name.
$csvFileName = 'example.csv';
//Open file pointer.
$fp = fopen('php://output', 'w');
//Loop through the associative array.
foreach($sortedData as $row){
//Write the row to the CSV file.
fputcsv($fp, $row,";");
}
//Finally, close the file pointer.
fclose($fp);
$response = $response->withHeader('Content-Type', 'text/csv; charset=utf-8');
$response = $response->withHeader('Content-Disposition', 'attachment; filename="file.csv"');
$stream = fopen('php://memory', 'r+');
return $response->withBody(new \Slim\Http\Stream($stream));

Related

Output mysql query result to formated excel table with php

I have to fetch the result of a mysql query to a "user friendly" excel (.xls or .xlsx) table.
I don't want to use imports or packages for php.
This is what I got so far:
<?php
function query_to_csv($database, $query, $filename, $attachment = false, $headers = true) {
if ($attachment) {
// send response headers to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysqli_query($database, $query) or die(mysqli_error($database));
foreach ($result as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
This is the
Result
How can I get the array sperated in different Cells?
Sadly I had to use a library named PHP Excel (old) or PhpSpreadsheet (new).
$objReader->setDelimiter(',');
That's the PHP Excel Function to set the Delimiter.

How to export multiple csv files at once

This exports one file with 2 rows in it. How can export 2 files each with one row in it?
<?php
$list = array (
array("Peter", "Griffin" ,"Oslo", "Norway"),
array("Glenn", "Quagmire", "Oslo", "Norway")
);
$file = fopen("contacts.csv","w");
foreach ($list as $line) {
fputcsv($file, $line);
}
fclose($file);
?>
I tried this:
$list = array (
array("Peter", "Griffin" ,"Oslo", "Norway"),
array("Glenn", "Quagmire", "Oslo", "Norway")
);
$file = fopen('php://output', 'w');
$i = 1;
foreach ($list as $line) {
header('Content-Disposition: attachment; filename="' . $i . 'wp.csv"');
fputcsv($file, $line);
fclose($file);
$i++;
}
But it only downloads one file. At least it only has the one row in it though.
I found this example. Even though it creates 2 separate csv files, the data is identical in each file instead of each file containing an individual record.
// some data to be used in the csv files
$headers = array('id', 'name', 'age', 'species');
$records = array(
array('1', 'gise', '4', 'cat'),
array('2', 'hek2mgl', '36', 'human')
);
// create your zip file
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create 3 csv files
for ($i = 0; $i < 3; $i++) {
// create a temporary file
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
// write the data to csv
fputcsv($fd, $headers);
foreach($records as $record) {
fputcsv($fd, $record);
}
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('file-'.$i.'.csv', stream_get_contents($fd) );
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
You can only put one "file" into an HTTP response.
If you want to generate multiple CSV files then you'll need to get more exotic. You could generate a HTML document of links to URLs that each generate a CSV file, or you could generate a zip file containing the CSV files.
Just make a new File and use it like this
$file2 = fopen("contacts2.csv", "w");
fputcsv($file2, $list[1]);
You always write in the same file here, because you are refering to $file
fputcsv($file, $list[1]);

Delete the first line of the file

Im having a problem of exporting my csv. Yes it can export but when it exported the colmun name is included. How can i remove the first row (column name) after i exported?
Tried looking for other solution yet it doesnt fit on my program
<?php
//include database configuration file
include 'config2.php';
//get records from database
$query = $db->query("SELECT * FROM maternalproblem ");
if($query->num_rows > 0){
$delimiter = ",";
$filename = "maternalproblem" . date('Y-m-d') . ".csv";
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('MPID', 'district_id', 'barangay_id', 'PID', 'tuberculosis', 'sakit','diyabetes','hika','bisyo');
fputcsv($f, $fields, $delimiter);
//output each row of the data, format =line as csv and write to file pointer
while($row = $query->fetch_assoc()){
$lineData = array($row['MPID'], $row['district_id'], $row['barangay_id'], $row['PID'], $row['tuberculosis'],$row['sakit'],$row['diyabetes'],$row['hika'],$row['bisyo']);
df.to_csv($filename , header=False);
fputcsv($f, $lineData, $delimiter);
}
//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);
}
exit;
?>
I just need to export the data and not with the column name. Thank you
It would probably be simpler to just not put the column titles out into the file
So remove these lines
//set column headers
$fields = array('MPID', 'district_id', 'barangay_id', 'PID', 'tuberculosis', 'sakit','diyabetes','hika','bisyo');
fputcsv($f, $fields, $delimiter);

How to execute code after writing to csv without it being included in the csv

I'm writing to a CSV file using the following code:
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
echo "Do something else";
exit();
I want to execute code after fclose($fp);. But in the above example echo "Do something else"; is included in the CSV file. How can I ensure that any code after the fclose is not included in the outputted csv file?
You could put the code that you want to run after the csv file is generated in a seperate file and then call that file to run using fopen() after the csv has been created.
You have included headers as content disposition. So you can NOT echo something. It will be always printed in the excel sheet.
However you can perform other tasks such as insert/update/select/delete in database and other things which does not print anything.

Database to CSV(Done) trying to Save file to folder on server

I've have been successful in exporting my database to csv as a downloadable file. However what I now need to do is instead of creating a straight .csv file that's downloaded I need it to just save to a folder called "csv" on the server. Here is my code for the current export. I need help in the saving it to server. I'm not saving the data correctly.
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('tax_class_id','_product_websites'));
// fetch the data
mysql_connect('localhost:3036', 'x', 'x');
mysql_select_db('lato');
$rows = mysql_query('SELECT taxclass,productwebsite FROM product');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
$filename = "data.csv"; // Trying to save file in server
file_put_contents("download/" . $filename, "$header\n$rows");
Why do write in streams, read it and than try to save the content?
I would do it in a smaller way:
//Open a file in write-mode (he creates it, if it not exists)
$fp = fopen('./my/path/on/server/data.csv', 'w');
// output the column headings
fputcsv($fp, array('tax_class_id','_product_websites'));
// fetch the data
mysql_connect('localhost:3036', 'x', 'x');
mysql_select_db('lato');
$rows = mysql_query('SELECT taxclass,productwebsite FROM product');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($fp, $row);
//close the handler
fclose($fp);

Categories