php - 使用 PHP 从 URL 中获取 "property og"元标记

标签 php url fetch facebook-opengraph meta-tags

我想创建一个类似于 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/

相关文章:

php - 如何格式化数据库查询的url

javascript - 获取数据,函数 Error() { [native code] } <constructor> : "Function"

php - 将 Magento 安装复制到另一台本地计算机

php - 如何使用 cURL 在 php 中调用 Base crm REST api?

python - 从 URL 下载返回的 Zip 文件

ruby - ruby 中是否有 url 编码点 ('.' ) 的函数

javascript - 将 fetch get 转换为 axios 方法

javascript - 为什么 fetch 在我的移动浏览器上不起作用?

php - Doctrine postSave、postUpdate 和国际化(检测修改)

php - 如何移动 Composer?