1

我有一个 json 脚本,我需要使用 CURL 和 json_decode 将其转换为 PHP 数组。CURL 位是通过函数完成的。我的 $getcontent 有数据,但是一旦我把它通过 json_decode,$content 是空的。

它只是返回一个空字符串。

PHP

$url='http://lab.volzy.dk/index.json';
$getcontent = get_data($url);

$content = json_decode($getcontent, true);

if(empty($getcontent)) {
echo "getcontent empty";
} else {
echo "getcontent not empty";
}

if(empty($content)) {
echo "content empty";
} else {
echo "content not empty";
}

function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

如果我从 URL 复制数据并将其放在单引号内,我会收到数据,但尝试从 URL 获取数据我什么也得不到。

有人知道如何解决这个问题吗?

4

2 回答 2

1

您的脚本运行良好,可能是 $timeout 吗?尝试将其设置得更高(15)。

function get_data($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}


$url='http://lab.volzy.dk/index.json';
$getcontent = get_data($url);


$content = json_decode($getcontent, true);

var_dump($content);

我得到了一个不错的 json 对象。

于 2012-07-04T14:28:06.053 回答
0

你的http请求好像没什么特别的,所以不需要curl,试试把你的get_data()换成file_get_contents('http://lab.volzy.dk/index.json');

于 2012-07-04T14:37:29.843 回答