I want to send an array to Excel file, this is an array containing different categories.
Each categories should go into one column. The code I have written was sending all the values to one field on Excel. Where am I getting it wrong?
$shop['id']=$id_array;
$shop['name']=$name_array;
$shop['cat1'] = $cat1;
$shop['cat2'] = $cat2;
$shop['cat3'] = $cat3;
$id_excel=implode(",",$shop['id']);
$name_excel=implode(",",$shop['name']);
$cat1_excel=implode(",",$shop['cat1']);
$cat2_excel=implode(",",$shop['cat2']);
$cat3_excel=implode(",",$shop['cat3']);
}
$filename ="cat.xls";
$contents = "$id_excel \t $name_excel \t $cat1_excel \t $cat2_excel \t $cat3_excel \t \n";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
echo $contents;
Try to use this nice plugin: PHPExel
With this plugin it's simple
Please try to return a CSV file instead of Excel. Here is the code:
<? $shop['id']=$id_array;
$shop['name']=$name_array;
$shop['cat1'] = $cat1;
$shop['cat2'] = $cat2;
$shop['cat3'] = $cat3;
$id_excel[]=implode(",",$shop);
$filename ="cat.csv";
$contents = implode("\n",$id_excel);
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $contents;
?>
Related
<?php
// // $bin = pack("S", 65535);
// // $ray = unpack("S", $bin);
// $ray = pack("H*hex", $data);
// print_r($ray);die();
// echo "UNSIGNED SHORT VAL = ", $ray[1], "\n";
$file = file_get_contents("C:\\Users\\qwerty\Downloads\\image001.jpg", true);
// $file = file_get_contents("C:\\Users\\qwerty\\Downloads\\request.pdf", true);
$data = '0x'.unpack('H*hex', $file)['hex'];
header('Content-Description: File Transfer');
header("Content-Transfer-Encoding: Binary");
// header('Content-Disposition: attachment; filename="request.pdf');
header('Content-Disposition: attachment; filename="image001.jpg');
header('Cache-Control: must-revalidate');
header('Content-Length: 80685');
echo $data;
?>
I want am trying to create File from unpacking the same file. I am recreating this from my other function that unpacks a file stores the data in database and recreate the file again using the data. The above is my sample demo for the bigger function. What it does is unpack file content then echo again. Problem is the downloaded file (image or pdf) cant be opened. Any idea is appreciated
I think I saw the problem when I opened the file in notepad it has a newline before the image data how can I make sure there will be no new line in before the data?
I am trying to turn my array in PHP into a csv to download.
Currently the array looks something like this
Array[0] = "Name,age,ID"
Array[1] = "Alex,26,1"
Array[2] = "Ryan,12,2"
Array[3] = "Steph,56,7"
etc
I was unsure how to make this download as a csv, where each array position is its own line is csv obviously.
I set the headers to the following :
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
then I tried to echo each element of the array, hoping this would work. as follows:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
foreach ($lines as &$line) {
echo $line;
}
Where $lines was my array.
However it did all one line in the csv. Is there a way I can turn this array to print properly in csv?
You have to add a newline
echo $line . "\n";
Even better
echo $line . PHP_EOL; //constant for correct line-ending depending on OS.
One of solution is fputcsv function.
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
$output = fopen('php://output', 'w');
foreach ($lines as $line) {
$row = explode(',', $line);
fputcsv($output, $row);
}
fclose($output);
I am trying to create a xls file in php. And I am making a string in html format lets say <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table> and want to print in xls file as it is. but My problem is that when I try to print in xls file its getting render. but I want raw html string without rendered in xls file.
Here is my code:-
<?php
$file="demo.xls";
$test="<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header('Content-type: application/excel');
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>php
You can also use a service called DocRaptor which does html to excel conversion. http://docraptor.com/ , Multiple language supported
Or You can use the below code to download the file in Excel but first you have to download the PHPExcel class files and include like below .
require_once "excel/Classes/PHPExcel.php";
$objTpl = new PHPExcel();
$l=0;
$row_num = 1;
$objTpl->getActiveSheet()->getDefaultStyle()->getFont()->setName('Calibri');
$objTpl->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
$objTpl->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objTpl->getActiveSheet()->duplicateStyle($objTpl->getActiveSheet()->getStyle('A1'), 'B1:Z1');
$objTpl->getActiveSheet()->getStyle('A1:Z1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// you can use loop over here remember to set $row_num = 2 if using loop and increment it inside $row_num++
$objTpl->getActiveSheet()->setCellValueByColumnAndRow($l++,$row_num, 'Cell 1');
$objTpl->getActiveSheet()->setCellValueByColumnAndRow($l++,$row_num, 'Cell 2');
$filename='some_file.xls'; //just some random filename
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5'); //downloadable file is in Excel 2003 format (.xls)
$objWriter->save('php://output'); //send it to user, of course you can save it to disk also!
exit; //done.. exiting!
There is a way by either writing html in file or comma separated text
With HTML
$xlsx_file = $pathinfo['dirname']."/".$pathinfo['filename'].".xlsx" ;
$fh = fopen($xlsx_file, 'w+');<br>
fwrite($fh, $table); // your table <br>
fclose($fh);<br>
with array or string of csv
$data = '"Name"t"City"t"Country"' . "n";<br>
$data .= '"Ashok"t"New Delhi"t"India"' . "n";<br>
$data .= '"Krishna"t"Bangalore"t"India"' . "n";<br>
$f = fopen('data.xls' , 'wb');<br>
fwrite($f , $data );<br>
fclose($f);<br>
this is temporary solution but if you want full set of options you go for PHP Excel as suggested by others
I have text file contains Sample of CSV file format, I want my users can download that file on a link click.
This file resides in this folder stucture:
assets->csv->Sample-CSV-Format.txt
This is the code that I have tried to far:
<?php
$file_name = "Sample-CSV-Format.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.') + 1);
header('Content-disposition: attachment; filename=' . $file_name);
if (strtolower($ext) == "txt") {
// works for txt only
header('Content-type: text/plain');
} else {
// works for all
header('Content-type: application/' . $ext);extensions except txt
}
readfile($decrypted_file_path);
?>
<p class="text-center">Download the Sample file HERE It has a sample of one entry</p>
This code is downloading the file on page load instead of link click. Also, it is downloading the whole html structure of the page I want only the text what I have written in text file.
Please guide where is the issue?
You can do this simply in by HTML5 download atrribute . Just add this line in your downloading link .
HERE
You can do it like this, it won't redirect you and also works good for larger files.
In your controller "Controller.php"
function downloadFile(){
$yourFile = "Sample-CSV-Format.txt";
$file = #fopen($yourFile, "rb");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=TheNameYouWant.txt');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($yourFile));
while (!feof($file)) {
print(#fread($file, 1024 * 8));
ob_flush();
flush();
}
}
In your view "view.php"
Download
make it like this
someother_file.php
<?php
$file_name = "Sample-CSV-Format.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) == "txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
?>
some_html_page.html
<p class="text-center">Download the Sample file HERE It has a sample of one entry</p>
To my view its better to have the download code to the client side, than to have a controller-method written for this.
you can use this ref
public function getTxt()
{
$this->load->helper('download');
$dataFile = "NOTE87";
$dataContent = array();
$dt = "Date :23/07/2021";
$dataContent= array(
"\n",
"\t\t\tUTI AMC Limited\n",
"\t\tDepartment of Fund Accounts\n",
"\n",
"\tReissue of Non Sale Remittance - Axis Bank Cases\n",
"\n",
"\t\t\t\tDate :".$dt."\n",
"\n",
);
force_download($dataFile,implode($dataContent));
}
So I am trying to create a Zip file from 2 strings. 1 is a html string, the other is plain text. So far I only seem to get the text string to work correctly but the file thats supposed to be HTML is just a blank file. Any idea why?
$string1 = $_POST["html_string"];
$string2 = "Some data Some data Some data Some data Some data Some data";
$filename = "test.zip";
$zip = new ZipArchive();
if ($zip->open($filename, ZIPARCHIVE::CREATE)==TRUE) {
$zip->addFromString("string1.html", $string1);
$zip->addFromString("string2.txt", $string2);
$zip->close();
}
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
//clearstatcache();
header("Content-Length: ".filesize($filename));
readfile($filename);
unlink($filename);
Thanks for any help.
Tryed your code replacing
$string1 = $_POST["html_string"];
with
$string1 = '<html>
<title></title>
</html>';
and worked.
Are you sure $_POST["html_string"] is not empty? Add var_dump($_POST); to see if there is some data or update your code adding a check at the begining.
if (empty($_POST["html_string"]))
{
echo 'html_string is empty';
exit;
}