php - Unable to parse JSON web service response with json_decode() -


i'm struggling parsing web service response json in cases service returns error.

example json - success flow:

{     "response": [{         "iconpath" : "/img/theme/destiny/icons/icon_psn.png",         "membershiptype": 2,          "membershipid": "4611686018429261138",             "displayname": "spuff_monkey"      }],     "errorcode": 1,     "throttleseconds": 0,     "errorstatus": "success",     "message": "ok",     "messagedata":{} } 

example json - error flow:

{     "errorcode": 7,     "throttleseconds": 0,     "errorstatus": "parameterparsefailure",     "message": "unable parse parameters.  please correct them, , try again.",     "messagedata": {} } 

now php:

function hitwebservice($endpoint) {      $curl = curl_init($endpoint);     curl_setopt($curl, curlopt_header, false);     curl_setopt($curl, curlopt_returntransfer, true);     curl_setopt($curl, curlopt_httpheader, array("content-type: application/json"));      $json_response = curl_exec($curl);      if(curl_exec($curl) === false) {         echo "curl error: " . curl_error($curl);     }      curl_close($curl);      $array_response = json_decode($json_response, true);     $function_response = array();      if (!isset($array_response['response'])) {         $function_response = $array_response;     } else {         $function_response = $array_response['response'];     }      return $function_response; } 

what i'm trying achieve when json includes "response" block put in new array , return detail function, "response" isn't present want return full json array.

however @ present, there no "response" empty array.

there's wrong logic , can't past in tiny mind, it's time reach out help!

judging fact response array of objects in json, suspect error-flow response may contain response-field, empty array value ([]). explain current result.

therefore, not check existence of response. may empty array. instead, check errorcode, errorstatus or errormessage (whichever think suitable). example:

if ($array_response['errorstatus'] != "success") {     $function_response = $array_response; } else {     if (!isset($array_response['response'])) {         $function_response = null;     } else {         $function_response = $array_response['response'];     } } 

in success-case, want check existence of response, if not exist (but is expected), can raise error).

another possible solution count number of responses:

if (!isset($array_response['response'])) {     $function_response = $array_response; } else {     if (count($array_response['response']) > 0) {         $function_response = $array_response['response'];     } else {         $function_response = $array_response;     } } 

Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -