2

I have a question! I want to print an unicode string in php (like 'سلام')! but when I use echo only some ??? apear!!!

what whould I do??? This happens hen I want to cho string that retrieved from database!

echo 'سلام';

result is:

????

I tried using header function but that didn't help me!

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
undone
  • 7,857
  • 4
  • 44
  • 69
  • Did you specify the proper character encoding? – Gumbo Sep 06 '10 at 10:42
  • Not sure why this was down-voted, the question is perfectly valid. The solution I finally found to work is here: http://stackoverflow.com/questions/2446778/how-to-display-unicode-data-with-php – Wex Mar 19 '12 at 12:26

3 Answers3

6

You need to do three things:

  1. Make sure you're receiving the data as UTF-8 data. For MySQL, query SET NAMES 'utf8' before selecting records.
  2. Make sure you're using UTF-8 compatible functions when dealing with UTF-8 strings.
  3. Make sure you're setting the output encoding as UTF-8. For HTML, this can be done by setting the Content-type HTTP header to (e.g.) text/html; charset=utf-8.

Of course, replace "UTF-8" with whatever encoding you want which supports the characters you need. There's no need to change the database tables (except for possible performance gains). You may need to change HTML templates, etc. if you decide on UTF-16 or something else which isn't (mostly) ASCII-compatible.

strager
  • 88,763
  • 26
  • 134
  • 176
  • If you plan on storing unicode data in mysql, you need to use a charset which supports it. Per default, Mysql uses latin1, but you can switch to utf-8. – troelskn Sep 06 '10 at 11:07
  • @troelskn, I'm assuming the data was already stored properly. I mentioned changing database tables because, say, if the site switches to UTF-16, the database's data's character set doesn't need to be changed, because the conversion is made for you. – strager Sep 06 '10 at 11:32
2

You need to declare the used character encoding in the HTTP response. You can use the header function:

header('Content-Type: text/html;charset=utf-8');

With this the output is declared to be HTML with the character encoding UTF-8. Note that you can’t use header when you’ve already sent data to the client without buffering it. So either use the output control to buffer the output so that you can modify the header although there already was some output or use header before any output.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

Maybe I'm a little too late but this worked for me:

echo utf8_encode('سلام');
Dũng Trần Trung
  • 6,198
  • 3
  • 24
  • 20