I created this JSON data:
{
"status" : "fail",
"data" : {
"error_message" : "Label already exists on your account for Network."
}
}
The code in my PHP page is:
$newaddr = json_decode($json, true);
echo $newaddr->status;
echo $newaddr->data;
and the result I get when I run it is:
fail
How can I show the value of error_message in my page? Because:
$newaddr->data
has the value null when I print it using var_dump($newaddr->data);
When you use json_decode(..., true); the second parameter means that you want to json to be parsed as associative arrays. But, you are trying to get the data by object property.
The solutions are:
Change the second parameter to false
$newaddr = json_decode($json, false);
echo $newaddr->status;
echo $newaddr->data->error_message;
Get data with array-way
$newaddr = json_decode($json, true);
echo $newaddr['status'];
echo $newaddr['data']['error_message'];
json_decode documentation
Related
I am trying to retrieve an array from an API, but every time it is returning an empty array after every attempt.
This is my coding which is fetching data from api:
<?php
$array=array("name"=>"name1");
$url = "http://getsjobs.esy.es/registerapi.php?".http_build_query($array);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
?>
this is my api code
<?php
if(isset($_GET['Array'])) {
$array = $_GET['Array'];
header('Content-type: application/json');
}
?>
Even if i use json_encode($array). It is returning empty array. I can receive single value or single array element, but not able to send and receive entire
array from json.
I am not able to find any relevant post. Any link or suggestion will be helpful
My PHP is rusty, but the problem looks to me to be because your API is looking for a parameter called "Array", but nowhere in your calling block does it actually send a GET parameter called "Array".
Your code looks a bit incomplete, so maybe I'm misunderstanding something.
look here: you're decoding it twice.
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
simply:
$data = json_decode($json,true);
if (is_array($data ))
{ echo 'array exists'; }
else { echo 'Not an array'; }
if it still doesn't works, see what echo json_last_error_msg(); returns.
Try to check if your $json is a valid json too. Check if what echo $json; returns is valid here: http://jsonformatter.curiousconcept.com/
I want to parse following json for value of
JSON (saved in my.json):
{
"mackoniv":{"entry":"","lastExit":"","userId":"OPENGOVTJOBS","userNick":"mack"},
"johanna":{"entry":"","lastExit":"","userId":"FREEJOBALERT","userNick":"jone"}
}
Code used :
$json = file_get_contents('my.json');
$json_data = json_decode($json,true);
$userToCheck='johanna';
echo 'userId'.$json_data->$userToCheck->userId;
The above code gives error "Trying to get property of non-object", which i understand as $userToCheck isnt an object of $json_data but how do i access the data of "mackoniv" or even "johanna" when userToCheck part is not to be hardcoded.
If i try following way, it gives same error.
echo 'userId'.$json_data[$userToCheck]['userId'];
first of all json_decode($jsondata, true); would return an array. try to var_dump your $json to make sure you've got the file and then var_dump $json_data.
If you write it like below it should work.
$json = file_get_contents('my.json');
$json_data = json_decode($json, true);
$userToCheck = 'johanna';
echo 'userId = ' . $json_data[$userToCheck]['userId'];
Basically change the line:
echo 'userId' . $json_data->$userToCheck->userId;
with:
echo 'userId = ' . $json_data[$userToCheck]['userId'];
if json_decode second paramether is true, it returns an array, if it is false (default), returns an object. So, if you want to use it as an object, just decode it like: $json_data = json_decode($json);. If this doesn't work, check what echo json_last_error_msg(); returns. If it returns "No error", then the problem is that your file_get_contents() is not refering to the correct file.
I am trying to access the value for one of the currencies (e.g. GBP) within the "rates" object of the following JSON file:
JSON file:
{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}
This was my approach:
PHP (CURL):
$url = ...
// initialize CURL:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);
// store decoded JSON Response in array
$exchangeRates = (array) json_decode($json);
// access parsed json
echo $exchangeRates['rates']['GBP'];
but it did not work.
Now, when I try to access the "timestamp" value of the JSON file like this:
echo $exchangeRates['timestamp'];
it works fine.
Any ideas?
Try removing (array) in front of json_decode and adding true in second parameter
Here is the solution.
$exchangeRates = (array) json_decode($json,TRUE);
https://ideone.com/LFbvUF
What all you have to do is use the second parameter of json_decode function.
This is the complete code snippet.
<?php
$json='{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}';
$exchangeRates = (array) json_decode($json,TRUE);
echo $exchangeRates["rates"]["GBP"];
?>
I usually manage to figure stuff out by myself, but on this occasion I've had to register an account and ask for help before I jump out the window.
I'm trying to output some basic JSON data to php, all I need to do is echo it out, the rest I'll figure out.
The API gives this guide:
{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}
An example of the URL I'll be using: https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC
All I want to output is the 'Last' data, I don't care about the rest, keeping the decimal in the right place is also important.
I've tried all sorts, I can't get it to output it properly :(. I've ran a var_dump which spits out:
array(3) { ["success"]=> bool(true) ["message"]=> string(0) "" ["result"]=> array(3) { ["Bid"]=> float(0.00011505) ["Ask"]=> float(0.000116) ["Last"]=> float(0.00011505) } }
If someone could just tell me the few lines of code to put the 'Last' number into a variable called $lastBid I will love you long time!
Thanks guys!
use json_decode - php method to decode json
http://php.net/manual/en/function.json-decode.php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
Here you have an example,
$contents = file_get_contents("https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC");
$json = json_decode($contents);
$lastBid = $json->result->Last;
$lastBid would then be set to 0.01189802
You need to json_decode() the result.
that kind of data is called json. php permits you to convert that json (which is a string) to a php array.
to get it, you need to convert it and then access to the value you'd like using array rules.
// save in a variable the data you're going to process
$json = '{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}';
// json_decode is a function that allows you to obtain an array
// (the second parameter set to true indicates that the array'll be an associative one)
$data = json_decode($json, TRUE);
/*
every php array has an internal pointer which points to a position in the array.
the end pointer, if not moved, points to the last position. to access to the value
you want, first get the last value (an array called "result"),
then access to the last value of that array (called "last").
the property you'll get is the float value you requested!
*/
var_dump(
end(
end($data)
)
);
and here, there is the output:
float(3.35579531)
Access it by:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data);
$last = $data->result->Last;
If you like using arrays instead of object orrientation style, json_decode has an extra boolean param, that converts it too an array if you feel more comfortable using that.
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data,true);
$last = $data['result']['Last'];
Side note; For accessing API's I would rather advice you to use curl instead of file_get_contents. It gives you better control, for instance with timeouts. But you have many more options. You can use this function;
function curl($URL,&$errmsg){
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$contents = curl_exec($c);
if (curl_errno($c)){
$errmsg = 'Failed loading content.';
curl_close($c);
return;
}
else{
curl_close($c);
return($contents);
}
}
And your code then would be:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = curl($url, $errmsg);
$data = json_decode($data,true);
$last = $data['result']['Last'];
json response as below:
{"Success":true,"ErrorCode":0,"UserInformation":{"UserID":"19"}......
how do I get the UserID value by using json_decode?
I tried the below code with no luck.
$Response = json_decode($Response[2]);
echo $Response[0][0][0];
This should work:
<?php
$json = '{"Success":true, "ErrorCode":"0","UserInformation":{"UserID":"19"}}';
$response = json_decode($json, true);
echo $userId = $response["UserInformation"]["UserID"];
?>
Please check the PHP documentation of json_decode at http://php.net/json_decode
You can use object as well if you skip the second parameter of the json_decode function.