Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove CGI default meta charset encoding in Perl?

Using the Perl code

#!/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;

I am getting the following output:

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>

And I don't know why

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

is in the output and I don't know how to get rid of it.

All suggestions will be appreciated.

like image 630
Ωmega Avatar asked Apr 17 '12 19:04

Ωmega


2 Answers

add an -encoding parameter to start_html and don't build the meta element by hand. (despite what the CGI docs suggest you do).

print $cgi->start_html(-title => "Test", -encoding => "utf-8")
like image 71
evil otto Avatar answered Nov 13 '22 12:11

evil otto


With recent versions of CGI.pm (I currently have 3.52 installed), you shouldn't need to construct that <meta> element manually. You only have to supply the charset when you call the header method. This program:

#!/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;

gives me this output:

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>
like image 4
cjm Avatar answered Nov 13 '22 11:11

cjm