1

我想在 php 中创建一个 CSV 文件,以 UTF-8 编码,所有字符都很好地呈现(甚至重音,因为我是法国人),除了引号,它们呈现为“ '”。

谁能帮我?

这是我在 Symfony2 中的代码示例

$response = new Response();
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-disposition', 'attachment; filename="'.$name.'.csv"');
$response->setContent(utf8_decode($csv));
$response->setStatusCode(200);

非常感谢

4

2 回答 2

0

Some pointers for you:

  1. utf8_decode produces ISO-8859-1 content. Therefore your output is not UTF-8.

  2. ' is the same in UTF-8, ASCII, Windows-1252 and ISO-8859-1

  3. I suspect ' is coming from your CSV source.

  4. If you're building the source, ensure you use UTF-8 chars. Then you don't need to convert. If you're reading from disk, make sure you know the original character set. Don't convert character sets unless you know the original character set.

于 2013-10-21T11:16:46.570 回答
0

这是对我有用的解决方案。我正在使用 Symfony 4.4。

headers=> 包含您的标题。
lines=> 包含你的台词。

$response = new StreamedResponse();
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition', $response->headers->makeDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'export.csv'
));

$response->setCallback(function () use ($headers, $lines) {
    $handle = fopen('php://output', 'w+');
    // Mandatory: Use bom + "Content-Type: application/force-download" => to allow to display special characters with excel
    fwrite($handle, $bom = chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF')));
    // headers
    fputcsv($handle, $headers, ';');
    // data
    foreach ($lines as $line) {
        fputcsv($handle, $line, ';');
    }
    fclose($handle);
});

于 2021-04-30T14:11:19.810 回答