How to decode this json in php?

Asked

Viewed 150 times

0

I saw some similar questions here on satckoverflow, but I found no answer to this problem.

I have a Result that brings me the json next:

HTTP/1.1 200 OK
Server: nginx
Date: Fri, 07 Jul 2017 19:44:04 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
callId: 12476bea-0ebc-409d-86cc-69aac003e356
Strict-Transport-Security: max-age=63072000
X-Frame-Options: DENY
X-Content-Type-Options: nosniff

{"paginacao":{"pagina":1,"quantidadeRegistros":10,"quantidadeTotalRegistros":10}

Turns out if I use json_decode($resul, true) it cannot separate the header so it does not return the object as needed it would be only from {"page...

How to proceed in this case, curl_setopt() to consume json at source

  • 2

    How are you doing to what this variable $resul return this request with the header? Edit the question and add the code.

  • 1

    Check out my answer: https://answall.com/a/217424/5878

1 answer

4


Suffice remove the option CURLOPT_HEADER that returns the headers:

curl_setopt($ch, CURLOPT_HEADER, 1);

Or set 0

curl_setopt($ch, CURLOPT_HEADER, 0);

And then take the answer and use the json_decode, example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

//Define um User-agent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

//Retorna a resposta
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Resposta
$data = curl_exec($ch);

//depurando
var_dump($data);

var_dump(json_decode($data));

Read more in the documentation: http://php.net/manual/en/function.curl-setopt.php

  • 1

    I was having problems when disabling the header, but now disabled as your suggestion and worked cool.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.