使用 PHP 获取 Facebook 元标记 [英] Get Facebook meta tags with PHP

查看:20
本文介绍了使用 PHP 获取 Facebook 元标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的 HTML 中获取 Facebook 的元标记.

I'm trying to get Facebook's meta tags from my HTML.

我使用简单的 html dom 从站点获取所有 html 数据.我试过 preg_replace,但没有运气.

I'm using simple html dom to get all html data from the site. I've tried with preg_replace, but without luck.

例如,我想获取此 fb 元标记的内容:

I want for example to get the content of this fb meta tag:

<meta content="IMAGE URL" property="og:image" />

希望有人能帮忙!:-)

Hope someone can help! :-)

推荐答案

我打算建议使用 get_meta_tags() 但它似乎不起作用(对我来说):s

I Was going to suggest to use get_meta_tags() but it seems to not work (for me) :s

<?php
$tags = get_meta_tags('http://www.example.com/');
echo $tags['og:image'];
?>

但我宁愿建议使用 DOMDocument 反正:

But I would rather suggest using DOMDocument anyways:

<?php
$sites_html = file_get_contents('http://example.com');

$html = new DOMDocument();
@$html->loadHTML($sites_html);
$meta_og_img = null;
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
    //If the property attribute of the meta tag is og:image
    if($meta->getAttribute('property')=='og:image'){ 
        //Assign the value from content attribute to $meta_og_img
        $meta_og_img = $meta->getAttribute('content');
    }
}
echo $meta_og_img;
?>

希望能帮到你

这篇关于使用 PHP 获取 Facebook 元标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆