Export CSV file from Codeigniter - php

I am using csv_helper.php file in helpers for exporting. It is grabing the results from mysql but showing the results only instead of downloading !
Here's the csv_helper
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('array_to_csv'))
{
function array_to_csv($array, $download = "")
{
if ($download != "")
{
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $download . '"');
}
ob_start();
$f = fopen('php://output', 'w') or show_error("Can't open php://output");
$n = 0;
foreach ($array as $line)
{
$n++;
if ( ! fputcsv($f, $line))
{
show_error("Can't write line $n: $line");
}
}
fclose($f) or show_error("Can't close php://output");
$str = ob_get_contents();
ob_end_clean();
if ($download == "")
{
return $str;
}
else
{
echo $str;
}
}
}
if ( ! function_exists('query_to_csv'))
{
function query_to_csv($query, $headers = TRUE, $download = "")
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('invalid query');
}
$array = array();
if ($headers)
{
$line = array();
foreach ($query->list_fields() as $name)
{
$line[] = $name;
}
$array[] = $line;
}
foreach ($query->result_array() as $row)
{
$line = array();
foreach ($row as $item)
{
$line[] = $item;
}
$array[] = $line;
}
echo array_to_csv($array, $download);
}
}
And here's the controller function:
public function exportUser() {
$this->load->database();
$query = $this->db->get('user');
$this->load->helper('csv');
query_to_csv($query, TRUE, 'toto.csv');
}
And in the view page it is showing the results:
user_id,user_name,user_email,user_pass,user_phone,user_country,user_city,user_zip,user_address,user_type,user_status 53,abcdef,abcd#yahoo.com,12,1,,0,,,Student,1 54,aws,abc#yahoo.com,12,12,Afghanistan,Kapisa,,,"Resource Person",0 55,onti,ontika#ya.com,12,12,,0,,,"Registered User",1 56,edf,df#abc.com,12,12,Albania,Bulqize,,dewde,"Admin User",1 58,meena,meena#abc.com,,,,,,,"Registered User",0
61,nisat,nisat#abc.com,,,,,,,"Registered User",0
but not downloading ! Tried Chrome and mozilla both....
What to do???
Thank you in advance !

Try modifying the headers in array_to_csv() funtion:
// Disable caching
$time = gmdate('D, d M Y H:i:s');
header('Expires: Tue, 03 Jul 2001 06:00:00 GMT');
header('Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate');
header('Last-Modified: ' . $time . ' GMT');
// Force download
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
// Set encoding
header('Content-Disposition: attachment;filename=' . $download);
header('Content-Transfer-Encoding: binary');
Then after the output section, add an exit:
if ($download == "")
{
return $str;
}
else
{
echo $str;
}
exit;
Or try using CodeIgniter's built-in functions:
public function exportUser() {
// Load database and query
$this->load->database();
$query = $this->db->get('user');
// Load database utility class
$this->load->dbutil();
// Create CSV output
$data = $this->dbutil->csv_from_result($query);
// Load download helper
$this->load->helper('download');
// Stream download
force_download('toto.csv', $data);
}
Thanks,
Andrew

Related

Data from separate function being merged in excel

Im working on 2 json data which I need to transfer the data to separate excel files. What I did is, I made 2 function so that I can choose what file to be downloaded. The problem is when I tried to call both, the data is merged on a single excel. What I expect is it will be downloaded separately.
I tried adding sleep after the first function but didn't work, still the same output. I tried also using die after both function but only the first one is working.
Hope you help me.
SAMPLE CODE
function.php
<?php
function bjpk(){
$json = 'api link...';
$arr = json_decode(file_get_contents($json), true);
$name = $arr['code'];
header("Content-Disposition: attachment; filename=\"$name.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
$data = array();
foreach ($arr['data'] as $key => $value) {
$data['date'] = substr($value['opentime'], 0, -9);
$data['num'] = substr($value['expect'], 4);
$codes = explode(',', $value['opencode']);
foreach ($codes as $key => $code) {
$data[$key] = $code;
}
fputcsv($out, $data,"\t");
}
fclose($out);
}
function cqssc(){
$json = 'api link..';
$arr = json_decode(file_get_contents($json), true);
$name = $arr['code'];
header("Content-Disposition: attachment; filename=\"$name.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
$data = array();
foreach ($arr['data'] as $key => $value) {
$date = DateTime::createFromFormat('Ymd', substr($value['expect'], 0, -3));
$data['date'] = $date->format('Y-m-d');
$data['num'] = substr($value['expect'], 8);
$codes = explode(',', $value['opencode']);
foreach ($codes as $key => $code) {
$data[$key] = $code;
}
fputcsv($out, $data,"\t");
}
fclose($out);
}
index.php
<?php
require_once ('function.php');
bjpk();
cqssc();

Cakephp CSV helper generating leading space

I'm creating a CSV file using CakePHP CSV helper.
I'm always getting one space at the beginning of the column. I have used trim, ltrim but nothing works.
I have also added ob_start and ob_end_clean but nothing works.
My CSV code is
<?php
class CsvHelper extends AppHelper {
var $delimiter = ',';
var $enclosure = '"';
var $filename = 'Export.csv';
var $line = array();
var $buffer;
function CsvHelper() {
$this->clear();
}
function clear() {
$this->line = array();
$this->buffer = fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+');
}
function addField($value) {
$this->line[] = $value;
}
function endRow() {
$this->addRow($this->line);
$this->line = array();
}
function addRow($row) {
fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
}
function renderHeaders() {
ob_start();
header('Content-Encoding: UTF-16LE');
header('Content-Type: text/csv; charset=UTF-8');
header("Content-type:application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="' . $this->filename . '"');
header("Pragma: no-cache");
header("Expires: 0");
ob_end_clean();
}
function setFilename($filename) {
$this->filename = $filename;
if (strtolower(substr($this->filename, -4)) != '.csv') {
$this->filename .= '.csv';
}
}
function render($outputHeaders = true, $to_encoding = null, $from_encoding = "auto") {
if ($outputHeaders) {
if (is_string($outputHeaders)) {
$this->setFilename(trim($outputHeaders));
}
$this->renderHeaders();
}
rewind($this->buffer);
$output = stream_get_contents($this->buffer);
if ($to_encoding) {
$output = mb_convert_encoding($output, $to_encoding, $from_encoding);
}
return $this->output(trim($output));
}
}
?>
I'm calling this helper from this ctp file to download and generate report.
<?php
$line = $gen_reports[0]['Report'];
$arrayKeys = array_keys($line);
$this->CSV->addRow($arrayKeys);
echo $this->CSV->render("filename");die;
?>
and the result I'm getting always a leading space at the very first column:
How can I get rid of this space?
Not sure if only a copy-paste error but you have an extra space right before your CsvHelper opening php tag which could result in a space in the output buffer.

Save query results to .csv with PHP

I have the following query running and I am looking at the best way to export the data to a .csv or .xls file.
<?php
$channels = ee()->db->select('channel_titles.entry_id, channel_titles.title, channel_data.field_id_164')
->from('channel_titles')
->join('channel_data', 'channel_titles.entry_id = channel_data.entry_id')
->where(array(
'channel_titles.channel_id' => '12',
))
->or_where(array(
'channel_titles.channel_id' => '31',
))
->get();
if ($channels->num_rows() > 0)
{
$i = 0;
foreach($channels->result_array() as $row)
{
$i++;
echo $row['field_id_164'].",".$row['title']."<br />\n";
}
echo $i;
}
?>
I have tried a few methods but cannot seem to figure out the best option.
The classic echo explode(',',$col) etc way is fine, but you can also write directly to the csv file using php's built in functions.
$filename = 'test.csv';
$file = fopen($filename,"w");
if ($channels->num_rows() > 0) {
foreach($channels->result_array() as $key => $row) {
if ($key==0) fputcsv($file, array_keys((array)$row)); // write column headings, added extra brace
foreach ($row as $line) {
$line = (array) $line;
fputcsv($file, $line);
}
}
}
fclose($file);
edit:
If you want to download/view the file instantly you have to set the headers.
$filename = 'test.csv';
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$file = fopen('php://output', 'a');
if ($channels->num_rows() > 0) {
foreach($channels->result_array() as $key => $row) {
if ($key==0) fputcsv($file, array_keys((array)$row)); // write column headings, added extra brace
foreach ($row as $line) {
$line = (array) $line;
fputcsv($file, $line);
}
}
}
fclose($file);

Creating Excel file from MySQL

I am trying to generate an XLS file from a table in a MySQL DB, but the Excel file is not properly formatted & given error when the Excel file generated "The file which you are trying to open is in different format than one specified". When the file is opened the data is not properly formatted.
Any ideas what I am missing?
<?php
$host = 'XXXXXXX';
$dbname = 'XXXXXXXX';
$username = 'XXXXXXXX';
$password = 'XXXXXXXX';
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
$conn = null;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$q = "SELECT * FROM tablename";
$qr = mysql_query( $q ) or die( mysql_error() );
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
header("Content-Transfer-Encoding: binary ");
xlsBOF();
$col = 0;
$row = 0;
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
if( $first )
{
foreach( $qrow as $k => $v )
{
xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
$col++;
}
$col = 0;
$row++;
$first = false;
}
// go through the data
foreach( $qrow as $k => $v )
{
// write it out
xlsWriteLabel( $row, $col, $v );
$col++;
}
// reset col and goto next row
$col = 0;
$row++;
}
xlsEOF();
exit();
I'm not sure about .xls but for outputting a MySQL result as a CSV table the fputcsv function does it without much fuss:
// Clear any previous output
ob_end_clean();
// I assume you already have your $result
$num_fields = mysql_num_fields($result);
// Fetch MySQL result headers
$headers = array();
$headers[] = "[Row]";
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = strtoupper(mysql_field_name($result , $i));
}
// Filename with current date
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
// Open php output stream and write headers
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: no-cache');
header('Expires: 0');
echo "Title of Your CSV File\n\n";
// Write mysql headers to csv
fputcsv($fp, $headers);
$row_tally = 0;
// Write mysql rows to csv
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$row_tally = $row_tally + 1;
echo $row_tally.",";
fputcsv($fp, array_values($row));
}
die;
}
use http://phpexcel.codeplex.com/
C'est la meilleur solution pour générer un fichier excel
Vous pouvez même créer plusieurs feuilles dans le fichier et formater les cellules (couleur, police, bordure, ...)
Google translate:
This is the best solution to generate an excel file You can even create multiple sheets in the file and format the cells (color, font, border, ...)
<?php
//download.php page code
//THIS PROGRAM WILL FETCH THE RESULT OF SQL QUERY AND WILL DOWNLOAD IT. (IF YOU HAVE ANY QUERY CONTACT:rahulpatel541#gmail.com)
//include the database file connection
include_once('database.php');
//will work if the link is set in the indx.php page
if(isset($_GET['name']))
{
$name=$_GET['name']; //to rename the file
header('Content-Disposition: attachment; filename='.$name.'.xls');
header('Cache-Control: no-cache, no-store, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Content-Type: application/x-msexcel; charset=windows-1251; format=attachment;');
$msg="";
$var="";
//write your query
$sql="select * from tablename";
$res = mysql_query($sql);
$numcolumn = mysql_num_fields($res); //will fetch number of field in table
$msg="<table><tr><td>Sl No</td>";
for ( $i = 0; $i < $numcolumn; $i++ ) {
$msg.="<td>";
$msg.= mysql_field_name($res, $i); //will store column name of the table to msg variable
$msg.="</td>";
}
$msg.="</tr>";
$i=0;
$count=1; //used to print sl.no
while($row=mysql_fetch_array($res)) //fetch all the row as array
{
$msg.="<tr><td>".$count."</td>";
for($i=0;$i< $numcolumn;$i++)
{
$var=$row[$i]; //will store all the values of row
$msg.="<td>".$var."</td>";
}
$count=$count+1;
$msg.="</tr>";
}
$msg.="</table>";
echo $msg; //will print the content in the exel page
}
?>
<?php
//index.php page
$name="any file name";
echo "<a href='download.php?name=".$name."'>Click to download</a>"; //link to download file
?>
Here is simple Excel file generation function, very fast and exactly .xls file.
$filename = "sample_php_excel.xls";
$data = array(
array("User Name" => "Abid Ali", "Q1" => "$32055", "Q2" => "$31067", "Q3" => 32045, "Q4" => 39043),
array("User Name" => "Sajid Ali", "Q1" => "$25080", "Q2" => "$20677", "Q3" => 32025, "Q4" => 34010),
array("User Name" => "Wajid Ali", "Q1" => "$93067", "Q2" => "$98075", "Q3" => 95404, "Q4" => 102055),
);
to_xls($data, $filename);
function to_xls($data, $filename){
$fp = fopen($filename, "w+");
$str = pack(str_repeat("s", 6), 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); // s | v
fwrite($fp, $str);
if (is_array($data) && !empty($data)){
$row = 0;
foreach (array_values($data) as $_data){
if (is_array($_data) && !empty($_data)){
if ($row == 0){
foreach (array_keys($_data) as $col => $val){
_xlsWriteCell($row, $col, $val, $fp);
}
$row++;
}
foreach (array_values($_data) as $col => $val){
_xlsWriteCell($row, $col, $val, $fp);
}
$row++;
}
}
}
$str = pack(str_repeat("s", 2), 0x0A, 0x00);
fwrite($fp, $str);
fclose($fp);
}
function _xlsWriteCell($row, $col, $val, $fp){
if (is_float($val) || is_int($val)){
$str = pack(str_repeat("s", 5), 0x203, 14, $row, $col, 0x0);
$str .= pack("d", $val);
} else {
$l = strlen($val);
$str = pack(str_repeat("s", 6), 0x204, 8 + $l, $row, $col, 0x0, $l);
$str .= $val;
}
fwrite($fp, $str);
}
<?php
ob_end_clean();
$num_fields = mysql_num_fields($result);
$headers = array();
$headers[] = "[Row]";
for ($i = 0; $i < $num_fields; $i++)
$headers[] = strtoupper(mysql_field_name($result , $i));
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: no-cache');
header('Expires: 0');
echo "Title of Your CSV File\n\n";
fputcsv($fp, $headers);
$row_tally = 0;
// Write mysql rows to csv
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$row_tally = $row_tally + 1;
echo $row_tally.",";
fputcsv($fp, array_values($row));
}
die;
}
?>

PHP Mysql table conversion to excel:The file you are trying to open is in a different format than specified by the extension

I have a code that converts mysql table to excel sheet. It converts and the excel sheet is downloaded but whenever I try to open the file it gives an error msg in excel 2007:"The file you are trying to open is in a different format than specified by the extension...".The excel sheet opens after I click on 'Yes' but it is nothing but a white blank sheet.I have seen the similar posts but none of them solves my problem...Please help...Thank you
<?php
include('dbcon.php');
?>
<?php
$sql = "SELECT * FROM stu_gen_info";
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($rec,$i)."\\t";
}
while($row = mysql_fetch_row($rec))
{
$line = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = "\\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\\n";
}
$data = str_replace("\\r" , "" , $data);
if ($data == "")
{
$data = "\\n No Record Found!\n";
}
header("Content-Type: application/vnd.ms-excel");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\\n$data";
?>
try adding this
header("Content-Type: application/vnd.ms-excel");

Categories