Created
August 25, 2012 18:15
-
-
Save guisehn/3468760 to your computer and use it in GitHub Desktop.
CEP (PHP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function cep_dados($cep) | |
{ | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, 'http://www.buscacep.correios.com.br/servicos/dnec/consultaLogradouroAction.do'); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, 'CEP=' . $cep . '&Metodo=listaLogradouro&TipoConsulta=cep&StartRow=1&EndRow=10'); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 60); | |
$res = curl_exec($ch); | |
curl_close($ch); | |
if (strpos($res, 'CEP NAO ENCONTRADO') !== false) | |
{ | |
return false; | |
} | |
$tabelas = explode('<table', $res); | |
$tabela = ''; | |
foreach ($tabelas as $tbl) | |
{ | |
if (strpos($tbl, 'javascript:detalharCep') !== false) | |
{ | |
$tabela = $tbl; | |
break; | |
} | |
} | |
$tr = explode('<tr', $tabela); | |
preg_match_all('/\<td[^>]+\>(.*?)\<\/td\>/', $tr[1], $tds); | |
return array( | |
'logradouro' => $tds[1][0], | |
'bairro' => $tds[1][1], | |
'cidade' => $tds[1][2], | |
'estado' => $tds[1][3] | |
); | |
} | |
var_dump(cep_dados('13537000')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment