首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从外部网站获取标题和元标签

从外部网站获取标题和元标签
EN

Stack Overflow用户
提问于 2010-09-15 01:27:51
回答 17查看 138.6K关注 0票数 62

我想试着找出如何获得

代码语言:javascript
复制
<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做了一些类似的事情,但通过使用以下方式来正确使用它:

代码语言:javascript
复制
<meta property="og:description" content="Description blabla" />

我想像这样的东西,这样当有人发布链接时,它应该检索标题和元标签。如果没有meta标签,则忽略它,或者用户可以自己设置它(但我稍后会这样做)。

EN

回答 17

Stack Overflow用户

回答已采纳

发布于 2010-09-15 01:55:00

这是它应该是的方式:

代码语言:javascript
复制
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";
票数 174
EN

Stack Overflow用户

发布于 2012-03-15 09:02:59

代码语言:javascript
复制
<?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
?>
票数 41
EN

Stack Overflow用户

发布于 2011-01-10 01:34:22

除了标题以外,get_meta_tags将帮助您完成所有工作。要获得标题,只需使用正则表达式。

代码语言:javascript
复制
$url = 'http://some.url.com';
preg_match("/<title>(.+)<\/title>/siU", file_get_contents($url), $matches);
$title = $matches[1];

希望这能有所帮助。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3711357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档