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"];
Author by
johnny
Updated on June 09, 2022Comments
-
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 almost 13 yearsHey 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 almost 13 yearsAlso I have tried example.com and then I get this error:
Cannot use object of type DOMNodeList as array
-
Baronth over 11 years@johnny just edited adding ->item(0)->nodeValue; instead of [0]. Just tested and it works now
-
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 over 11 yearsSomeone 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 over 10 yearsNote 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ý over 8 yearsyou should do
$description = $meta->getAttribute('content');
instead ofgetAttribute('value')