Justin Liang
Justin Liang

Reputation: 211

get JSON data from url via curl

I am trying to get JSON data from the url via curl connection. When I open the link: it shows {"version":"N/A","success":true,"status":true}.
Now, I want to get above content.

So far I have use this:

$loginUrl = 'http://update.protect-website.com/index.php?plugin=firewall&action=getVersion';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$loginUrl);
$result=curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result));

However, I always get NULL, Does someone have idea where is wrong?

Upvotes: 4

Views: 16044

Answers (3)

Moredhel
Moredhel

Reputation: 1

curl_setopt($ch, CURLOPT_HEADER, 0);

Upvotes: -1

xdazz
xdazz

Reputation: 160963

The website check the user agent. Add an agent option, and it will work.

$loginUrl = 'http://update.protect-website.com/index.php?plugin=firewall&action=getVersion';
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$result=curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result));

Upvotes: 5

danschmidt5189
danschmidt5189

Reputation: 151

You're getting NULL because json_decode isn't able to parse the returned string.

From the docs:

Return Values: ... NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Try dumping the $result variable instead to see what it looks like. It's possible CURLOPT_HEADER=true, in which case the headers would make the response invalid JSON.

Edit: After checking your API endpoint, it seems to be valid JSON. While this doesn't bear on your specific question, you should set the Content-Type: application/json header.

Upvotes: 1

Related Questions