从导出php-mysqli格式化列csv

时间:2016-04-01 08:29:04

标签: php csv mysqli

以下代码导出包含多列的.csv文件。专栏" PRET"是一般格式化的,它包含格式为xx.xx的产品的价格。我想在xx,xx中转换我的值。如何格式化Text类型的列PRET,或者我应该替换"。"用","何时导出文件?

<?php
// call export function
exportMysqlToCsv('export_stoc.csv');

// export csv
function exportMysqlToCsv($filename = 'export_stoc.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
}
//v

$sql_query = "SELECT
      produse.DENUMIRE,
      clase.CLASA,
      furnizori.NUME_J,
      furnizori.NUME_F,
      stoc.CANTITATE,
      produse.PRET,
      produse.VALUTA,
      stare.STARE
FROM clase
JOIN produse ON produse.ID_CLASA = clase.ID
JOIN furnizori ON produse.ID_FURNIZOR = furnizori.ID
JOIN stoc ON stoc.ID_PRODUS = produse.ID
JOIN stare ON stare.ID = stoc.ID_STARE;
     //execute this sql and fetch your results as needed

// Gets the data from the database
$result = $conn->query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
         if ($first) {
                 fputcsv($f, array_keys($row), ';')
                 $first = false;
         }
         fputcsv($f, $row, ';');
} // end while

$conn->close();
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// 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");
fpassthru($f);
exit;
}
// db connection function
function dbConnection(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}

?>

谢谢!

1 个答案:

答案 0 :(得分:0)

没有&#34;格式&#34;用CSV格式; CSV只是由一些分隔符分隔的纯文本。

因此...

  

我应该更换&#34;。&#34;用&#34;,&#34;何时导出文件。

...是