[php] PHP read and write JSON from file

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!

This question is related to php json

The answer is


If you want to display the JSON data in well defined formate you can modify the code as:

file_put_contents($file, json_encode($json,TRUE));


$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));

$context=stream_context_create($headers);

$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);

$str1=utf8_encode($str);

$str1=json_decode($str1,true);



foreach($str1 as $key=>$value)
{

    echo "key is: $key.\n";

    echo "values are: \t";
        foreach ($value as $k) {

        echo " $k. \t";
        # code...
    }
        echo "<br></br>";
        echo "\n";

}

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));

You need to make the decode function return an array by passing in the true parameter.

json_decode(file_get_contents($file),true);


When you want to create json format it had to be in this format for it to read:

[ 
  {
    "":"",
    "":[
     {
       "":"",
       "":""
     }
    ]
  }
]

Or just use $json as an object:

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

This is how it is returned without the second parameter (as an instance of stdClass).


Try using second parameter for json_decode function:

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

This should work for you to get the contents of list.txt file

$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));

$context=stream_context_create($headers);

$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);

$str=utf8_encode($str);

$str=json_decode($str,true);

print_r($str);