14

I'm trying to use file_get_contents() to grab a twitter feed, however I'm getting the following warning:

failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

My code:

$feed = 'http://twitter.com/statuses/user_timeline.rss?screen_name=google&count=6';
$tweets = file_get_contents($feed);

I'm using Google just for the sake of testing. allow_url_fopen is enabled in my php.ini file.

Any idea what could be wrong?

Brandon
  • 16,382
  • 12
  • 55
  • 88
Marcin
  • 1,266
  • 3
  • 15
  • 31

2 Answers2

34

You should use the PHP cURL extension if it's available, as it's many times faster, more powerful, and easier to debug. Here is an example that does the same thing you were trying:

function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$feed = 'http://twitter.com/statuses/user_timeline.rss?screen_name=google&count=6';
$tweets = curl($feed);
Brandon
  • 16,382
  • 12
  • 55
  • 88
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • It's also a lot easier to debug, since you can get it to dump the request and headers it sends (malformed requests being the usual cause of HTTP 400 errors) – Frank Farmer Aug 21 '10 at 01:49
  • 1
    http://stackoverflow.com/questions/555523/file-get-contents-vs-curl-what-has-better-performance – Felipe Cardoso Martins Aug 21 '10 at 02:02
  • For all you know, he may be using curl, if it was compiled with http wrappers. – Artefacto Aug 21 '10 at 02:19
  • @webarto, may I request you to have a look at http://stackoverflow.com/questions/11548965/file-get-contents-or-curl-way-nothing-works-in-internet-server-though-thos on a related issue ? – Istiaque Ahmed Jul 18 '12 at 20:37
  • This is *not* an answer to the question at hand, which was how to fix file_get_contents. I do not have the option of using curl, as PEAR is what is failing for me. I am not rewriting the source code of PEAR to use curl... – ashgromnies Mar 06 '13 at 20:01
  • @ashgromnies it is obvious that request was not properly formed, now instead of debating why is that (it can be number of things), it's safe to assume that curl is bundled, and such can be used. I'm not a fan of curl PHP API. *failing* can also mean that you are failing. – Dejan Marjanović Mar 06 '13 at 20:17
0

Most probably, your server have mod_security enabled. Add the below lines in your .htaccess after any existing rules and then try to see the issue is still there, after that addition.

<IfModule mod_security.c>
 SecFilterScanPost
</IfModule>