Last active
January 14, 2017 03:27
-
-
Save ogabrielsantos/b967e318ca789d413e65 to your computer and use it in GitHub Desktop.
Buscar CEP diretamente no Correios
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 getAddressDetails($cep) | |
{ | |
$data = [ | |
'cepEntrada' => $cep, | |
'tipoCep' => '', | |
'cepTemp' => '', | |
'metodo' => 'buscarCep' | |
]; | |
$requestOptions = [ | |
CURLOPT_URL => 'http://m.correios.com.br/movel/buscaCepConfirma.do', | |
CURLOPT_HEADER => false, | |
CURLOPT_POST => true, | |
CURLOPT_POSTFIELDS => http_build_query($data), | |
CURLOPT_RETURNTRANSFER => true | |
]; | |
$handler = curl_init(); | |
curl_setopt_array($handler, $requestOptions); | |
$response = curl_exec($handler); | |
curl_close($handler); | |
return $response; | |
} | |
function searchDomByText($xpath, $text) | |
{ | |
$result = $xpath->query( | |
'//span[@class="resposta"][contains(., "' . $text . '")]/following-sibling::span' | |
)->item(0); | |
if ($result) { | |
return $result->nodeValue; | |
} | |
return null; | |
} | |
function fetchAddressDetails($html) | |
{ | |
libxml_use_internal_errors(true); | |
$dom = new DOMDocument(); | |
$dom->preserveWhiteSpace = false; | |
$dom->loadHTML($html); | |
$xpath = new DOMXPath($dom); | |
$results = [ | |
'cep' => searchDomByText($xpath, 'CEP'), | |
'address' => searchDomByText($xpath, 'Logradouro'), | |
'district' => searchDomByText($xpath, 'Bairro'), | |
'city' => null, | |
'state' => null | |
]; | |
$cityWithState = searchDomByText($xpath, 'Localidade / UF'); | |
if ($cityWithState != null) { | |
list($city, $state) = explode('/', $cityWithState); | |
$results['city'] = $city; | |
$results['state'] = $state; | |
unset($cityWithState, $city, $state); | |
} | |
return array_map('trim', $results); | |
} | |
$cep = '13537-000'; | |
$html = getAddressDetails($cep); | |
$results = fetchAddressDetails($html); | |
var_dump($results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment