3

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
  • 1
    You can use file_get_contents(). Commented May 25, 2016 at 6:44
  • 1
    Or you can use CURL php.net/manual/en/book.curl.php which is fast and have more options. Commented May 25, 2016 at 6:48
  • file_get_contents() worked out thank you Commented May 25, 2016 at 6:57

3 Answers 3

4

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...)

Sign up to request clarification or add additional context in comments.

Comments

0

you can use file_get_contents() function. http://php.net/manual/en/function.file-get-contents.php

4 Comments

What if the server doesn't allow_url_fopen? Perhaps it's a security concern. Wouldn't a simple cURL request be better?
@Ohgodwhy What if the curl extension isn't available. Wouldn't a simple url wrapper be better? ...gets circular at this point ;-)
@VolkerK Understood, and valid.
@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.)
0

Using file_get_contents you can get the json.

If you link gievs the josn as response.

$storeVar = file_get_contents("https://graph.facebook.com/me?access_token=xxxx");

$arr = json_decode($storeVar); //Here is the array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.