edit JSON Objects in JSON Objecs with PHP - php

How can i increment x or y in this JSON file? I posted my PHP code to increment the counter, but i dont know how to acces the "infos" -> "x" or "y".
JSON file
{
"counter": 4,
"infos": {
"x": 1,
"y": 2
}
}
PHP file
<?php
$contents = file_get_contents('../test.json');
$contentsDecoded = json_decode($contents, true);
$contentsDecoded['counter']++;
$json = json_encode($contentsDecoded);
file_put_contents('../test.json', $json);
?>

Just use
$decoded['infos']['x']++;

Related

Php Json Decode - Display value of second level items

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()

Data Not getting Added to JSON using PHP

After thorough research I have not been able to find the solution of a simple problem of appending an object to my JSON.
{
"menu": {
"parentmenu1": {
},
"parentmenu1": {
"pm_name": "iceberg 98 ",
"pm_time": "icebeest-98"
}
},
"projectname": "project1",
"place": "gzb",
"firstlogo": "flogo",
"logo": "logo",
"colordirection": "TopLeft",
"color1": "color1",
"color2": "color2",
"fontcolor": "fontcolor"
}
And my PHP code looks like this
<?php
$parentmenu="Sixty";
$childmenu= "hell";
$grandchildmenu= "icebeest";
$parentmenu1="PUSH Approach-98";
$childmenu1= "iceberg 98 ";
$grandchildmenu1= "icebeest-98";
$data = file_get_contents('format.json');
$json_arr = json_decode($data, true);
//$json_arr['menu']=array($parentmenu2);
$parentarray = array('pm_name'=>$childmenu1, 'pm_time'=>$grandchildmenu1);
echo $parentarray['pm_name'];
$json_arr['menu']['parentmenu1'] = $parentarray;
//array_push($json_arr['menu'], $parentarray);
file_put_contents('results_new.json', json_encode($json_arr));
?>
The parentmenu1 gets removed as soon as I re-run the code.
But if I try adding the 2 arrays at once in same file, then it will add.
So please let me find out the way in which I can add data with key to the end of the structure. TIA

How to put an API return string into an array

I have a string that i get from an API and i wish i could put it in a array so i could check the values that came from the return.
String return example:
{
"code":"000",
"message":"XXX",
"date":"2018-05-17",
"hour":"09:16:09",
"revision":"",
"server":"XX",
"content":{
"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}
}
}
What I need:
echo $string['code'];
Javascript has no problem with JSON encode command. But how can I do it with PHP?
First of all your JSON data seems to be invalid (Some brackets missing). It needs to be like this:-
{
"code": "000",
"message": "XXX",
"date": "2018-05-17",
"hour": "09:16:09",
"revision": "",
"server": "XX",
"content": {
"nome": {
"info": "SIM",
"conteudo": [{
"field1": "XXXX",
"field2": "XX"
}]
}
}
}
Now You need to decode this JSON data and then get data based on the index
$array = json_decode($json,true);
echo $array['code'];
Output:-https://eval.in/1005949
You can decode the JSON string to Array in PHP.
$str = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}';
$decodedValue = json_decode($str, true);
var_dump($decodedValue);
Your example string is not valid json, you are missing some closing brackets.
This should be the correct way:
'{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}'
As for your question. in PHP you can easily use json_decode
Example:
<?php
$json = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}';
$decoded_json = json_decode($json, true);
echo $decoded_json['code'];
You can see it working here

PHP insert json object without main key

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);

How to get value from JSON php [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
This is my JSON.
{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}
My Questions are:
1. How to get OUT_STAT value?
2. How to get id_doc_proj value?
I am sorry if my questions are silly because i am new at get value from JSON.
Thanks in advance.
UPDATE
I am sorry if you are saying i duplicated Parsing JSON file with PHP. I have tried code from there but i don't get any JSON from my response. I don't know where is the mistake. If you want to help, this is my php script.
<?php
$file_path = "";
$id_project = "16";
$p_id_doc_proj = "50";
$id_doc_type = "1";
$id_user = "4";
$url = $file_path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url)){
$ws = "http://172.xx.x.xx:xxxx/rest/com/acc/uw/in/httprest/apponline/uploadtrough/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";
$opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));
$context = stream_context_create($opts);
$arrayLog=array();
$data1 = file_get_contents($ws, false, $context);
$result = json_decode($data1, true);;
//$result = array("result" => "success");
}else{
$result = array("result" => "error");
}
echo json_encode($result);
?>
The result should show my JSON above but it was null. Any answers will help me. Thanks in advance.
$data="{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}";
$op=json_decode($data, true);
echo $op['OUT_STAT'];
echo $op['OUT_DATA'][0]['id_doc_proj'];
http://php.net/json_deocde. it will make output as associative array. you can then use the result as you would do with an assoc array. you can also use var_dump() to introspect the structure.
you can use json_decode to convert json to array or object:
$json = '{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}';
$object = json_decode($json);
$out_stat = $object->OUT_STAT;
$id_doc_proj = $object->OUT_DATA[0]->id_doc_proj;

Categories