Search code examples
phpcsvpolish

PHP CSV Generation - Polish charater turned to their html entities


When i try to insert polish character in Csv file .The polish character automatically turned to their respective htmlentities

<?php

header('Content-Type: text/csv; charset=UTF-8');   
header( 'Content-Disposition: attachment;filename=reports.csv');

echo ('åĄĆĘŁŃÓŚŹŻąćęłńóśźż');

?>
Output: å&#260;&#262;&#280;&#321;&#323;Ó&#346;&#377;&#379;&#261;&#263;&#281;&#322;&#324;ó&#347;&#378;&#380;

I need polish character to be displayed there.

Can anyone help me in order to solve this?

Thank you


Solution

  • Try this:

    <?php
    
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename=reports.csv');
    
    $data = 'åĄĆĘŁŃÓŚŹŻąćęłńóśźż';
    
    $csv_output = '="'.$data.'"'.chr(9).chr(13);
    
    $csv_output = chr(255).chr(254).mb_convert_encoding($csv_output, 'UTF-16LE', 'UTF-8');
    
    echo $csv_output;
    
    ?>
    

    Also do not forget to save your php file as UTF-8 without BOM ...

    chr(9) seprates fields and chr(13) separates rows ...