"; $daysJson = json_encode($days); echo $daysJson ."
"; echo "
"; // Write JSON string to file file_put_contents("data.json", $daysJson); // Verify the content in data.json //////////////////////////////////////// // Let's create a friend info array $friend1 = array("name"=>"Duh", "email"=>"duh@uva.edu", "phone"=>"999-999-9999", "age"=>9); echo "Convert PHP associative array into JSON string
"; $friend1_Json = json_encode($friend1); echo $friend1_Json ."
"; echo "
"; // Write friend1 info to data.json file file_put_contents("data.json", $friend1_Json); // Verify the content in data.json // Notice that the original content was replaced // To keep the original content, do one of the following // 1. use file_get_contents to read the entire file, // store the content in a variable, // then append the new content to the variable, // write the variable to file // (this option is similar to open a file as a write mode) $content = file_get_contents("data.json"); $content .= "\n" . $friend1_Json; file_put_contents("data.json", $content); // 2. open file as an append mode, // append the new content to the file, // be sure to close the file when done $file = fopen("data.json", "a"); fputs($file, "\n" . $friend1_Json); fclose($file); //////////////////////////////////////// // Let's create a new friend object class Friend { public $name = ""; public $email = ""; public $phone = ""; public $age = ""; } // create an instance of a friend object $friend2 = new Friend(); // assign values to friendObj's properties, // use an array operator to access an object's data $friend2->name = "Someone"; $friend2->email ="someone@uva.edu"; $friend2->phone = "444-444-4444"; $friend2->age = "22"; // put friend1 and friend2 in a PHP array, createing a 2-D array $friends_array = array($friend1, $friend2); // convert 2-D array into JSON $friends_array_Json = json_encode($friends_array); // write friends array to file file_put_contents("data.json", $friends_array_Json); //////////////////////////////////////// // read from JSON file $content = file_get_contents("data.json", "r"); // convert JSON string read from file into PHP associative array $list_of_friends = json_decode($content, true); var_dump($list_of_friends); echo "

List of friends

"; foreach ($list_of_friends as $friend) { echo $friend["name"]; echo "" . "" . "" . "" . "
Email" . $friend["email"] . "
Phone" . $friend["phone"] . "
Age" . $friend["age"] . "
"; } echo "
"; //////////////////////////////////////// // read from friends.json that is stored in a folder named "data" $content = file_get_contents("data/friends.json", "r"); $list_of_friends = json_decode($content, true); var_dump($list_of_friends); echo "

List of friends

"; foreach ($list_of_friends as $friend) { var_dump($friend); $friend_info = $friend; echo ""; } ?>