So I have this piece of code here I got off the internet, it's supposed to export data from mySQL database to an excel file.
The thing is that how am I supposed to trigger this? There's no graphical side of this, no button to trigger the script, nothing.
How can I make it work?
<?PHP
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
include('config.php');
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = pg_query("SELECT * FROM norse5_proov ORDER BY id") or die('Query failed!');
while(false !== ($row = pg_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
?>
Here's some code that works for me in a commercial app;
if($_REQUEST["EXCEL"]){
header("Content-Type: application/excel");
header("Content-Disposition: attachment; FileName=assets.xls");
header("Cache-Control: private");
header("Content-Length: ".strLen($data));
echo $data;
exit;
}
The $data is tab delimited text, but the excel headers open Excel and imports the text
Related
Error Message while opening the file
Second error message when trying to update the file...
Code in PHP
<?php
$filename = "test.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
echo implode("\t", ["Username", "Order Number"]) . "\n";
echo implode("\t", ["wswswsw#s.com", "1234454542122232"]) . "\n";
exit();
?>
Am I missing anything?
This code may be able to assist you in finding a solution to your issue. If it doesn't work as expected, there may be other options that you can try.
<?php
$filename = "test.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
// Generate the data for the file
$data = [
["Username", "Order Number"],
["wswswsw#s.com", "1234454542122232"]
];
// Use a loop to generate the rows of the file
foreach ($data as $row) {
// Use implode() to concatenate the values in the row into a single string
echo implode("\t", $row) . "\n";
}
exit();
?>
İ can export json data to excel with PHP. But I use ə,ü,ç,ı,ö and so on. This caracters don`t show.
My code:
$file = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$file\"");
header("Content-Type: application/vnd.ms-excel; ");
$flag = false;
foreach($output as $row) {
if(!$flag) {
$arr = implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
$arr = $arr.implode("\t", array_values($row)) . "\r\n";
}
echo $arr;
Help me please
Change the header to
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
to enforce using the UTF-8 character set.
When this does not work, please show what your filter does.
How can I set UTF8 character coding with this code?
My problem is that when I open the exported file in Excel, I have to set the encoding manually.
$filename = "termekek.xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = mysqli_query($kapcs, $sql) or die('SQL error - '.mysqli_error($kapcs));
while($row = mysqli_fetch_assoc($result))
{
if(!$flag)
{
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
You need to send a UTF8 BOM (Byte Order Mark) after sending your headers and before the data:
$filename = "termekek.xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
echo "\xEF\xBB\xBF"; // UTF8 BOM
$flag = false;
$result = mysqli_query($kapcs, $sql) or die('SQL error - '.mysqli_error($kapcs));
while ($row = mysqli_fetch_assoc($result)) {
if (!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit();
I can easily export data as excel file with a simple code but I get a problem when I need to call the export.php by j query code. Data is not downloaded as export.php file. The code is :
<?php
include '../../config.php';
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv<span>; charset=UTF-16LE</span>");
$out = fopen("php://output", 'w');
$flag = false;
$result = mysql_query("SELECT * FROM employee") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
fputcsv($out, array_keys($row), ',', '"');
$flag = true;
}
array_walk($row, 'cleanData');
if($row['photo']!='')
{
$row['photo']="http://localhost/admin/employee_image/".$row['photo'];
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
Is there any way to call this file by jquery?
No you cannot do this by Javascript using jQuery or any other library, AJAX calls data in Javascript engine inside the browser.
But you can use HTML5 download attribute:
Download Excel
And give proper headers in PHP:
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=your_file.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
EDIT:
Although the above will work, I take my words back as I found this:
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
Made by https://stackoverflow.com/users/455556/john-culviner , ask him for help if you need
Cheers!
i'd like to make an export into CSV format, but the mutualised host i use has deactivate the FILE functions in mysql.
I did a simple SELECT and then a fopen and fwrite with PHP.
The problem is that in fields there is carriage returns or double quotes.
How to keep them and build a correct csv file?
Thanks a lot.
To build a best CSV. you can do following way.
$filename ='data.csv';
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$results = array('1','2','3');// value
$schema_insert = '';
$header = array('a','b','c');// header
for ($i = 0; $i< count($header); $i++)
{
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
stripslashes($header[$i])) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
} // end for
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
// Format the data
for($i=0;$i<count($results);$i++)
{
$row = $results[$i];
$schema_insert = '';
for ($j = 0; $j < count($header); $j++)
{
if ($row[$j] == '0' || $row[$j] != '')
{
if ($csv_enclosed == '')
{
$schema_insert .= $row[$j];
} else
{
$schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
}
} else
{
$schema_insert .= 'NULL';
}
if ($j < count($header) - 1)
{
$schema_insert .= $csv_separator;
}
} // end for
$out .= $schema_insert;
$out .= $csv_terminated;
} // end while
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
// Output to browser with appropriate mime type, you choose <img src="http://thetechnofreak.com/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley">
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
Notice that,
+ when you make enclosed for description which has html code , you should use double quote.
+ Empty value --> Change to Null text or Zero value
They will make your CSV better.
You can download file.csv by use header()
Output everything you want (base on csv format) after header function, for example:
$filename = "output";
header('Content-Type: text/csv');
header('Content-disposition: attachment;'.$filename.'=.csv');
$separate = ","; //or ;
$endline = "\r\n";
foreach($data as $key => $item)
{
echo $key.$separate.$value.$endline;
}
protected function getCsv( $fileName, array $data )
{
// alot of headers here, make force download work on IE8 over SSL
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.'"');
header("Content-Transfer-Encoding: binary");
// Joe Green says:
// based on http://www.php.net/manual/en/function.fputcsv.php#100033
$outStream = fopen("php://output", "r+");
function __getCsv( &$vals, $key, $filehandler ) {
fputcsv( $filehandler, $vals, ',', '"');
}
array_walk( $data, '__getCsv', $outStream );
fclose($outStream);
}
fputcsv is your friend. Also, I had to refine this function to get it to this point. Some of those headers are required by IE to force the csv to open as a csv, particularly over SSL. I seem to recall it had something to do with IE8 not recognising the 'text/csv' content type in the first instance and some security features around SSL downloads in the second.