Home  >  Article  >  Database  >  How to Display Unicode Data Correctly in PHP?

How to Display Unicode Data Correctly in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 03:55:01561browse

How to Display Unicode Data Correctly in PHP?

Displaying Unicode Data with PHP

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.

Example

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.

Solution

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.

Updated Example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn