dongmaijie5200 2014-10-02 15:59
浏览 51

ISO-8859-2编码文件中的外来字符

I have to do CSV file export, and that file has to have ISO-8859-2 character encoding, and display properly foreign characters.

The controller looks like this:

public function exportAction(Request $request) {    
        $repository = $this->getDoctrine()
            ->getManager()
            ->getRepository('AdminBundle:ShopPayroll');

        $request = $this->get('request');

        $response = $this->render('AdminBundle:Payroll:csv.html.twig', [
            'list' => $repository->getSomeData()
        ]);

        $handle = fopen('php://memory', 'r+');
        $header = array();

        fputcsv($handle, (array)utf8_decode($response));

        rewind($handle);

        $content = stream_get_contents($handle);
        fclose($handle);

        $response->setCharset('ISO-8859-2');
        $response->headers->set('Content-Type', 'text/csv; charset=ISO-8859-2');
        $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
        $response->prepare($request);

        return $response->send();
    }

And the csv.html.twig file itself (the file is encoded as ISO-8859-2):

{% for payroll in list %}
{{ payroll.fvatName|slice(0,32)|lower|title|raw|convert_encoding('UTF-8', 'ISO-8859-2') }}
{% endfor %}

Ok, it does downloads the file in ISO-8859-2 encoding, BUT if the string variable contains foreign characters, it changes those characters into some weird symbols.


I tried using iconv inside fputcsv() function, I tried using it as a twig built-in function - none works.

How can I solve this problem?

  • 写回答

2条回答 默认 最新

  • dousi2029 2014-10-02 16:08
    关注

    The utf8_decode() function doesn't exactly what you think. There's a user comment from a Stack Overflow regular that explains it wonderfully (emphasis mine):

    Please note that utf8_decode simply converts a string encoded in UTF-8 to ISO-8859-1. A more appropriate name for it would be utf8_to_iso88591. If your text is already encoded in ISO-8859-1, you do not need this function. If you don't want to use ISO-8859-1, you do not need this function.

    You want to convert from UTF-8 to ISO-8859-2 thus this function is totally inappropriate.

    Alternatives includes iconv() and mb_convert_encoding().

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?