get JSON data from url via curl

15,890

Solution 1

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

Solution 2

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.

Share:
15,890
Justin Liang
Author by

Justin Liang

Updated on August 22, 2022

Comments

  • Justin Liang
    Justin Liang over 1 year

    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?