10

如何使用PHP Simple HTML DOM Parsertitle提取页面和元数据?description

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

4

9 回答 9

22
$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;

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

于 2013-03-18T17:32:43.200 回答
9

我只是看了一下 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;
于 2012-07-08T20:47:49.263 回答
6
$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[描述]

于 2013-02-05T02:59:50.350 回答
4

取自上面 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;
}
于 2016-03-29T08:10:47.117 回答
3
$html->find('meta[name=keywords]',0)->attr['content'];
$html->find('meta[name=description]',0)->attr['content'];
于 2016-09-22T22:45:54.633 回答
2
$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;
于 2012-09-24T15:13:30.603 回答
1

你可以使用 php 代码,很容易知道。像这儿

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

于 2013-11-12T02:27:19.730 回答
1

正确答案是:

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

上面的代码把html变成对象格式,然后find方法寻找一个名字为description的meta标签,最后需要返回meta标签内容的值,而不是别人说的innertext或者plaintext。

这已经过测试并在实时代码中使用。最好的

于 2015-11-01T16:12:22.803 回答
0

我找到了进行描述的简单方法

$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);
于 2018-01-28T16:32:24.633 回答