因项目需要省市区三级联动行政区划选择,现成的部分存在缺失的情况,最好的办法就是直接到国家统计局网站抓取最新的数据。
<?php
//获取全国最新行政区域编码
function getCityCode(){
ini_set('memory_limit', '4096M'); // 临时设置最大内存占用
set_time_limit(0); // 设置脚本最大执行时间 为0 永不过期
//抓取2023年的全国最新行政区域编码
$data = file_get_contents('http://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/index.html');
//echo $data;
$html = getSubstr($data, '请务必结合有关实际情况', '</td></tr></table></TD></TR></TBODY>');
//echo $html;
//<a href="13.html">河北省<br /></a>
$pat = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';
preg_match_all($pat, $html, $province);
//echo json_encode($province,JSON_UNESCAPED_UNICODE);
$province_code = [];
$city_code = [];
$area_code = [];
foreach ($province[4] as $key => $value) {
//补全省的行政编码
$code = explode('.', $province[2][$key])[0] . '0000000000';
$province_code[$code] = [
'id' => (int)$code,
'name' => trim($value, '<br/>'),
'parent_id' => 0, //省级
'level' => 1,
];
}
//echo json_encode($province_code,JSON_UNESCAPED_UNICODE);
//市/区/街道
foreach ($province[2] as $key => $value) {
$province_code_num = explode('.', $value)[0] . '0000000000';
$city_data = getMore($value, $province_code_num);
//组城市
for ($i = 0; $i < count($city_data[4]); $i += 2) {
$city_code_num = $city_data[4][$i];
$city_code[$city_code_num] = [
'id' => (int)($city_code_num),
'name' => $city_data[4][$i + 1],
'parent_id' => (int)$province_code_num,
'level' => 2,
];
//组区数据
$area_data = getMore($city_data[2][$i]);
for ($j = 0; $j < count($area_data[4]); $j += 2) {
$area_code_num = $area_data[4][$j];
$area_code[$area_code_num] = [
'id' => (int)($area_code_num),
'name' => $area_data[4][$j + 1],
'parent_id' => (int)$city_code_num,
'level' => 3,
];
}
}
}
$all_code = array_merge($province_code, $city_code, $area_code);
//写入文件
file_put_contents('./city.php', "<?php \n return " . var_export($all_code, true) . ";");
exit('完毕');
}
function getMore($url){
$data = file_get_contents('http://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/' . $url);
$html = getSubstr($data, '<td>名称</td></tr>', '</td></tr></table></TD></TR></TBODY></TABLE>');
$pat = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';
preg_match_all($pat, $html, $html_data);
if (count($html_data[2]) > 0) {
$html_data['is_end'] = 'false';
} else {
$html_data['is_end'] = 'true';
}
return $html_data;
}
function getSubstr($str, $leftStr, $rightStr){
$llen = strlen($leftStr);
$left = strpos($str, $leftStr);
$right = strpos($str, $rightStr, $left + $llen);
if ($left < 0 || $right < $left)
return "";
return substr($str, $left + $llen, $right - $left - $llen);
}
getCityCode();
?>