When I open https://graph.facebook.com/me?access_token=xxxx I get an JSON file. I want to store it in a php variable and then use json_decode() function to convert it into a string. How can I directly store the JSON content in PHP variable by giving the link.
3
-
1You can use file_get_contents().Shalu Singhal– Shalu Singhal2016-05-25 06:44:31 +00:00Commented May 25, 2016 at 6:44
-
1Or you can use CURL php.net/manual/en/book.curl.php which is fast and have more options.Ali– Ali2016-05-25 06:48:28 +00:00Commented May 25, 2016 at 6:48
-
file_get_contents() worked out thank youRaja Panda– Raja Panda2016-05-25 06:57:03 +00:00Commented May 25, 2016 at 6:57
Add a comment
|
3 Answers
Simplest solution is to use the http stream wraper with file_get_contents().
$data = json_decode( file_get_contents('theurl') );
If you need more control over the http request made, take a look at the stream context options.
If you need more error handling take a look at stream notifications.
You can also use
$fp = fopen('http://....', 'rb');
if ( !$fp ) {
someErrorHandling();
}
$data = json_decode( stream_get_contents($fp) );
In that case you can combine it with stream_get_meta_data() to get more http relaed stuff from the request/stream.
see also: allow_url_fopen (because the url wrappers can be disabled via configuration...)
Comments
4 Comments
Ohgodwhy
What if the server doesn't
allow_url_fopen? Perhaps it's a security concern. Wouldn't a simple cURL request be better?VolkerK
@Ohgodwhy What if the curl extension isn't available. Wouldn't a simple url wrapper be better? ...gets circular at this point ;-)
Ohgodwhy
@VolkerK Understood, and valid.
VolkerK
@Ohgodwhy But by all means, write an answer using the curl extension. It's a perfectly valid alternative. In some regards it's even superior (...I think; there's no alternative to multi_exec yet, is there? And the GSSAPI.)