【问题标题】:PHP Download the json filePHP 下载 json 文件
【发布时间】:2016-11-20 13:02:02
【问题描述】:

我的 wordpress 中有一个 json 数据,我希望它可以作为.json 的文件下载。

$arr = array();
foreach($wp_options as $key){
    $variable = get_option($key);
    $arr[$key] = $variable;
}
$json = json_encode($arr);

我试过file_put_contents喜欢

$file = 'file.json';
file_put_contents($file, json_encode($arr));

但什么也没发生。

关于如何将这些数据下载为.json 文件的任何想法?

【问题讨论】:

    标签: php json wordpress file


    【解决方案1】:

    在回显 JSON 数据之前,您可以尝试设置 HTTP 响应标头Content-Disposition(提示用户将响应保存在本地)和Content-Type(指示媒体类型)。

    $data = json_encode(['foo' => 'bar']);
    
    header('Content-Disposition: attachment; filename=data.json');
    header('Content-Type: application/json');
    echo $data;
    

    【讨论】:

      【解决方案2】:

      你可以做下一件事:

      $data = json_encode(['foo' => 'bar', 'baz' => 1]);
      header('Content-Type: application/json');
      header('Content-Disposition: attachment; filename=data.json');
      header('Expires: 0'); //No caching allowed
      header('Cache-Control: must-revalidate');
      header('Content-Length: ' . strlen($data));
      file_put_contents('php://output', $data);
      

      【讨论】:

        【解决方案3】:

        我认为你可以使用 FILE I/O 功能。 试试这个

        $fp = fopen('file.json', 'a');
        fwrite($fp, json_encode($arr));
        fclose($fp);
        

        【讨论】:

        • 仍然没有提示下载文件。服务器中有什么我必须做的吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-01
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 2014-04-05
        • 2020-01-13
        • 2023-04-04
        相关资源
        最近更新 更多