I have the following data from an api call:
$userId = 1234; and $accessToken = 6789;. I want to write this to a json file called users.json.
Following this I make another api call and receive the following data:
$userId = 5678; and $accessToken = 0123;.
I then want to add this to the json file so that it looks like this:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
},
]
My code for writing to the json file looks like this. The $userId and $accessToken are defined elsewhere and are returning the correct values:
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
print_r($tempArray); // this doesn;t show anything as the users.json file contains `null`
array_push($tempArray, $userId);
array_push($tempArray, $accessToken);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
Unfortunately this isn't working. When I view the json file it just contains null Can anyone see any error with my code?
Thanks Raul
Your code is wrong. Correct it to look like this
<?php
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
if(empty($tempArray)){
$tempArray = [];
}
$newData = [
"userId" => $userId,
"accessToken" => $accessToken
];
array_push($tempArray, $newData);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
This will definitely work.
You need to to json_decode($content, true); to obtain an array and not an object.
See http://php.net/manual/fr/function.json-decode.php
Also the array_push is not correctly called.
It should be : array_push($tempArray, ["userid"=>$userId,"accesstoken" => $accessToken]);
You have error in json file so that all suggesion not working remove , at end of array. Then try below code :
Your json file should be:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
}
]
php :
$content = file_get_contents('user.json');
$tempArray = json_decode($content,true);
$new_array = array("userId"=>$userId,"accesstoken"=>$accessToken);
array_push($tempArray, $new_array);
$jsonData = json_encode($tempArray);
file_put_contents('user.json', $jsonData);
Related
I'm trying to decode JSON format
My API Endpoint is https://api.reliableserver.host/api/landings
And this is the output
{
"success": true,
"data": [
{
"id": 1,
"primary_balance": "$4,184.37",
"primary_currency": "USD",
"secondary_balance": "¥0",
"secondary_currency": "JPY",
"tertiary_balance": "฿0.00",
"tertiary_currency": "THB",
"first_language": "ไทย",
"second_language": "English",
"footer_text": "a",
"created_at": "2020-10-26T07:45:49.000000Z",
"updated_at": "2020-10-28T05:31:04.000000Z",
"deleted_at": null
}
],
"message": "Landings retrieved successfully"
}
I need to echo individual values, for example: Primary Balance: $4,184.37
I tried using this:
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode($url);
echo $obj>primary_balance;
But it didnt work, kindly guide me what am I doing wrong.
You can do this way :
$url = '{"success": true,"data": [{"id": 1,"primary_balance": "$4,184.37","primary_currency": "USD","secondary_balance": "¥0","secondary_currency": "JPY","tertiary_balance": "฿0.00","tertiary_currency": "THB","first_language": "ไทย","second_language": "English","footer_text": "a","created_at": "2020-10-26T07:45:49.000000Z","updated_at": "2020-10-28T05:31:04.000000Z","deleted_at": null}],"message": "Landings retrieved successfully"}';
$obj = json_decode($url, true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Above code tested here
You need file_get_contents() method to get the JSON data from your given URL.
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode(file_get_contents($url), true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Basically, you are not calling that api anywhere. If it is an open endpoint (without auth or headers, you can do file_get_contents() or I suggest you to use curl.
Also, you need to check on response data structure, it has a 'data' key which is an array. so you need to use foreach to iterate on the 'data' key.
I have given a sample answer that should work if there is only 1 item in data.
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp);// will return in object form
echo $obj->data[0]->primary_balance;
or
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp, true); // will return in array form
echo $obj['data'][0]['primary_balance'];
json_decode()
I am struggled at this point.
I am using the script for inserting/updating website languages.
The main structure of the JSON file looks like this
{
"English": {
"shortcode": "EN"
}
}
Here is a sample of the code I am using to insert a language into my JSON file
$data['french'] = $_POST;
array_push($json, $data);
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
But when I insert a new record into my JSON file new key appends in my JSON file and it looks like this,
{
"English": {
"shortcode": "EN"
},
"0": {
"French": {
"shortcode": "FR"
}
}
}
So my question is how can I insert a new record but to not insert the key "0", "1"..
Thanks in advance.
You only have to make $json[key] = value
$json['French'] = $_POST;
If it does not exist it is added, otherwise it is updated
It seems the $_POST is an array.
So you are pushing an array onto the $json array
Try this:
$json = $json + $_POST;
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
I get the json data using cURL as an input:
curl -H "Content-Type: application/json" -X GET http://localhost:8000/jsontest --data-binary #test.json
It is simple json with couple of fields:
{
"id": "12345",
"blockId": "9000",
"spot": {
"id": "7890",
"length": 23,
"name": "test",
"country": "de"
},
"channel": "tv:rtl.de",
"startTimestamp": "1323872435345",
"endTimestamp": "13243498394384329"
}
And this is my code for getting the data and storing in database:
public function test()
{
$string = file_get_contents('php://input');
$json_a = json_decode($string, true);
foreach ($json_a as $json => $test) {
$tvib = new TVIB;
$tvib->spotid = $test["spot"]["id"];
$tvib->name = $test["spot"]["name"];
$tvib->channel = $test["channel"];
$tvib->start = $test["startTimestamp"];
$tvib->end = $test["endTimestamp"];
$tvib->save();
}
var_dump($json_a);
}
When I run cURL request I get this error and a lot of html and js code:
ErrorException: Illegal string offset 'spot' in file TestController.php on line 18 ($tvib->spotid = $test["spot"]["id"];)
If I run this locally like this:
$string = file_get_contents('test.json');
everything works fine. But there is obviously problem with php input.
Any suggestions?
PS I use Laravel 5.5
not need foreach. so change code to :
public function test()
{
$string = file_get_contents('php://input');
$json_a = json_decode($string, true);
//foreach ($json_a as $json => $test) {
$tvib = new TVIB;
$tvib->spotid = $json_a["spot"]["id"];
$tvib->name = $json_a["spot"]["name"];
$tvib->channel = $json_a["channel"];
$tvib->start = $json_a["startTimestamp"];
$tvib->end = $json_a["endTimestamp"];
$tvib->save();
//}
var_dump($json_a);
}
I'm reading a json file using
$jsonStr = file_get_contents("connection.json");
$jsonParsed = json_decode($jsonStr,true);
and I want $jsonParsed to be a associative array like this:
$jsonParsed = { "SERVER" => "111.222.333.444" , "USER" => "edvaldo" , "PASSWORD" => "my_password_here", "DATABASE" => "my_database_here" };
What is the format of the JSON needed to do this?
I tried this
{
"SERVER": "111.222.333.444",
"USER": "edvaldo",
"PASSWORD": "my_password_here",
"DATABASE": "my_database_here"
}
but even with JSONLint saying this piece og JSON is valid, I can't get the result I need.
I'm not really very used to JSON and then I will appreciate a lot any help given.
EDITED:
This is the function I'm using:
private function set_mysql_parameters() {
$this->connectionParams = array();
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_mysql = file_get_contents($json_file);
$json_parsed = json_decode($json_file,true,250);
foreach($json_parsed as $key => $value) {
$this->connectionParams[$key] = $value;
}
}
My goal is to fill this array $this->connectionParams with data extracted from the JSON file.
I notice that you are trying to decode the filename instead of the content.
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_parsed = json_decode($json_file,true,250);
Shouldn't it be
$json_parsed = json_decode($json_mysql, true, 250);
<?php
$handle = fopen("https://graph.facebook.com/search?q=sinanoezcan#hotmail.com&type=user&access_token=2227472222|2.mLWDqcUsekDYK_FQQXYnHw__.3600.1279803900-100001310000000|YxS1eGhjx2rpNYzzzzzzzLrfb5hMc.", "rb");
$json = stream_get_contents($handle);
fclose($handle);
echo $json;
$obj = json_decode($json);
print $obj->{'id'};
?>
Here is the JSON: {"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}
It echos the JSON but I was unable to print the id.
Also I tried:
<?php
$obj = json_decode($json);
$obj = $obj->{'data'};
print $obj->{'id'};
?>
Note that there is an array in the JSON.
{
"data": [ // <--
{
"name": "Sinan \u00d6zcan",
"id": "610914868"
}
] // <--
}
You could try $obj = $obj->{'data'}[0] to get the first element in that array.
data is an array, so it should be:
print $obj[0]->{'id'};
It looks like the key "data" is an array of objects, so this should work:
$obj = json_decode($json);
echo $obj->data[0]->name;
Have you tried $obj->data or $obj->id?
Update: Others have noted that it should be $obj->data[0]->id and so on.
PS You may not want to include your private Facebook access tokens on a public website like SO...
It's a bit more complicated than that, when you get an associative array out of it:
$json = json_decode('{"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}', true);
Then you may echo the id with:
var_dump($json['data'][0]['id']);
Without assoc, it has to be:
var_dump($json->data[0]->id);