Error handling JSON data from a PHP API

Asked

Viewed 170 times

0

I am in error when manipulating JSON data from an API, some fields I can even manipulate. I’m taking the responsibility of the API, converting to a PHP object with the json function Code the problem is that in this API, the client name is as "person.name" and when making a foreach to display the data of each client, an error appears saying that "name" has not been set.

<?php
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.com.br/v1/entidades/HoraTrabalhada?campos=pessoa.nome,totalHoraTrabalhada,valorTotalOriginal,proprietario.nome&page&pageSize=100&criterio",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Authorization: ",
        "Content-Type: application/json"
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {

    $json_obj    = json_decode($response);
    $clientes    = $json_obj->rows;

    foreach ($clientes as $cliente) {
        echo "Valor hora: $cliente->valorTotalOriginal - Cliente: " . $cliente->pessoa.nome . "<br />";
    }

    echo "<br />";
    echo "<a href='index.php'><button>Voltar</button><a>";

}

?>

Error:

Notice: Undefined property: stdClass::$pessoa in C:\xampp\htdocs\apidatajuri\entidades.php on line 33

Warning: Use of undefined constant nome - assumed 'nome' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\apidatajuri\entidades.php on line 33
Valor hora: 0,00 - Cliente: nome

Notice: Undefined property: stdClass::$pessoa in C:\xampp\htdocs\apidatajuri\entidades.php on line 33

Warning: Use of undefined constant nome - assumed 'nome' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\apidatajuri\entidades.php on line 33
Valor hora: 0,00 - Cliente: nome

JSON received:

{"rows":[{"id":101448.0,"pessoa.nome":"Nome da pessoa","pessoaId":"79271","totalHoraTrabalhada":"","valorTotalOriginal":"5,86","proprietario.nome":"Nome da pessoa","proprietarioId":"4204"},{"id":101447.0,"pessoa.nome":"Nome da empresa","pessoaId":"74115","totalHoraTrabalhada":"","valorTotalOriginal":"8,79","proprietario.nome":"Nome da pessoa","proprietarioId":"4204"}],"listSize":51229.0,"modulo":"HoraTrabalhada","pageSize":2.0,"page":0.0}
  • $cliente->pessoa.nome, here you are concatenating the value $cliente->pessoa with nome. This second, by default, will be considered as a string and launched the Warning which you have obtained by not being a definite constant. Could [Edit] the question with an excerpt from the received JSON?

  • I made the edit by displaying the received JSON.

2 answers

1


When trying to access the person.name property php will try to concatenate the $client->person with a name "name" constant. To solve the problem put the value inside keys and quotes, as example below:

<?php
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.com.br/v1/entidades/HoraTrabalhada?campos=pessoa.nome,totalHoraTrabalhada,valorTotalOriginal,proprietario.nome&page&pageSize=100&criterio",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Authorization: ",
        "Content-Type: application/json"
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {

    $json_obj    = json_decode($response);
    $clientes    = $json_obj->rows;

    foreach ($clientes as $cliente) {
        echo "Valor hora: $cliente->valorTotalOriginal - Cliente: " . $cliente->{"pessoa.nome"} . "<br />";
    }

    echo "<br />";
    echo "<a href='index.php'><button>Voltar</button><a>";

}
  • Thank you very much indeed, it was 3 days that I was breaking my head in this mistake

1

You did:

$json_obj    = json_decode($response);

If you use print_r($json_obj) or use any debug tool, you will see that the variable is:

stdClass Object
(
    [rows] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 101448
                    [pessoa.nome] => Nome...
                    [pessoaId] => 79271
                    [totalHoraTrabalhada] =>
                    [valorTotalOriginal] => 5,86
                    [proprietario.nome] => Nome...
                    [proprietarioId] => 4204
                )

            [1] => stdClass Object
                (
                    [id] => 101447
                    [pessoa.nome] => Nome...
                    [pessoaId] => 74115
                    [totalHoraTrabalhada] =>
                    [valorTotalOriginal] => 8,79
                    [proprietario.nome] => Nome...
                    [proprietarioId] => 4204
                )

        )

    [listSize] => 51229
    [modulo] => HoraTrabalhada
    [pageSize] => 2
    [page] => 0
)

To access the property pessoa.nome you can’t do $cliente->pessoa.nome, because for PHP this will be a concatenation operation between values $cliente->pessoa and nome, this second being indefinite will be considered as string and will be launched the warnng who reported in the question.

To properly access this field you must use the keys, {}, together with a string:

$cliente->{"pessoa.nome"}

And so you get the value you want.

If you pass true as the second parameter of json_decode:

$json_obj = json_decode($response, true);

You will get a array associative instead of an object, so just do $cliente["pessoa.nome"], which simplifies in the vast majority of cases.

Browser other questions tagged

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