VIACEP did not find the cep variable to return to the result in PHP

Asked

Viewed 374 times

0

Hello,

Only the zip code search to find the city and state works, but the city and state search [and neighborhood] to find the zip code does not work because in JSON, the zip code variable ($result->cep) is within the keys of the numerical class and there is no city-state class.

Eis in PHP:

if ($_SERVER['REQUEST_METHOD'] === 'POST') 
{

 function webClient($url)
 {
     $ch = curl_init();

     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

     $data = curl_exec($ch);

     curl_close($ch);

     return $data;
 }

 $descubra = $_POST['descubra'];

 switch ($descubra)
 {
  case "lugar":
   $cidade = $_POST['cidade'];
   $estado = $_POST['estado'];
   $bairro = $_POST['bairro'];
   $url = sprintf('https://viacep.com.br/ws/%s/%s/%s/json/ ', $estado, $cidade, $bairro);
   $result = json_decode(webClient($url));
   echo $result->cep;
   break;

  case "ceplocal":
   $cep    = $_POST['cep'];
   $url = sprintf('https://viacep.com.br/ws/%s/json/ ', $cep);
   $result = json_decode(webClient($url));
   echo $result->localidade;
   echo $result->uf;
   break;

  default:
    echo "Inválido!";
 }

}

1 answer

1


Actually your code is working, note what the documentation says about searching by address:

The result will be ordered by the proximity of the street name and has a maximum limit of 50 (fifty) Zip Codes.

Then your search will pick up all the streets it contains X word, and will return a array, See the example below:

$cidade = 'Americana';
$estado = 'SP';
$bairro = 'Frezzarin';

You’ll get the return:

Array
(
    [0] => stdClass Object
        (
            [cep] => 13467-019
            [logradouro] => Praça José Frezzarin
            [complemento] => 
            [bairro] => Jardim São José
            [localidade] => Americana
            [uf] => SP
            [unidade] => 
            [ibge] => 3501608
            [gia] => 1650
        )

    [1] => stdClass Object
        (
            [cep] => 13465-789
            [logradouro] => Praça Marcílio Frezzarin
            [complemento] => 
            [bairro] => Vila Frezzarin
            [localidade] => Americana
            [uf] => SP
            [unidade] => 
            [ibge] => 3501608
            [gia] => 1650
        )
    ...
)

To use the echo must inform the index $result[0]->cep and so on.

You can see it working in repl it.

  • I also use the Open ZIP code and observe that it does not have array. Verifies: https://repl.it/@Gustavo_benedit/Naoexistearraynocepaberto.

Browser other questions tagged

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