问题
I am trying to echo a chinese word in php from a table data but it seems it is not displaying properly
Here's my code
<?php
echo'<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-Hans" lang="zh-Hans">
';
?>
<head>
<title>A Test Page</title>
</head>
<body>
<?php
//Insert connection string
require_once 'confx/confx.php';
$ID = 222;
$conn = odbc_connect($odbc_dsn, $odbc_usr, $odbc_pwd);
if(!$conn) { die('Epic Fail!'); }
$query = odbc_exec($conn, "SELECT * FROM member WHERE userid = '$ID'");
$result = odbc_result($query, 'usernick');
echo $result;
odbc_free_result($query);
?>
</body>
</html>
I have saved the source code into UTF-8 and yet it is not working properly, Instead of displaying the supposed text, it prints out ???
回答1:
Remove this line echo'<?xml version="1.0" encoding="utf-8"?>
. Then, rework your code to look like this (HTML5 compliant). Keep the note of the meta
attribute in header:
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<title>A Test Page</title>
<meta charset="utf-8">
</head>
<body>
<?php
// Start PHP code from here
$value = "黄后乎";
echo $value;
?>
</body>
</html>
Note: The HTML lang
attribute can be used to declare the language of a Web page or a portion of a Web page. This is meant to assist search engines and browsers.
EDIT:
You have to specify the SQL`s result character encoding, by instructing the MySQL server, BEFORE your actual query, like this:
$query = odbc_exec($conn, "SET NAMES 'utf8'");
$query = odbc_exec($conn, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
//Your actual DB query
$query = odbc_exec($conn, "SELECT * FROM member WHERE userid = ". (int) $ID);
//Note the `(int) $ID` section, this is in order to prevent SQL injection attack.
回答2:
<!DOCTYPE html>
<?php
header('Content-Type: text/html; charset=utf-8');
?>
<html lang="zh-Hans">
<head>
<title>A Test Page</title>
<head>
<title>A Test Page</title>
</head>
<body>
<?php
$value = "黄后乎";
echo $value;
?>
回答3:
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>A Test Page</title>
<head>
<title>A Test Page</title>
</head>
<body>
<?php
$value = "黄后乎";
echo $value;
?>
来源:https://stackoverflow.com/questions/27143452/php-utf8-not-displaying-chinese-characters-properly