It’ll be pretty good if you replace this (due to a lot of international characters in links nowadays):
$urls[$key] = $permalink;
to this:
function encodeURL($url) {
$reserved = array('%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
$unescaped = array('%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':','%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$');
$score = array('%23'=>'#');
return strtr(rawurlencode($url), array_merge($reserved,$unescaped,$score));
}
$urls[$key] = encodeURL($permalink);