Search ZIP Post Office

Asked

Viewed 7,027 times

4

I’m trying an implementation in php via simplexml_load_file for verification and return of data together with the Post API. In this case, it is necessary to pass variables in the url. I’m doing like this:

I’m doing like this:

function encontraCep() {
      $cep = $_POST["txtCep"];

      $url = "https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl&txtCep=".$cep;      
      $xml = simplexml_load_file($url);


      return $xml;

  }

 dados = encontraCep();

a simple

 print "<pre>";
 print_r($dados);
 print "</pre>";

Call me back:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [name] => AtendeClienteService
            [targetNamespace] => http://cliente.bean.master.sigep.bsb.correios.com.br/
        )

)

Where am I going wrong?

I’m following the tutorial given in http://www.eduardorizo.com.br/2014/12/04/correios-webservice-para-consulta-de-enderecos-a-partir-de-um-cep/, made in Asp.net

There he makes a form:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
    <h1>Teste WS dos Correios</h1><br />
    <asp:Panel ID="Panel1" runat="server" GroupingText="Busca Endereço">
      CEP:
      <asp:TextBox ID="txtCep" runat="server"></asp:TextBox>&amp;nbsp;<asp:Button ID="btnBuscarEndereco" runat="server" OnClick="btnBuscarEndereco_Click" Text="Buscar Endereço" />
      <br />
      <asp:Label ID="lblEndereco" runat="server"></asp:Label>
    </asp:Panel>
    </div>
  </form>
</body>
</html>

And a function that picks up the return:

protected void btnBuscarEndereco_Click(object sender, EventArgs e)
{
  wsCorreio.AtendeClienteClient ws = new wsCorreio.AtendeClienteClient("AtendeClientePort"); //Verificar o nome do endpoint no arquivo Web.config
  var dados = ws.consultaCEP(txtCep.Text);
  if (dados != null)
  {
    lblEndereco.Text = string.Format(@"Endereço: {0}<br />
                       Complemento 1: {1}<br />
                       Complemento 2: {2}<br />
                       Bairro: {3}<br />
                       Cidade: {4}<br />
                       Estado: {5}",
                       dados.end,
                       dados.complemento,
                       dados.complemento2,
                       dados.bairro,
                       dados.cidade,
                       dados.uf);
  }
  else
    lblEndereco.Text = "CEP não encontrado.";
}

But there is no action in the form of him to see the sending of url.

3 answers

7


You have use in PHP Soapclient to carry the WSDL (Web Service) and use its features.

In the code just below you recover the information by the ZIP code number.

<?php   

    $config = array(
        "trace" => 1, 
        "exception" => 0, 
        "cache_wsdl" => WSDL_CACHE_MEMORY
    );

    $address = 'https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl';   

    $client = new SoapClient($address, $config);

    $cep  = $client->consultaCEP(['cep' =>'01415000']);

Upshot

object(stdClass)#2 (1) { ["return"]=> object(stdClass)#3 (8) 
{ ["bairro"]=> string(12) "Consolação" ["cep"]=> string(8) "01415000"
  ["cidade"]=> string(10) "São Paulo" ["complemento"]=> string(0) "" 
  ["complemento2"]=> string(21) "- até 586 - lado par" 
  ["end"]=> string(15) "Rua Bela Cintra" ["id"]=> int(0) 
  ["uf"]=> string(2) "SP" } 
}

Sequence:

$config: configurações do serviço

$address: endereço do WSDL

$client: instância da classe SoapClient com as configurações e endereço

$cliente->consultaCEP: é a função que recupera as informações do CEP informado

Remarks:

1) No consultaCEP to works is an Array in format [cep => 'numero do cep']

2) That Webservice is too slow!


Invalid zip code and errors:

Use like this:

try
{
    $cep  = $client->consultaCEP(['cep' =>'11111111']);
    var_dump($cep);
}
catch(Exception $e) 
{
    var_dump($e);
}

Object(Soapfault)#3 (10) { ["message":protected]=> string(18) "CEP NAO FOUND" ["string":"Exception":private]=> string(0) "" ["code":protected]=> int(0) ["file":protected]=> string(26) "C: Inetpub wwwroot cep.php" ["line":protected]=> int(16) ["trace":"Exception":private]=> array(1) { [0]=> array(6) { ["file"]=> string(26) "C: Inetpub wwwroot cep.php" ["line"]=> int(16) ["Function"]=> string(6) "__call" ["class"]=> string(10) "Soapclient" ["type"]=> string(2) "->" ["args"]=> array(2) { [0]=> string(11) "consultation" 1=> array(1) { [0]=> array(1) { ["cep"]=> string(8) "11111111" } } } } } ["Previous":"Exception":private]=> NULL ["faultstring"]=> string(18) "ZIP CODE NOT FOUND" ["faultcode"]=> string(11) "Soap:Server" ["Detail"]=> Object(stdClass)#2 (1) { ["Sigepclienteexception"]=> string(18) "ZIP CODE NOT FOUND" } }

You can then check if nothing returned!

Ready-made PHP package alternatives on the Site Packagistthe PHP Package Repository

1 - Zizaco/cep-Consult by the post office website

2 - canducci/cep by viacep.com.br

3 - cagartner/post office consultation has even freight calculation

  • error on this line: $cep = $client->query CEP(['cep' =>'01415000']);

  • what mistake? @Carlosrocha

  • I arranged asim $cepC = array ('cep'=>'36880000'); $cep = $client->query CEP($cepC);. But it tells me 2 things: does this return not inform error codes? Why do you say that this web service is too slow? Do you use another one? In fact, what happens is that in the store, as soon as the customer puts the zip code, it goes to an address form page, and then it goes to the freight calculation page. I’m not finding a webservice that returns price and term and also address data

  • It must be the version of your php because of the error, but I already fix blz. If the cep is not found it informs yes type a invalid cep. The webservice takes time to answer in PHP already in . Net is normal that I do not know and yes the post office. I use (viacep.com.br)[viacep.com.br]

  • But it does not return error code this request. Instead, it gives error in SOAP. That’s right?

  • Another thing: viacep is safe?

  • The viacep.com.br is an alternative that never left me in the lurch. I made an edition in the reply, Observer and use in the best possible way.

  • 1

    thank you very much. Thank you very much!

  • stopped working this script. Add in your reply the vi cep implementation doing favor

  • added in another reply!

Show 5 more comments

2

There is an example in PHP for this, including I’ve used, access http://www.rafaelwendel.com/2012/08/preenchimento-automatico-do-endereco-a-partir-do-cep/. In the Url you use in your example does not return anything ,it uses the url http://cep.republicavirtual.com.br/web_cep.php?formato=xml&cep= that you can even test in your browser that works, just pass the zip code.

As you can see in the example just call the url and work with the return:

<?php

$cep = $_POST['cep'];

$reg = simplexml_load_file("http://cep.republicavirtual.com.br/web_cep.php?formato=xml&cep=" . $cep);

$dados['sucesso'] = (string) $reg->resultado;
$dados['rua']     = (string) $reg->tipo_logradouro . ' ' . $reg->logradouro;
$dados['bairro']  = (string) $reg->bairro;
$dados['cidade']  = (string) $reg->cidade;
$dados['estado']  = (string) $reg->uf;

echo json_encode($dados);

?>
  • 3

    It is. But the url I use is the post office, and this is the virtual republic. Isn’t there a risk that this is outdated? Because after checking the zip code, I need to calculate the freight price in the post office api. If the database is not the same, then I may have problems.

0

Another way is by viacep.com.br

Code:

<?php   

    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;
    }
    $cep = "01414000";
    $url = sprintf('http://viacep.com.br/ws/%s/json/ ', $cep);
    $result = json_decode(webClient($url));

    var_dump($result);

Upshot:

object(stdClass)#1 (9) { 
 ["cep"]=> string(9) "01414-000" 
 ["logradouro"]=> string(16) "Rua Haddock Lobo" 
 ["complemento"]=> string(20) "até 1048 - lado par" 
 ["bairro"]=> string(16) "Cerqueira César" 
 ["localidade"]=> string(10) "São Paulo" 
 ["uf"]=> string(2) "SP" 
 ["unidade"]=> string(0) "" 
 ["ibge"]=> string(7) "3550308" 
 ["gia"]=> string(4) "1004" }

How to use:

echo $result->cep;
echo $result->logradouro;
echo $result->complemento;
echo $result->bairro;
echo $result->localidade;
echo $result->uf;
echo $result->unidade;
echo $result->ibge;
echo $result->gia;

Browser other questions tagged

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