You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP使用Nominatim API?空响应问题求助

用PHP的file_get_contents调用Nominatim API的问题解答

仍然可以通过file_get_contents调用Nominatim API,你遇到的空响应基本是因为请求不符合API的使用规范,以下是解决方法和注意事项:

  • 必须设置合法的User-Agent头
    Nominatim API强制要求请求携带能明确识别应用的User-Agent信息,不能使用PHP默认的空标识或模糊UA,否则服务器会拒绝返回内容。

  • 示例可用代码

$apiUrl = 'https://nominatim.openstreetmap.org/search?q=grindelwald&countryCodes=CH&addressdetails=1&format=json';
// 构造请求头,替换成你的应用信息和联系方式
$requestOpts = [
    'http' => [
        'header' => "User-Agent: 我的地理查询应用/1.0 (example@mail.com)\r\n"
    ]
];
$context = stream_context_create($requestOpts);
$response = file_get_contents($apiUrl, false, $context);

if ($response) {
    $locationData = json_decode($response, true);
    // 处理返回的经纬度等数据
    print_r($locationData);
} else {
    // 排查错误
    $lastError = error_get_last();
    echo "请求失败: " . $lastError['message'];
}
  • 其他关键注意事项
    • 遵守API使用限制:单次请求间隔至少1秒,禁止批量高频请求,否则会被封禁IP。
    • 核对请求参数:确保countryCodes是合法的ISO 3166-1 alpha-2国家代码,format参数设置正确。
    • 排查响应状态:如果请求失败,可以通过全局变量$http_response_header查看HTTP状态码,定位具体问题(比如403表示权限被拒,429表示请求频率过高)。

内容的提问来源于stack exchange,提问作者Simon Ferndriger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:42:34