将 JSON 输出保存到 json 文件

STE*_*EIN 5 php json

得到这个代码:

<?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);
Run Code Online (Sandbox Code Playgroud)

但没有任何内容被保存到新news.json文件中,这是为什么呢?正如我所学到的 - 创建文件是使用这种方法完成的。(wfopen

med*_*ill 5

请检查您目录中的写入权限。还指定 news.json 文件的绝对路径,因为您的 PHP 服务器似乎无法读取相对路径:

改变

$file = fopen('news.json','w'); 
Run Code Online (Sandbox Code Playgroud)

$file = fopen(__DIR__ . '/news.json','w');
Run Code Online (Sandbox Code Playgroud)