PHP Development
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPHP Development

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old December 21st, 2012, 03:29 PM
marnieg marnieg is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 5 marnieg User rank is Just a Lowly Private (1 - 20 Reputation Level) 
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.

Reply With Quote
  #2  
Old December 21st, 2012, 04:03 PM
AndrewSW's Avatar
AndrewSW AndrewSW is offline
JavaScript is not spelt java
Dev Shed Novice (500 - 999 posts)
 
Join Date: Feb 2011
Location: Landan, England
Posts: 743 AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level) 
Time spent in forums: 2 Weeks 1 Day 23 h 14 m 42 sec
Reputation Power: 164
PHP Code:
echo "$requests"

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.

Reply With Quote
  #3  
Old December 21st, 2012, 04:06 PM
requinix's Avatar
requinix requinix is online now
Still alive
Dev Shed God 16th Plane (12500 - 12999 posts)
 
Join Date: Mar 2007
Location: Washington, USA
Posts: 12,867 requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)  Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1
Time spent in forums: 5 Months 1 Week 5 Days 6 h 11 m 57 sec
Reputation Power: 8977
Send a message via AIM to requinix Send a message via MSN to requinix Send a message via Yahoo to requinix Send a message via Google Talk to requinix
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?

Reply With Quote
  #4  
Old December 23rd, 2012, 04:05 PM
larsmw larsmw is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 2 larsmw User rank is Just a Lowly Private (1 - 20 Reputation Level) 
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.

Reply With Quote
  #5  
Old December 23rd, 2012, 04:13 PM
AndrewSW's Avatar
AndrewSW AndrewSW is offline
JavaScript is not spelt java
Dev Shed Novice (500 - 999 posts)
 
Join Date: Feb 2011
Location: Landan, England
Posts: 743 AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level) 
Time spent in forums: 2 Weeks 1 Day 23 h 14 m 42 sec
Reputation Power: 164
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.

Reply With Quote
  #6  
Old December 23rd, 2012, 04:52 PM
requinix's Avatar
requinix requinix is online now
Still alive
Dev Shed God 16th Plane (12500 - 12999 posts)
 
Join Date: Mar 2007
Location: Washington, USA
Posts: 12,867 requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)requinix User rank is General 120th Grade (Above 100000 Reputation Level)  Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1Folding Points: 417516 Folding Title: Super Ultimate Folder - Level 1
Time spent in forums: 5 Months 1 Week 5 Days 6 h 11 m 57 sec
Reputation Power: 8977
Send a message via AIM to requinix Send a message via MSN to requinix Send a message via Yahoo to requinix Send a message via Google Talk to requinix
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.

Reply With Quote
  #7  
Old December 23rd, 2012, 05:03 PM
AndrewSW's Avatar
AndrewSW AndrewSW is offline
JavaScript is not spelt java
Dev Shed Novice (500 - 999 posts)
 
Join Date: Feb 2011
Location: Landan, England
Posts: 743 AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level) 
Time spent in forums: 2 Weeks 1 Day 23 h 14 m 42 sec
Reputation Power: 164
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 .

Reply With Quote
  #8  
Old December 25th, 2012, 08:22 PM
marnieg marnieg is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 5 marnieg User rank is Just a Lowly Private (1 - 20 Reputation Level) 
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"

Reply With Quote
  #9  
Old December 25th, 2012, 09:47 PM
AndrewSW's Avatar
AndrewSW AndrewSW is offline
JavaScript is not spelt java
Dev Shed Novice (500 - 999 posts)
 
Join Date: Feb 2011
Location: Landan, England
Posts: 743 AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level)AndrewSW User rank is First Lieutenant (10000 - 20000 Reputation Level) 
Time spent in forums: 2 Weeks 1 Day 23 h 14 m 42 sec
Reputation Power: 164
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($rMYSQLI_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($outarray_keys($row), ',''"');
                
$flag true;
            }
            
array_walk($row'cleanData');
            
fputcsv($outarray_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();
?>

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPHP Development > PHP5 - Export data to csv file not prompting for save file

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap