Skip to content

Instantly share code, notes, and snippets.

@alexfigueiredo
Created September 27, 2012 14:58
Show Gist options
  • Save alexfigueiredo/3794476 to your computer and use it in GitHub Desktop.
Save alexfigueiredo/3794476 to your computer and use it in GitHub Desktop.
Busca CEP por endereço nos Correios
<?php
/*
* Busca o CEP com base no endereço diretamente na base dos Correios.
*
* Alex Figueiredo
* alex@focusteam.com.br
*/
function cep_por_endereco($logradouro = '') {
if (empty($logradouro))
return array();
$postdata = http_build_query(
array(
'relaxation' => $logradouro,
'TipoCep' => 'ALL',
'semelhante' => 'N',
'cfm' => '1',
'Metodo' => 'listaLogradouro',
'TipoConsulta' => 'relaxation',
'StartRow' => '1',
'EndRow' => '10'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://www.buscacep.correios.com.br/servicos/dnec/consultaEnderecoAction.do', false, $context);
$dom = new DOMDocument;
$dom->loadHTML($result);
$div = $dom->getElementById('lamina');
$table = $div->getElementsByTagName('table')->item(2);
$tr = $table->getElementsByTagName('tr');
$result = array();
foreach ($tr as $item) {
$inside = array();
$children = $item->childNodes;
foreach ($children as $child) {
$td = $child->nodeValue;
if (trim($td) != '') {
array_push($inside, utf8_decode($td));
}
}
array_push($result, $inside);
}
return $result;
}
function cep_por_endereco_table($logradouro = '') {
$array = $this->cep_por_endereco($logradouro);
$template = '<table class = "table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Logradouro</th>
<th>Bairro</th>
<th>Localidade</th>
<th>UF</th>
<th width="65">CEP</th>
</tr>
</thead>
<tbody>';
foreach ($array as $value) {
$template .= '<tr>';
foreach ($value as $item)
$template .= '<td>' . $item . '</td>';
$template .= '</tr>';
}
$template .= '</tbody></table>';
return utf8_encode($template);
}
// Uso:
// cep_por_endereco('Avenida Nações Unidas, Bauru');
// cep_por_endereco_table('Avenida Nações Unidas, Bauru');
?>
@rafanake
Copy link

Mto bom, mas esta lançando troçentos warnings no DOMDocument::loadHTML()

@carolinatoledo
Copy link

alex, tudo bem? parabéns pelo script. utilizavamos até ontem, mas percebemos que o URL http://www.buscacep.correios.com.br/servicos/dnec/consultaLogradouroAction.do está offline, você sabe informar se houve alguma alteração pelos Correios? grata!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment