Advertisement
gilbertoalbino

Busca Endereço Correios

May 6th, 2013
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.89 KB | None | 0 0
  1. /**
  2.  * @author Gilberto Albino
  3.  * @description Baseado em
  4.  * http://www.phpclasses.org/package/7728-PHP-Get-the-address-from-a-CEP-zip-code-in-Brazil.html
  5.  *
  6.  */
  7. class Correios
  8. {
  9.  
  10.     public function getEnderecoByCep( $cep )
  11.     {
  12.         $ch = curl_init();
  13.  
  14.         $url = "http://www.buscacep.correios.com.br/"
  15.              . "servicos/dnec/consultaEnderecoAction.do"
  16.         ;
  17.        
  18.         curl_setopt_array( $ch,
  19.             array (
  20.                 CURLOPT_URL => $url,
  21.                 CURLOPT_POST => TRUE,
  22.                 CURLOPT_POSTFIELDS => "relaxation={$cep}"
  23.                     . "&TipoCep=ALL"
  24.                     . "&semelhante=N"
  25.                     . "&Metodo=listaLogradouro"
  26.                     . "&TipoConsulta=relaxation"
  27.                     . "&StartRow=1"
  28.                     . "&EndRow=10"
  29.                     . "&cfm=1",
  30.                 CURLOPT_RETURNTRANSFER => TRUE
  31.             )
  32.         );
  33.  
  34.         $response = curl_exec( $ch );
  35.         curl_close( $ch );
  36.  
  37.         preg_match_all( "/>(.*?)<\/td>/", $response, $matches );
  38.  
  39.         $dados = $matches[1];        
  40.        
  41.         /**
  42.          * Retornará nullo || Will return null
  43.          */
  44.         $obj = new stdClass();
  45.        
  46.         $obj->logradouro = isset( $dados[0] ) ? $dados[0] : null;
  47.         $obj->bairro = isset( $dados[1] ) ? $dados[1] : null;
  48.         $obj->localidade = isset( $dados[2] ) ? $dados[2] : null;
  49.         $obj->uf = isset( $dados[3] ) ? $dados[3] : null;
  50.         $obj->cep = isset( $dados[4] ) ? $dados[4] : null;
  51.        
  52.         return $obj;
  53.     }
  54.    
  55. }
  56.  
  57. /**
  58.  * Uso simples || Simple usage
  59.  */
  60. $correios = new Correios();
  61. $info = $correios->getEnderecoByCep( '01046-000' );
  62. echo $info->logradouro;
  63.  
  64. /**
  65.  * Debug simples em caso de erro || Simple debug if fault
  66.  */
  67. $info = $correios->getEnderecoByCep( '12121-121' );
  68. var_dump($info->logradouro);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement