The iso-latin-1 character set is much smaller than the Unicode character set. Fortunately, HTML provides a mechanism to encode character not present in the used character set.
Option 1 (Works with any encoding):
my $to_entitise = q{<>&"'}; # Unsafe for HTML my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html, Encode::FB_HTML +CREF);
Option 2 (Leverages our knowledge of iso-latin-1):
my $to_entitise = q{<>&"'} . # Unsafe for HTML q{\x{100}-\x{1FFFFF}}; # Not present in iso-8859-1 my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html);
Option 3 (Works with any encoding by using HTML entities for more than needed):
my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text); my $latin1_html = encode('iso-latin-1', $decoded_html);
If your UTF-8 encoded data is HTML rather than text, you can use:
my $to_entitise = q{\x{100}-\x{1FFFFF}}; # Not present in iso-8859-1 my $decoded_html = decode('UTF-8', $utf8_html); $decoded_html = encode_entities($decoded_html, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html);
Common headers and test data:
use charnames qw( :full ); # For \N on older Perls use Encode qw( encode decode ); use HTML::Entities qw( encode_entities ); my $utf8_text = encode('UTF-8', "a\N{U+00E9}\N{U+2660} 1<4"); my $utf8_html = encode('UTF-8', "a\N{U+00E9}\N{U+2660} <b>foo</b>");
Update: Small fixes to bugs found during testing.
In reply to Re: Converting UTF8 to Latin1
by ikegami
in thread Converting UTF8 to Latin1
by sumeetgrover
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |