在 .csv 中更改 Mysqli 中 “;” 中的分隔符 “,”


change separator "," in ";" from Mysqli in .csv

此代码导出一个文件.csv并用"," 分隔列

我对这段代码还有另一个小问题。我的电脑的区域设置不是在美国,而是在罗马尼亚。这意味着在美式分隔中由","完成,在罗马尼亚语中由";"完成,Excel采用PC的区域设置。我该怎么做才能用";"进行编码?谢谢!

<?php
// call export function
exportMysqlToCsv('export_csv.csv');
// export csv
function exportMysqlToCsv($filename = 'export_csv.csv')
{
   $conn = dbConnection();
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql_query = "SELECT id, firstname, lastname FROM MyGuests";
    // 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 = "myDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    return $conn;
}
?>

您必须像下面这样使用,您可以在 php 中将逗号作为分隔符导出到 CSV 以获取更多信息。

$delimiter = ',';
$enclosure = '"';
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
    fputcsv($f, $row, $delimiter, $enclosure);
}