Skip to content
Advertisement

How can I access the json returned in PHP by my Web Api?

I am using the following code to send and retrieve data from my Web API

JavaScript

this is what I get in response

JavaScript

I am trying to access the JSON with the following code (Because it worked for me on a similar request):

JavaScript

But as you can see the variable $data stopped being a JSON and became a bool(true).

Does anyone know how I can access the JSON msj or why the $data variable changed from JSON to bool?

Advertisement

Answer

The return values section of the PHP manual for curl_exec says

Returns true on success or false on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, false on failure.

Maybe it could be more specific – that option must be set to true. See the definition of the option in the curl_setopt documentation:

true to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.

So, you’re seeing the JSON response because it’s being output directly by curl_exec, then bool(true) because curl_exec has returned true to the $data variable you’re dumping.

Set CURLOPT_RETURNTRANSFER to true instead to get what you’re expecting.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement