Export MySQL table to CSV with custom header - php

Why when i try to export MySql table to CSV with header('Content-Disposition:attachment; filename="'.$filename.'"'); It doesn't get done properly:
it does create the CSV file
however it does it on the beginning of the file, where the page code is
and after the code the is table content
This is the code witch exports it:
$this->view->table = $model->info('name');
$is_csv = $this->_getParam('csv');
if ($this->_request->isPost() && $is_csv) {
$fichier = 'file.csv';
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="'.$fichier.'"');
$fp = fopen('php://output', 'w+');
$data = $model->fetchAll();
foreach ($data as $fields) {
fputcsv($fp, $fields->toArray());
}
fclose($fp);
}
And here i'm calling this with button:
<form method="post">
<input type="hidden" name="table" value="<?php echo $this->table ?>" />
<button type="submit" class="btn" name="csv" value="csv">
<?php echo Core_Locale::translate('CSV')?>
</button>
</form>

put this code up in your application then application create view.
I had same issue but i solved it this way..
i put peace of code to function/block and place it over echo or render html
put exit; on the end of function/block
if(isset($_POST['submit'])) {
$csv = new Csv();
$filename = $csv->generateFileDate();
if($filename !== false) {
$data = file_get_contents($csv->folder .'reports/'. $filename);
header('Content-Type: application/csv; charset=utf-8');
header('Content-Disposition: attachement;filename="'.$filename.'";');
echo $data;
exit;
}
}
?>
<!doctype html>
<html lang="us">
<head> .........
hope this help to you

Related

PHP including HTML in readfile

I have the following code which kind of works but for some reason the $download includes the part inside into the downloaded file.
<form method="post">
<button id="click" name="click">Download</button>
</form>
<?php
if(isset($_POST['click'])){
$files = scandir('/local/path', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
$download = $newest_file;
header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$download.'"');
readfile("/local/path/$download");
}
?>
Downloaded file
form method="post">
<button id="click" name="click">Download</button>
</form>
Start-of-the-actual-log
blabla
blabla
blabla
What is causing this to happen? I only want to download the newest file in a folder.
Dont print anything or send header before downloading, look at this :
<?php
if(isset($_POST['click'])){
$files = scandir('/local/path', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
$download = $newest_file;
header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$download.'"');
readfile("/local/path/$download");
}else{
echo'
<form method="post">
<button id="click" name="click">Download</button>
</form>';
}
?>

downloads corrupt files from the file location on server

The file moves to desired location and opens in the folder but when i download it downloads a corrupt file
I have tried all the suggestions from the existing posts but it doesn't seem to do the trick.
<?php
$error = "error";
$con = mysqli_connect('localhost','root','') or die($error);
mysqli_select_db($con, 'folder') or die($error);
$sql = "SELECT * FROM documents";
$res = mysqli_query($con, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Photo<br><br>
<?php
while ($row = mysqli_fetch_array($res)) {
$id = $row['id'];
$name = $row['name'];
$path = $row['path'];
echo $id." ".$name." <a href='download.php?dow=$path'>Download</a><br>";
}
?>
</body>
</html>
The upload code is:
<?php
$error = "error";
$con = mysqli_connect('localhost','root','') or die($error);
mysqli_select_db($con,'servicereport') or die($error);
if (isset($_POST['submit'])) {
$doc_name = $_POST['doc_name'];
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name) {
$location = "documents/$name";
move_uploaded_file($tmp_name, $location);
$query = mysqli_query($con,"INSERT INTO documents(name,path) VALUES ('$doc_name','$location') ");
header('location:photos.php');
}
else
die("please select a file");
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="doc_name">
<input type="file" name="myfile">
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
The download code is:
<?php
include('inc/db.php');
if (isset($_GET['dow'])) {
$path = $_GET['dow'];
$res = mysqli_query("SELECT * FROM documents WHERE path = '$path' ");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length:'.sprintf("%u", filesize($path)));
set_time_limit(0);
readfile($path);
}
?>
Please add these two lines of code after 'set_time_limit(0);' & before 'readfile($path);', because these functions are necessary for removing unnecessary data or preventing from corruption.
Find the code below, which are to be added:
ob_clean();
flush();
I hope, this will solve your problem.

Exporting multiple CSV files from MySQL into zip

Major Edit: I've updated my code to better include the Archive class, as well as the ZIP download. The table is written to the database just fine, but I get an error in my error log saying "No such file or directory." Where do I write the file per table?
Thanks so much for any help/suggestions!
Below is my code:
HTML Form
if($_POST['submit']){
if(empty($_POST['jobtitles'])) echo "<strong>Error: You have not entered a Job Title, please go back and enter one.</strong>";
else echo "<strong>Your documents are processing and being exported.</strong>";
}
?>
<body>
<center><strong><u>BLS Data Processor and Exporter</u></strong></center>
<form method="post" action="handler.php">
<p>Enter all of the desired jobs, each separated by a new line. Note: All jobs must be spelled exactly as contained in the BLS data</p>
<textarea name="jobtitles" rows="10" cols="50">
</textarea>
<p>Upon clicking submit, your tables will be generated and exported as a CSV file</p>
<p>Select the table types you would like to receive</p>
<input type="checkbox" name="tabletype[]" value="local">Local<br>
<input type="checkbox" name="tabletype[]" value="msa">MSA<br>
<input type="checkbox" name="tabletype[]" value="nmsa">NMSA<br>
<input type="checkbox" name="tabletype[]" value="state">State<br>
<input type="checkbox" name="tabletype[]" value="nat">National<br>
<input type="submit" value="Submit and Export">
</form>
</body>
PHP side
header("Content-disposition: attachment; filename=".$fileName);
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: application/zip;\n");
header("Pragma: no-cache");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public");
header("Expires: 0");
// Create the ZIP file
$zip = new ZipArchive;
$result_zip = $zip->open($fileName, ZipArchive::CREATE); // We open the file
if ($result_zip === TRUE) {
$pdo = new PDO("mysql:host=localhost;dbname=BLSdata","root","root");
$tableList = $pdo->prepare('SHOW TABLES FROM BLSdata LIKE "localTable" AND "msaTable" AND "nmsaTable" AND "stateTable" AND "natTable"');
$tableList->execute(array(''));
// For each table
foreach($tableList as $aTableList)
{
$content = export_table($aTableList[0]);
$fileName = $aTableList[0].'.csv';
$zip->addFile($fileName, $fileName);
}
$zip->close();
}
else
{
echo 'Failed, code:' . $result_zip;
}
readfile($fileName);
$deleteLocal = "DROP TABLE localTable";
$pdo->query($deleteLocal);
exit();

Download html textarea content as a file

I am working on a project where the requirement is to download a textarea content as a .txt file on a wordpress site.
After searching previous questions, I got below code which marked as a correct answer.
<html>
<body>
<form action="#" method="post">
<textarea name="text" rows="20" cols="100"></textarea>
<input type="submit" value="submit">Download Text</input>
</form>
<?PHP
if(isset($_POST['submit']))
{
$text = $_POST['text'];
print ($text);
$filename = 'test.txt';
$string = $text;
$fp = fopen($filename, "w");
fwrite($fp, $string);
fclose($fp);
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
readfile('test.txt');
}
?>
</body>
</html>
But for me it is not creating a .txt file. please help me to identify the issue
Modified little bit in your code.
First put your php code
<?php
if(isset($_POST['submit']))
{
$text = $_POST['text'];
print ($text);
$filename = 'test.txt';
$string = $text;
$fp = fopen($filename, "w");
fwrite($fp, $string);
fclose($fp);
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
readfile('test.txt');
die; //modified code
}
?>
after that put your html code
<html>
<body>
<form action="#" method="post">
<textarea name="text" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
add name attribute in submit button.
Your code actually creates a file on the server and it does not get deleted afterwards. If the code failed, it is possible that you didn't have permission to write on your server. You can trim your code down to the following so as no file is generated in the process:
<?php
if(isset($_POST['text']))
{
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
echo $_POST['text'];
exit; //stop writing
}
?>
<html>
<body>
<form action="" method="post">
<textarea name="text" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
</body>
</html>
Firstly, you should output the file before printing anything on screen and secondly, you forgot to add name="submit" to your original code. I didn't use it here, but I included for you to get an idea.
In the WordPress Context:
Add this to your functions.php or plugin file:
function feed_text_download(){
if(isset($_POST['text_to_download']))
{
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
echo $_POST['text_to_download'];
exit; //stop writing
}
}
add_action('after_setup_theme', 'feed_text_download');
Add the form to one of your template files or in the HTML editor of your post:
<form action="" method="post">
<textarea name="text_to_download" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
It should be good :)
EDIT: Add Filename
HTML:
<form action="" method="post">
<label>Filename:<input type="text" name="filename" /></label>
<label>Text:<textarea cols="100" name="text_to_download" rows="20"></textarea></label>
<input type="submit" name="submit" value="Download Text" />
</form>
PHP:
function feed_text_download() {
if ( isset( $_POST['text_to_download'] ) && isset( $_POST['filename'] ) ) {
$filename = sanitize_file_name( $_POST['filename'] );
header( 'Content-disposition: attachment; filename=' . $filename );
header( 'Content-type: application/txt' );
echo $_POST['text_to_download'];
exit; //stop writing
}
}
add_action( 'after_setup_theme', 'feed_text_download' );
Try following code, that will help you:
<?php ob_start();?>
<html>
<body>
<?php
if(isset($_POST['tarea'])){
$filename = 'test.txt';
$data = $_POST['tarea'];
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
echo $data;
exit;
}
?>
<form action="" method="post">
<textarea name="tarea"></textarea>
<input type="submit">
</form>
</body>
</html>

how to save .html file by PHP by save as button?

I've created a PHP file which shows the results from a MySQL database as we all create like in
echo "<table><tr><td>";
...
echo "</td></tr></table>";
But now I want to make a button at the bottom of the table, something like 'save report', which saves the created table into HTML format.
So how could it be done?
You can use the following scripts:
index.php
In index.php, you have the HTML table.
<?php
$contents = "<table><tr><td>A</td><td>B</td></tr><tr><td>One</td><td>Two</td></tr><tr><td>Three</td><td>Four</td></tr></table>"; // Put here the source code of your table.
?>
<html>
<head>
<title>Save the file!</title>
</head>
<body>
<?php echo $contents; ?>
<form action="savefile.php" method="post">
<input type="hidden" name="contents" value="<?php echo htmlspecialchars($contents); ?>">
<input type="submit" value="Save file" />
</form>
</body>
</html>
savefile.php
And then use the file savefile.php to popup your browser's download dialog to save the file.
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
header('Content-type: text/html');
header('Content-Disposition: attachment; filename="table.html"');
echo $_POST['contents'];
}
?>
I think you want to save reports generated by PHP/MySQL as HTML file?
<?php
// Open file for writing
$fileHandle = fopen("/DestinationPath/DestinationFile.html", "w");
// Dump File
$head = "<html><head><title>my reports</title></head><body>\n";
fwrite($fileHandle, $head);
$sql = mysql_query("Your sql query here");
while ($result = mysql_fetch_assoc($sql)) {
$line = $result['yourmysqlfield']."\n";
fwrite($fileHandle, $line);
}
$foot = "</body></html>\n";
fwrite($fileHandle, $foot);
// Close File
close($fileHandle);
?>

Categories