This is the SQL query
$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table;
if (!$result = mysqli_query($con, $query))
{
exit(mysqli_error($con));
}
This is the part that outputs the text file
$filename = "output.txt";
$file = fopen($filename, "w");
foreach ($result as $rows)
{
fwrite($file, implode("\t",$rows).PHP_EOL);
}
header('Content-Description: File Transfer');
header('Content-type: text/tab-separated-values');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
This is the current output:
This is the output that I need:
As commented out by #Slava Rozhnev and best way is to use csv like this:
<?php
$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table";
$result = mysqli_query($con, $query);
$fp = fopen('file.csv', 'w');
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
fputcsv($fp, $row);
}
fclose($fp);
Related
I'm trying to develop a short code that allows me to get the entire data from on column from a table to a .txt file.
$query = $connection->prepare("SELECT * FROM newsletter WHERE status = :status");
$query->execute(array(":status" => "1"));
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$file = $_SERVER['DOCUMENT_ROOT']."/assets/files/".$date=date("d-m-Y")."-newsletter.txt";
$openf = fopen($file, "w");
$current = file_get_contents($file);
$current .= "".$row["email"].",";
file_put_contents($file, $current);
fwrite($openf, $current);
fclose($openf);
}
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
readfile($file);
this is what i have so far, but the main problem is that it only prints 1 line to the .txt file, whether it should print at least 2.
Anyone can help me solve this? I've tried different methods and none worked so far.
create the file before loop and save after loop
$query = $connection->prepare("SELECT * FROM newsletter WHERE status = :status");
$query->execute(array(":status" => "1"));
//create file
$file = $_SERVER['DOCUMENT_ROOT']."/assets/files/".$date=date("d-m-Y")."-newsletter.txt";
$openf = fopen($file, "w");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$current = file_get_contents($file);
$current .= "".$row["email"].",";
file_put_contents($file, $current);
}
//save and close
fwrite($openf, $current);
fclose($openf);
...
Now in system it is possible to download .txt file generated from MySQL table row. I am trying to make it possible to download all .txt files in one zip file. Actually, I stuck on the point where I am not sure if my approach is possible.
if (isset($_POST["ExportAll"])) {
$query = $con->query("SELECT id, filename FROM thistable");
$MultiArray = Array();
while($result = $query->fetch_assoc()){
$rowArray = Array();
$rowArray[] = $result['id'];
$rowArray[] = $result['filename'];
$MultiArray[] = $rowArray;
}
foreach ($MultiArray as $arg) {
$query = "SELECT * FROM thistable WHERE id LIKE '" . $arg[0] . "';";
$result = mysqli_query($con, $query);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $arg[1] );
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$output = fopen("php://output", "w");
while ($row = mysqli_fetch_assoc($result)) {
foreach(array_slice($row,2) as $line) {
echo ("$line \r\n");
}
}
fclose($output);
}
}
It is possible to put all $output values into some kind of $zipArray = Array() and then download it with header("Content-type: application/zip");
?
Yes you can download multiple text files as single zip file using php ZipArchive class. This is sample only you can try with your own scenario.
$zipname = 'sample.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$files_array = ["sample1", "sample2"]; // List of file names
foreach ($files_array as $file) {
$row = ["Line 1", "Line 2", "Line 3", "Line 5"]; // Assuming as your table row
$filename = $file.".txt";
$lines_to_add = "";
foreach(array_slice($row, 2) as $line) {
$lines_to_add .= $line."\r\n";
}
$zip->addFromString($filename, $lines_to_add); // Adding lines to file
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
unlink($zipname); // Remove zip file if you don't want be in server
I am facing with strange problem while exporting my csv file on safari it is just displaying on browser instead of downloading .While same code is working with Firefox and Crome.I have searched but nothing is working for me. Please help. Here is my code-
<?php
ob_clean();
ob_start();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
function exportData() {
$fp = fopen('php://output', 'w');
fputcsv($fp, array('Market ID', 'Market Name', 'Suburb', 'State', 'Start Time', 'End Time', 'Status',"~"));
include "database.php";
$dbquery = #$_POST['query'];
$queryAllUser = $dbquery;
$resultAllUser = mysql_query($queryAllUser);
$countAllUser = mysql_num_rows($resultAllUser);
if($countAllUser > 0)
{
while($rowMarketId= mysql_fetch_assoc($resultAllUser))
{
$marketId = $rowMarketId['mrkt_id'];
$isCancel = $rowMarketId['is_cancel'];
$openning_tim = $rowMarketId['openning_time'];
$closing_tim = $rowMarketId['closing_time'];
$suburb = $rowMarketId['suburb'];
$name = $rowMarketId['name'];
$state = $rowMarketId['state'];
if($isCancel == 0)
{
$status_type = "Open";
}
else
{
$status_type = "Close";
}
$val = array();
$val[] = $marketId;
$val[] = $name;
$val[] = $suburb;
$val[] = $state;
$val[] = $openning_tim;
$val[] = $closing_tim;
$val[] = $status_type;
$val[] = "~";
fputcsv($fp, $val);
}
}
}
exportData();
?>
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' .urlencode(basename($filename)));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
Try With this Headers........ This should Work..
I'm storing pdf's on the filesystem and path in database table. I want now based on the ID to open corresponded PDF document in the browser. How can I open and read PDF's?
What I have so far is this
require_once("database.php");
if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))
{
$fileFolder='uploads/';
$sql = "SELECT file FROM documents WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$result->execute();
$resArray = $result->fetchAll();
$file = $resArray['file'];
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileFolder.$file));
#read($fileFolder.$file);
}
When I click on the button and tried to open the pdf I got this message in the Chrome
Failed to load PDF document
RELOAD
You can get your file name using fetch(PDO::FETCH_ASSOC); which Return next row as an array indexed by column name
$sql = "SELECT file FROM documents WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$result->execute();
$resArray = $result->fetch(PDO::FETCH_ASSOC);
$file = $resArray['file'];// get your file name
By using fetchAll
Pass PDO::FETCH_COLUMN, 0
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$file = $resArray[0];// get your file name
try the following:
require_once("database.php");
if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))
{
$fileFolder='uploads/';
$sql = "SELECT file FROM documents WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$result->execute();
$resArray = $result->fetchAll();
$file = $resArray['file'];
$myFilePath = $fileFolder . $file;
if (file_exists($myFilePath)) {
// the file exists, so open it
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileFolder.$file));
#read($fileFolder.$file);
} else {
// the file doesn´t exits
// handle the error if neccessary
echo "the file doesn´t exist";
}
}
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);
}