json_decode返回空字符串

时间:2012-07-04 11:06:04

标签: curl json string

我有一个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中获取数据我什么都没得到。

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

2 个答案:

答案 0 :(得分: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对象。

答案 1 :(得分:0)

你的http请求似乎并不特别,所以不需要curl,尝试用file_get_contents('http://lab.volzy.dk/index.json')替换你的get_data();

相关问题