0

Creating a preview for URL in post message, like on FB. On post url in textarea a preview for this url shown below. Title, description, image, etc.

Had a problem with charset encoding of different pages. My page in UTF-8, and if preview url is not in utf-8, incorrect text shown on my page. I needed to get charset of url, convert it to utf-8 and then get needed info from and show it on my page.

Actually i stackoverflowed it )) but didn't find an good method to do this.

Finally i did it like this, and it works nice. Could you please check if this is right and shorter way to do it.

$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); }

If it's ok, than may be someone need it. Thank you.

Arsen
  • 3
  • 2
  • Sounds actually good, you could look for the charset that php thinks it is, if charset is missing, by this http://stackoverflow.com/questions/21485116/mysql-charset-latin1-into-utf-8-conversion-issue/21485518#21485518 answer I gave. ;) – loveNoHate Jan 31 '14 at 17:23
  • I've tried to use `mb_detect_encoding` but it's not working properly. As i know it is using system locale, and it will work just in some situations. – Arsen Jan 31 '14 at 17:32
  • So where do you have that from, that is uses locale? – loveNoHate Jan 31 '14 at 21:54

0 Answers0