获取页面的charset并转换它

时间:2014-01-31 17:03:40

标签: php curl utf-8 character-encoding

在帖子消息中创建URL的预览,就像在FB上一样。 在textarea的帖子网址上,此网址的预览如下所示。 标题,描述,图像等

有不同页面的字符集编码问题。 我的页面是UTF-8,如果预览网址不在utf-8中,我页面上显示的文字不正确。 我需要获取网址字符集,将其转换为utf-8,然后从我的页面上显示并显示所需信息。

实际上我堆栈溢出它))但没有找到一个好的方法来做到这一点。

最后我这样做了,效果很好。 你能否检查一下这是否正确而且更短。

$post_url='http://website.domain';

/// Get headers ////////////////////////////////////////////////////////////
function get_headers_curl($url) 
{ 
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL,            $url); 
    curl_setopt($ch, CURLOPT_HEADER,         true); 
    curl_setopt($ch, CURLOPT_NOBODY,         true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_TIMEOUT,        15); 

    $r = curl_exec($ch); 
    return $r; 
}
$the_header = get_headers_curl($post_url);
/// check for redirect /////////////////////////////////////////////////
if (preg_match("/Location:/i", $the_header)) {
    $arr = explode('Location:', $the_header);
    $location = $arr[1];

    $location=explode(chr(10), $location);
    $location = $location[0];

$the_header = get_headers_curl(trim($location));
}
/// Get charset /////////////////////////////////////////////////////////////////////
if (preg_match("/charset=/i", $the_header)) {
    $arr = explode('charset=', $the_header);
    $charset = $arr[1];

    $charset=explode(chr(10), $charset);
    $charset = $charset[0];
    }
///////////////////////////////////////////////////////////////////////////////
// echo $charset;

if($charset && $charset!='UTF-8') { $html = iconv($charset, "UTF-8", $html); }

如果没关系,可能有人需要它。 谢谢。

0 个答案:

没有答案