Search code examples
phpjsonfacebook-page

Facebook page feed doesn't work with php file_get_contents()


When I go to this url in by browser, it shows me the json feed i expect:

https://www.facebook.com/feeds/page.php?format=json&id=237173582992285

When in PHP I do a

<?php
print_r(file_get_contents('https://www.facebook.com/feeds/page.php?format=json&id=237173582992285'));
?>

I get an html page saying my browser is not supported by facebook and that I should upgrade. How do I make the file_get_contents return the json feed I'm expecting?

Additional Notes I also tried from bash wget https://www.facebook.com/feeds/page.php?format=json&id=237173582992285 and the file I downloaded also has html content saying browser not supported.


Solution

  • Try this, it works for me

     $ch = curl_init("https://www.facebook.com/feeds/page.php?format=json&id=237173582992285");
      curl_setopt( $ch, CURLOPT_POST, false );
      curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
      curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
      curl_setopt( $ch, CURLOPT_HEADER, false );
      curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
      $data = curl_exec( $ch );
      echo $data;
    

    As pointed by @Michael Mior, it violates facebook terms. But this is the answer to your question, facebook has a simple check to ensure that page should be opened by browser and thus we are mimicking it by setting useragent header.