Forum Moderators: coopster
Here is a basic example of outputting a csv file. Just use the basic structure and work your data in using a loop or something similar. Don't forget the newlines(\n).
<?php
$filename = 'whatever.csv';
$csv_output = ' "ID", "NAME", "EMAIL" \n';
$csv_output .= ' "1", "John Doe", "johndoe@foo.com" \n';
$csv_output .= ' "2", "Jane Doe", "janedoe@foo.com" \n';
header("Content-type: application/x-msexcel");
header("Content-disposition: attachment; filename=".$filename);
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
?>
"Warning: Cannot modify header information - headers already sent by (output started at /home3/user/my-domain/my_directory/my_file.php:7) in /.......php on line 76"
<form action="csv.php" method="post">
<input type="hidden" name="id" value="<?=$idVariable?>" />
<input type="submit" value="Download" />
</form>
Or...
<a href="csv.php?id=<?=$idVariable?>">Download</a>
Use one of the above methods in your existing page then, in the csv script, build your mysql_query() with the variable, $_POST['id'] or $_GET['id'].
Be sure your variables are safe [us4.php.net] before sending them to mysql.
-------------------
<?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=ajareport.xls>");
header("Pragma: no-cache");
header("Expires: 0");
include("dbconnect.inc.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("Unable to select database");
$select = "SELECT * FROM aja_myfile";
$export = mysql_query($select);
$count = mysql_num_fields($export);
for ($i = 0; $i < $count; $i++) {
$header .= mysql_field_name($export, $i)."\t";
}
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("\r", "", $data);
if ($data == "") {
$data = "\n(0) Records Found!\n";
}
print "$header\n$data";
?>
---------------------