Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing title of a website using DOM [duplicate]

Tags:

html

dom

php

Possible Duplicates:
Get title of website via link
How do I extract title of a website?

How can a website's title be grabbed using PHP DOM? (Which is the best way to grab it using PHP?)

like image 628
john Avatar asked May 03 '11 13:05

john


2 Answers

You can use the getElementByTagName() since there is technically only a single title attribute in your html so you can just grab the first one you come across in DOM.

$title = '';
$dom = new DOMDocument();

if($dom->loadHTMLFile($urlpage)) {
    $list = $dom->getElementsByTagName("title");
    if ($list->length > 0) {
        $title = $list->item(0)->textContent;
    }
}
like image 62
John Cartwright Avatar answered Nov 05 '22 04:11

John Cartwright


Suppresses any parsing errors from incorrect HTML or missing elements:

<?

$doc = new DOMDocument();
@$doc->loadHTML(@file_get_contents("http://www.washingtonpost.com"));

// find the title
$titlelist = $doc->getElementsByTagName("title");
if($titlelist->length > 0){
  echo $titlelist->item(0)->nodeValue;
 }
like image 42
Femi Avatar answered Nov 05 '22 06:11

Femi