นพ ทศพร นพ ทศพร - 5 months ago 12
PHP Question

Function chr (asciicode) return unknown alphabet in php

I am using function

chr
and trying to echo between
chr(161)
and
chr(206)
(www.ascii.ca/cp874.htm)

It displays unknown alphabet

enter image description here

<?php

echo "ภาษาไทย" ;

for ($i=161 ;$i<206;$i++)
{
echo "</BR>".chr($i)."</BR>";
}

?>


What should I do?

PS. File saved in utf-8

Answer

chr does not output "characters" or "alphabets"; in that sense it has a very misleading name.
chr merely turns a decimal number into a raw byte. chr(161) just returns the byte xA1. You're then outputting this byte to the browser. The browser now interprets this byte using an encoding; whatever encoding you specified in your HTTP Content-Type header or in an HTML charset <meta> attribute.

In your case it seems the browser is using UTF-8 to interpret the data. xA1 by itself doesn't make any sense in UTF-8, hence you get the "broken character" character instead. Try View → Encoding → Latin-1 instead in your browser to see other random characters appear.

See What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text for more information on the topic of encodings.

Comments