I m using google site verification recaptcha API for my website.
$json = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$ip);
when I print echo $json; its showing proper response
{ "success": true, "challenge_ts": "2018-08-23T12:43:42Z", "hostname": "staging.my.com" }
but when i tried
$data = json_decode($json,true);
echo $data->success;
its showing nothing
Could anybody tell me what i am missing??
$json = '{ "success": true, "challenge_ts": "2018-08-23T12:43:42Z", "hostname": "staging.my.com" }';
$data = json_decode($json,true);
This produces an associative array from your example JSON string, not an object (used var_dump($data); to see what you actually have stored).
Just use the proper syntax for accessing array values:
echo $data["success"]; // prints '1'
or:
echo ($data["success"])?'success':'failure'; // prints 'success'
According to PHP doc if you set the second parameter assoc to true the function returns associative arrays instead of std class.
mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )
assoc
When TRUE, returned objects will be converted into associative arrays.
So either try $data['success'] or change json_decode($json, true) to json_decode($json).
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 need to decode the below json from a mobile app
Array
(
[{"unm":"admin","pw”:”password”}] =>
)
and my php code is
$obj1 = print_r($_REQUEST, true); //get $_request variable data(responce of login) data as it is
foreach($obj1 as $key => $value)
{
$obj2 = $key; //get first key
}
$obj3 = json_decode($obj2); //decode json data to obj3
$mob_user_name = $obj2['unm']; //getting json username field value
$mob_user_password = $obj2['pw']; //getting json password field value
Hope this will fix your issue,
Note: content is nothing but which you have received from iOS app
content = Array (
[{"unm":"admin","pw”:”password”}] => )
parse that in php
$json = json_decode($content, true);
print json[0]['unm']; /* prints the username */
print json[0]['pw']; /* prints the password */
{"unm":"admin","pw”:”password”} is an object, and json_decode() will by default build it as so.
$obj = json_decode('{"unm":"admin","pw”:”password”}');
echo $obj->unm;
echo $obj->pw;
If for some reason you want it to be converted to an associative array, set the second parameter of json_decode() to true as specified in the manual.
$arr = json_decode('{"unm":"admin","pw”:”password”}', true);
echo $arr['unm'];
echo $arr['pw'];
I am using the following API: https://openweathermap.org and it gives a JSON response to get the current weather.
{
"coord":{
"lon":
"lat":
},
"weather":[
{
"id":521,
"main":"Rain",
"description":"shower rain",
"icon":"09n"
}
],
"base":"stations",
"main":{
"temp":289.22,
"pressure":1004,
"humidity":82,
"temp_min":288.15,
"temp_max":290.15
},
"visibility":10000,
"wind":{
"speed":4.1,
"deg":210
},
"clouds":{
"all":100
},
"dt":1501793400,
"sys":{
"type":1,
"id":5060,
"message":0.0039,
"country":"GB",
"sunrise":1501734589,
"sunset":1501790444
},
"id":3333126,
"name":"Borough of Blackburn with Darwen",
"cod":200
}
What is the correct way to go about getting the main and description in the JSON?
I have attempted the code below but it doesn't work:
$url = "http://api.openweathermap.org/data/2.5/weather?lat=" . $latitude . "&lon=" . $longitude . "&APPID=71f4ecbff00aaf4d61d438269b847f11";
$dirty_data = file_get_contents( $url );
$data = json_decode( $dirty_data );
echo $data['weather']['main'];
When using json_decode() to convert json data to php type, it will always convert it into an object. To be clear you can access weather's main and description property like this:
echo $data->weather[0]->main // outputs main
echo $data->weather[0]->description // outputs description
Update:
Besides you can also convert data into an associative array by passing bool(true) $assoc argument to the json_decode() function.
$data = json_decode( $dirty_data, true );
And extract your data like this:
echo $data['weather'][0]['main']; // for main
echo $data['weather'][0]['description']; // for description
Yo can always do var_dump($data) to see what you have and how to access it.
json_decode returns a stdClass not an array.
$data->weather[0]->main;
Should be the right thing.
{} symbolizes an object and [] symbolizes an array. Notice weather:[{...}] which means weather is an array of objects.
Try
$data = json_decode( $dirty data, true)
It doesn't convert to an object if you supply the true argument.
I'm trying to access the information in a JSON string by using json_decode,
but it is returning a string instead of a object. My code
var_dump(json_decode($json)); // print json object to make sure it is working
$obj = json_decode($json); // get json object
print $obj->{'time'}; // 12345 // error because obj is a string
Try this below one instead of $obj = json_decode($json)
$obj = json_decode($json,true);
Ex:
$obj = '{"name":"vijay","age":27,"city":"New York"}';
$obj = json_decode($obj,true);
echo $obj["name"]; // vijay
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.