Search code examples
phpmeta-tags

can't get og:image php


I'm using this script to get the og:image tag from a website:

function getFrontImage($url){
  $page_content = file_get_contents($url);

  $dom_obj = new DOMDocument();
  $dom_obj->loadHTML($page_content);
  $meta_val = null;

  foreach($dom_obj->getElementsByTagName('meta') as $meta) {

    if($meta->getAttribute('property')=='og:image'){ 

        $meta_val = $meta->getAttribute('content');
    }
  }

  return $meta_val;
}

however, this only seems to work on some webpages. For example, i can get the og:image tag from the following link: http://lietuvosdiena.lrytas.lt/aktualijos/2017/06/16/news/partnerystei-nepritare-konservatoriai-sulauke-liberalu-kircio-1702264/

But i can't get it from this link: http://sportas.lrytas.lt/krepsinis/2017/06/16/news/martynas-pocius-del-traumu-baigia-karjera-1703843/ which is weird, since they don't differ in any way as i understan


Solution

  • I solved my problem by using curl. Here's the final code:

    function getFrontImage($url){
    
    libxml_use_internal_errors(true);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
    curl_setopt($ch, CURLOPT_ENCODING , "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    
    
    $page_content = curl_exec($ch); 
    
    $dom_obj = new DOMDocument();
    $dom_obj->loadHTML($page_content);
    $meta_val = null;
    
    foreach($dom_obj->getElementsByTagName('meta') as $meta) {
    
    if($meta->getAttribute('property')=='og:image'){ 
    
        $meta_val = $meta->getAttribute('content');
    
    }
    
    
    
    
    }
    
    return $meta_val;
    }