PHP Export not working right in Safari

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kristiandavid
Forum Newbie
Posts: 1
Joined: Tue Jun 17, 2008 1:17 am

PHP Export not working right in Safari

Post by kristiandavid »

Hello all.
i added a script obtained from this site... http://www.wlscripting.com/tutorial/37 ... for exporting data from a MySQL table to a CSV file. this works perfectly except in safari. for some reason it adds a .exe extension on the end which is odd seeing as i'm on a mac.

here's the actual code. thanks in advance.

<?php
$db = mysql_connect('localhost', 'username', 'password'); // Connect to the database
$link = mysql_select_db('database name', $db); // Select the database name

function parseCSVComments($comments) {
$comments = str_replace('"', '""', $comments); // First off escape all " and make them ""
if(eregi(",", $comments) or eregi("\n", $comments)) { // Check if I have any commas or new lines
return '"'.$comments.'"'; // If I have new lines or commas escape them
} else {
return $comments; // If no new lines or commas just return the value
}
}

$sql = mysql_query("SELECT * FROM tableName"); // Start our query of the database
$numberFields = mysql_num_fields($sql); // Find out how many fields we are fetching

if($numberFields) { // Check if we need to output anything
for($i=0; $i<$numberFields; $i++) {
$head[] = mysql_field_name($sql, $i); // Create the headers for each column, this is the field name in the database
}
$headers = join(',', $head)."\n"; // Make our first row in the CSV

while($info = mysql_fetch_object($sql)) {
foreach($head as $fieldName) { // Loop through the array of headers as we fetch the data
$row[] = parseCSVComments($info->$fieldName);
} // End loop
$data .= join(',', $row)."\n"; // Create a new row of data and append it to the last row
$row = ''; // Clear the contents of the $row variable to start a new row
}
// Start our output of the CSV
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=log.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $headers.$data;
} else {
// Nothing needed to be output. Put an error message here or something.
echo 'No data available for this CSV.';
}
?>
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: PHP Export not working right in Safari

Post by VladSun »

Try using text/plain instead of application/x-msdownload.
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply