How to Properly Display Chinese Characters in PHP

How to properly display Chinese characters in PHP?

Simple:

  1. save your source code in UTF-8
  2. output an HTTP header to specify to your browser that it should interpret the page using UTF-8:

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

Done.

utf8_encode is for converting Latin-1 encoded strings to UTF-8. You don't need it.

For more details, see Handling Unicode Front To Back In A Web App.

Properly display Chinese character from MySQL and PHP through ajax

Could you try to set UTF-8 charset encoding on all of code sides, like AJAX requests[optional], PHP files with header() function, html files and also MySQL table fields charsets.

cannot display chinese characters in php

Use <meta charset="utf-8"> before <title>

Some old style browers checks http header first, so you may set

<?php
header("Content-Type: text/html; charset=utf-8");

or change your web server config file

Example in Nginx:

add this lines after server {

charset utf-8;
charset_types
text/css
application/javascript
application/x-javascript
text/xml
text/plain;

Example in Apache:

AddDefaultCharset Off

or

AddDefaultCharset utf-8

PHP Displaying Strange Chinese Characters?

Try to explode by "\n" instead of "/n".

The Chinese charakters are there because the file is encoded in UTF-16, so you need to do this:

$data = mb_convert_encoding($data,'UTF-8','UTF-16');

before you start to work with the data. I made a working example here:

http://www.servisio.com/test.html

It contains these four lines:

$data  = file_get_contents("http://proxylists.connectionincognito.com/proxies_657.txt");
$data = mb_convert_encoding($data,'UTF-8','UTF-16');
$lines = explode("\n", $data);
foreach($lines as $line) echo $line.'<br>';

PHP displaying Chinese characters: SET NAMES 'utf8' not working

For MySQL DB, this solves the problem:

$dbh = mysql_connect($hostname, $username, $password);    
mysql_select_db($db, $dbh);
mysql_set_charset('utf8', $dbh);

PDO solution:

$dbh = new PDO('mysql:host=$hostname;dbname=$db;charset=UTF-8', $username, $password);


Related Topics



Leave a reply



Submit