codingtcher.com
Theme Night
Home
Login

How to get page title in php

Php Code
function page_title($url) {
        $fp = file_get_contents($url);
        if (!$fp)
            return null;

        $res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches);
        if (!$res)
            return null;

        $title = preg_replace('/\s+/', ' ', $title_matches[1]);
        $title = trim($title);
        return $title;
}

echo page_title("https://codingtcher.com");

ini_set("allow_url_fopen", 1);

$dom = new DOMDocument();
if($dom->loadHTMLFile("https://codingtcher.com")){
   $list = $dom->getElementsByTagName("title");
   if ($list->length > 0){
       $title = $list->item(0)->textContent;
   } else{
       $title = "title not found!";
   }
   echo $title;
}

function curl_get_file_contents($URL){
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_URL, $URL);
    $contents = curl_exec($c);
    curl_close($c);
    if ($contents) return $contents;
    else return false;
}

function get_title($html){
    preg_match("/<title(.+)<\/title>/siU", $html, $matches);
    if(!empty($matches[1])){
        $title = $matches[1];

        if(strstr($title, '>')){
            $title = explode( '>', $title, 2 );
            $title = $title[1];
            return trim($title);
        }   
    }
}

$html = curl_get_file_contents("https://codingtcher.com");
$title = get_title($html);
echo $title;

Related Code