STEIN
STEIN

Reputation: 303

Save JSON output to a json file

Got this code:

<?php
  $jsonurl = "https://newsapi.org/v1/articles?source=cnn&sortBy=top&apiKey=d8dfc55aa005430c9567416cac34e3fa";
  $json = file_get_contents($jsonurl);
  var_dump(json_decode($json));

          $file = fopen('news.json','w');
          fwrite($file, $json);
          fclose($file);

But nothing gets saved to the new news.json file, why would this be? As I was taught - creating files is done using this method. (w on fopen)

Upvotes: 5

Views: 16356

Answers (2)

justtry
justtry

Reputation: 639

enable php errors to see the issue, do you see data in var_dump(could be SSL thing)? also check permissions on news.json file

Upvotes: 2

medskill
medskill

Reputation: 330

Please check the write permissions in your directory. Specify also the absolute path to the news.json file, because it seems like your PHP server can't read the relative path :

Change

$file = fopen('news.json','w'); 

to

$file = fopen(__DIR__ . '/news.json','w');

Upvotes: 5

Related Questions