Skip to content

Instantly share code, notes, and snippets.

@eli-oat
Created June 14, 2017 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eli-oat/71131d8e5190e7273cc455b7e85d575c to your computer and use it in GitHub Desktop.
Save eli-oat/71131d8e5190e7273cc455b7e85d575c to your computer and use it in GitHub Desktop.
Get title attribute form a URL via PHP curl

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);
    
    // get the code of request
    $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)); // supports line breaks inside <title>
            preg_match("/\<title\>(.*)\<\/title\>/i", $str, $title); // ignore case
            return $title[1];
            }
        }
    }

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment