Question

I send a GET request to a server using curl and get back json data. When I print this data in the browser I can see the proper json structure without slashes(magic quotes turned off)-no problem at all.

Even when I copy paste this json data from the browser to another php file in a variable and then try to decode it it works fine. The data is decoded in that file.

However after getting the data from the cURL request when I try to decode the data it fails. All it returns is: Array

Here is what I'm trying:

$resp = curl_exec($curl);
$d=json_decode($resp,true);

I don't know why this weird behaviour?? I have tried almost everything mentioned in this thread json_decode returns NULL after webservice call

I've also detected the encoding of the string returned by cURL call using mb_detect_encoding and it is UTF-8

This thing is driving me crazy...

Update: OK.....it seems json_decode has infact decoded the data and returned in $d variable but I'm not able to access the element from the array. I used print_r to see the structure of the array. It is somewhat lik this:

Array ( 
    [response] => Array ( 
                    [start] => 0 
                    [docs] => Array ( 
                              [0] => Array ( 
                                       [id] => S132250037010452  
                                       [slno] => 452 
                                     ) 
                            )
                    [numFound] => 1 
                  ) 
) 



When I try to access the element id using:

echo $d[response][docs][0][id];

I get a notice stating: Use of undefined constant response - assumed 'response' on that line. What does this mean??

Was it helpful?

Solution

After your edit, to access this field you need to enclose between '

echo $d['response']['docs'][0]['id']; // <--- Will return 'S132250037010452'

If you don't enclose the names, PHP will try to use as constants

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top