This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
This is the first time I have used curl, and am confused how exactly the $response is formatted, and how I go about accessing the information I want in it. I am trying to access a particular variable from a curl response in PHP to be used in a future conditional. I was provided the URL, and headers to use as an API endpoint, and thus can't change anything on that end. Here is the code for the curl response :
$ch = curl_init();
$url = "https://thewebsitesurl.com";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-branch: 21',
'x-branchhash: fijef89ivjw8934y8f9fifk920a',
'accept: application/json'
));
$response = curl_exec($ch);`
The contents of a var_dump($response) yields :
string(187) "{"code":"5122","time":"1589812650","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}"
I need to access the "redeemed" and "voided" field. Of course this being a big long string means I can't do that (I believe). Is there a CURLOPT I should be setting so the response isn't received as one big string?
Further if I decode it with $data = var_dump(json_decode($result, true)); the contents are :
array(3) { ["code"]=> string(4) "5122" ["time"]=> string(10) "1589814039" ["voucher"]=> array(8) { ["code"]=> string(4) "5122" ["comments"]=> string(0) "" ["amount"]=> string(5) "11.00" ["balance"]=> string(5) "11.00" ["created"]=> string(10) "1589609333" ["expiry"]=> string(10) "1652616000" ["redeemed"]=> bool(false) ["voided"]=> bool(false) } }
To me this seems much more workable than a long string. However I am struggling to access the ["expiry"], ["redeemed'], and ["voided"] variables. In fact I am struggling just to access the ["code"] string "5122" I have tried :
echo $data[0]['code'];
echo $data[0]["code"];
echo $data['code'];
echo $data["code"];
All 4 of those echos are blank. I have tried to remove "curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);" as well. Afterwards var_dump($result); looks like :
{"code":"5122","time":"1589815247","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}bool(true)
I am probably misunderstanding something basic here. But any help would be appreciated on how I could access the values in ["expiry"], ["redeemed'], and ["voided"]. Thank you for your assistance.
$data = json_decode($result, true);
This will return an array
$data = json_decode($result);
This will return an object.
Do not use var_dump inside this because it is a parse function, just for dumping data. So the final should be:
$data = json_decode($result, true);
$code = $data['code']; // " or ' are not different in this case
Related
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How to use cURL to get jSON data and decode the data?
(6 answers)
Closed 10 months ago.
I have a code which should fetch courseID from JSON response obtained , But currently it is not fetching anything . It shows me the entire response and not one . can someone help me with this .
JSON response obtained.
{
"results": [
{
"CourseID": "ASPO",
"Success": "Yes"
}
]
}
i just want to retrieve the CourseID.
and below is my code
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://AbC:3939');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "ABC=AE");
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Authorization: Bearer hjhjhjhjhjhj338sj';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch) ;
}else{
$result_value = json_decode($result);
print_r($result_value->results[0]->CourseID);
}
curl_close($ch);
?>
I have tried this with your shared result and got the COURSEID.
$resp = '{
"results": [
{
"CourseID": "ASPO",
"Success": "Yes"
}
]
}';
$res = json_decode($resp);
print_r($res->results[0]->CourseID);
Note: this answers the original question (extract information from JSON response).
The top level element in your JSON string is an object with a single results key that holds everything. You aren't referencing such key anywhere in your code.
The name of the local PHP variable where you store the results is irrelevant, there isn't any automatic behaviour linked to that.
If you use json_decode() with the $associative flag you get JSON objects converted to PHP arrays (JSON arrays become PHP arrays no matter the flags). If unsure, just inspect your data with either a step debugger or e.g. var_dump($result_value):
array(1) {
'results' =>
array(1) {
[0] =>
array(2) {
'CourseID' =>
string(4) "ASPO"
'Success' =>
string(3) "Yes"
}
}
}
In php you can access array elements by specifying the key inside square brackets so:
var_dump($result_value['results'][0]['CourseID'], $result_value['results'][0]['Success']);
string(4) "ASPO"
string(3) "Yes"
I'm using this little PHP function that I wrote to make calls to my master database:
$db_request = curl_init(DB_ROOT.'/action/register.php');
curl_setopt($db_request, CURLOPT_HEADER, 0);
curl_setopt($db_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($db_request, CURLOPT_POSTFIELDS, http_build_query($variables));
$db_response = curl_exec($db_request);
curl_close ($db_request);
parse_str($db_response, $information);
On register.php I use the following to respond:
echo http_build_query(array(
'test1'=>'value1',
'test2'=>'value2',
'test3'=>'value3'
));
My problem comes when trying to retrieve the first index of any given response. I can use var_dump($information) and will receive array(3) { ["test1"]=> string(6) "value1" ["test2"]=> string(6) "value2" ["test3"]=> string(6) "value3" }. However, when I try to echo $information['test1'], I receive this: Notice: Undefined index: test1 in....
Echoing anything other than the first index doesn't give me this problem.
Does anyone have any thoughts?
parse_str return type is void
Update your code
parse_str($db_response, $information);
I was trying to parse the json data from a url using cURL and then json_decode to access the objects but I failed. I already search it how to access but I failed.
this is the links that I visited hoping that I can solve the problem.
http://www.dyn-web.com/tutorials/php-js/json/decode.php
https://stackoverflow.com/questions/12429029/php-get-values-from-json-encode
https://stackoverflow.com/questions/20193575/fetch-json-data-using-php
https://stackoverflow.com/questions/12429029/php-get-values-from-json-encode
https://stackoverflow.com/questions/4433951/decoding-json-after-sending-using-php-curl
this is the result of the var_dump($obj);
array(1) {
["login"]=>
array(2) {
["error"]=>
bool(false)
["user"]=>
array(5) {
["br_code"]=>
int(0)
["mem_id"]=>
int(202)
["username"]=>
string(8) "johndoe"
["email"]=>
string(33) "johndoe#gmail.com"
["created_at"]=>
string(19) "2017-08-07 15:35:39"
}
}
}
and this is my PHP code
<?php
session_start();
$ch = curl_init('http://localhost/sample/login.php');
$username= $_SESSION["USERNAME"];
$password= $_SESSION["PASSWORD"];
$credentials = [
'username' => $username,
'password' => $password
];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);
curl_setopt($ch, CURLOPT_USERNAME, "{$username}:{$password}");
// execute!
$response = curl_exec($ch);
// close the connection
curl_close($ch);
$obj= json_decode($response, true);
// echo $obj; // Notice: Array to string conversion in
// echo $obj[0]; // Undefined offset
// echo $obj->user; //Trying to get property of non-object in
var_dump($obj);
?>
seems an array of array so
eg: for username
var_dump($obj['login']['user']['username']);
and so on for others values
$my_username = $obj['login']['user']['username']);
Your data is in login array so try following to get details of user
$user = $obj['login']['user'];
//to print email
echo $user['email'];
//to print username
echo $user['username'];
//so on
When you do json_decode($response, true), and you are using second parameter as true, it will decode it into associative array.
Your var_dump also says that it is array. So, you need to access $obj as array not object
if you want to access the user array:
$obj['login']['user']
if you want to access the username/br_code:
$obj['login']['user']['username'];
$obj['login']['user']['br_code'];
more info about json_decode
json_decode decodes a JSON string into a multi dimensional array
you get that error because in PHP objects are not arrays
just access with [] and you are fine
$obj['user']['field_requested']
I'd like to display the number of likes for my Facebook page on my website. The previous method I used isn't working anymore since a couple of days.
When I call the Facebook graph API like this:
https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/549585444&format=json
It gives me the following output (fictional example):
[{"url":"http:\/\/www.facebook.com\/549585444","normalized_url":"http:\/\/www.facebook.com\/549585444","share_count":0,"like_count":122,"comment_count":0,"total_count":122,"click_count":0,"comments_fbid":null,"commentsbox_count":0}]
Now I like to echo the like count:
<?php
$fb_page = "549585444";
$url = "https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/".$fb_page."&format=json";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_returned = curl_exec($curl);
curl_close($curl);
$json_returned = json_decode($json_returned, true);
echo $json_returned['like_count'];
?>
But the number doesn't appear. Any idea why?
As you can see in the JSON output, the answer is wrapped in an array:
array(1) {
[0]=>
array(9) {
["url"]=>
string(33) "http://www.facebook.com/549585444"
["normalized_url"]=>
string(33) "http://www.facebook.com/549585444"
["share_count"]=>
int(0)
["like_count"]=>
int(0)
["comment_count"]=>
int(0)
["total_count"]=>
int(0)
["click_count"]=>
int(0)
["comments_fbid"]=>
NULL
["commentsbox_count"]=>
int(0)
}
}
To get the number output, you'll have to get the first item in the array by changing this row:
echo $json_returned['like_count'];
To this:
echo $json_returned[0]['like_count'];
I'm building a script to verify a transaction receipt with Apple's itunesconnect site (iphone dev) and I can't figure out where's the error in my code. I want to get the "status" value.
Please help me to find what am I doing wrong:
<?php
include("config.php");
$receipt = json_encode(array("receipt-data" => $_GET["receipt"]));
$response_json = do_post_request($url, $receipt);
$response = json_decode($response_json);
//Here's where I try to get the "status" key but doesn't work
echo $response['status'];
//echo $response->status;
function do_post_request($url, $data)
{
//initialize cURL
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
// howmany parameter to post
curl_setopt($ch, CURLOPT_POST, 1);
// the receipt as parameter
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result= curl_exec ($ch);
curl_close ($ch);
return $result;
}
?>
and the answer to the iPhone looks like:
{"receipt":{"item_id":"327931059", "original_transaction_id":"1000000000074412", "bvrs":"1.0", "product_id":"sandy_01", "purchase_date":"2009-09-29 16:12:46 Etc/GMT", "quantity":"1", "bid":"com.latin3g.chicasexy1", "original_purchase_date":"2009-09-29 16:12:46 Etc/GMT", "transaction_id":"1000000000074412"}, "status":0}
but only "status":0 matters for now
- Thank's
From the manual on json_decode()
Returns an object or if the optional
assoc parameter is TRUE, an
associative array is instead returned.
NULL is returned if the json cannot
be decoded or if the encoded data is
deeper than the recursion limit.
So either send TRUE for the 2nd parameter
$response = json_decode($response_json, true);
Or access the decoded JSON with object syntax
$response->status;
EDIT
Isolated test
$json = <<<JSON
{"receipt":{"item_id":"327931059", "original_transaction_id":"1000000000074412", "bvrs":"1.0", "product_id":"sandy_01", "purchase_date":"2009-09-29 16:12:46 Etc/GMT", "quantity":"1", "bid":"com.latin3g.chicasexy1", "original_purchase_date":"2009-09-29 16:12:46 Etc/GMT", "transaction_id":"1000000000074412"}, "status":0}
JSON;
$response = json_decode( $json );
echo $response->status;
$response2 = json_decode( $json, true );
echo $response2['status'];
Output is
00
You should be able to use:
$response->status;
Passing an optional param of true to the json_decode function will bring the results back as an associative array.
Have you checked your response_json variable to check that the data is being deserialised correctly? i.e:
var_dump($response);
Which should yield:
object(stdClass)#1 (2) {
["receipt"]=>
object(stdClass)#2 (9) {
["item_id"]=>
string(9) "327931059"
["original_transaction_id"]=>
string(16) "1000000000074412"
["bvrs"]=>
string(3) "1.0"
["product_id"]=>
string(8) "sandy_01"
["purchase_date"]=>
string(27) "2009-09-29 16:12:46 Etc/GMT"
["quantity"]=>
string(1) "1"
["bid"]=>
string(22) "com.latin3g.chicasexy1"
["original_purchase_date"]=>
string(27) "2009-09-29 16:12:46 Etc/GMT"
["transaction_id"]=>
string(16) "1000000000074412"
}
["status"]=>
int(0)
}