Receive data from external Json and display its contents in loop as array using PHP

Asked

Viewed 86 times

0

The external url has a data structure that I receive in my code and it is being received as a string JSON, I tried to decode it but I didn’t get any results.

http://publisher.windi.com.br/manager/estoquejson/? hash=8d37ddfa64d1e0a2d9cb887c2ed86619&l=8910809

I hope to receive the string JSON and convert it into the format below:

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

My PHP

<?php
ini_set("allow_url_fopen", 1);
header("Content-type: text/html; charset=iso-8859-1");
$urlPath = "http://publisher.windi.com.br/manager/estoquejson/?hash=8d37ddfa64d1e0a2d9cb887c2ed86619&l=8910809";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $urlPath);
$result = curl_exec($ch);
curl_close($ch);

// Imprimo
echo $result;
// Aqui sai como string, tentei converter a estrutura para array mas sem sucesso.

// { "vehicles": [ { "id": 164999, "highlight": 0, "anoFabricacao": 2011, "anoModel": 2012, "km": 86000, "doors": 4, "valorVenda": 29990.0, "dateTetdate": "Apr 27, 2019 12:00:00 PM", ................

Knowing that:

PHP> = 5.2.0 presents a function, json_decode, that decodes a JSON sequence in a PHP variable. By default, it returns an object. The second parameter accepts a boolean which, when set to true, tells it to return objects as associative matrices. You can learn more about json_decode in PHP documentation.

The way out for the change I made does not result in anything.

<?php
ini_set("allow_url_fopen", 1);
header("Content-type: text/html; charset=iso-8859-1");
$urlPath = "http://publisher.windi.com.br/manager/estoquejson/?hash=8d37ddfa64d1e0a2d9cb887c2ed86619&l=8910809";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $urlPath);
$result = curl_exec($ch);
curl_close($ch);

// Decodifiquei a string `JSON` esperando algo, mas a exibição foi em branco.
$obj = json_decode($result, true);
print_r($obj);

// Ou com var_dump(); retornou NULL
var_dump($obj);

3 answers

2

There are two very common errors in JSON-formatted strings, the first is in relation to the charset since the function json_decode supports UTF-8 only; the second may be string formatting error, the structure itself, maybe a key is missing {}, an quotation mark " or any other control character.

That’s why it’s always good to use the error handling that comes by default in PHP.

You can find out exactly what is happening with a small modification in the code:

<?php

// ...

$obj = json_decode($result, true);

if (JSON_ERROR_NONE !== json_last_error()) {
    echo json_last_error_msg();
}

And from there take the necessary steps.

1


By default json_decode is already true, so there is no need to set it unless you want to receive it in array, hence arrow to false. Try converting the charset before converting to the json Decode:

$rtn = json_decode(utf8_encode($result))
print_r($rtn);

Here’s what I did and it worked:

function getExternalUrl($url_metodo, $info = false)
{

    try {
        $mime_type = null;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url_metodo);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        list($mime, $charset) = explode(';', curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
        $saida = curl_exec($ch);
       curl_close($ch);
    } catch (Exception $e) {
        $mime = null;
        $charset = null;
        $saida = file_get_contents($url_metodo);
    }
    if ($info) {
        return array('file' => $saida, 'mime' => $mime, 'charset' => $charset);
    } else {
        return $saida;
    }
}

$obj = getExternalUrl('http://publisher.windi.com.br/manager/estoquejson/?hash=8d37ddfa64d1e0a2d9cb887c2ed86619&l=8910809');

print_r(json_decode(utf8_encode($obj)));

0

With the help of @Diego Martins' reply I was able to solve the problem by checking the error that prevented the conversion of JSON string to objects as associative matrices and below follows the solution.

<?php
ini_set("allow_url_fopen", 1);
header("Content-type: text/html; charset=utf-8");
$urlPath = "http://publisher.windi.com.br/manager/estoquejson/?hash=8d37ddfa64d1e0a2d9cb887c2ed86619&l=8910809";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $urlPath);
$result = curl_exec($ch);
$result = utf8_encode($result);
curl_close($ch);

$obj = json_decode($result, true);

if (JSON_ERROR_NONE !== json_last_error()) {
    echo json_last_error_msg();
}

if(is_array($obj)) {
    echo "<p>É array</p>";
} else {
    echo "<pre>Não é array</pre>";
}

// Retornou "É array"

echo "<pre>";
print_r($obj);
echo "</pre>";

// Retornou a estrutura de array
  • I kept IF and PRINT_R for information purposes only, as well as json_last_error for being a development environment, with I can continue what I have to do.

Browser other questions tagged

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