Get JSON data from url via curl

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

So far I have used 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 anyone have an idea where is wrong?

+4
source share
3 answers

The website is being verified by the user agent. Add an agent parameter 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)); 
+5
source

You get NULL because json_decode cannot parse the returned string.

From the docs:

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

Try resetting the $ result variable to see how it looks. Perhaps CURLOPT_HEADER = true, in which case the headers will invalidate the JSON response.

Edit: After checking the API endpoint, it seems to be valid JSON. Although this is not related to your specific question, you should set the Content-Type: application / json header.

+1
source
 curl_setopt($ch, CURLOPT_HEADER, 0); 
-one
source

Source: https://habr.com/ru/post/1494389/


All Articles