Last active
December 20, 2015 04:08
-
-
Save paulofreitas/6068224 to your computer and use it in GitHub Desktop.
Gerador de schema SQL para tabelas de estados e cidades diretamente do site do IBGE
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 | |
header('Content-Type: text/plain; charset=utf-8'); | |
$schema = <<<SQL | |
-- | |
-- Tabela 'Estado' | |
-- | |
CREATE TABLE Estado ( | |
codEstado INT(1) NOT NULL AUTO_INCREMENT, | |
estado VARCHAR(20) NOT NULL, | |
sigla CHAR(2) NOT NULL, | |
CONSTRAINT pk_codEstado PRIMARY KEY (codEstado), | |
CONSTRAINT ak_estado UNIQUE (estado), | |
CONSTRAINT ak_sigla UNIQUE (sigla) | |
); | |
%estados% | |
-- | |
-- Tabela 'Cidade' | |
-- | |
CREATE TABLE Cidade ( | |
codCidade INT(2) NOT NULL AUTO_INCREMENT, | |
codEstado INT(1) NOT NULL, | |
cidade VARCHAR(40) NOT NULL, | |
CONSTRAINT pk_codCidade PRIMARY KEY (codCidade), | |
CONSTRAINT fk_codEstado FOREIGN KEY (codEstado) REFERENCES Estado (codEstado) ON DELETE RESTRICT ON UPDATE CASCADE | |
); | |
%cidades% | |
SQL; | |
$estados = array(); | |
$cidades = array(); | |
$codEstado = 0; | |
$codCidade = 0; | |
foreach (str_split('acalamapbacedfesgomamgmsmtpapbpepiprrjrnrorrrsscsespto', 2) as $uf) { | |
$dom = new DOMDocument(); | |
@$dom->loadHTMLFile("http://www.ibge.gov.br/cidadesat/download/mapa_e_municipios.php?uf=$uf"); | |
$xpath = new DOMXPath($dom); | |
$header = $xpath->query('//h1'); | |
list($estado, $sigla) = explode(' - ', $header->item(0)->nodeValue); | |
$estados[] = sprintf("INSERT INTO Estado VALUES (%d, '%s', '%s');", | |
++$codEstado, $estado, $sigla); | |
foreach ($xpath->query('//tbody/tr/td[1]') as $data) { | |
$cidades[] = sprintf("INSERT INTO Cidade VALUES (%d, %d, '%s');", | |
++$codCidade, $codEstado, $data->nodeValue); | |
} | |
} | |
print str_replace( | |
array('%estados%', '%cidades%'), | |
array(implode("\n", $estados), implode("\n", $cidades)), | |
$schema | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment