Looking for a little bit I found this method of consulting the ZIP code from neighborhood and city or all the data from the zip code. But this query is only working when I put the information directly in the code in quotation marks. I am not able to use a variable (which I enter the data passed by POST) within $buscarcep->busca('[Aqui dentro!]')
.
The problem is the one below in // View routine
This is the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento</title>
</head>
<body>
<?php
$rua01 = 'Rua diadema';
$cidade01 = 'Foz do Iguaçu';
$endereco01 = $rua01.' '.$cidade01;
class BuscaCEP
{
protected function formata($response)
{
$dom = new DOMDocument();
@$dom->loadHTML($response);
$xpath = new DOMXPath($dom);
$values = $xpath->query('//*[@class="respostadestaque"]');
$result = [];
// Se não encontrar CEP, retorna false
if (!$values->length) {
return false;
}
// Obtém informações desejadas, tratando-as quando necessário
foreach ($values as $value) {
$result[] = preg_replace(
'~[\s]{2,}~',
'',
trim($value->childNodes->item(0)->nodeValue)
);
}
list($logradouro, $bairro, $localidade, $cep) = $result;
list($localidade, $uf) = explode('/', $localidade);
return compact('logradouro', 'bairro', 'localidade', 'uf', 'cep');
}
public function busca($cep)
{
$response = file_get_contents(
'http://m.correios.com.br/movel/buscaCepConfirma.do',
false,
stream_context_create([
'http' => [
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query([
'cepEntrada' => $cep,
'metodo' => 'buscarCep',
]),
],
])
);
return $this->formata($response);
}
}
// Rotina de Exibir
$buscarcep = new BuscaCEP();
$dados = $buscarcep->busca($endereco01);
print_r($dados['bairro']);
?>
</body>
</html>
I've already put
$dados = $buscarcep->busca($enderecoP);
$dados = $buscarcep->busca("$enderecoP");
And it just did not show up. No error, simply nothing was printed.
Updating with more information, because they have generated different forms of interpretation. La at the end of the code when I put:
// Rotina de Exibir
$buscarcep = new BuscaCEP();
$dados = $buscarcep->busca($endereco01);
print_r($dados['bairro']);
Within the $ endereco01 variable I have $ rua01. ' '. $ city01 , that if I gave an echo in it, it would be shown Street diadema Foz do Iguaçu . But the way it does not recognize! Now if I take $ endereco01 and just put 'Street address Foz do Iguaçu' like this:
// Rotina de Exibir
$buscarcep = new BuscaCEP();
$dados = $buscarcep->busca('Rua diadema Foz do Iguaçu');
print_r($dados['bairro']);
It fully recognizes and monitors the information for this address.