This is my PHP code:
What's the encoding of your file? It should be UTF8 too. What's the default charset of your http server? It should be UTF-8 as well.
Encoding only works if:
When working with databases, you also have to set the right encoding for your DB fields and the way the MySQL client communicates with the server (see mysql_set_charset()
). Fields only are not enough because your MySQL client (in this case, PHP) could be set to ISO by default and reinterprets the data. So you end up with UTF8 DB -> ISO client -> injected into UTF8 PHP script. No wonder why it's messed up at the end :-)
How to serve the file with the right charset?
header('Content-type: text/html; charset=utf-8')
is one solution
.htaccess file containing AddDefaultCharset UTF-8
is another one
HTML meta content-type might work too but it's always better to send this information using HTTP headers.
PS: you also have to use mb_strlen()
because strlen()
on UTF8 strings will probably report more than the real length.
try this:
header('Content-Type: text/html; charset=UTF-8');
header("Content-type: application/octetstream");
header("Pragma: no-cache");
header("Expires: 0");
//print "$name_field\n$data";
// با این کد درست شد
print chr(255) . chr(254) . mb_convert_encoding("$name_field\n$data", 'UTF-16LE', 'UTF-8');
if you are just using php echo with no html headers etc., this worked great for me.
$connect = mysqli_connect($host_name, $user_name, $password, $database); mysqli_set_charset($connect,"utf8");
I suppose, your code is in windows-1251
encoding since it is Russian :)
convert your string to utf-8:
$str = iconv('windows-1251', 'utf-8', $str);
Just add this line at the beginning, after the connection with server:
mysqli_set_charset($conn,"utf8");
If your database is UTF-8, it's ok for mysql.
For your echo, if you do it in a web site, put this in the top page:
header('Content-Type: text/html; charset=UTF-8');