Jump to content

Saving a CSV file


IGGt

Recommended Posts

I have a set of scripts that are all designed to run a MySQL query. They then pass that query ($Query), along with the new filename ($Filename) to another php script which is designed to convert that to a csv file.

 

At the minute it works fine, except that it opens a dialogue box asking you to open or save the file. Ideally I need it to automatically save the file to a set location. Can I modify my existing code to do this, or is there a better way of doing this?

 

my code is:

 

<?php
function exportMysqlToCsv($Query,$filename)
{
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$sql_query = $Query;

// Gets the data from the database
$result = mysql_query($sql_query);
$fields_cnt = mysql_num_fields($result);
$schema_insert = '';
for ($i = 0; $i < $fields_cnt; $i++)
{
	$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
		stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
	$schema_insert .= $l;
	$schema_insert .= $csv_separator;
} // end for
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
// Format the data
while ($row = mysql_fetch_array($result))
{
	$schema_insert = '';
	for ($j = 0; $j < $fields_cnt; $j++)
	{
		if ($row[$j] == '0' || $row[$j] != '')
		{
			if ($csv_enclosed == '')
			{
				$schema_insert .= $row[$j];
			} else
			{
				$schema_insert .= $csv_enclosed .
				str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
			}
		} else
		{
			$schema_insert .= '';
		}
		if ($j < $fields_cnt - 1)
		{
			$schema_insert .= $csv_separator;
		}
	} // end for
	$out .= $schema_insert;
	$out .= $csv_terminated;
} // end while
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
// Output to browser with appropriate mime type, you choose 
//header("Content-type: text/x-csv");
//header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
//echo "Download the file <a href=reportFiles/$filename>here</a>";
echo $out;
exit;
}
?>

Link to comment
https://forums.phpfreaks.com/topic/185224-saving-a-csv-file/
Share on other sites

you can only do a set location on the server. If it's going to be saved on the client then you'll need the file dialog. Otherwise you open the client up for HUGE security holes. Can you image being able to place any file you want on the client automatically without any notification? 

Link to comment
https://forums.phpfreaks.com/topic/185224-saving-a-csv-file/#findComment-977794
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.