Search code examples
phputf-8arabicfwrite

PHP fwrite function to write txt file in utf-8 encoding


I have made a form where a user writes his message in Arabic and submits it by a submit button. The message is saved in database and I need to create a .txt file on the server for some other application which shows something like this :

د پوليسو Ù¾Ø

I successfully used the fopen, fwrite functions to create my txt files.

When I open the file in notepad the Arabic text is shown correctly but when I open it in eclipse I get something like this :

د پوليسو پر روزنيز مرکز توغندويي بريد وشو

Well afterwards when I save the txt file in notepad as utf-8 encoding the above unknown stuff changes to Arabic.
But I cant do that manually for every message.

I searched a lot on the internet and did these:

  1. I saved the script in utf-8
  2. I used utf8_encode function
  3. I set this too ini_set('default_charset', 'UTF-8');
  4. this too <meta http-equiv="Content-Type" content="text/html; charset=utf-8; encoding=utf-8" />
  5. I change the parameter in fwrite to "wb" where b is for binary

Any solution to this problem ill be very glad I have continuously worked on this issue for the last week. I know the problem is in the encoding so how can I write utf-8 encoded files using PHP?


Solution

  • If the text displays fine in one program but not another, that just means one program interprets the file correctly while the other doesn't. Most likely Notepad sets a UTF-8 BOM on the file when you save it again, so Eclipse now automatically recognizes that it's UTF-8 encoded. Without that, Eclipse assumes latin-1 or some other encoding as the default.

    Two options:

    A BOM can be helpful for making programs recognize UTF-8 but can also cause problems in other programs that don't expect or want BOMs. Whether to use a BOM or not depends on your intended use and target audience.