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

//data
    $data = array("Id_Empresa" => 1);


    try {
        $ch = curl_init($url);
        $data_string = json_encode($data);
    
        if (FALSE === $ch)
            throw new Exception('failed to initialize');
    
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $data = curl_exec($ch);
            var_dump($data);
            $json = json_decode($data);
            foreach ($json->msg as $item) {
                  echo "$item->Nombre, $item->Descripcion" . PHP_EOL;
            }
        // ...process $output now
    } catch(Exception $e) {
    
        trigger_error(sprintf(
            'Curl failed with error #%d: %s',
            $e->getCode(), $e->getMessage()),
            E_USER_ERROR);
    }

this is what I get in response

{"ok":true,"msg":[{"Nombre":"Carnicerias","Descripcion":"Comercio al por menor de carnes rojas","H_Open":"01:00:00","H_Close":"02:00:00"}]}bool(true)

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

$json = json_decode($data);
foreach ($json->msg as $item) {
    echo "$item->Nombre, $item->Descripcion" . PHP_EOL;
}

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