将数组变量导出到csv时,如何删除两个或多个构成一个字符串的变量的双引号?

时间:2018-10-11 11:12:42

标签: php mysql csv export

$query = "SELECT * FROM clients";   

if (!$result = mysqli_query($con, $query)) {
    exit(mysqli_error($con));
}

$users = array();
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $users[] = $row;
    }
}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=Users.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('name'));

if (count($users) > 0) {
    foreach ($users as $row) {
        fputcsv($output, $row);
    }
}

mysqli_close($con);

我得到的输出:

Lubbe,
Williams,
"van den Berg",
"van Straaten",
Schutte

预期输出:

Lubbe,
Williams,
van den Berg,
van Straaten,
Schutte

1 个答案:

答案 0 :(得分:0)

您可以使用str_replace函数从查询输出(数组)中删除双引号。

尝试:

if (count($users) > 0) {
    // loop over query output
    foreach ($users as $row) {

        // remove double quotes
        $row_modified = str_replace('"', '', $row);

        // write to csv
        fputcsv($output, $row_modified);
    }
}