如何使用PHP Simple HTML DOM Parsertitle
提取页面和元数据?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[描述]
取自上面 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方法寻找一个名字为description的meta标签,最后需要返回meta标签内容的值,而不是别人说的innertext或者plaintext。
这已经过测试并在实时代码中使用。最好的
我找到了进行描述的简单方法
$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);