Skip to content

Instantly share code, notes, and snippets.

@mikestreety
Created July 22, 2013 13:42
Show Gist options
  • Save mikestreety/6053898 to your computer and use it in GitHub Desktop.
Save mikestreety/6053898 to your computer and use it in GitHub Desktop.
Adds an extra key/value pair to a json file
<?php
// This takes a get of location and postcode to put into a json file for use with https://github.com/MrQwest/activity
/* Example use:
$.ajax({
url: 'file.php',
type: 'GET',
data: {
location: [LOCATION - VARIABLE OR STRING],
postcode: [POSTCODE - VARIABLE OR STRING],
data_type: options.dataType,
latest_item: latest_item
}
})
*/
$file_name = 'json_file.json'; // Location of JSON file
$location = $_GET['location']; // Gets the location from url
$postcode = $_GET['postcode']; // Gets the post code
$file = file_get_contents($file_name); // Gets the contents of a file
$json = json_decode($file, true); // Decodes the file - the true sets it as an array
$json[$location] = $postcode; // Adds the location and post code to the array
$json = json_encode($json); // Re-endodes the arry as json
file_put_contents($file_name, $json); // Puts it back in the file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment