![](/img/trans.png)
[英]How to convert null values to empty string in Laravel 5.6 json response?
[英]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.