php script to convert csv to pdf - php

I'm going to modify the below php script such that it downloads the database as a .pdf file rather than in a .csv format. How should I do that? Currently when this script is called, the database will be downloaded as a .csv file. The database is defined in directadmin.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'db.php';
define("tableStuff", "stuff");
define("tableUser", "user");
define("ERR", '{"status":1}');
define("INVALID", '{"status":2}');
define("rowUserId", "user_id");
define("rowRegDate", "reg_date");
define("rowStuffName", "stuff_name");
define("rowPurchaseDate", "purchase_date");
define("rowStuffCount", "stuff_count");
define("rowStuffDescription", "stuff_description");
define("rowPicUrl", "pic_url");
define("rowUserName", "user_name");
//**********************************************************************
$mysqli = mysqli_connect(DBIP, DBUN, DBPW, DBNAME);
if ($mysqli->connect_errno) {
echo ERR;
die;
}
mysqli_set_charset($mysqli, "utf8");
$result = $mysqli->query("SELECT ".rowStuffName.",".rowStuffCount.",".rowStuffDescription.",".rowPurchaseDate.",".tableStuff.".".rowRegDate.",".rowUserName." FROM " . tableStuff .",".tableUser.
" WHERE " . tableStuff.".".rowUserId . " = " . tableUser.".".rowUserId);
if ($result->num_rows > 0) {
$array = array();
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$array[] = $row;
}
header('Content-Encoding: UTF-8');
header('Content-Type: application/csv; charset=utf-8' );
header(sprintf( 'Content-Disposition: attachment; filename=stuff.csv', date( 'dmY-His' ) ) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//echo pack("CCC",0xef,0xbb,0xbf);
$title = array("نام کالا","تعداد (مقدار)","توضیحات","زمان ثبت","نام فرد ثبت کننده");
$out = fopen("php://output", 'w');
//fputs($out,"\xEF\xBB\xBF");
fputcsv($out, $title,"\t");
foreach ($array as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
} else {
echo INVALID;
}
mysqli_close($mysqli);

I am late,but i am using FPDF to generate all PDF files,It includes a built in example of making PDF with tables from CSV file,I just changed the source of CSV file.It is super easy.

Related

Download Blob file with php ( mysql )

I have a MySQL database where I have a table call for example "ALL" can contain a blob files.
In the table i have stored the: size of the file, the type, the name and the content.
The problem come when i try download the blob file.
This is my script:
<?php
$connection = mysqli_connect("localhost","user","password",dbname)
or die('Database Connection Failed');
mysqli_set_charset($connection,'utf-8');
$query = "SELECT * " ."FROM ALL WHERE id = '25'";
$result = mysqli_query($connection,$query)
or die('Error, query failed');
list($id, $user_made, $title, $category, $sub_category, $text, $type, $date, $time, $namefile1, $typefile1, $sizefile1, $contentfile1, $namefile2, $typefile2, $sizefile2, $contentfile2, $namefile3, $typefile3, $sizefile3, $contentfile3) = mysqli_fetch_array($result);
echo $id . $namefile1 . $typefile1 . $sizefile1;
header('Content-Length: '.$sizefile1);
header('Content-Type: '.$typefile1);
header('Content-Disposition: attachment; filename="'.$namefile1.'"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
ob_clean();
flush();
// echo $contentfile1;
mysqli_close($connection);
exit;
?>
But the page output only the echo of "$contentfile1" and "$id . $namefile1 . $typefile1 . $sizefile1".
Everyone can help me?
Thanks
Add this code before ob_clean.
$context = stream_context_create();
$file = fopen($filename, 'rb', FALSE, $context);
while(!feof($file))
{
echo stream_get_contents($file, max_bytes_to_read);
}
fclose($file);
You can get more information about stream_get_contents at http://php.net/manual/en/function.stream-get-contents.php

Export csv to any other program user has on his system

I want to export my db data to CSV or asking user "Open with his local supporting program".
Exporting to csv I could understand using this code:
<?php
header("Content-type: text/csv; charset=UTF-8");
header('Content-Disposition: attachment; filename=Export.csv');
//connection
$con = mysql_connect('localhost', 'root', '');
if(!$con){
echo "Error connection";
}
//select db
$select_db = mysql_select_db('country', $con);
if(!$select_db){
echo "Error to select database";
}
mysql_set_charset("utf8", $con);
//Mysql query to get records from datanbase
$user_query = mysql_query('SELECT * FROM countries');
//While loop to fetch the records
$contents = "ccode,country\n";
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['ccode'].",";
$contents.=$row['country']."\n";
}
$contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8");
print $contents_final;
?>
How 2nd part could be managed? Showing option to open with local installed program?
Above code is correct?
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/csv');
header('Content-Disposition: attachment; filename="your_file_name.csv"');
header('Content-Transfer-Encoding: binary');
This will cause the browser to display the dialog box to Save / Open the file.
You should also consider a) switching to mysqli_ or PDO and b) using PHP's built-in csv functions, e.g.
ob_start();
$f = fopen('php://output', 'w');
// $results comes from mysqli_ functions
foreach ( $results as $k => $v ) {
fputcsv($f, $v);
}
$output = ob_get_contents();
ob_end_clean();
echo $output;

Download csv from codeigniter mysql

I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.
Here's my code:
<?php
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);
?>
$stories is my array created from the MySQL query.
Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?
final working code:
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output');
$name = 'data.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
You can call model CSV() from your controller as
$this->load->model('Users_model');
$this->Users_model->csv();
and in the model
function csv()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->query("SELECT * FROM Users");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
force_download('CSV_Report.csv', $data);
}
Your File will start downloading
I can't tell what headers are set from the Codeigniter force_download() function sets. If it is indeed going to the screen I would suspect the necessary headers are missing. You can add the below headers to your code to set correct csv dowload headers (The cache control will ensure fresh data download each time:
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$name);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
i am use this and its work
header('Content-Type: text/csv; charset=utf-8');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header("Content-Disposition: attachment; filename=backup" . date('y-m-d') . ".csv");
header('Last-Modified: ' . date('D M j G:i:s T Y'));
$outss = fopen("php://output", "w");
$this->db->order_by('ID', 'DESC');
$query = $this->db->get('urls');
foreach ($query->result_array() as $rows) {
fputcsv($outss, $rows);
}
fclose($outss);
return;
If you are trying to generate reports in csv format then it will quite easy with codeigniter.
Place this code in your Controller
function get_report()
{
$this->load->model('Main_Model');
$this->load->dbutil();
$this->load->helper('file');
/* get the object */
$report = $this->Main_Model->print_report();
$delimiter = ",";
$newline = "\r\n";
$new_report = $this->dbutil->csv_from_result($report, $delimiter, $newline);
write_file( 'application/third_party/file.csv', $new_report);
$this->load->view('report_success.php');
}
Put this code into Model
public function print_report()
{
return $query = $this->db->query("SELECT * FROM Table_name");
}
report_success.php is just Successful Notification.
Your Report is being Exported. Thank you
Finally Your "file.csv" is generated.
its basically stored at physical storage.
In CodeIgniter/application/third-party/file.csv
it works.
it will help you.
Here we have sample result set from MySQL and want to export in CSV file.
Step 1: Get MySql data in key value pair.
$data = array(
'0' => array('Name'=> 'Parvez', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
'1' => array('Name'=> 'Alam', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
'2' => array('Name'=> 'Sunnay', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
'3' => array('Name'=> 'Amir', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
'4' => array('Name'=> 'Amir1', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
'5' => array('Name'=> 'Amir2', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);
Step 2: PHP code to get options type and force to browser download file instead of display.
if(isset($_POST["ExportType"]))
{
switch($_POST["ExportType"])
{
case "export-to-csv" :
// Submission from
$filename = $_POST["ExportType"] . ".csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
ExportCSVFile($data);
//$_POST["ExportType"] = '';
exit();
default :
die("Unknown action : ".$_POST["action"]);
break;
}
}
function ExportCSVFile($records) {
// create a file pointer connected to the output stream
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// output the column headings
fputcsv($fh, array_keys($row));
$heading = true;
}
// loop over the rows, outputting them
fputcsv($fh, array_values($row));
}
fclose($fh);
}
Step 3: Define html layout for display data in table and button to fire export-to-csv action.
<div>Export to csv</div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
<input type="hidden" value='' id='hidden-type' name='ExportType'/>
</form>
<table id="" class="table table-striped table-bordered">
<tr>
<th>Name</th>
<th>Status</th>
<th>Priority</th>
<th>Salary</th>
</tr>
<tbody>
<?php foreach($data as $row):?>
<tr>
<td><?php echo $row ['Name']?></td>
<td><?php echo $row ['Status']?></td>
<td><?php echo $row ['Priority']?></td>
<td><?php echo $row ['Salary']?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Step 3: Now we will use jQuery code to get click event.
<script type="text/javascript">
$(document).ready(function() {
jQuery('#export-to-csv').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
case 'export-to-csv' :
$('#hidden-type').val(target);
//alert($('#hidden-type').val());
$('#export-form').submit();
$('#hidden-type').val('');
break
}
});
});
</script>

save html output in txt file with php

need to generate a txt file with the following output html code
<?php
function video() {
$video = 'BYN-DEM7Mzw';
echo '<script type="text/javascript">
function youtubeFeedCallback( data ){
document.writeln( data.entry[ "media$group" ][ "media$description" ].$t.replace( /\n/g, "<br/>" ) + "<br/>" ); }
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/'.$video.'?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>';
}
ob_start();
video();
$output = ob_get_clean();
$desc = $output;
$video = 'BYN-DEM7Mzw';
$arq = $video.".txt";
$f = fopen($arq, "w+");
fclose;
$f = fopen($arq, "a+");
$content = "";
if(filesize($arq) > 0)
$content = fread($f, filesize($arq));
fwrite($f, $desc);
fclose($f);
?>
the problem that the file is saving up my script and not the output html
I think you should be using the right headers and the correct mime in it.
For example
header('Content-Description: File Transfer');
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
if ($file != '')
{
echo file_get_contents($file);
}

Form downloads same ZIP over and over

Thanks to the users community on this forum, I wrote a very simple web form that allows my user to view text files from within their Internet browser.
I have now two functions whereby the text files returned by the search are compressed into a ZIP. Here's my code
function getFilesFromSite() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBSite'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$getfilename = mysql_query("select filename from search_table where site='" . $DBSite . "'") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("/bin/rm -f SearchResult.zip;/usr/bin/zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
//header for forced download
header("Pragma: public");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$fileName = 'SearchResult.zip';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: binary");
header('Content-type: application/zip');
header("Content-length: " . filesize($fileName));
header('Content-Disposition: attachment; filename="' . $fileName . '"');
ob_start(); // Starts output buffering.
readfile($fileName); // "Outputs" the file.
$content = ob_get_flush(); // Grabs the output and assigns it to a variable.
print base64_encode($content);
}
function getFilesFromError() {
//Just a copy paste from above with different input parameter...
}
The problem is that the ZIP file with the contents from whatever search was done first gets downloaded over and over again. For instance, the results from getFilesFromSite() will always get downloaded even though I did a search with getFilesFromError() afterwards.
I suspect my headers are incorrectly set but I am not sure where.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
Using Base64 was actually not working for reasons well stated here. Instead, I turned zlib compression off and reverted back to using binary as output format. Finally, I set Content-Type to application/octet-stream in my header. Everything is working fine now ; here's my code:
function getFiles() {
ini_set('zlib.output_compression', 'Off');
$result = null;
$ZIPresult = null;
$cleanup = null;
$output = null;
$fileName = null;
//remove old zip if any
$cleanup = shell_exec("/bin/rm -f SearchResult.zip");
error_log("SHELL OUTPUT=>" . $cleanup, 0);
//test
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR; // set from the CONSTANT
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select /*! SQL_CACHE */ filename from automation where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
$output = shell_exec("/usr/bin/zip SearchResult.zip ". $ZIPresult ." ");
error_log("SHELL OUTPUT=>" . $output, 0);
$fileName = 'SearchResult.zip';
error_log("ZIP FILENAME=>" . $fileName, 0);
if (file_exists($fileName)) {
//header for forced download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
}
return $result;
}
Thanks to all for taking the time!!

Categories