当前位置: 移动技术网 > IT编程>开发语言>其他编程 > 彻底解决页面文字编码乱码问题

彻底解决页面文字编码乱码问题

2017年12月08日  | 移动技术网IT编程  | 我要评论
本文提供一种方法,通过将字符串编码成unicode格式,保证数据在展示和传输过程中万无一失。无论客户端浏览器如何改变编码,页面上的编码都不会乱码。
对于html/xml,采用 &# + 十位unicode码 + ; 的形式格式化字符。
对于js,采用 \u + 4位unicode码 来格式化字符串.
示例采用c#编写,使用了 中文、俄文、韩文、日文 来展示。对于php,文章末尾将会提到。
首先,有一个string的扩展类。
复制代码 代码如下:

using system.text.regularexpressions;
namespace xxoo
{
/// <summary>
/// 扩展方法,提供html编码 和 脚本编码
/// </summary>
public static class stringextension
{
private static string gethtmlencodedstr(match m)
{
string x = m.tostring();
return string.format("&#{0};", (int)x[0]);
}
/// <summary>
/// 将字符串转换为html编码格式
/// </summary>
/// <param name="text">字符串</param>
/// <returns>输出形如:中文丰厚警</returns>
public static string htmlencode( this string text )
{
return regex.replace(text
, "([^\\000-\\127]|&|\\\"|\\<|\\>|')"
, new matchevaluator(gethtmlencodedstr)
, regexoptions.ecmascript | regexoptions.compiled
);
}
private static string getscriptencodedstr(match m)
{
string x = m.tostring();
return "\\u" + string.format("{0:x}", (int)x[0]).padleft( 4, '0');
}
/// <summary>
/// 将字符串编码成unicode格式 如:\uxxxx
/// </summary>
/// <param name="text">字符串</param>
/// <returns>输出形如:\u4e2d\u6587\u4e30\u539a\u8b66\u65b9</returns>
public static string scriptencode( this string text )
{
return regex.replace(text
, "([^\\000-\\127]|&|\\\"|'|\\<|\\>|\\n|\\r|\\t)"
, new matchevaluator(getscriptencodedstr)
, regexoptions.ecmascript | regexoptions.compiled
);
}
}
}

它提供了2个方法,给测试页面使用。
测试页面(asp.net)
复制代码 代码如下:

<%@ page language="c#" autoeventwireup="true" codebehind="webform1.aspx.cs" inherits="webapplication1.webform1" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<pre runat="server" id="pre"></pre>
<asp:placeholder runat="server" id="placeholder"></asp:placeholder>
</form>
</body>
</html>

测试页面代码:
复制代码 代码如下:

using xxoo;
namespace webapplication1
{
public partial class webform1 : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
var str = @"中文丰厚警方过后发达看见发的话该快发动机后购房贷款好
китайское посольство в ираке и багдаде отделение
이라크에서 중국 대사관과 알의 바그다드 지사 - 만수르 호텔
イラクでの大使館やアルのバグダッド支局-マンスールホテル
1234567890!@#$%^&*()<>""'\|}{][:;
";
pre.innerhtml = str.htmlencode();
htmlgenericcontrol control = new htmlgenericcontrol("script");
control.attributes["language"] = "javascript";
control.attributes["type"] = "text/javascript";
control.innerhtml = string.format("alert(\"{0}\");", str.scriptencode());
placeholder.controls.add(control);
}
}
}

运行后得到的html:
复制代码 代码如下:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="webform1.aspx" id="form1">
<pre id="pre">中文丰厚警方过后发达看见发的话该快发动机后购房贷款好
Китайское посольство в Ираке и Багдаде отделение
이라크에서 중국 대사관과 알의 바그다드 지사 - 만수르 호텔
イラクでの大使館やアルのバグダッド支局-マンスールホテル
1234567890!@#$%^&*()<>"'\|}{][:;
</pre>
<script language="javascript" type="text/javascript"><!--
alert("\u4e2d\u6587\u4e30\u539a\u8b66\u65b9\u8fc7\u540e\u53d1\u8fbe\u770b\u89c1\u53d1\u7684\u8bdd\u8be5\u5feb\u53d1\u52a8\u673a\u540e\u8d2d\u623f\u8d37\u6b3e\u597d\u000d\u000a\u041a\u0438\u0442\u0430\u0439\u0441\u043a\u043e\u0435 \u043f\u043e\u0441\u043e\u043b\u044c\u0441\u0442\u0432\u043e \u0432 \u0418\u0440\u0430\u043a\u0435 \u0438 \u0411\u0430\u0433\u0434\u0430\u0434\u0435 \u043e\u0442\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u000d\u000a\uc774\ub77c\ud06c\uc5d0\uc11c \uc911\uad6d \ub300\uc0ac\uad00\uacfc \uc54c\uc758 \ubc14\uadf8\ub2e4\ub4dc \uc9c0\uc0ac - \ub9cc\uc218\ub974 \ud638\ud154\u000d\u000a\u30a4\u30e9\u30af\u3067\u306e\u5927\u4f7f\u9928\u3084\u30a2\u30eb\u306e\u30d0\u30b0\u30c0\u30c3\u30c9\u652f\u5c40-\u30de\u30f3\u30b9\u30fc\u30eb\u30db\u30c6\u30eb\u000d\u000a1234567890!@#$%\u005e\u0026*()\u003c\u003e\u0022\u0027\u005c\u007c\u007d\u007b\u005d\u005b:;\u000d\u000a");
// --></script>
</form>
</body>
</html>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="webform1.aspx" id="form1">
<pre id="pre">中文丰厚警方过后发达看见发的话该快发动机后购房贷款好
Китайское посольство в Ираке и Багдаде отделение
이라크에서 중국 대사관과 알의 바그다드 지사 - 만수르 호텔
イラクでの大使館やアルのバグダッド支局-マンスールホテル
1234567890!@#$%^&*()<>"'\|}{][:;
</pre>
<script language="javascript" type="text/javascript"><!--
alert("\u4e2d\u6587\u4e30\u539a\u8b66\u65b9\u8fc7\u540e\u53d1\u8fbe\u770b\u89c1\u53d1\u7684\u8bdd\u8be5\u5feb\u53d1\u52a8\u673a\u540e\u8d2d\u623f\u8d37\u6b3e\u597d\u000d\u000a\u041a\u0438\u0442\u0430\u0439\u0441\u043a\u043e\u0435 \u043f\u043e\u0441\u043e\u043b\u044c\u0441\u0442\u0432\u043e \u0432 \u0418\u0440\u0430\u043a\u0435 \u0438 \u0411\u0430\u0433\u0434\u0430\u0434\u0435 \u043e\u0442\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u000d\u000a\uc774\ub77c\ud06c\uc5d0\uc11c \uc911\uad6d \ub300\uc0ac\uad00\uacfc \uc54c\uc758 \ubc14\uadf8\ub2e4\ub4dc \uc9c0\uc0ac - \ub9cc\uc218\ub974 \ud638\ud154\u000d\u000a\u30a4\u30e9\u30af\u3067\u306e\u5927\u4f7f\u9928\u3084\u30a2\u30eb\u306e\u30d0\u30b0\u30c0\u30c3\u30c9\u652f\u5c40-\u30de\u30f3\u30b9\u30fc\u30eb\u30db\u30c6\u30eb\u000d\u000a1234567890!@#$%\u005e\u0026*()\u003c\u003e\u0022\u0027\u005c\u007c\u007d\u007b\u005d\u005b:;\u000d\u000a");
// --></script>
</form>
</body>
</html>

这样,不管浏览器采用何种编码,页面都不会出现乱码。
==============================================
php
php的情况就复杂一点,需要考虑mysql的编码。这些姑且不论。
下面给出一点示例,将gbk进行html编码。仅作参考:
复制代码 代码如下:

function htmlencode($text)
{
$encoded = "";
for( $index = 0; $index < strlen($text); $index++)
{
if( ord($text[$index]) <= 127 )
{
switch(ord($text[$index]))
{
case 34:
case 38:
case 39:
case 60:
case 62:
$encoded .= "&#" .ord($text[$index]).";";
break;
default:
$encoded .= $text[$index];
}
}
else
{
$char = $text[$index] . $text[$index+1];
$char = mb_convert_encoding( $char, "utf-16", "gbk");
$encoded .= "&#" . (ord($char[0])*256 + ord($char[1])) . ";";
$index++;
}
}
return $encoded;
}
function htmlencode($text)
{
$encoded = "";
for( $index = 0; $index < strlen($text); $index++)
{
if( ord($text[$index]) <= 127 )
{
switch(ord($text[$index]))
{
case 34:
case 38:
case 39:
case 60:
case 62:
$encoded .= "&#" .ord($text[$index]).";";
break;
default:
$encoded .= $text[$index];
}
}
else
{
$char = $text[$index] . $text[$index+1];
$char = mb_convert_encoding( $char, "utf-16", "gbk");
$encoded .= "&#" . (ord($char[0])*256 + ord($char[1])) . ";";
$index++;
}
}
return $encoded;
}

然后通过xml返回,这样就能够彻底杜绝乱码。
复制代码 代码如下:

echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
echo "<result>";
echo "<success>". ($success ? 1 : 0) ."</success>";
echo "<message>" . htmlencode($message) . "</message>";
if( $success )
{
echo "<nickname>" . htmlencode($nickname) . "</nickname>";
echo "<userid>".$userid."</userid>";
echo "<siteid>".$siteid."</siteid>";
echo "<isteacher>". ($isteacher ? 1 : 0) ."</isteacher>";
echo "<ipaddress>" . htmlencode($ipaddress) . "</ipaddress>";
}
echo "</result>";
本文来自csdn博客,转载请标明出处:http://blog.csdn.net/wangjia184/archive/2009/10/26/4728318.aspx

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网