首页 > 解决方案 > Algolia:使用 CURL (PHP) 获取数据返回的结果与使用 places.js 的示例结果不同

问题描述

我正在尝试使用 Algolia 但使用我的服务器进行地点搜索。我尝试完全按照提供的示例(https://community.algolia.com/places/examples.html - 第一个简单输入)重现搜索,但系统返回的结果略有不同。特别是 - 如果您输入Paris输入,您将看到首先显示巴黎城市,然后显示其他结果,这是正确的方法。但是当我使用 CURL 执行相同的请求时,它会返回Paris 17e Arrondissement, thenParis 8e Arrondissement和其他。实际的巴黎城市仅作为第 5 个结果出现。

$cURLConnection = curl_init('https://places-dsn.algolia.net/1/places/query?x-algolia-agent=Algolia%20for%20JavaScript%20(3.35.1)%3B%20Browser%20(lite)%3B%20Algolia%20Places%201.18.2&x-algolia-application-id=MYAPPID&x-algolia-api-key=MYAPIKEY');
curl_setopt($cURLConnection, CURLOPT_POST, 1);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, '{"params":"hitsPerPage=10&language=en&query='.$keyword.'"}');

curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($cURLConnection);
curl_close($cURLConnection);
exit($result);

这种行为的原因可能是什么?谢谢。

标签: phpcurlalgolia

解决方案


找到所需的参数。问题是默认情况下 aroundLatLngViaIP 是打开的,使得结果显示接近服务器位置的结果。这次我还通过 REST API 文档以正确的方式编写了代码,并进行了 gzip 压缩以加快获得结果的速度:

$cURLConnection = curl_init('https://places-dsn.algolia.net/1/places/query');
curl_setopt($cURLConnection, CURLOPT_POST, 1);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, '{"query": "'.$keyword.'", "language" : "fr", "aroundLatLngViaIP" : "false", "hitsPerPage" : "10"}');

curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'X-Algolia-Application-Id: MyAppKey',
    'X-Algolia-API-Key: MyAPIKey',
    'Accept: application/json',
    'Accept-Encoding: gzip, deflate, br',
    'Connection: keep-alive',
    'content-type: application/x-www-form-urlencoded',
    'Host: places-dsn.algolia.net'
];

curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($cURLConnection);
curl_close($cURLConnection);
if ( (ord($result[0])==0x1f) && (ord($result[1])==0x8b) ) {
    // skip header and ungzip the data
    $result = gzinflate(substr($result,10));
}

推荐阅读