in reply to Re^2: Parsing extended ascii characters using XML::LibXML...
in thread Parsing extended ascii characters using XML::LibXML...
How do i "actually" encode the doc in UTF-8?
That depends on how you generate the document. If you create it by hand, it could look something like
use charnames ':full'; { my %escapes = ( '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''', ); sub xml_text { (my $s = $_[0]) =~ s/([<&])/$escapes{$1}/g; $s } sub xml_att_val { (my $s = $_[0]) =~ s/([<&"])/$escapes{$1}/g; qq{"$s"} } } my $s_7bit = "A"; my $s_8bit = "\N{LATIN CAPITAL LETTER A WITH CIRCUMFLEX}"; my $s_32bit = "\N{BLACK SPADE SUIT}";
open(my $fh, '>:encoding(UTF-8)', $qfn) or die; print($fh qq{<?xml version="1.0" encoding="UTF-8"?>\n}); print($fh qq{<foo>\n}); print($fh qq{ <bar>}, xml_text($s_7bit), qq{</bar>\n}); print($fh qq{ <bar>}, xml_text($s_8bit), qq{</bar>\n}); print($fh qq{ <bar>}, xml_text($s_32bit), qq{</bar>\n}); print($fh qq{</foo>\n});
The :encoding PerlIO layer will encode the characters as UTF-8. Without the :encoding layer, the IO system will assume the characters are already encoded (and will freak out if you pass it characters that aren't bytes).
Update: Fixed bug in code (wasn't using the handle I opened). Added the required prefix to the original code.
|
|---|