VIACEP did not find the ZIP code variable to return to the result in PHP

0

Hello,

Only the zip code search to find the city and state works, but the city and state search to find the ZIP code does not work because in JSON, the zip code (% with%) is inside the keys of the numeric class and there is no state-city class.

Here's 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!";
 }

}
    
asked by anonymous 05.04.2018 / 09:12

1 answer

1

In fact your code is working, note the documentation on search 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 fetch all streets containing X word, and will return a array , see the example below:

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

You will have 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 echo you have to enter the index $result[0]->cep and so on.

  

You can see it working at repl.it

    
05.04.2018 / 09:37