5

使用 Perl 代码

#!/usr/bin/perl

use strict;
use warnings;
use CGI ":all";
use Encode;

my $cgi = new CGI;

$cgi->charset('utf-8');

print $cgi->header(-type    => 'text/html',
                   -charset => 'utf-8');

print $cgi->start_html(-title => 'Test',
                       -head  => meta({-http_equiv => 'Content-Type',
                                       -content => 'text/html; charset=utf-8'}));
my $text = 'test'; # for now

Encode::from_to($text, 'latin1', 'utf8');

print $cgi->p($text);
print $cgi->end_html;

我得到以下输出:

Content-Type: text/html; charset=utf-8

<!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" lang="en-US" xml:lang="en-US">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>test</p>
</body>

我不知道为什么

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

在输出中,我不知道如何摆脱它。

所有建议将不胜感激。

4

2 回答 2

4

使用最新版本的CGI.pm(我目前安装了 3.52),您不需要<meta>手动构建该元素。您只需在调用该header方法时提供字符集。这个程序:

#!/usr/bin/perl

use strict;
use warnings;
use CGI ":all";
use Encode;

my $cgi = CGI->new;
binmode STDOUT, ':utf8';

print $cgi->header(-type => 'text/html',
                   -charset => 'utf-8');

print $cgi->start_html(-title => 'Test');
my $text = "\x{201c}test\x{201d}"; # for now

print $cgi->p($text);
print $cgi->end_html;

给我这个输出:

Content-Type: text/html; charset=utf-8

<!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" lang="en-US" xml:lang="en-US">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p> test </p>
</body>
</html>
于 2012-04-17T19:19:41.513 回答
4

添加-encoding参数start_html并且不要手动构建元元素。(尽管 CGI 文档建议您这样做)。

print $cgi->start_html(-title => "Test", -encoding => "utf-8")
于 2012-04-17T19:44:03.757 回答