将查询打印为csv时出现问题


Issue with printing query as csv

我这里有这个查询,这是我将其输出到csv的方式,有人能帮我吗?那里很乱,如果我把它打印成Excel会更好,我尝试了一些版本,但我使用odbc查询的事实让我有点难以将它与我在网上找到的样本相适应。

$result = "SELECT forma.*, SMS_MONTIME.IDTICKET,SMS_MONTIME.MBYLLUR,
SMS_MONTIME.time_added FROM forma 
LEFT JOIN SMS_MONTIME ON forma.ID = SMS_MONTIME.IDTICKET WHERE 
forma.data_fillim >= '$df' AND forma.data_fillim <= '$dm' ORDER BY forma.id DESC"; 
$user_query = odbc_exec($connection, $result) or die(odbc_error());
//While loop to fetch the records
while($row = odbc_fetch_array($user_query))
{
$contents.=$row['klienti'].",";
$contents.=$row['id'].",";
$contents.=$row['tekniku_emer'].",";
$contents.=$row['telefoni'].",";
$contents.=$row['data_fillim'].",";
$contents.=$row['difekti'].",";
$contents.=$row['tekniku_mesazh'].",";
$contents.=$row['shenime'].",";
}
// remove html and php tags etc.
$contents = strip_tags($contents); 
//header to make force download the file
header("Content-Disposition: attachment; filename=Kondicioner".date('d-m-Y').".csv");
print $contents;

输出csv的更好方法是使用fputcsv函数。。

<?php
$result = "SELECT forma.*, SMS_MONTIME.IDTICKET,SMS_MONTIME.MBYLLUR,
SMS_MONTIME.time_added FROM forma 
LEFT JOIN SMS_MONTIME ON forma.ID = SMS_MONTIME.IDTICKET WHERE 
forma.data_fillim >= '$df' AND forma.data_fillim <= '$dm' ORDER BY forma.id DESC"; 
$user_query = odbc_exec($connection, $result) or die(odbc_error());
//While loop to fetch the records
header("Content-Disposition: attachment; filename='Kondicioner".date('d-m-Y').".csv'");
$fp = fopen("php://output","w");
// here you set up your header
fputcsv($fp, array("klienti","id","tekniku_emer","telefoni","data_fillim","difekti","tekniku_mesazh", "shenime");
while($row = odbc_fetch_array($user_query))
{
   $row = array_map("strip_tags", $row);
   fputcsv($fp, array($row['klienti'],$row['id'],
                      $row['tekniku_emer'],$row['telefoni'],
                      $row['data_fillim'],$row['difekti'],
                      $row['tekniku_mesazh'],$row['shenime']));
}
fclose($fp);