Wojtokuba
Wojtokuba

Reputation: 11

Json_decode, file_get_contents var_dump returns NULL

I'm trying to get file contents from php-generated file with json data.

Json has been already checked by jsonlint.com site. It's valid.

$result = file_get_contents("url"); 
var_dump(json_decode($result,true));

Nginx does not displaying any errors.

Why it doesn't work? Json generator is on external server. When i pasted it on http://php.fnlist.com/php/json_decode website it was converted correctly.

Upvotes: 1

Views: 3614

Answers (3)

Holy Thirteen
Holy Thirteen

Reputation: 338

It may be irrelevant but in my case this solved the problem. As seen in the picture, the "file_get_contents" needs "allow_url_fopen" in "PHP Selector" of CPanel to be turned on.enter image description here

Upvotes: 1

Ugy Astro
Ugy Astro

Reputation: 417

Even though this is old question, may be this answer can help someone when see the same issue.

To handle this, make sure that:

  1. allow_url_fopen is ON, check in php.ini file.
  2. url is an valid url. To skip some issu about passing variable you can use http_build_query
  3. return of json is valid. You can check the return is valid with jsonlint.com
  4. stream_context is already setup so file_get_contents knows how to handle the request. Even though we’re puting data over HTTPS, we need to use the http context. We set method to PUT, Content-type to application/json, Accept to application/json, Connection to close, and Content-length to the length of our JSON string. We’re PUTing this data over HTTP1.1 so we set the to 1.1. We’re sending the JSON in the body of the request, so we set this in the content. And as we are using HTTPS, we need to configure the ssl settings.

    $context = stream_context_create([ 'http' => [ 'method' => 'PUT', 'header' => "Content-type: application/json\r\n" . "Accept: application/json\r\n" . "Connection: close\r\n" . "Content-length: " . strlen($json_data) . "\r\n", 'protocol_version' => 1.1, 'content' => $json_data ], 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false ] ]);

Finally put the data by calling file_get_contents like this:

$getData = file_get_contents($url, false, $context);
$results = json_decode($getData, TRUE);

Hopely usefull, thanks.

Upvotes: 0

Barry
Barry

Reputation: 3318

You can get the last error message from the encode / decode...

Upvotes: 1

Related Questions