【问题标题】:Get Facebook meta tags with PHP使用 PHP 获取 Facebook 元标记
【发布时间】:2012-08-14 09:33:27
【问题描述】:

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

我正在使用简单的 html dom 从站点获取所有 html 数据。 我已经尝试使用 preg_replace,但没有运气。

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

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

希望有人可以提供帮助! :-)

【问题讨论】:

标签: php facebook facebook-opengraph


【解决方案1】:

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

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

但我还是建议使用DOMDocument

<?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;
?>

希望对你有帮助

【讨论】:

  • 第一种方法不起作用,因为 get_meta_tags() 只传递带有名称属性的元标记。
  • 我第一眼看到这是有道理的,但是在尝试实现它并让它失败之后,如果 file_get_contents() 调用自身,它不会导致递归问题,因为 PHP 解析器会一次又一次地被召唤?
  • @J-a-n-u-s 如果它自己调用它会。
  • @LawrenceCherone 感谢您的回复。我首先使用 PHP 构建元数据,然后在我需要它们时调用相同的变量,而不是尝试使用 PHP 读取硬编码的 html 元数据,从而结束了整个事情。
【解决方案2】:

按照此方法,您将获得 fabcebook 开放图形标签的密钥对数组。

 $url="http://fbcpictures.in";
 $site_html=  file_get_contents($url);
    $matches=null;
    preg_match_all('~<\s*meta\s+property="(og:[^"]+)"\s+content="([^"]*)~i',     $site_html,$matches);
    $ogtags=array();
    for($i=0;$i<count($matches[1]);$i++)
    {
        $ogtags[$matches[1][$i]]=$matches[2][$i];
    }

【讨论】:

    猜你喜欢
    • 2013-11-10
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多