繁体   English   中英

如何在 Laravel 5.6 中转换 json 文件中的 json 数据

[英]How to convert json data in json file in Laravel 5.6

我需要在文件.json转换我的 json 数据。 我在这段代码中将数据解析array of json

$movies = Movie::all();
return response()->json($movies);

我需要创建movies.json文件。 我的文件必须在哪里,哪个文件夹? 怎么办?

采用

use Illuminate\Support\Facades\Storage;

接着

Storage::disk('public')->put('movies.json', response()->json($movies));

该文件将保存在公用文件夹中

在您的web.php

Route::get('/download','MoviesController@downloadJSON')->name('download_movies');

将以下代码粘贴到您的控制器中:

 public function downloadJSON(Request $request){
         $table = Movie::all();
         $filename = "movies.json";
         $handle = fopen($filename, 'w+');
         fputs($handle, $table->toJson(JSON_PRETTY_PRINT));
         fclose($handle);
         $headers = array('Content-type'=> 'application/json');
         return response()->download($filename,'movies.json',$headers);
    }

了解有关响应下载的更多信息

根据您要在服务器上创建文件的事实,也许可以像这样使用Laravel中的文件存储功能

use Illuminate\Support\Facades\Storage;

$movies = Movie::all();
Storage::put('Movies.json', $movies);
return true;

将来,如果您想以下载形式提供它,则可以创建一个响应宏。 对于HTML下载,我也做了同样的事情

文件:App \\ Providers \\ AppServiceProvider @ boot

\Response::macro('attachment', function ($content) {

            $headers = [
                'Content-type' => 'text/json',
                'Content-Disposition' => "attachment; filename='Movies.json'",
            ];

            return \Response::make($content, 200, $headers);

        });

并称之为

return response()->attachment($movies); //App\Providers\AppServiceProvider

这是简单的方法

use File 
File::put(public_path('/upload/json/'.$fileName),$data);

$ fileName是文件名。 $ data是要存储在此文件中的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM