0

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??

Community
  • 1
  • 1
Alok
  • 63
  • 1
  • 10
  • What did you set for your `curl_setopt`? If you `var_dump($resp)` what does it show? – Javad May 08 '14 at 15:05
  • ok some progress.....I'm able to see the structure of the array using print_r, which means the json is decoded, but still not able to access the elements – Alok May 08 '14 at 15:14

1 Answers1

0

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

Sal00m
  • 2,938
  • 3
  • 22
  • 33
  • still the same result. this time error also has the quote. Use of undefined constant response - assumed 'response' – Alok May 08 '14 at 16:40
  • It's not possible to get the same result.... if you use `'` or `"` PHP doesn't try to use as constants. Are you sure you write exactly as i wrote? (or with `"` instead of `'`) – Sal00m May 08 '14 at 16:43
  • double quotes finally worked for me......thanks man you made my day....:) – Alok May 08 '14 at 16:48