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

Hen*_*ast 10 html php parsing dom simpledom

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

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

Far*_*ona 20

$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;
Run Code Online (Sandbox Code Playgroud)

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


Rya*_*n B 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;
Run Code Online (Sandbox Code Playgroud)

  • 这段代码对我不起作用了(---答案比最新版本的库还旧),因为find可能会返回多个元素.为了使它工作,我需要添加一个值为0的第二个参数来查找:$ html-> find('title',0) - > plaintext; (4认同)

chu*_*911 6

$html = new simple_html_dom();
$html->load_file('http://www.google.com'); 
$title = $html->find('title',0)->innertext;
Run Code Online (Sandbox Code Playgroud)

$html->find('title') 将返回一个数组

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