Getting meta title and description

11,138

Solution 1

This should work fine:

$doc = new DOMDocument;
$doc->loadHTMLFile('http://example.com');

$title = $doc->getElementsByTagName('title');
$title = $title[0];

$metas = $doc->getElementsByTagName('meta');

foreach ($metas as $meta) {
  if (strtolower($meta->getAttribute('name')) == 'description') {
    $description = $meta->getAttribute('value');
  }
}

More info: http://www.php.net/manual/en/book.dom.php

Edit: this shorter version can also work to find the description:

$xpath = new DOMXPath($doc);
$description = $xpath->query('//meta[@name="description"]/@content');

Solution 2

$url = "http://www.thegooddrugsguide.com/lsd/index.htm";    
$tags = get_meta_tags($url);
$description = $tags["description"];
Share:
11,138
johnny
Author by

johnny

Updated on June 09, 2022

Comments

  • johnny
    johnny almost 2 years

    I am having trouble getting the meta description/title from this specific site.

    Here is some code:

    $file = file('http://www.thegooddrugsguide.com/lsd/index.htm');
    $file = implode("",$file);
    if (preg_match('/<title>(.*?)<\/title>/is',$file,$t)) $title = $t[1];
    

    It works with other sites, but not with the site in question. What could be the problem?

  • johnny
    johnny almost 13 years
    Hey I am getting this error: DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: Invalid char in CDATA 0x1F in http://www.thegooddrugsguide.com/lsd/index.htm, line: 1
  • johnny
    johnny almost 13 years
    Also I have tried example.com and then I get this error: Cannot use object of type DOMNodeList as array
  • Baronth
    Baronth over 11 years
    @johnny just edited adding ->item(0)->nodeValue; instead of [0]. Just tested and it works now
  • Code
    Code over 11 years
    @Baronth : what are you talking about? I am getting the same error 'Cannot use object of type DOMNodeList as array', can you please mention the change in seriousdev's answer?
  • Baronth
    Baronth over 11 years
    Someone modified it again(or the modify wasn't approved)... I'll write it here: Instead of $title = $title[0]; use $title = $title->item(0)->nodeValue;
  • olliefinn
    olliefinn over 10 years
    Note that the Edit contains an error. $description = $xpath->query('/html/head/meta[name@="description"]/@content‌​'); should read $description = $xpath->query('/html/head/meta[@name="description"]/@content‌​'); The @ should come before the name attribute selector not afterwards.
  • Michael Konečný
    Michael Konečný over 8 years
    you should do $description = $meta->getAttribute('content'); instead of getAttribute('value')