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 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程