Search code examples
phpencodingtext-filesspecial-charactersfwrite

PHP - writing special characters with fwrite- looks good in notepad but wrong in browser


I have a small issue with writing special characters (Danish, but also some symbols) text to .txt-files with PHP. Take this example:

<?php

$words = "å æ ø"; 

$file = fopen("test.txt","w");
fwrite($file, ($words));
fclose($file);

?>

Above code will work fine and looks correct when I open it in notepad. But for a online purpose I need to open the generated .txt-file with a browser (fx. Firefox) and in the browser the characters are not shown correctly unless I chose "Unicode" as "character encoding" from the show-menu in Firefox, default character encoding in Firefox is "western".

If I make a normal .txt-file with notepad and write "å æ ø" and saving it the normal way it looks correctly in a browser.

I have been searching around looking for information about encoding options for the fwrite but I don't really know where to start.

Kind Regards


Solution

  • The solution is the following: As the UTF-8 byte-order mark is '\xef\xbb\xbf' we should add it to the document's header.

    <?php
        function writeStringToFile($file, $string) {
           $f = fopen($file, "wb");
           $string= "\xEF\xBB\xBF".$string; // utf8 bom
           fputs($f, $string);
           fclose($f);
         }
    ?>
    

    read about BOM