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?

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().

it works for me.

//open file pointer to standard output
$fp = fopen('php://output', 'w');

//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

fclose($fp);

return $response->send();