感谢京东大哥的慷慨解囊
https://fts.jd.com/area/get?fid=4744
4744就是起始值,拿到的就是一级数据(全国各省的数据以及直辖市)  浏览器是经过编码的,unicode解码就可以看到数据,不过php不需要,直接就可以拿到数据  前三级的街道,一次性拿到,代码没有写请求失败后的处理,不过将请求失败时候,将complete改为flase,这样子请求完后只需要将为false的重新请求即可
public function address()
{
set_time_limit(3600);
$province = $this->get_address('4744');
if (false == $province) {
throw new Exception('一级省份请求失败,fid:4744');
}
foreach ($province as $value) {
if ('海外' == $value['name']) {
continue;
}
$value = (array) $value;
$province_add_info = [
'name' => $value['name'],
'parent_id' => '',
'level' => 1,
'order_no' => $value['id'],
'complete' => true,
];
$province_id = $this->db->default->insert('province_city', $province_add_info);
$city = $this->get_address($value['id']);
if (false == $city) {
$this->db->default->update('province_city', ['_id' => $province_id], ['complete' => false]);
continue;
}
if(empty($city)){
continue;
}
foreach ($city as $value) {
$value = (array) $value;
$city_add_info = [
'name' => $value['name'],
'parent_id' => $province_id,
'level' => 2,
'order_no' => $value['id'],
'complete' => true,
];
$city_id = $this->db->default->insert('province_city', $city_add_info);
$area = $this->get_address($value['id']);
if (false == $area) {
$this->db->default->update('province_city', ['_id' => $city_id], ['complete' => false]);
continue;
}
if(empty($area)){
continue;
}
foreach ($area as $value) {
$value = (array) $value;
$area_add_info = [
'name' => $value['name'],
'parent_id' => $city_id,
'level' => 3,
'order_no' => $value['id'],
"complete" => true,
];
$this->db->default->insert('province_city', $area_add_info);
}
}
}
}
拿到第四级街道的数据
public function get_four_address()
{
set_time_limit(7200);
$area = $this->db->default->get_rows('province_city', ['level' => 3]);
if(empty($area)){
throw new Exception("没有第三级数据");
}
foreach ($area as $area_info) {
$street = $this->get_address($area_info['order_no']);
if (false == $street) {
$this->db->default->update('province_city', ['_id' => $area_info['id']], ['complete' => false]);
continue;
}
if (empty($street)) {
continue;
}
foreach ($street as $value) {
$value = (array) $value;
$area_add_info = [
'name' => $value['name'],
'parent_id' => $area_info['id'],
'level' => 4,
'order_no' => $value['id'],
];
$this->db->default->insert('province_city', $area_add_info);
}
}
}
发起请求,通过传递fid参数来请求拿到下一级的数据
public function get_address($fid)
{
$result = http_get('https://fts.jd.com/area/get?fid='.$fid);
$result = str_replace('\ ', ' ', $result);
$result = json_decode($result, true);
if (!$result || is_object($result)) {
return false;
}
return $result;
}
拿到的数据,order_no既可以作为排序,也可以作为请求下一级的fid请求参数(比如天津的order_no是3,所以get_address(3)拿到的数据就是天津下一级的区,如果已经是叶子节点了,再往下就是[]空数组) 
|