2012-07-04 200 views
1

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

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

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复制数据,并把它放在单引号我收到的数据里面,而是试图从我得到什么网址获取数据。

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

回答

1

你的脚本工作正常,它可能是$超时?尝试将其设置得更高(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对象。

0

你的http请求看起来并不特殊,所以不需要curl,试着用file_get_contents('http://lab.volzy.dk/index.json')替换你的get_data()。

+0

如果可以,请始终使用卷曲,速度要快得多。 http://www.anildewani.com/benchmarking-file_get_contents-and-curl-whose-faster/ –