0

I doing a post curl request

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_POST, 1);
        $headers = array();
        $headers = ["Content-Type:application/json","Accept:application/json"];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close ($ch);
        return $result;

The above curl request should return a json formated string but getting a string in javascript object form.

string(68) "{data:{errorCode:AC01,errorMessage:SansID 53563857 is exist.}}"

Where as when i try to do the same thing from post man api is returning perfect json.

{"data":{"errorCode":"AC01","errorMessage":"SansID 53563857 is exist."}}

Please let me know where i'm doing wrong.

7
  • Whatever response you get is not the fault of the curl_* functions. Noone will be able to advise on that API without knowing more about it. Commented Jul 27, 2018 at 10:40
  • are you using var_dump() for printing response data? Commented Jul 27, 2018 at 10:41
  • 1
    i think API response is okay, please use json_decode() method for converting json to array and print that value using print_r method. Commented Jul 27, 2018 at 10:49
  • @sohanverma i used dd(), when json_decode() the string it gives NULL Commented Jul 27, 2018 at 11:14
  • okay, please use json_decode after $result = curl_exec($ch); line. please use this code: $responseArray = json_decode($result); print_r($responseArray); die; please check my suggestion and let me know if still same error. Commented Jul 27, 2018 at 11:20

1 Answer 1

0

Use json_decode to convert String into Object (stdClass) or array: I was having the same issue working with WordPress(cURL) and Laravel(passport) powered API that was returning JSON but in string format. I saved the response

//save json string into variable json object and return result
$response = curl_exec($curl);
//convert t
return (json_decode($response));

refer to this link here for a similar solution

Check out this screenshot console logs for before and after the fix

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.