我想弄清楚如何获得
<title>A common title</title>
<meta name="keywords" content="Keywords blabla" />
<meta name="description" content="This is the description" />
即使它以任何顺序排列,我也听说过PHP Simple HTML DOM Parser,但我真的不想使用它。除了使用PHP Simple HTML DOM Parser之外,是否可以使用解决方案。
如果它是无效的HTML,preg_match
将无法做到这一点?
cURL可以用preg_match做这样的事吗?
Facebook做了类似这样的事情,但它通过使用正确使用:
<meta property="og:description" content="Description blabla" />
我想要这样的东西,以便当有人发布链接时,它应该检索标题和元标记。如果没有元标记,那么它会被忽略或者用户可以自己设置(但我稍后会自己做)。
这是应该的方式:
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";
从url获取meta标签,php函数示例:
function get_meta_tags ($url){
$html = load_content ($url,false,"");
print_r ($html);
preg_match_all ("/<title>(.*)<\/title>/", $html["content"], $title);
preg_match_all ("/<meta name=\"description\" content=\"(.*)\"\/>/i", $html["content"], $description);
preg_match_all ("/<meta name=\"keywords\" content=\"(.*)\"\/>/i", $html["content"], $keywords);
$res["content"] = @array("title" => $title[1][0], "descritpion" => $description[1][0], "keywords" => $keywords[1][0]);
$res["msg"] = $html["msg"];
return $res;
}
例:
print_r (get_meta_tags ("bing.com") );
Easy和php的内置功能。
<?php
// ------------------------------------------------------
function curl_get_contents($url) {
$timeout = 5;
$useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
// ------------------------------------------------------
function fetch_meta_tags($url) {
$html = curl_get_contents($url);
$mdata = array();
$doc = new DOMDocument();
$doc->loadHTML($html);
$titlenode = $doc->getElementsByTagName('title');
$title = $titlenode->item(0)->nodeValue;
$metanodes = $doc->getElementsByTagName('meta');
foreach($metanodes as $node) {
$key = $node->getAttribute('name');
$val = $node->getAttribute('content');
if (!empty($key)) { $mdata[$key] = $val; }
}
$res = array($url, $title, $mdata);
return $res;
}
// ------------------------------------------------------
?>
现在,大多数网站都会在其网站上添加元标记,提供有关其网站或任何特定文章页面的信息。如新闻或博客网站。
我创建了一个Meta API,它为您提供了所需的元数据,如OpenGraph,Schema.Org等。
如果你正在使用PHP,请查看pear.php.net上的Pear包,看看你是否找到了对你有用的东西。我已经有效地使用了RSS包,它节省了大量时间,前提是您可以通过他们的示例了解他们如何实现代码。
具体来看看Sax 3,看看它是否适合您的需求。 Sax 3不再更新,但可能就足够了。
正如已经说过的,这可以解决这个问题:
$url='http://stackoverflow.com/questions/3711357/get-title-and-meta-tags-of-external-site/4640613';
$meta=get_meta_tags($url);
echo $title=$meta['title'];
//php - Get Title and Meta Tags of External site - Stack Overflow
我根据最佳答案制作了这个小作曲家包:https://github.com/diversen/get-meta-tags
composer require diversen/get-meta-tags
然后:
use diversen\meta;
$m = new meta();
// Simple usage, get's title, description, and keywords by default
$ary = $m->getMeta('https://github.com/diversen/get-meta-tags');
print_r($ary);
// With more params
$ary = $m->getMeta('https://github.com/diversen/get-meta-tags', array ('description' ,'keywords'), $timeout = 10);
print_r($ary);
它需要CURL和DOMDocument作为最佳答案 - 并且构建方式,但可以选择设置curl超时(以及获取所有类型的元标记)。
我已经以不同的方式工作,并认为我会分享它。代码少于其他人,发现它here。我添加了一些东西,使它加载你所在的页面元而不是某个页面。我希望这能自动将默认页面标题和描述复制到og标签中。
出于某种原因,无论我尝试过哪种方式(不同的脚本),页面加载超级慢在线但在wamp上即时。不知道为什么所以我可能会使用开关盒,因为该网站并不大。
<?php
$url = 'http://sitename.com'.$_SERVER['REQUEST_URI'];
$fp = fopen($url, 'r');
$content = "";
while(!feof($fp)) {
$buffer = trim(fgets($fp, 4096));
$content .= $buffer;
}
$start = '<title>';
$end = '<\/title>';
preg_match("/$start(.*)$end/s", $content, $match);
$title = $match[1];
$metatagarray = get_meta_tags($url);
$description = $metatagarray["description"];
echo "<div><strong>Title:</strong> $title</div>";
echo "<div><strong>Description:</strong> $description</div>";
?>
并在HTML标题中
<meta property="og:title" content="<?php echo $title; ?>" />
<meta property="og:description" content="<?php echo $description; ?>" />
上面的@shamittomar改进了答案,以获取元标记(或来自html源的指定标记)
可以进一步改进...与php的默认get_meta_tags的区别在于即使有unicode字符串也能正常工作
function getMetaTags($html, $name = null)
{
$doc = new DOMDocument();
try {
@$doc->loadHTML($html);
} catch (Exception $e) {
}
$metas = $doc->getElementsByTagName('meta');
$data = [];
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if (!empty($meta->getAttribute('name'))) {
// will ignore repeating meta tags !!
$data[$meta->getAttribute('name')] = $meta->getAttribute('content');
}
}
if (!empty($name)) {
return !empty($data[$name]) ? $data[$name] : false;
}
return $data;
}
我们不应该使用OG吗?
选择的答案是好的,但是当站点被重定向时非常常见(非常常见!),并且不返回OG标签,这些标签是the new industry standard。这是一个在2018年更有用的小功能。它试图获取OG标签并且如果它们不能它们则回退到meta标签:
function getSiteOG( $url, $specificTags=0 ){
$doc = new DOMDocument();
@$doc->loadHTML(file_get_contents($url));
$res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;
foreach ($doc->getElementsByTagName('meta') as $m){
$tag = $m->getAttribute('name') ?: $m->getAttribute('property');
if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = $m->getAttribute('content');
}
return $specificTags? array_intersect_key( $res, array_flip($specificTags) ) : $res;
}
/////////////
//SAMPLE USE:
print_r(getSiteOG("http://www.stackoverflow.com")); //note the incorrect url
/////////////
//OUTPUT:
Array
(
[title] => Stack Overflow - Where Developers Learn, Share, & Build Careers
[description] => Stack Overflow is the largest, most trusted online community for developers to learn, shareâ âtheir programming âknowledge, and build their careers.
[type] => website
[url] => https://stackoverflow.com/
[site_name] => Stack Overflow
[image] => https://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]?v=73d79a89bded
)
<?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
?>
这里是PHP简单的DOM HTML Class 2行代码,以获取页面META的详细信息。
$html = file_get_html($link);
$meat_description = $html->find('head meta[name=description]', 0)->content;
$meat_keywords = $html->find('head meta[name=keywords]', 0)->content;
除了标题之外,get_meta_tags
将帮助您。要获得标题只需使用正则表达式。
$url = 'http://some.url.com';
preg_match("/<title>(.+)<\/title>/siU", file_get_contents($url), $matches);
$title = $matches[1];
希望有所帮助。
Php的本机函数:get_meta_tags()
你最好的选择就是使用DOM Parser - 这是“正确的方法”。从长远来看,它将为您节省更多时间,而不是学习如何。已知使用正则表达式解析HTML是不可靠的,并且不能容忍特殊情况。
get_meta_tags
没有标题。
只有名称属性的元标记
<meta name="description" content="the description">
将被解析。
不幸的是,内置的php函数get_meta_tags()需要name参数,某些站点(例如twitter)将其关闭以支持property属性。此函数使用正则表达式和dom文档的混合,将从网页返回键控数组的元标记。它检查name参数,然后检查property参数。这已经在instragram,pinterest和twitter上进行了测试。
/**
* Extract metatags from a webpage
*/
function extract_tags_from_url($url) {
$tags = array();
$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);
$contents = curl_exec($ch);
curl_close($ch);
if (empty($contents)) {
return $tags;
}
if (preg_match_all('/<meta([^>]+)content="([^>]+)>/', $contents, $matches)) {
$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="utf-8" ?>' . implode($matches[0]));
$tags = array();
foreach($doc->getElementsByTagName('meta') as $metaTag) {
if($metaTag->getAttribute('name') != "") {
$tags[$metaTag->getAttribute('name')] = $metaTag->getAttribute('content');
}
elseif ($metaTag->getAttribute('property') != "") {
$tags[$metaTag->getAttribute('property')] = $metaTag->getAttribute('content');
}
}
}
return $tags;
}
http://php.net/manual/en/function.get-meta-tags.php
<?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
?>
我们使用Apache Tika通过php(命令行实用程序)和-j为json:
<?php
shell_exec( 'java -jar tika-app-1.4.jar -j http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying' );
?>
这是随机监护人文章的示例输出:
{
"Content-Encoding":"UTF-8",
"Content-Length":205599,
"Content-Type":"text/html; charset\u003dUTF-8",
"DC.date.issued":"2013-07-21",
"X-UA-Compatible":"IE\u003dEdge,chrome\u003d1",
"application-name":"The Guardian",
"article:author":"http://www.guardian.co.uk/profile/nicholaswatt",
"article:modified_time":"2013-07-21T22:42:21+01:00",
"article:published_time":"2013-07-21T22:00:03+01:00",
"article:section":"Politics",
"article:tag":[
"Lynton Crosby",
"Health policy",
"NHS",
"Health",
"Healthcare industry",
"Society",
"Public services policy",
"Lobbying",
"Conservatives",
"David Cameron",
"Politics",
"UK news",
"Business"
],
"content-id":"/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
"dc:title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
"description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
"fb:app_id":180444840287,
"keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
"msapplication-TileColor":"#004983",
"msapplication-TileImage":"http://static.guim.co.uk/static/a314d63c616d4a06f5ec28ab4fa878a11a692a2a/common/images/favicons/windows_tile_144_b.png",
"news_keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
"og:description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
"og:image":"https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pixies/2013/7/21/1374433351329/Lynton-Crosby-008.jpg",
"og:site_name":"the Guardian",
"og:title":"Tory strategist Lynton Crosby in new lobbying row",
"og:type":"article",
"og:url":"http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
"resourceName":"tory-strategist-lynton-crosby-lobbying",
"title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
"twitter:app:id:googleplay":"com.guardian",
"twitter:app:id:iphone":409128287,
"twitter:app:name:googleplay":"The Guardian",
"twitter:app:name:iphone":"The Guardian",
"twitter:app:url:googleplay":"guardian://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
"twitter:card":"summary_large_image",
"twitter:site":"@guardian"
}