Jak*_*kov 8 php url fetch meta-tags opengraph
我想创建一个类似于Facebook使用的发布功能(您将链接粘贴到文本框中,点击帖子并发布标题,描述和图像).我意识到最好提取具有og属性的元标记,例如"og:title"和"og:image",因为如果我使用普通标记,有时它们会有换行符和其他类似的东西而且会出现错误.
有没有办法使用PHP获取这些标签的内容,但没有AJAX或其他自定义解析器?起点是:
<?php
$url = $_POST['link'];
?>
Run Code Online (Sandbox Code Playgroud)
我们通过POST方法获取上一页的URL,但其余的怎么做?
Jak*_*kov 10
解决方案是这样的:
libxml_use_internal_errors(true);
$c = file_get_contents("http://url/here");
$d = new DomDocument();
$d->loadHTML($c);
$xp = new domxpath($d);
foreach ($xp->query("//meta[@property='og:title']") as $el) {
echo $el->getAttribute("content");
}
foreach ($xp->query("//meta[@property='og:description']") as $el) {
echo $el->getAttribute("content");
}
Run Code Online (Sandbox Code Playgroud)
使用如下所示的内容:
libxml_use_internal_errors(true); // Yeah if you are so worried about using @ with warnings
$doc = new DomDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$query = '//*/meta[starts-with(@property, \'og:\')]';
$metas = $xpath->query($query);
foreach ($metas as $meta) {
$property = $meta->getAttribute('property');
$content = $meta->getAttribute('content');
$rmetas[$property] = $content;
}
var_dump($rmetas);
Run Code Online (Sandbox Code Playgroud)
在如何通过php获取网页的开放图谱协议上找到了这个? - 搜索很有帮助,谷歌也是如此!
http://www.google.co.uk/search?q=meta+property+og+tags