How to converts JSON string into a PHP variable? - php

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']

Related

I cannot echo the first index of a PHP cURL response

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

Accessing variables of curl response in PHP [duplicate]

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

Using Curl to decode and echo a RESTful API response

I am trying to simply take and display the data from "Last" from this API:
https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc
Here is what I have so far, however it is not returning anything. I am not an experienced developer, and pieced this code from a few different sources. Any help is greatly appreciated.
<?php
$service_url = 'https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$decoded = json_decode($curl_response);
echo $decoded->Last;
?>
Your code works. But you have to check the JSON response more proper. If you want to get "Last" you first have to get result.
This is the JSON decoded Response from your code:
object(stdClass)#1 (3) {
["success"]=>
bool(true)
["message"]=>
string(0) ""
["result"]=>
object(stdClass)#2 (3) {
["Bid"]=>
float(3760)
["Ask"]=>
float(3765)
["Last"]=>
float(3765)
}
}
So, you would have to echo "$decoded->result->Last"
$decoded return standard object so you cant directly print using echo .if you print decoded variable then
<?php
$service_url = 'https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$decoded = json_decode($curl_response);
echo "<pre>";
print_r($decoded);
?>
Result:
stdClass Object
(
[success] => 1
[message] =>
[result] => stdClass Object
(
[Bid] => 3741.5957385
[Ask] => 3745
[Last] => 3745
)
)
so you can access
echo $decoded->success; //return 1
echo $decoded->result->Bid; //3741

Sending request to API server return nothing

actually I'm working on coding an API for my business, I have an issue on my code and I couldn't figure out the problem, here is the class:
<?php
class ApiCaller
{
//some variables for the object
private $_app_id;
private $_app_key;
private $_api_url;
//construct an ApiCaller object, taking an
//APP ID, APP KEY and API URL parameter
public function __construct($app_id, $app_key, $api_url)
{
$this->_app_id = $app_id;
$this->_app_key = $app_key;
$this->_api_url = $api_url;
}
//send the request to the API server
//also encrypts the request, then checks
//if the results are valid
public function sendRequest($request_params)
{
//encrypt the request parameters
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
//create the params array, which will
//be the POST parameters
$params = array();
$params['enc_request'] = $enc_request;
$params['app_id'] = $this->_app_id;
//initialize and setup the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$result = curl_exec($ch);
//json_decode the result
$result = #json_decode($result);
//check if we're able to json_decode the result correctly
if( $result == false || isset($result->success) == false ) {
throw new Exception('Request was not correct');
}
//if there was an error in the request, throw an exception
if( $result->success == false ) {
throw new Exception($result->errormsg);
}
//if everything went great, return the data
return $result->data;
}
}
The problem that there is no data returned from the sendRequest function, just throw 'Request was not correct' exception, I tried to test the code but with no luck. I'm using xampp-win32-5.6.8-0-VC11 and I have curl-7.43.0-win64 installed,,,
Any help will be appreciated and thanks.
Edit:
I use this code to test the function and it worked:
<?php
$_app_key = '28e336ac6c9423d946ba02d19c6a2632';
$_api_url = 'http://localhost/myAPI/simpletodo_api/';
$_app_id = 'APP001';
$params = array(
'controller' => 'todo',
'action' => 'read',
'username' => 'nikko',
'userpass' =>'test1234'
);
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $_app_key, json_encode($params), MCRYPT_MODE_ECB));
$pa = array();
$pa['enc_request'] = $enc_request;
$pa['app_id'] = $_app_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pa);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$errorNo = curl_errno ($ch );
$result = #json_decode($result);
var_dump($result);
and the result:
"object(stdClass)#1 (2) { ["data"]=> array(2) { [0]=> object(stdClass)#2 (5) { ["todo_id"]=> string(10) "1323343689" ["title"]=> string(10) "test title" ["description"]=> string(28) "test description weee wasted" ["due_date"]=> string(10) "12/02/2011" ["is_done"]=> string(4) "true" } [1]=> object(stdClass)#3 (5) { ["todo_id"]=> string(10) "1323429521" ["title"]=> string(3) "wee" ["description"]=> string(11) "adsa wasada" ["due_date"]=> string(10) "12/21/2011" ["is_done"]=> string(4) "true" } } ["success"]=> bool(true) }"
So where is the problem then??
Be carefull with the following line :
$result = #json_decode($result);
You are hiding any error message by using the #.
I would suspect you are not receiving a valid json response and then $result would be set to false, because json_decode would not work.
So what happens if you not getting a valid json back? Your code should handle that error case.
In order to debug, try to add var_dump($result); just after the curl_exec call, that should help you understand what's wrong.
As stated in the comments you should check the curl error codes
$errorNo = curl_errno ($ch );
http://php.net/manual/en/function.curl-errno.php
In the case of a 404 or other error you have no way to know in your code as formatted.

php JSON management: get a value from a decoded JSON object

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

Categories