« Oatmeal

Currently, whenever I reply to or like a link the source URL displays. I’ve found a really sturdy way to parse content titles, but the performance is absolutely abysmal. Wicked wicked wicked slow. I think it may be something to do with how I’m invoking the function. I’ll keep poking at it, though, since it makes for a much better presentation.


function url_get_title($url)
{
if (!function_exists('curl_init'))
{
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// FAIL
if ($httpCode == 400) return $url;

// SUCCEED!
if ($httpCode == 200)
{
$str = file_get_contents($url);
if (strlen($str) > 0)
{
$str = trim(preg_replace('/\s+/', ' ', $str)); 
preg_match("/\<title\>(.*)\<\/title\>/i", $str, $title); 
return $title[];
}
}
}

Pass the function a URL and you’ll get the <title> attribute back unless curl fails for some reason (looking at you every Squarespace site ever), then you just get the URL back again.

Post a response on your own site? Send me a webmention!