如何在 php 中生成带有渲染良好引号的 UTF8 CSV 文件? [英] How to generate UTF8 CSV file in php with well rendered quotes?
本文介绍了如何在 php 中生成带有渲染良好引号的 UTF8 CSV 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 php 中创建一个 CSV 文件,以 UTF-8 编码,所有字符都得到了很好的呈现(即使是口音,因为我是法国人),除了引号,呈现为 "'
".
I want to create a CSV file in php, encoded in UTF-8, all caracters are well rendered (even accents, cause I am french), except quotes, that are rendered as "'
".
有人可以帮我吗?
这是我的代码示例,在 Symfony2 中
Here is an example of my code, in 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);
非常感谢
推荐答案
这是适合我的解决方案.我使用的是 Symfony 4.4.
This is the solution that works for me. I am using Symfony 4.4.
headers
=>包含您的标题.行
=>包含您的台词.
headers
=> contains your headers.
lines
=> contains your 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);
});
这篇关于如何在 php 中生成带有渲染良好引号的 UTF8 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文