How do I get a string returned from the inner execution of a URL to turn it into a JSON object? [closed]

0

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

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

How do I get the string returned from the URL execution to turn it into a JSON object?

    
asked by anonymous 20.11.2016 / 12:08

2 answers

1

This string already comes in JSON format, to make an object use the 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 )

In order to access the keys of this new object ( $data ) does:

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

Note that headers do not always have to be set to User-Agent , but for many cases the server to which we are going to make the request "requires" that there is a User-Agent defined otherwise the response is empty or responds error message type

    
20.11.2016 / 12:22
0

Final solution galera! 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.
    
20.11.2016 / 19:09