To correctly display Unicode data in PHP, it's essential to set the appropriate character encoding. When PHP connects to a database, it may not handle Unicode data properly by default.
Consider the following code:
<code class="php">$sql = mysql_query("select title from abd where tid='1'"); $row = mysql_fetch_array($sql); $title = $row['title']; echo $title;</code>
This code attempts to retrieve and display the title column from the abd table. However, if the column contains Unicode characters, it may not render correctly and display as question marks.
To resolve this issue, set the character encoding after establishing a connection to the database:
<code class="php">mysql_query("set character_set_client='utf8'"); mysql_query("set character_set_results='utf8'"); mysql_query("set collation_connection='utf8_general_ci'");</code>
By setting the client character set, result character set, and connection collation to UTF-8, PHP will properly handle and display Unicode characters.
After adding the character encoding settings, the code will be:
<code class="php">mysql_query("set character_set_client='utf8'"); mysql_query("set character_set_results='utf8'"); mysql_query("set collation_connection='utf8_general_ci'"); $sql = mysql_query("select title from abd where tid='1'"); $row = mysql_fetch_array($sql); $title = $row['title']; echo $title;</code>
This updated code will correctly display Unicode characters, resolving the issue of garbled output.
The above is the detailed content of How to Display Unicode Data Correctly in PHP?. For more information, please follow other related articles on the PHP Chinese website!