PHP UTF8无法正确显示中文字符

时间:2014-11-26 07:29:16

标签: php html sql sql-server odbc

我试图用表数据回显php中的中文单词,但似乎没有正确显示

这是我的代码

<?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>

我已将源代码保存为UTF-8但却无法正常工作,而不是显示所谓的文本,而是打印出???

3 个答案:

答案 0 :(得分:1)

删除此行echo'<?xml version="1.0" encoding="utf-8"?>。然后,将代码重新编写为符合此标准(符合HTML5)。在标题中保留meta属性的注释:

<!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>

注意:HTML lang属性可用于声明网页的语言或网页的一部分。这旨在帮助搜索引擎和浏览器。

修改

您必须通过指示MySQL服务器指定SQL的结果字符编码, BEFORE 您的实际查询,如下所示:

$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.

答案 1 :(得分:0)

<!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;
    ?>

 

答案 2 :(得分:0)

<!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;
    ?>