Skip to content
Advertisement

Keep getting Undefiend Index when using json_decode

I’m working with an API and I keep getting Undefined Index when trying to echo the data out,

If I use this code:-

    <?php
$registration= $_GET['registration'];

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests/?registration=$registration",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/json",
    "x-api-key: mykey"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);


echo $response;


?>

I get this output:-

[{"registration":"myreg","make":"TOYOTA","model":"PRIUS","firstUsedDate":"2014.10.26","fuelType":"Hybrid Electric (Clean)","primaryColour":"White","motTests":[{"completedDate":"2018.02.07 17:57:53","testResult":"PASSED","expiryDate":"2019.02.06","odometerValue":"21645","odometerUnit":"mi","motTestNumber":"827555092722","rfrAndComments":[]}]}]

And then if I add this to the end of the code

$info=json_decode($response,true);
echo $info['registration'];
     

I get a “Notice: Undefined index: registration”

Looking at the docs for json_decode I cannot see what I am doing wrong. On another API I have used I noticed it was using CURLOPT_CUSTOMREQUEST => “POST”, and had this line underneath CURLOPT_POSTFIELDS => json_encode([‘registration’ => $registration]),

And it would echo out. This one wont and the only difference I see is the GET

So has it got something to do with the CURLOPT_CUSTOMREQUEST => “GET”, line to why I cannot echo anything out?

Thanks in advance for any help

Advertisement

Answer

If the answer is “[{something: whatever}]”, you’re getting an array with an object inside.

So, your registration is actually $info[0]['registration'].

Or you can extract it by first doing $info = $info[0].

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement