PHP - Load JSON, edit and save - php

I load JSON from file:
{ "timestampRead": [11, 22, 33], "timestampCurrent": [66, 77, 88] }
to PHP:
$local_json = json_decode(file_get_contents('/Temp/chat-users.json'));
and I don't know how I can:
update all values in timestampRead ($local_json->timestampRead[] = '99'?)
update one value in timestampCurrent ($local_json->timestampCurrent[2] = '33')
save updated json to file ($local_json array to json)

1) update all values in timestampRead: $local_json->timestampRead = array( [your comma separated values] );
2) update one value in timestampCurrent: $local_json->timestampCurrent[2] = '33'; (correct)
3) save updated json to file: file_put_contents('path/to/file', json_encode($local_json));

Once have the json data loaded into a variable, you can access each property as you would a normal class:
$local_json->timestampRead = $new_timestampRead;
$local_json->timestampCurrent[an_index] = "whatever you want";
To save the data back to a file, you can use the counter part of file_get_contents() called file_put_contents():
file_put_contents("path/to/file", $local_json);

Related

Get JSON from a URL by PHP

I have a URL that returns a JSON object like this:
{
"USD" : {"15m" : 7809.0, "last" : 7809.0, "buy" : 7809.85, "sell" : 7808.15, "symbol" : "$"},
"AUD" : {"15m" : 10321.42, "last" : 10321.42, "buy" : 10322.54, "sell" : 10320.3, "symbol" : "$"},
}
URL : https://blockchain.info/ticker
more info : https://blockchain.info/api/exchange_rates_api
I want to get all the data from the first line and echo it and to have it keep requesting it so its live
I have used the examples on git hub
https://github.com/blockchain/api-v1-client-php/blob/master/docs/rates.md
but it displays all of the data output and you have to refresh it to get it updated
please can some one point me in the right direction
ideally I would end up with something like
15 m Last Buy Sell
USD ($) 7794.87 7794.87 7795.72 7794.02
I have the table and data going to the table but its echoing the whole data set rather than the first line and also I dont know how to select individual fields
How can I do it through PHP?
What you need is a request php page, which will make:
1 - Get data from te site:
$data = file_get_contents('https://blockchain.info/ticker');
2 - decode the json
$decodedData = json_decode($data);
3 - Here you can access it using OOP:
var_dump($decodedData->USD);
The point here will be to retrieve data as you wish, you can mix it up with HTML in a table for example.
Then, you need a JS script, that will execute a function with setInterval, each few miliseconds. That function should make a request to a PHP page that you created earlier, get that data and change with the updated one.
This Should do it:
<?
$seconds = 5;
function get_live_quote($key){
$json_string = file_get_contents('https://blockchain.info/ticker');
$json_array = json_decode($json_string, TRUE);
$quote = $json_array[$key];
$keys = implode(" ",array_keys($quote));
$values = implode(" ", array_values ($quote));
return "$keys $values \n";
}
while(TRUE){
echo get_live_quote("USD");
sleep($seconds);
}
Save the preceding code to a file like "quote.php". Then from your terminal just run: php quote.php

Updating JSON file using PHP causes duplicate entries

I am trying to use PHP forms to update a JSON file, but when I edit a field of the file, it creates a duplicate of the entry, but with the updated information. For example:
[
{"toolName":"tool1", "url":"https://google.com/", "phase":"None"},
{"toolName":"tool2", "url":"http://yahoo.com/", "phase":"None"},
{"toolName":"tool3", "url":"http://bing.com/", "phase":"None"}
]
If on submission the PHP form wants to change the "phase" for "tool1", it adds a new entry with the updates. Like:
[
{"toolName":"tool1", "url":"https://google.com/", "phase":"None"},
{"toolName":"tool2", "url":"http://yahoo.com/", "phase":"None"},
{"toolName":"tool3", "url":"http://bing.com/", "phase":"None"},
{"toolName":"tool1", "url":"https://google.com/", "phase":"NewPhase"}
]
How can this be avoided? I am using the index of the tool in the array as the identifier when I update, so my current solution is this:
$toolId = $_POST['tool-id'];
$toolName = $_POST['tool-name'];
$toolUrl = $_POST['tool-url'];
$toolPhase = $_POST['tool-phase'];
$data = file_get_contents("../assets/js/tools.json");
$json_data = json_decode($data, true);
$json_data[$toolId]->toolName = $toolName;
$json_data[$toolId]->url = $toolUrl;
$json_data[$toolId]->phase = $toolPhase;
$json_data = array_values($json_data);
file_put_contents("../assets/js/tools.json", stripslashes(json_encode($json_data)));
**Note: When submitting the form, I am using a Bootstrap modal, so I am only sending the data for the current visible tool (i.e. the tool at index "toolId"), so I do not iterate through the entire JSON file.
The true statement in this line instructs PHP to return an array
$json_data = json_decode($data, true);
However, these lines create an object
$json_data[$toolId]->toolName = $toolName;
$json_data[$toolId]->url = $toolUrl;
$json_data[$toolId]->phase = $toolPhase;
If you change them to this it should work
$json_data[$toolId]['toolName'] = $toolName;
$json_data[$toolId]['url'] = $toolUrl;
$json_data[$toolId]['phase'] = $toolPhase;

Accessing json with php

I want to read the json data on the page http://mattrb.com/txt.txt
For example, let's say I want to get the name "Bulbasaur." I have this code:
<?php
$file = file_get_contents("http://mattrb.com/txt.txt");
$json = json_decode($file);
echo $json->1->name;
?>
This code causes the php to simply not load. Is this because you can't use a number? Next I tried this:
<?php
$file = file_get_contents("http://mattrb.com/txt.txt");
$json = json_decode($file);
$num = 1;
echo $json->$num->name;
?>
This allows the php to load, but still returns nothing. What am I doing wrong?
Your json is invalid. Please check at http://jsonlint.com/.
Also you can access "1" in php like this: echo $json->{1}->name;
Your json file isn't valide You have a comma problem item number 135 try to delete it so you can parse the file .
"135": {, //the problem of your json data is here
"levels": [5, 15],
"probability": 4 "name": "Jolteon",
"attack": 65,
"defense": 60,
"type": "electric",
"moves": [
"tackle",
"thundershock",
"thunder"
],
"curve": 1.6
},
Your json should not contain newline and other invalid characters.
In other words - your json is invalid. json_decode does not work on the file.
$file = file_get_contents("http://mattrb.com/txt.txt");
var_dump(json_decode($file));
// NULL

Read and return data from json file in laravel 4

I have a file called data.txt in the public path , it has this
{"data":[{"name": "Jack", "age": 13},{"name": "Mary", "age": 15}]}
and I want to read these data and also return the age for both Jack and Mary,
I know that I can read the file using the decode_json(file_get_contents) but I have no clue how to fetch the data and return specific records from it.
Any help is much appreciated !
You can load the file and decode the content with:
$content = json_decode(file_get_contents($path), true);
This will give you the associative array that contains your JSON content.
You can access data in user objects like that:
$userData = $content['data']; // content of "data" field
$jackData = $userData[0]; // first object in "data" array - Jack
$jackName = $jackData['name']; // Jack's name

Extracting a precise value from a Json array with PHP (like a MySQL db)

another (probably) easy question for you.
As I wrote many times, I'm not a programmer but thanks to you I was able to build an interesting site for my uses.
So again thx.
This is my new problem:
I have a site that recover json data from a file and store it locally once a day (this is the code - I post it so it can be useful to anyone):
// START
findList();
function findList() {
$serverName = strtolower($_POST["Server"]); // GET SERVER FROM FORM POST
$localCoutryList = ("json/$serverName/countries.json"); // LOCAL LOCATIONS OF FILE
$urlCountryList = strtolower("url.from.where.I.get.Json.file.$serverName/countries.json"); // ONLINE LOCATION OF FILE
if (file_exists($localCoutryList)) { // FILE EXIST
$fileLastMod = date("Y/m/d",filemtime($localCoutryList)); // IF FILE LAST MOD = FILE DATE TIME
$now = date('Y/m/d', time()); // NOW
if ($now != $fileLastMod) { // IF NOW != FILE LAST MOD (date)
createList($serverName,$localCoutryList,$urlCountryList); // GO AND CREATE FILE
} else { // IF NOW = FILE LAST MOD (date)
jsonList($serverName,$localCoutryList,$urlCountryList); // CALL JSON DATA FROM FILE
}} else { // FILE DOESN'T EXIST
createList($serverName,$localCoutryList,$urlCountryList); // CALL CREATE FILE
}};
function createList($serverName,$localCoutryList,$urlCountryList) {
file_put_contents($localCountryList, file_get_contents($urlCountryList)); // CREATE FILE
jsonList($serverName); // CALL JSON DATA FROM FILE
};
function jsonList($serverName,$localCoutryList,$urlCountryList) { // JSON DATA FROM FILE
$jsonLoopCountry = file_get_contents($localCoutryList); // GET CONTENT OF THE LOCAL FILE
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
foreach ($countryList as $dataCountry) { // FOR EACH "COUNTRY" IN JSON DECODED OBJECT
// SET VARS FOR ALL THE COUNTRIES
$iscountryID = ($dataCountry['id']); // TEST
$countryCurrency = ($dataCountry['curr']); // TEST
$countryName = ($dataCountry['name']);} // TEST
echo "<br>total country list: ".count($countryList); // THIS RETURN TOTAL ELEMENTS IN THE ARRAY
[...]
The kind of Json data I'm working with is structured as it follows:
{"country":[{"id":130,"curr":"AFN","name":"Afghanistan"},{"id":55,"curr":"ALL","name":"Albania"},{"id":64,"curr":"DZD","name":"Algeria"},{"id":65,"curr":"AOA","name":"Angola"},{"id":24,"curr":"ARS","name":"Argentina"}...
So I can say that
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
creates the JSON ARRAY right? (Because JSON array starts with {"something":[{"..."...)
if it was [{"a":"answer","b":"answer",...} ... it would have a been a JSON Object right?
So to access to the array I uses
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
right?
So I understood that arrays are a fast useful ways to store relational data and access to it right?
So the question is how to make a precise search inside the array, so to make it works like a Query MySQLi, like "SEARCH INSIDE ARRAY WHERE id == 7" and have as a result "== ITALY" (ex.).
The way exist for sure, but with whole exmples I found on the net, I was able to fix one to make it works.
Thx again.
Alberto

Categories