Search code examples
phpapicurlphp-curl

API GET request values cannot set to variables and echo using curl json_decode in PHP


Why can't I echo $phone_number in this code? It says

Undefined index: phone_number. but when I echo $response it returns the values

    <?php

        $ch = curl_init( 'https://mighty-inlet-78383.herokuapp.com/api/hotels/imagedata');
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => TRUE
        ));

        // Send the request
        $response = curl_exec($ch);

        // Check for errors
        if($response === FALSE){
            die(curl_error($ch));
            echo 'No responce';
        }

        // Decode the response
        $responseData = json_decode($response);

        // Print the date from the response
        $phone_number = $responseData['phone_number'];
        echo $phone_number;
   ?>

Solution

  • Because these are arrays within arrays you need to go one level deeper to get the data you want. First, make sure you're returning the JSON as an array, using the 'true' attribute:

    $responseData = json_decode($response, true);
    

    Then you can get the first phone number (or any phone number by changing the array index):

    echo $responseData[0]['phone_number'];
    echo $responseData[1]['phone_number'];
    

    You can also loop through the responses:

    foreach($responseData AS $response) {
        echo $response['phone_number'];
    }