How to take a string returned from the internal execution of a URL to turn it into a JSON object?

Asked

Viewed 235 times

0

I need to execute this URL internally on the server. The result of the execution generates a string in JSON format:

{"success":false,"errorMessage":"Token inválido"}

How to take the string returned from running the URL to turn it into a JSON object?

2 answers

1


This string comes in JSON format, to transform into an object uses the method json_decode();

Using PHP has at least two ways:

Using Curl:

$url = 'https://sandbox.boletobancario.com/boletofacil/integration/api/v1/fetch-payment-details?paymentToken=1234';
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1');
$rawData = curl_exec($curl);
curl_close($curl);
$data = json_decode($rawData);
print_r($data); // stdClass Object ( [success] => [errorMessage] => Token inválido )

Using file_get_contents:

$url = 'https://sandbox.boletobancario.com/boletofacil/integration/api/v1/fetch-payment-details?paymentToken=1234';
$opts = array(
    'http' => array(
        'method'=>"GET",
        'ignore_errors' => true, // para este caso, isto é necessário senão seria ".. 400 Bad Request .."
        'header' => array(
            'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",
        )
    ),
);
$context = stream_context_create($opts);
$rawData = file_get_contents($url, false, $context);
$data = json_decode($rawData);
print_r($data); // stdClass Object ( [success] => [errorMessage] => Token inválido )

On to access the Keys of this new object ($data) ago:

$data->errorMessage; // Token inválido

Note that it is not always necessary to define in the headers a User-Agent, but for many cases the server to which we will make the request "requires" that there is a User-Agent set, otherwise the answer comes empty or responds some kind of error message

  • Very good Miguel. I had managed to do here using Curl. It got a little different but it worked too. I found the second method interesting too. Thanks.

0

Final solution guys! Using Curl

$url = 'https://sandbox.boletobancario.com/boletofacil/integration/api/v1/fetch-payment-details?paymentToken='.$paymentToken;

$ch = curl_init(); 
curl_setopt( $ch, CURLOPT_URL, $url);
// define que o conteúdo obtido deve ser retornado em vez de exibido
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
$order = curl_exec($ch); //Pega a string JSON obtida.
curl_close($ch);
$array = json_decode($order, true); //transforma a string em um array associativo.

Browser other questions tagged

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