如何使用PHP Simple HTML DOM Parser提取标题和元描述


How to extract title and meta description using PHP Simple HTML DOM Parser?

如何使用PHP Simple HTML DOM Parser提取页面的title和元description

我只需要页面的标题和关键字的纯文本。

$html = new simple_html_dom();
$html->load_file('some_url'); 
//To get Meta Title
$meta_title = $html->find("meta[name='title']", 0)->content;
//To get Meta Description
$meta_description = $html->find("meta[name='description']", 0)->content;
//To get Meta Keywords
$meta_keywords = $html->find("meta[name='keywords']", 0)->content;

注意:元标记的名称区分大小写!

我刚刚看了一下HTML DOM Parser,尝试:

$html = new simple_html_dom();
$html->load_file('xxx'); //put url or filename in place of xxx
$title = $html->find('title');
echo $title->plaintext;
$descr = $html->find('meta[description]');
echo $descr->plaintext;
$html = new simple_html_dom();
$html->load_file('http://www.google.com'); 
$title = $html->find('title',0)->innertext;

$html->find('title')将返回一个阵列

所以你应该使用$html->find('title',0),meta[description]也是如此

取自LeiXC的上述解决方案,您需要使用简单的html dom类:

$dom = new simple_html_dom();
$dom->load_file( 'websiteurl.com' );// put your own url in here for testing
$html = str_get_html($dom);
$descr = $html->find("meta[name=description]", 0);
$description = $descr->content;
echo $description;

我已经测试了这个代码,是的,它是区分大小写的(一些元标签使用大写D进行描述)

以下是一些拼写错误的错误检查:

if( is_object( $html->find("meta[name=description]", 0)) ){
    echo $html->find("meta[name=description]", 0)->content;
} elseif( is_object( $html->find("meta[name=Description]", 0)) ){
    echo $html->find("meta[name=Description]", 0)->content;
}
$html->find('meta[name=keywords]',0)->attr['content'];
$html->find('meta[name=description]',0)->attr['content'];
$html = new simple_html_dom();
$html->load_file('xxx'); 
//put url or filename in place of xxx
$title = array_shift($html->find('title'))->innertext;
echo $title;
$descr = array_shift($html->find("meta[name='description']"))->content;
echo $descr;

您可以使用php代码,而且了解起来非常简单。像这里

$result='site.com';$tags=get_meta_tags("html/".$result);

正确答案是:

$html = str_get_html($html);
$descr = $html->find("meta[name=description]", 0);
$description = $descr->content;

上面的代码将html转换为对象格式,然后find方法查找带有名称描述的元标记,最后您需要返回元标记内容的值,而不是其他人概述的innertext或明文。

这已经在实时代码中进行了测试和使用。最佳

我发现了获取描述的简单方法

$html = new simple_html_dom(); 
$html->load_file('your_url');
$title = $html->load('title')->simpletext; //<title>**Text from here**</title>
$description = $html->load("meta[name='description']", 0)->simpletext; //<meta name="description" content="**Text from here**">

如果你的线路包含额外的空格,那么试试这个

$title = trim($title);
$description = trim($description);