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;
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);
This question already has answers here:
Is there a JSON api based CMS that is hosted locally? [closed]
(1 answer)
Update JSON value if exists otherwise add it in PHP
(2 answers)
Closed 3 years ago.
I am running an app from AndroidHive which has feed.json which the app loads the content below from.
http://api.androidhive.info/feed/feed.json and this is the post url http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/
{
"feed": [{
"id": 1,
"name": "National Geographic Channel",
"image": "A URL",
"status": "Science and etc"
And Cosmos is all about making science an experience.
","
profilePic ": "
A URL ","
timeStamp ": "
1403375851930 ","
url ": null
}]
}
the above is the default content am wondering how to i add more to this content from or using a php script. I would love to know how to do it because I noticed that most application source code created in www_androidhive_info uses .json to load content which is an alternative to webview
You can use json_decode() function to convert JSON string to object, add your variable, and then conver the object back to JSON
$obj = json_decode($json, true);
$obj->feed[0]->url = "google.com"
:
Load the JSON
Decode the JSON
Add your content
Encode to JSON
Send it to your app
Code:
<?php
function failure($reason) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['failure' => $reason]);
exit;
}
// 1. Load the JSON
$content = file_get_contents('http://api.androidhive.info/feed/feed.json');
if (!$content) {
return failure('Failed to load upstream JSON');
}
// 2. Decode the JSON
$decodedContent = json_decode($content, true);
if ($decodedContent === false) {
return failure('Failed to parse upstream JSON');
} elseif (empty($decodedContent)) {
return failure('Upstream JSON empty');
}
// 3. Add your content
$decodedContent['feed'][] = [
"id": 12,
"name": "An example name",
"image": "https://example.com/test_image.jpg",
"status": "Hello!",
"profilePic": "https://example.com/test_profile_pic.jpg",
"timeStamp" => time(),
"url" => "https://example.com"
];
// 4. Encode to JSON
$responseContent = json_encode($decodedContent);
// 5. Send it to your app
echo $responseContent;
Decode the JSON and make new function for changes then encode back.
<?php
$JsonVar = file_get_contents('http://api.androidhive.info/feed/feed.json');
$myjson = json_decode($JsonVar,true);
function Changes() {
$myjson->feed[2]->name = "FeedID2";
$myjson->feed[2]->id = "2";
$myjson->feed[2]->image = "link to image.png";
$myjson->feed[2]->status = "I am here.";
$myjson->feed[2]->profilePic = "link to image.png";
$myjson->feed[2]->timeStamp = time();
$myjson->feed[2]->url = 'http://url.com';
}
json_encode(Changes());
?>
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);
I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.