我想创建一个类似于 Facebook 使用的发布功能(您将链接粘贴到文本框中,点击发布,它会发布标题、描述和图像)。我意识到最好提取具有 og 属性的元标记,例如“og:title”和“og:image”,因为如果我使用普通标记,有时它们会有换行符和其他类似的东西,并且会出现错误.
有没有办法使用 PHP 获取这些标签的内容,但不使用 AJAX 或其他自定义解析器?起点是:
<?php
$url = $_POST['link'];
?>
我们通过 POST 方法获取了上一页的 URL,但是剩下的怎么办呢?
最佳答案
解决方案是这样的:
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");
}
关于php - 使用 PHP 从 URL 中获取 "property og"元标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9240549/