#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    34
    Rep Power
    3

    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.
  2. #2
  3. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    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 05:19 PM.
  4. #3
  5. Jealous Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,302
    Rep Power
    9400
    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?
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep 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.
  8. #5
  9. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    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.
    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 05:15 PM.
  10. #6
  11. Jealous Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,302
    Rep Power
    9400
    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.
  12. #7
  13. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    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 .
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    34
    Rep Power
    3

    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"
  16. #9
  17. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    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();
    ?>

IMN logo majestic logo threadwatch logo seochat tools logo