Fetch Facebook OG Meta Tags with PHP

OG (Open Graph) meta tag is designed by Facebook to make url share easy on social networking websites. Now days these tags are widely used by other websites. If you are running a social networking website or planning to run one. You can make url sharing easy by fetching these tags.

Today I will show you how we can get/fetch OG meta tags with PHP script.

fetch_og PHP function

 * Fetch OG Metatags
 * @param string $url
 * @return array
function fetch_og($url)
    $data = file_get_contents($url);
    $dom = new DomDocument;
    $xpath = new DOMXPath($dom);
    # query metatags with og prefix
    $metas = $xpath->query('//*/meta[starts-with(@property, \'og:\')]');

    $og = array();

    foreach($metas as $meta){
        # get property name without og: prefix
        $property = str_replace('og:', '', $meta->getAttribute('property'));
        # get content
        $content = $meta->getAttribute('content');
        $og[$property] = $content;

    return $og;


$og = fetch_og('http://www.w3bees.com');
echo $og['title'];


  1. For some URLs I never get the correct response.

    Can anyone please help me on this issue.

  2. for any post from nytimes.com I always get null while fetching og.

    Please help !


Go to top