Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Facebook meta tags with PHP

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

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

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

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

Hope someone can help! :-)

like image 281
Simon Thomsen Avatar asked Nov 29 '22 09:11

Simon Thomsen


1 Answers

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

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

Hope it helps

like image 75
Lawrence Cherone Avatar answered Dec 14 '22 06:12

Lawrence Cherone