skip to Main Content

I am writing a WP plugin. I am using json_decode($result, true). When I test connecting plugin on localhost (xampp) I use this code:

 $result = curl_exec($ch);
 $json = json_decode($result, true);
 $access_token = $json["access_token"];
 curl_close($ch);

The plugin works great, but if I put the plugin on a real site – I get a warning:

"Warning: Undefined array key "access_token" in /storage/conte…api/create-paypal-order.php on line 67"

Tried another json_decode($result) – if I test the plugin on localhost (xampp) and use the code:

    $result = curl_exec($ch);
    $json = json_decode($result);
    $access_token = $json->access_token;
    curl_close($ch);

The plugin works great, but if I put the plugin on a real site – I get a warning:

"Warning: Undefined property: stdClass::$access_token in /storage/cont…/includes/api/create-paypal-order.php on line 65"

How to fix these warnings?

2

Answers


  1. $result = curl_exec($ch);
    $json = json_decode($result);
    $access_token = isset($json->access_token)?$json->access_token:"";
    curl_close($ch);
    

    Apply isset($json->access_token) I think this will help you

    Login or Signup to reply.
  2. first of all you need to print the json variable.
    so you will get idea about access_token.
    use print_r() function to print $json variable.

    if the json data is in array format then use $json['access_token']
    if the json data is in Object format then use $json->access_token

    below is the code for Array type variable

    $result = curl_exec($ch);
    $json = json_decode($result, true);
    $access_token = $json['access_token'] ? $json['access_token'] : '';
    curl_close($ch);
    

    below is the code for Object type Variable

    $result = curl_exec($ch);
    $json = json_decode($result, true);
    $access_token = $json->access_token ? $json->access_token : '';
    curl_close($ch);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search