Skip to content
PHP Logo

How can PHP be used to update a specific value in a JSON file while preserving the rest of the data intact?

To update a specific value in a JSON file using PHP while preserving the rest of the data intact, you can read the JSON file, decode it into an associative array, update the specific value, encode the array back into JSON, and write it back to the file.

php
// Read the JSON file
$jsonData = file_get_contents('data.json');

// Decode JSON data into an associative array
$data = json_decode($jsonData, true);

// Update the specific value
$data['key_to_update'] = 'new_value';

// Encode the array back into JSON
$newJsonData = json_encode($data);

// Write the updated JSON data back to the file
file_put_contents('data.json', $newJsonData);