douzheng1853 2013-06-18 18:18
浏览 80

使用cURL从URL获取JSON数据

I am trying to read JSON from a URL and I can't get cURL to retrieve the data.

I have the following PHP:

$curl = curl_init($url);

$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 5,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER =>array('Accept: application/json', "Content-type: application/json"),
CURLOPT_FAILONERROR => FALSE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_SSL_VERIFYHOST => FALSE
);

curl_setopt_array($curl, $options);

$response = curl_exec($curl);
print "curl_error returned: ".curl_error($curl)."
 <br />
";
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
print "Status of HTTP: ".$status."
";
$response = json_decode($response);
print_r($response)

The problem is that this returns as:

curl_error returned: couldn't connect to host
Status of HTTP: 0

The JSON data I am reading is about 300 characters total, and is not formatted (does this matter?) What I mean by not formatted is that the JSON is all on one line.

I tried using fopen() and file_get_contents(), but that did the same thing (returned nothing).

Another problem I am encountering is the time it takes to connect. When I visit the URL in browser it renders the JSON immediately, but when I use cURL (or file_get_contents() for that matter) it takes a very long time to complete. That's why I specifically limited the timeouts. If I let the time outs go with not limit, the page renders after about 2 minutes with the same results as with the time out.

I'm not sure how I can read this URL now. To give a description of the URL contents, it is literally just JSON data rendered on one line (and it's not a large file, it's actually fairly small). If it matters, there is some 'Get' information in the URL.

Thanks for any help.

Someone suggested that this might be a firewall/connectivity issue, but from my end I am able to send requests to other websites and check their status codes accurately. On the URL's end, I am able to access it through my browser...?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 求数据集和代码#有偿答复
    • ¥15 关于下拉菜单选项关联的问题
    • ¥20 java-OJ-健康体检
    • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
    • ¥15 使用phpstudy在云服务器上搭建个人网站
    • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
    • ¥15 vue3+express部署到nginx
    • ¥20 搭建pt1000三线制高精度测温电路
    • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
    • ¥15 画两个图 python或R