[英]How to convert json data in json file in Laravel 5.6
I need convert my json data in file .json
.我需要在文件
.json
转换我的 json 数据。 I parsing data to array of json
in this code我在这段代码中将数据解析
array of json
$movies = Movie::all();
return response()->json($movies);
I need create movies.json
file.我需要创建
movies.json
文件。 Where my file must be, which folder?我的文件必须在哪里,哪个文件夹? And how to it?
怎么办?
use 采用
use Illuminate\Support\Facades\Storage;
and then 接着
Storage::disk('public')->put('movies.json', response()->json($movies));
and this file will be save in public folder 该文件将保存在公用文件夹中
in your web.php
在您的
web.php
Route::get('/download','MoviesController@downloadJSON')->name('download_movies');
paste below code in your controller : 将以下代码粘贴到您的控制器中:
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);
}
read more about Response download 了解有关响应下载的更多信息
According to the fact that you want to create the file on the server, maybe you can use the file-storage functions in Laravel like this 根据您要在服务器上创建文件的事实,也许可以像这样使用Laravel中的文件存储功能
use Illuminate\Support\Facades\Storage;
$movies = Movie::all();
Storage::put('Movies.json', $movies);
return true;
In the future, if you want to offer it as a download you can create a response macro. 将来,如果您想以下载形式提供它,则可以创建一个响应宏。 I've done the same for a HTML download
对于HTML下载,我也做了同样的事情
File: App\\Providers\\AppServiceProvider@boot 文件: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);
});
And call it as 并称之为
return response()->attachment($movies); //App\Providers\AppServiceProvider
This is the Simple way 这是简单的方法
use File
File::put(public_path('/upload/json/'.$fileName),$data);
$fileName is the name of file. $ fileName是文件名。 $data is the data you want to store in this file.
$ data是要存储在此文件中的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.