Save csv to server rather than download - php

I have a php page that takes my query results and saves them to a csv, which then prompts to download the csv file (all which is working fine).
What I need is for the file to save in the same location on the server but I cannot seem to get it to work.
Any idea how to save to the server rather than download?
<?php
// Database Connection
include "connection.php"; //Connect to Database
// Fetch Record from Database
$output = "";
$sql = mysql_query("select '$select' from'$from' where'$where'"
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "file.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
exit;
?>

Just use file_put_contents() function to save your CSV file into your server:
file_put_contents('yourfile.csv', $output);
So your code would be like:
<?php
// Database Connection
include "connection.php"; //Connect to Database
// Fetch Record from Database
$output = "";
$sql = mysql_query("select '$select' from'$from' where'$where'"
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "file.csv";
file_put_contents($filename, $output);

Related

Export PHP CSV File Columns not displayed

The code below exports data from mysql table correctly but the column names are not displayd in the outputted csv file. Please help
if(isset($_POST["export"])){
$branchcode=$_POST['branchcode'];
$start=$_POST['start'];
$end=$_POST['end'];
$sql=mysqli_query($conn,"select tk_file,tk_date,userid,tk_from,tk_to from rfc_timekeeping_history where branchcode='$branchcode' and (tk_date between '$start' and '$end');")or die(mysqli_error());
$output = "";
$columns_total = mysqli_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysqli_fetch_fields($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
A different approach using the standard php methods of writing to a csv file ( fputcsv ) and using stdout stream you could try along these lines. The column names are obtained in the first loop before rewinding the recordset to actually process the recordset data.
<?php
if( isset( $_POST["export"], $_POST['branchcode'], $_POST['start'], $_POST['end'] ) ){
$filename = "myFile.csv";
$branchcode=$_POST['branchcode'];
$start=$_POST['start'];
$end=$_POST['end'];
/* store columns names in this array */
$headers=array();
/* Run the query */
$sql = mysqli_query( $conn, "select `tk_file`,`tk_date`,`userid`,`tk_from`,`tk_to` from `rfc_timekeeping_history` where `branchcode`='{$branchcode}' and ( `tk_date between` '{$start}' and '{$end}');")or die(mysqli_error());
/* fetch the fields */
$fields = mysqli_fetch_fields( $sql );
/* add each column name to the array */
foreach( $fields as $field ) {
$headers[]=$field->name;
}
/* establish basic csv formatting parameters */
$delimiter=',';
$enclosure='"';
/* write output to stdout */
$output=fopen('php://output','w+');
fputcsv( $output, $headers, $delimiter, $enclosure );
/* rewind the recordset to begin processing data */
mysqli_data_seek( $sql, 0 );
/* process each row - add to stdout */
while( $row = mysqli_fetch_array( $sql ) ) {
fputcsv( $output, $row, $delimiter, $enclosure );
}
/* close stdout stream */
fclose( $output );
/* send the data */
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename={$filename}");
ob_flush();
exit();
}
?>

CSV file displays content in browser instead of downloading from browser

I want to create a csv file from some results in my database. But it display the content instead of prompting the download.
I know there are alot of questions about this, but no luck for me.
if(isset($_POST['export'])){
$resultExport = mysql_query("SELECT question.id, question.question, answer, A, B, C, D, question.publish
FROM question
INNER JOIN packagequestion
ON question.id = packagequestion.questionid
WHERE packagequestion.packageid = '".$packageID."' AND question.publish = 1
ORDER BY question.id DESC");
if (!$resultExport) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($resultExport);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($resultExport , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $resultExport)
{
// name the file by current category and package
$filename = $categorie."".$packageName;
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename.".csv");
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($resultExport))
{
fputcsv($fp, array_values($row));
}
die;
}
}
hope this will help you
<?php
include 'connection.php';
// Fetch Record from Database
$output = "";
$sql = mysql_query("select* from tablename");//your query
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
?>
for that you just have to remove following line from your code.
header('Content-Type: text/csv');

How to save database table in text file? And how to specify format in text file?

I am using a script for saving a database table in .txt file. The script is working perfectly.The table fields are like this :
8,c.s.e,computer ,9,0
9,m.c.a,b.a. in hindi ,10,0
but i want it to be like this-:
{ "table_name": [
["8","c.s.e","computer","9","0"],
["9","m.c.a","computer","10","0"],
]
}
and here is my script:
$fh = fopen('db.txt', 'w');
$con = mysql_connect("localhost","root","");
mysql_select_db("dot", $con);
$result = mysql_query("SELECT * FROM class_master");
while ($row = mysql_fetch_array($result)) {
$num = mysql_num_fields($result) ;
$last = $num - 1;
for($i = 0; $i < $num; $i++) {
fwrite($fh, $row[$i]);
if ($i != $last) {
fwrite($fh, ",");
}
}
fwrite($fh, "\n");
}
fclose($fh);
Implement this line in your code
fwrite($fh, json_encode($row[$i]));

PHP - Export MySQL query to CSV Changeup

I see plenty of postings about the proper ways to export to CSV, and most developers recommend to use fputcsv()
How would I convert the script below to use fputcsv ?
You'll see I'm also exporting the Header row, which reflects the table column names, and I'd like to keep it.
<?php
$sql = "SELECT * FROM `tbl_customers`";
$result = mysql_query($sql, $dbdata_conn) or die(mysql_error());
$header = $csv_output = '';
$fields = mysql_num_fields($result);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($result, $i) . ",";
}
$header .= "\n";
while ($rowr = mysql_fetch_row($result)) {
for ($j=0; $j<$i; $j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$csv_output = $header.$csv_output;
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=test.csv");
header("Pragma: no-cache");
header("Expires: 0");
print "$csv_output";
exit;
?>
I'm aware that mysql_query is deprecated, so this is for the sake of practice.
As a side note, I'm not familiar with fputcsv, but I am reading that it's rather useful for formatting the data for the csv output, saving us time with all the escapes and such.
(I'm also very very open to improvements to what's above)
Simple demonstration (following your mysql_* functions):
$header=array();
$fields = mysql_num_fields($result);
for ($i = 0; $i < $fields; $i++) {
$header[] = mysql_field_name($result, $i);
}
header("...");
$f=fopen("php://output","wt");
fputcsv($f,$header);
while ($row = mysql_fetch_row($result)) {
fputcsv($f,$row);
}
fclose($f);
As you have stated, mysql_* functions are deprecated, so you should work on that too.
If you want to download it as attachment, it is OK not to use fputcsv(), but if you want to use it, here is a workaround:
$sql = "SELECT * FROM `tbl_customers`";
$result = mysql_query($sql, $dbdata_conn) or die(mysql_error());
$header = array();
$csv_output = array();
$fields = mysql_num_fields($result);
for ($i = 0; $i < $fields; $i++) {
$header[] = mysql_field_name($result, $i);
}
$csv_output[] = $header;
while ($rowr = mysql_fetch_array($result)) {
$csv_output[] = $rowr;
}
$fp = fopen('/path/to/file.csv', 'w');
foreach ($csv_output as $line) {
fputcsv($fp, $line);
}
fclose($fp);
// if you pick up the file from the directory manually, the following is not needed
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=test.csv");
header("Pragma: no-cache");
header("Expires: 0");
print file_get_contents('/path/to/file.csv');
unlink('/path/to/file.csv');
exit;

Export row from CSV file to JSON

I want to export a row in CSV file to JSON file with require : 1 line in CSV export 1 file JSON. I success to export file,but can't filter the row that i want to export. Can anyone help me?
<?php
header('Content-type: application/json');
$feed = 'jsondata_palpad.csv';
$keys = array();
$newArray = array();
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
$data = csvToArray($feed, ',');
$count = count($data) - 1;
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
//Xuat file JSON
for ($i = 0; $i < 5; $i++) {
$json = json_encode($newArray[$i]);
echo $json . "<br />\n";
$filename = $data[$i][1] . ".json";
echo $filename . "<br />\n";
//echo "title[" . $data[$i][4] . "]";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
?>
If recommend = 2,it will export line whre id=2.
I want to export id,product_id,title,outline to JSON file.This is sample JSON file:
http://img839.imageshack.us/img839/5277/21527799.png
This is CSV file :
http://img690.imageshack.us/img690/1526/43004273.png
You are looping through all 6 lines of the csv file and saving them to the JSON file:
for ($i = 0; $i < 5; $i++) {
...
}
If you know what row number it is you want, don't loop through every row - just call the code inside the loop for that row. For example, if you wanted the 2nd row:
$row_we_want = 1;
$json = json_encode($newArray[$row_we_want]);
$filename = $data[$row_we_want][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
If you are unsure about which row it is and need to check each one, you could do so in the loop:
for ($i = 0; $i < 5; $i++) {
if (some_condition) {
$json = json_encode($newArray[$i]);
$filename = $i][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
}
Also it might be worth replacing 5 in your loop with the length of the array using the count function if it is not always a fixed length.

Categories