当我在特定网址上运行curl时,网站停止响应并且不会生成错误,尽管我已将错误报告设置为打开.我已经尝试将curl超时设置为低值,然后它会生成错误,所以我知道它不会超时.
我想知道的主要事情是,怎么会发生这种情况,我怎么能找出原因呢?
我正在尝试访问的URL是对Factual api的调用,以及我在这里使用的URL
(http://api.factual.com/v2/tables/bi0eJZ/read?api_key=*apikey*&filters= { "类别": "汽车", "$ LOC":{ "内$":{"$中心":[[41,-74],80467.2]}})
将它放入浏览器时可以正常工作.如果您将纬度和经度更改为基本上任何其他值,则PHP脚本将按预期工作.
error_reporting(E_ALL);
ini_set('display_errors', '2');
$url="http://api.factual.com/v2/tables/bi0eJZ/read?api_key=*apikey*&filters={\"category\":\"Automotive\",\"\$loc\":{\"\$within\":{\"\$center\":[[41,-74],80467.2]}},\"website\":{\"\$blank\":false}}";
Echo "\n\n1";
$ch = curl_init($url);
Echo 2;
curl_setopt($ch, CURLOPT_HEADER, 0);
Echo 3;
curl_setopt($ch, CURLOPT_POST, 1);
Echo 4;
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,15);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT,30);
Echo 5;
$output = curl_exec($ch) or die("hhtrjrstjsrjt".curl_error($ch));
Echo 6;
curl_close($ch);
Echo "out: ".$output;
Run Code Online (Sandbox Code Playgroud)
看起来您的 PHP 配置文件中存在一些错误。
要修复您的错误,您必须编辑您的php.ini
文件。
要在开发模式下显示错误,请将error_reporting
值更改为E_ALL
。
error_reporting=E_ALL
Run Code Online (Sandbox Code Playgroud)
然后你必须启用 cURL 扩展。要在 php.ini 中启用它,您必须取消注释以下行:
extension=php_curl.dll
Run Code Online (Sandbox Code Playgroud)
编辑此值后,不要忘记重新启动您的网络服务器(Apache 或 Nginx)
我也同意我的同事的意见,你应该使用url_encode
你的 JSON 字符串。
从我的角度来看,代码应该是:
<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);
$apiKey = '*apikey*';
$filters = '{"category":"Automotive","$loc":{"$within":{"$center":[[41,-74],80467.2]}},"website":{"$blank":false}}';
$params = '?api_key=' . $apiKey . '&filters=' . url_encode($filters);
$url = 'http://api.factual.com/v2/tables/bi0eJZ/read';
$url .= $params;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$output = curl_exec($ch) or die("cURL Error" . curl_error($ch));
curl_close($ch);
echo "out: " . $output;
Run Code Online (Sandbox Code Playgroud)
编辑:
另一种方法是使用 Factual API 的官方 PHP 驱动程序: Official PHP driver for the Factual API
此代码仅用于测试,只需根据我的代码修改您的代码即可
<?php
$useragent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
Chrome/8.0.552.224: Safari/534.10'; // notice this
$url="http://api.factual.com/v2/tables/bi0eJZ/read?api_key=*apikey*&filters={\"category\":\"Automotive\",\"\$loc\":{\"\$within\":{\"\$center\":[[41,-74],80467.2]}},\"website\":{\"\$blank\":false}}";
$ch = curl_init(); // notice this
curl_setopt($ch, CURLOPT_URL, $url); // notice this
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$contents = curl_exec($ch);
echo $contents;
?>
Run Code Online (Sandbox Code Playgroud)