1

I have a json script which I need to convert to PHP array with CURL and json_decode. The CURL bit is done via a function. My $getcontent has data, but once I put it through json_decode, $content is empty.

It simply returns an empty string.

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;
}

If I copy data from the URL and put it inside single quotes I receive data, but trying to get data from the URL I get nothing.

Anybody who has a clue on how to fix this?

2 Answers 2

1

Your scripts works fine ,could it be the $timeout? try setting it higher ( 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);

I get a nice json object.

Sign up to request clarification or add additional context in comments.

Comments

0

Your http request does not seem to be special, so there is no need for curl, try replacing your get_data() by file_get_contents('http://lab.volzy.dk/index.json');

1 Comment

Always use curl if you can , it is much faster. anildewani.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.