你可以用这两个功能来完成它
function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"')
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('You must submit a valid result object');
}
$out = '';
// First generate the headings from the table column names
foreach ($query->list_fields() as $name)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
}
$out = rtrim($out);
$out .= $newline;
// Next blast through the result array and build out the rows
foreach ($query->result_array() as $row)
{
foreach ($row as $item)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
}
$out = rtrim($out);
$out .= $newline;
}
return $out;
}
function write_file($path, $data, $mode = 'wb')
{
if ( ! $fp = @fopen($path, $mode))
{
return FALSE;
}
flock($fp, LOCK_EX);
fwrite($fp, $data);
flock($fp, LOCK_UN);
fclose($fp);
return TRUE;
}将查询对象传递给函数。
$sql="select
description,
jobreceived,
timebookedfor,
bookedfor,
site_contact,
site_address,
invoice_contact,
invoice_address,
quotedprice,
cleardowndetails,
notes,
mo_number
from jobs";
$rs = mysql_query($sql,$conn) or die(mysql_error());现在将资源传递给csv_from_result函数
$file_data = csv_from_result($rs);现在你可以写文件了
$filename = "jobs.csv";
write_file($filename , $file_data); // $filename can be a complete path或回显以查看csv结果
echo $file_data;