How to get access the properties in this json response? - php

I am executing a curl request and get a response which returns a json response. Below is the code after the response is sent back.
Response: "Zeros Replaced real token"
{"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1
Code Used (For Testing) and accessing property:
$json = json_decode($result);
print_r($json); // Prints the Json Response
$firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object
$secondtry = $json['token'];
echo $firsttry.'<br>';//Code can't continue because of error from $firsttry.
print_r( $secondtry.'<br>');//Nothing Prints at all
I did notice a weird anomaly where it prints a 1 at the end, where as if i do
json_encode($json);
The return response replaces the one at the end of the string with a "true"
Could the "1 or true" at the end be throwing of the json decode?
Maybe I am missing something simple?
As Requested full test code
$url = "https://website.com/restapi.php";
//username of the user who is to logged in.
$userName="adminuser"; //not real user
$fields_string; //global var
$fields = array( //array will have more in the future
'username' => urlencode($userName)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { global $fields_string;
$fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url.'?'.$fields_string.'operation=getchallenge');
curl_setopt($ch,CURLOPT_POST, count($fields));
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);

json_decode(), by default makes child objects into stdClass objects rather than arrays unless they are explicitly arrays.
Try something like:
$firsttry = $json->result->token;

The var_dump shows you the data type. Since result itself is an object, access its token with -> rather than []
$response = '{"success":true...}'
$json = json_decode($response); //var_dumping this will show you it's an object
echo $json->result->token; // 000000000

I figured out the issue. In the Curl Options I did not have
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
Once i put this in #GentelmanMax solution worked for me, but the issue was in the curl response responding directly, where as the return transfer sends back a string that php can work with, which then allowed json_decode()to function as is should. I knew it was something simple.

Related

json_decode returning undefined/null when using etsy API

I'm creating a website that uses the etsy api to display shop info. I'm trying to access the individual values of the retruned json string. To do this I need to turn the returned string into an object. The only way I can see to do this is json_decode($response_body);, but I can't seem to get this to work. When I use the function it returns undefined/NULL when I try to get it's type. The returned string looks about like this: {"count":3,"results":[{"listing_id":252525252,"state":"active","user_id":1111111,"category_id":1234567,"title":"Title of product","description":"This is a description"}. Is there something I am doing completely wrong? Here is the code i'm using:
$url = "https://api.etsy.com/v2/shops/shopname/listings/active?api_key=".$apikey;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (intval($status) != 200) throw new Exception("HTTP $status\n$response_body");
$reponse_fixed = json_decode($response_body);
echo $response_fixed;
json_decode returning null can be possible if the data that has been passed as an argument is an invalid JSON or empty.
So make sure the response is in correct JSON format

Parsing json data using php from youtube data api v3

I am using Youtube data api v3 to retrieve data for search query using the below url
https://www.googleapis.com/youtube/v3/search?part=snippet&q=text&key=apikey&maxResults=25.
I am getting json response, while i am using json decode to parse the json data, i am getting empty result, can any one tell me how to retrieve the data
I am using below php code to parse
$videourl="https://www.googleapis.com/youtube/v3/search?part=snippet&q=hello&key=apikey&maxResults=25";
$json = file_get_contents($videourl);
$data = json_decode($json,true);
print_r($data);
obtaining the json response from the below url:
https://www.googleapis.com/youtube/v3/search?part=snippet&q=hello&key=apikey&maxResults=25
if (extension_loaded('curl')) {
# create a new cURL resource
$ch = curl_init();
# set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://googleapis.com/.....");
curl_setopt($ch, CURLOPT_HEADER, 0);
# Setting cURL's option to return the webpage data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
# grab URL and pass it to the browser
if($json = curl_exec($ch)) {
if(!($data = #json_decode($json)) instanceof stdClass) {
trigger_error('Unable to decode json. '. print_r(error_get_last(), true));
}
}
else trigger_error('CUrl Error:'.curl_error($ch));
# close cURL resource, and free up system resources
curl_close($ch);
}
else trigger_error('CUrl unsupported', E_USER_WARNING);
You should test the return value of file_get_contents. Be careful that this function will return FALSE in case of error (and not NULL). So you should test the return value with === FALSE in order to not be confused by empty values.
In your case, if you are trying to access the exact url that you posted in your question, google is returning a code 400 (bad request), this is why you get a return of FALSE.

Getting JSON Object by calling a URL with parameters in PHP

I'm trying to get json data by calling moodle url:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
the response format of moodle system is like this:
{"token":"a2063623aa3244a19101e28644ad3004"}
The result I tried to process with PHP:
if ( isset($_POST['username']) && isset($_POST['password']) ){
// test1 Test1
// request for a 'token' via moodle url
$json_url = "https://<moodledomain>/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$obj = json_decode($json_url);
print $obj->{'token'}; // should print the value of 'token'
} else {
echo "Username or Password was wrong, please try again!";
}
Result is: undefined
Now the question:
How can I process the json response format of moodle system? Any idea would be great.
[UPDATE]:
I have used another approach via curl and changed in php.ini following lines: *extension=php_openssl.dll*, *allow_url_include = On*, but now there is an error: Notice: Trying to get property of non-object. Here is the updated code:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$moodle = "https://<moodledomain>/moodle/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$result = curl($moodle);
echo $result->{"token"}; // print the value of 'token'
Can anyone advise me?
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOT do an http request to fetch the url's contents for you).
You have to fetch the json data yourself:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};

Decoding JSON after sending using PHP cUrl

I've researched everywhere and cannot figure this out.
I am writing a test cUrl request to test my REST service:
// initialize curl handler
$ch = curl_init();
$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);
$postArgs = 'order=new&data=' . $data;
// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');
// execute curl
curl_exec($ch);
This works fine and the request is accepted by my service and $_Post is populated as required, with two variables, order and data. Data has the encoded JSON object. And when I print out $_Post['data'] it shows:
{"products":{"product1":"abc","product2":"pass"}}
Which is exactly what is expected and identical to what was sent in.
When I try to decode this, json_decode() returns nothing!
If I create a new string and manually type that string, json_decode() works fine!
I've tried:
strip_tags() to remove any tags that might have been added in the http post
utf8_encode() to encode the string to the required utf 8
addslashes() to add slashes before the quotes
Nothing works.
Any ideas why json_decode() is not working after a string is received from an http post message?
Below is the relevant part of my processing of the request for reference:
public static function processRequest($requestArrays) {
// get our verb
$request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method) {
case 'post':
$data = $requestArrays->post;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if (isset($data['data'])) {
// translate the JSON to an Object for use however you want
//$decoded = json_decode(addslashes(utf8_encode($data['data'])));
//print_r(addslashes($data['data']));
//print_r($decoded);
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
Turns out that when JSON is sent by cURL inside the post parameters & quot; replaces the "as part of the message encoding. I'm not sure why the preg_replace() function I tried didn't work, but using html_entity_decode() removed the &quot and made the JSON decode-able.
old:
$return_obj->setData(json_decode($data['data']));
new:
$data = json_decode( urldecode( $data['data'] ), true );
$return_obj->setData($data);
try it im curious if it works.

json_decode in PHP to set a cookie

I want to decode Json returned from the WebService, And it should set a cookie, that i want to use to call next WebService API. I am not sure how to set a cookie, and decode this json.
I tried decoding it, but get the error. I need to extract sessionId. You can use the WebService.. I have put this on Internet.
Here is my code sample
<?php //extract data from the post
extract($_POST); //set POST variables
$url = 'http://202.83.243.119/ems/loginByEID.json';
$fields = array(
'eid'=>urlencode("7ea888b6-36e9-49db-84f3-856043841bef")
);
//url-ify the data for the POST
foreach($fields as $key=>$value) {
$fields_string .=
$key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection $ch = curl_init();
//set the url, number of POST vars,
POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post $result =
curl_exec($ch);
//close connection curl_close($ch);
//decoding Json $obj =
json_decode($result);
print $obj->{'stat'};
?>
Use setcookie() to set a cookie.
Avoid extract() like the plague; it can be used to introduce any client-specified variables into your code.
Use $fields_string = http_build_query($_GET) to build a query string instead of your hodge-podge above.
Format your code properly. For example, you put the $obj = inside the previous comment line.

Categories