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!
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)); ?>
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.
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With