Reputation: 31
I use mysql, Perl and Apache on Ubuntu.
I have the following code:
use utf8;
use CGI('-utf8'); #added based on another forum article i was reading.
use Encode;
.....
my $localcontent = JSON->new->utf8->encode($data);
#i write $localcontent back in mysql and can see that it is good.
print $cgi->header(
-type => 'application/json',
-cookie => $_sessioncookie,
-content_length => length($localcontent),
-charset => 'UTF-8'
);
Encode::encode( 'UTF-8', $localcontent );
#i also tried binmode for STDOUT (binmode(STDOUT, ':encoding(UTF-8)');) but that gives the same result.
Then in the browser I get unreadable content, the special chars are messed up. Any tips how I can proceed with debugging or has tips about setting this up correctly?
Upvotes: 0
Views: 92
Reputation: 2584
Just print the value instead of using Encode
:
use utf8;
use CGI('-utf8');
use JSON;
my $data = { foo => 'Бar' };
my $localcontent = JSON->new->utf8->encode($data);
print $cgi->header(
-type => 'application/json',
-cookie => $_sessioncookie,
-content_length => length($localcontent),
-charset => 'UTF-8'
);
print $localcontent;
CGI.pm
is deprecated, you should look into Plack
or Mojolicious
.
Here's an example of this same application using Plack
(without a framework):
use utf8;
use Plack::Builder;
use Plack::Request;
use JSON;
my $data = { foo => 'Бar' };
my $localcontent = JSON->new->utf8->encode($data);
builder {
mount "/" => sub {
my $req = Plack::Request->new(shift);
my $res = $req->new_response(200);
$res->content_type('application/json; charset=utf-8');
$res->body($localcontent);
return $res->finalize;
};
};
Then just run via plackup <file name>.pl
. You mention using Apache
as well, so you'd most likely need to change over to mod_proxy
from mod_cgi
to proxy to the Plack
process.
Upvotes: 1