HDTuto.com

How to read and write json file in PHP Laravel?


Hi PHP Dev,

do you require to modify or update your json file in laravel 5 application? If yes then i will let you know how to read and write json file in Laravel project. we will create json file and save json data.

Actually, i was working on my laravel app and i require to use laravel translation using laravel trans. but i need to use trans with json data. i was thinking how to read and write that json file like i created en.json file on lang folder and i was read and write both.

So here i wanted to share with you this small example so if you anyone require to use then it can be help you. So let's see below route.

web.php

Route::get('/', function () {


// Read File

$jsonString = file_get_contents(base_path('resources/lang/en.json'));

$data = json_decode($jsonString, true);


// Update Key

$data['country.title'] = "Change Manage Country";


// Write File

$newJsonString = json_encode($data, JSON_PRETTY_PRINT);

file_put_contents(base_path('resources/lang/en.json'), stripslashes($newJsonString));


// Get Key Value

dd(__('country.title'));

});

Output File: en.json

{

"name": "Hardik",

"title": "Odit",

"country.title": "Change Manage Country"

}

I hope you need it and help you....




June 11, 2018 | Category : PHP Laravel Laravel 5 Laravel 5.5 Laravel 5.6 JSON
Related Posts