Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP read and write JSON from file

Tags:

json

php

I have the following JSON in a file list.txt:

{ "bgates":{"first":"Bill","last":"Gates"}, "sjobs":{"first":"Steve","last":"Jobs"} } 

How do I add "bross":{"first":"Bob","last":"Ross"} to my file using PHP?

Here's what I have so far:

<?php  $user = "bross"; $first = "Bob"; $last = "Ross";  $file = "list.txt";  $json = json_decode(file_get_contents($file));  $json[$user] = array("first" => $first, "last" => $last);  file_put_contents($file, json_encode($json));  ?> 

Which gives me a Fatal error: Cannot use object of type stdClass as array on this line:

$json[$user] = array("first" => $first, "last" => $last); 

I'm using PHP5.2. Any thoughts? Thanks!

like image 803
Josiah Avatar asked Jan 13 '12 23:01

Josiah


People also ask

How to read and Write in JSON file using PHP?

php $user = "bross"; $first = "Bob"; $last = "Ross"; $file = "list. txt"; $json = json_decode(file_get_contents($file)); $json[$user] = array("first" => $first, "last" => $last); file_put_contents($file, json_encode($json)); ?>

How to read JSON data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

How to read JSON in PHP from URL?

Use the file_get_contents() Function to Get JSON Object From the URL in PHP. We can use file_get_contents() along with json_decode() to get the JSON object from a URL. The file_get_contents() function reads the file in a string format.

How show JSON data from HTML table in PHP?

To use PHP function file_get_contents () we can read a file and retrieve the data present in JSON file. After retrieving data need to convert the JSON format into an array format. Then with the use of looping statement will display as a table format.


2 Answers

The clue is in the error message - if you look at the documentation for json_decode note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.

So change your call to

$json = json_decode(file_get_contents($file), true); 

And it'll return an associative array and your code should work fine.

like image 69
John Carter Avatar answered Sep 23 '22 23:09

John Carter


The sample for reading and writing JSON in PHP:

$json = json_decode(file_get_contents($file),TRUE);  $json[$user] = array("first" => $first, "last" => $last);  file_put_contents($file, json_encode($json)); 
like image 20
4EACH Avatar answered Sep 25 '22 23:09

4EACH