根据IP地址获取当前地区的货币单位
php 版本7.3以上
php 扩展:intl(通用扩展 · 提供国际化支持)
//获取当前用户的ip protected function getUserRealIP() { $headers = array( 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR' ); foreach ($headers as $header) { if (isset($_SERVER[$header]) && filter_var($_SERVER[$header], FILTER_VALIDATE_IP)) { $ip = $_SERVER[$header]; } } //当前访问的ip地址 $ip = isset($ip) ? $ip : $_SERVER['REMOTE_ADDR']; return $this->getCurrencyByIP($ip); } //获取当前币种 protected function getCurrencyByIP($ip) { $apiUrl = "http://ip-api.com/json/" . $ip; $curl = curl_init($apiUrl); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl); $data = json_decode($response, true); if ($data && $data['status'] === 'success') { // 返回当地的货币代码,例如 'USD' 或 'EUR' return $data['countryCode']; } else { // 如果无法获取或API返回错误,则返回false return 'NT'; //默认台币 } } //请求 $res = $this->getUserRealIP(); var_dump($res);