我想试着找出如何获得
<title>A common title</title>
<meta name="keywords" content="Keywords blabla" />
<meta name="description" content="This is the description" />
即使它是以任何顺序排列的,我也听说过PHP简单的HTML DOM Parser,但我真的不想使用它。除了使用PHP简单的HTML DOM解析器之外,是否有其他解决方案。
如果它是无效的超文本标记语言,preg_match
将无法执行此操作?
cURL可以用preg_match做这样的事情吗?
Facebook做了一些类似的事情,但通过使用以下方式来正确使用它:
<meta property="og:description" content="Description blabla" />
我想像这样的东西,这样当有人发布链接时,它应该检索标题和元标签。如果没有meta标签,则忽略它,或者用户可以自己设置它(但我稍后会这样做)。
发布于 2010-09-15 01:55:00
这是它应该是的方式:
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$html = file_get_contents_curl("http://example.com/");
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description')
$description = $meta->getAttribute('content');
if($meta->getAttribute('name') == 'keywords')
$keywords = $meta->getAttribute('content');
}
echo "Title: $title". '<br/><br/>';
echo "Description: $description". '<br/><br/>';
echo "Keywords: $keywords";
发布于 2012-03-15 09:02:59
<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');
// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // name
echo $tags['keywords']; // php documentation
echo $tags['description']; // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>
发布于 2011-01-10 01:34:22
除了标题以外,get_meta_tags
将帮助您完成所有工作。要获得标题,只需使用正则表达式。
$url = 'http://some.url.com';
preg_match("/<title>(.+)<\/title>/siU", file_get_contents($url), $matches);
$title = $matches[1];
希望这能有所帮助。
https://stackoverflow.com/questions/3711357
复制相似问题