我遇到了这个问题,PHP 和 Laravel。我正在尝试从远程 ULR 读取 JSON 文件:
我使用的代码:
$re_url = 'https://services.realestate.com.au/services/listings/search?query={"channel":"buy","filters":{"propertyType":["house"],"surroundingSuburbs":"False","excludeTier2":"true","geoPrecision":"address","localities":[{"searchLocation":"Blacktown, NSW 2148"}]},"pageSize":"100"}';
$ch = curl_init($re_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$re_str = curl_exec($ch);
curl_close($ch);
$re_list = json_decode($re_str);
它不断收到错误“处理您的请求时发生错误。引用#30.96464868.1492255689.1829cf2”
我尝试了“https://google.com.au”的url,效果很好,所以看起来像是URL编码问题。但我不确定。
有人可以帮忙吗,或者有同样的问题吗?
谢谢
最佳答案
我相信您有两个问题,下面的代码可以解决它们。我的代码还使用了一些不同的方法来避免手动组装 JSON、URL 查询字符串等(请参阅所提供代码的第 3-41 行)
问题
- 您没有对查询参数值进行编码 - 可以使用参数值的
urlencode
进行修复,但我更喜欢http_build_query
,原因已在我的介绍性段落中指出。< - 您没有发送用户代理 (UA) header (远端似乎需要此 header 中的值,但不关心它是什么。收到带有 UA 的请求后,我认为它必须将 IP 列入白名单一会儿,因为它似乎并不需要在每个请求上都需要它。不过,我只会为每个请求发送它,因为它不会造成伤害,而且你永远不知道你的白名单何时会超时)。请参阅第 50-53 行,了解我在此脚本中设置的内容以及您拥有的一些选项
替换代码
带有解释性注释
<?php
/*
* The data that will be serialized as JSON and used as the value of the
* `query` parameter in your URL query string
*/
$search_query_data = [
"channel" => "buy",
"filters" => [
"propertyType" => [
"house",
],
"surroundingSuburbs" => "False",
"excludeTier2" => "true",
"geoPrecision" => "address",
"localities" => [
[
"searchLocation" => "Blacktown, NSW 2148",
],
],
],
"pageSize" => "100",
];
/*
* Serialize the data as JSON
*/
$search_query_json = json_encode($search_query_data);
/*
* Make a URL query string with a param named `query` that will be set as the
* JSON from above
*/
$url_query_string = http_build_query([
'query' => $search_query_json,
]);
/*
* Assemble the URL to which we'll make the request, and set it into CURL
*/
$request_url = 'https://services.realestate.com.au/services/listings/search?' . $url_query_string;
$ch = curl_init($request_url);
/*
* Set some CURL options
*/
// Have `curl_exec()` return the transfer as a string instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set a user agent header
curl_setopt($ch, CURLOPT_USERAGENT, 'H.H\'s PHP CURL script');
// If you want to spoof, say, Safari instead, remove the last line and uncomment the next:
//curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30');
/*
* Get the response and close out the CURL handle
*/
$response_body = curl_exec($ch);
curl_close($ch);
/*
* Unserialize the response body JSON
*/
$search_results = json_decode($response_body);
最后,顺便说一句,我建议您停止直接使用 CURL,并开始使用库来抽象一些 HTTP 交互,并使您的请求/响应开始更好地适应“标准”(PSR) 接口(interface)。由于您使用的是 Laravel,因此您已经处于具有 Composer 的生态系统中,因此您可以轻松 install something like Guzzle .
关于PHP 从远程 URL 读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43425590/