使用PHP获取Facebook元标记

Sim*_*sen 3 php facebook opengraph

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

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

我希望例如获取此fb元标记的内容:

<meta content="IMAGE URL" property="og:image" />
Run Code Online (Sandbox Code Playgroud)

希望有人可以帮忙!:-)

Law*_*one 22

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

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

但我宁愿建议使用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;
?>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你

  • 第一种方法不起作用,因为get_meta_tags()只传递带有名称属性的元标记. (3认同)