Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents() failed to open stream:

Tags:

php

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?

like image 929
Marcin Avatar asked Aug 21 '10 00:08

Marcin


People also ask

What is the use of file_get_contents () function?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

What will the file_get_contents () return?

Return Values ¶ The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.

Which is faster curl or file_get_contents?

Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

Does file_get_contents cache?

Short answer: No. file_get_contents is basically just a shortcut for fopen, fread, fclose etc - so I imagine opening a file pointer and freading it isn't cached.


1 Answers

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);
like image 80
Dejan Marjanović Avatar answered Sep 23 '22 16:09

Dejan Marjanović