php获取当前用户所在城市
php通过ip免申请api获取所在城市的代码包括省市区sql数据
<?php
function getName($pinyin,$lv){
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "ttx";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "连接数据库成功";exit;
} catch(PDOException $e) {
echo "连接数据库失败: " . $e->getMessage();exit;
}
// 层级(0:国家;1:省;2:市;3:区)
$sql = "SELECT * from cg_gym_city_info where pinyin='{$pinyin}' and level_type ={$lv}";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return isset($result['name'])?$result['name']:"";
}if($_GET['ip']){
$ip = $_GET['ip'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}
$url = "http://ip-api.io/json/{$ip}";
$response = file_get_contents($url);$data = json_decode($response, true);
$region = $data['region_name'];
$city = $data['city'];
$data['regionCNName']=getName($region,1);
$data['cityCNName']=getName($city,2);var_dump($data);exit;
发表评论 取消回复