LWP::UserAgent And Fetching UTF8 encoded XML (RSS/Atom Feeds)

LWP::UserAgent is supposed to be smart enough to parse the html headers (by default) and figure out the encoding. However, some of the xml responses out there don’t pass the right header information. Instead, they rely on the encoding attribute of the xml. For example


<?xml version="1.0" encoding="utf-8"?>

It could be utf-8 or some other encoding. So, one way to deal with this is using the following code


my $content = $response->content;
my $encoding = 'utf8'; # assume this is the default
if($content =~ /encoding="([^"]+)"/) {
$encoding = $1;
}
$content = $response->decoded_content((charset => $encoding));

That’s pretty much it.

Advertisements

Leave a comment

Filed under Tech - Tips

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s