The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> PHP Development
|
PHP5 - Export data to csv file not prompting for save file
Discuss Export data to csv file not prompting for save file in the PHP Development forum on Dev Shed. Export data to csv file not prompting for save file PHP Development forum discussing coding practices, tips on PHP, and other PHP-related topics. PHP is an open source scripting language that has taken the web development industry by storm.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

December 21st, 2012, 03:29 PM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 5
Time spent in forums: 1 h 24 m
Reputation Power: 0
|
|
|
PHP5 - Export data to csv file not prompting for save file
I am trying to export data from two tables into a csv file. When I execute my code it writes the data to the browser instead of opening dialog box for "open file" or "save file". I have similar code on another site that works fine. What is the problem?
PHP Code:
<?php
include ("dbconnect.inc.php");
$office = $_POST['office_loc'];
$query = mysql_query("SELECT * FROM rxrefill, rxprescriptions where office_loc = '$office' and rxid = rx_id order by rx_called_date desc");
$file = 'requests';
$requests = "User Called".","."Called Date".","."Patient Name".","."Comments"."\n";
while($row = mysql_fetch_array($query))
{
$usercalled = $row['rx_usr_called'];
$calleddate = $row['rx_called_date'];
$ptname = $row['pt_name'];
$comments = $row['addtl_cmt'];
$requests .= $usercalled.",".$calleddate.",".$ptname.",".$comments."\n";
}
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="'.$filename.'"');
echo "$requests";
exit;
?>
This is quite confusing and I know it must be something simple I'm missing. 
|

December 21st, 2012, 04:03 PM
|
 |
JavaScript is not spelt java
|
|
Join Date: Feb 2011
Location: Landan, England
|
|
You are echoing the output where you should write it to the file ($filename).
PHP Code:
fputcsv($filename, $requests);
fclose();
Corrected: Sorry, ignore me! I was basing my answer on the way I do this, but it's not the same. Sorry, again for the confusion.
Last edited by AndrewSW : December 21st, 2012 at 04:19 PM.
|

December 21st, 2012, 04:06 PM
|
 |
Still alive
|
|
Join Date: Mar 2007
Location: Washington, USA
|
|
|
Use something like Chrome or LiveHTTPHeaders (or whatever it's called) to look at the headers in the response. Do they include the Content-Disposition?
|

December 23rd, 2012, 04:05 PM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 2
Time spent in forums: 39 m 2 sec
Reputation Power: 0
|
|
|
Is it necessary to provide a content-disposition? I made a similar script a few days ago and it works fine just by providing the content-type and echo'ing the resulting text.
|

December 23rd, 2012, 04:13 PM
|
 |
JavaScript is not spelt java
|
|
Join Date: Feb 2011
Location: Landan, England
|
|
Quote: | Originally Posted by larsmw Is it necessary to provide a content-disposition? I made a similar script a few days ago and it works fine just by providing the content-type and echo'ing the resulting text. |
Quote: | If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog. |
Without a content-disposition you are relying on the browser to handle the download. For example, if it were a pdf, the browser might start an associated pdf-reader or plug-in. I'm not sure (without trying it) how browsers generally handle .csv's(?). I suppose some might even display their content in the browser window  . But I suspect most will trigger a download of the file.
Last edited by AndrewSW : December 23rd, 2012 at 04:15 PM.
|

December 23rd, 2012, 04:52 PM
|
 |
Still alive
|
|
Join Date: Mar 2007
Location: Washington, USA
|
|
Quote: | Originally Posted by AndrewSW I'm not sure (without trying it) how browsers generally handle .csv's(?). I suppose some might even display their content in the browser window  . But I suspect most will trigger a download of the file. |
Me too. Generally browsers will look up the content-type in some list and, if present, execute whatever action is associated. Like text/html maps to the built-in renderer and application/octet-stream maps to a download. Plugins add their own mapping, like if you have MS Office then application/msword (.doc) could start up the installed preview plugin. The OS itself might even lend some capabilities to this so the browser wouldn't need a plugin per se but could look up something in the global registry. Default action tends to depend on the MIME "super"-type: text/* might be displayed while application/* will probably show a download.
|

December 23rd, 2012, 05:03 PM
|
 |
JavaScript is not spelt java
|
|
Join Date: Feb 2011
Location: Landan, England
|
|
I suppose if the user has configured their browser (and/or os) to handle files in a certain way, then they should be able to continue in this manner. But, for me, the only sensible thing to do with a .csv is download and save it  .
|

December 25th, 2012, 08:22 PM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 5
Time spent in forums: 1 h 24 m
Reputation Power: 0
|
|
|
Trying other code found but still no save
I found some other code which I needed anyway to write out all the fields in my two tables with their values as csv file, but still not getting download of csv, just writing to browser. I have tried this on my Vista machine using Firefox and IE9 and also my W7 machine using Firefox and no download. I AM using a content-disposition statement and explicitly saving as csv file. ALSO NOTICED THAT "\n" is not creating a new line like it should just writing it all in one line.
PHP Code:
include ("dbconnect.inc.php");
$file = "requests";
$office = $_POST['office_loc'];
$select = "SELECT * FROM rxrefill, rxprescriptions where office_loc = '$office' and rxid = rx_id order by rx_called_date desc";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . ",";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = ",";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . ",";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found\n";
}
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="'.$filename.'"');
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
|

December 25th, 2012, 09:47 PM
|
 |
JavaScript is not spelt java
|
|
Join Date: Feb 2011
Location: Landan, England
|
|
Even though headers are not supposed to be case-sensitive, I would prefer Content- Disposition, and prefer echo to print (which has a return value).
I do this in a slightly different way - outputting as Excel/csv, and using output-buffering - so maybe my following code is not so useful to you  :
PHP Code:
<?php
include_once 'includes/config.inc.php'; // starts output buffering
// Original PHP code by Chirp Internet: www.chirp.com.au
function cleanData($str) {
if ($str == 't') $str = 'TRUE';
if ($str == 'f') $str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) ||
preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "bookmarks_data_" . date('Ymd') . ".csv";
if ($logged_in) {
require 'andy3_connect.php'; // connnect to the database
if (!$dbc) {
ob_end_clean();
exit();
}
$q = "SELECT user_id FROM users WHERE user_name='$username'";
$r = mysqli_query($dbc, $q) or
trigger_error("Could not find user\n<br>MySql Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) == 1) {
list($uid) = mysqli_fetch_array($r, MYSQLI_NUM);
$result = mysqli_query($dbc, "SELECT title, address, description, tags, created " .
" FROM bookmarks WHERE user_id=$uid ORDER BY title")
or trigger_error("Could not retrieve bookmarks: " . mysqli_error($dbc));
if (!$result) {
mysqli_close($dbc);
ob_end_flush();
exit();
}
$flag = false;
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
// header("Content-Type: text/plain");
$out = fopen("php://output", 'w');
while ($row = mysqli_fetch_assoc($result)) {
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = true;
}
array_walk($row, 'cleanData');
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
mysqli_close($dbc);
}
} else {
// redirect
ob_end_clean();
header("Location: " . BASE_URL . "index.php");
exit();
}
// flush the buffered output:
ob_end_flush();
?>
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|