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

How to Display Unicode Data Correctly in PHP?

Mary-Kate Olsen
Release: 2024-10-31 03:55:01
Original
643 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template