PHP Telegram bot gives empty variables from Google Maps API response

I’m developing a Telegram bot in PHP that’s supposed to access the Google Maps Distance Matrix API to get travel information. While the code runs correctly on testing platforms, it returns empty values when the bot is operational.

Here’s my code snippet:

$apiUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=New+York&destinations=Brooklyn&mode=driving&sensor=false";
$jsonData = file_get_contents($apiUrl);
$dataArray = json_decode($jsonData, TRUE);
$travelDistance = $dataArray[rows][0][elements][0][distance][text];
$travelTime = $dataArray[rows][0][elements][0][duration][text];
$botMessage = "Travel time: $travelTime. Distance to cover: $travelDistance";

$botParams = array('chat_id' => $userId, "text" => $botMessage);
$botParams["method"] = "sendMessage";
echo json_encode($botParams);

The response from the bot is:

"Travel time: {. Distance to cover: {"

However, the API response appears correct:

{
   "destination_addresses" : [ "Brooklyn, NY, USA" ],
   "origin_addresses" : [ "New York, NY, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "8.2 mi",
                  "value" : 13201
               },
               "duration" : {
                  "text" : "28 mins",
                  "value" : 1680
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Why are my variables returning empty fields? It seems like the JSON decode function is operating correctly, but accessing the array isn’t yielding the expected results.

The Problem:

Your Telegram bot, designed to fetch travel information from the Google Maps Distance Matrix API using PHP, returns empty values when operational, despite working correctly on testing platforms. The JSON decoding appears successful, but accessing the array elements yields unexpected results. The bot’s response shows empty braces ("Travel time: {. Distance to cover: {" ) instead of the expected travel time and distance.

:thinking: Understanding the “Why” (The Root Cause):

The core issue lies in how you’re accessing elements within the decoded JSON array. PHP requires string keys to be enclosed in single quotes when accessing associative arrays. Without the quotes, PHP treats rows, elements, distance, and duration as constants, leading to empty values. Additionally, the Google Maps Distance Matrix API requires authentication via an API key. Without it, you’ll receive incomplete or erroneous responses.

:gear: Step-by-Step Guide:

Step 1: Correct Array Access Syntax:

Modify your code to include single quotes around the array keys:

$apiUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=New+York&destinations=Brooklyn&mode=driving&sensor=false&key=YOUR_API_KEY"; // Add your API key here!
$jsonData = file_get_contents($apiUrl);
$dataArray = json_decode($jsonData, TRUE);

//Corrected array access
if (isset($dataArray['rows'][0]['elements'][0]['distance']['text'])) {
    $travelDistance = $dataArray['rows'][0]['elements'][0]['distance']['text'];
} else {
    $travelDistance = "Distance data unavailable"; //Handle cases where data is missing
}

if (isset($dataArray['rows'][0]['elements'][0]['duration']['text'])) {
    $travelTime = $dataArray['rows'][0]['elements'][0]['duration']['text'];
} else {
    $travelTime = "Duration data unavailable"; //Handle cases where data is missing
}

$botMessage = "Travel time: " . $travelTime . ". Distance to cover: " . $travelDistance;

$botParams = array('chat_id' => $userId, "text" => $botMessage);
$botParams["method"] = "sendMessage";
echo json_encode($botParams);

Step 2: Include Your Google Maps API Key:

Replace YOUR_API_KEY with your actual Google Maps API key. You must obtain this key from the Google Cloud Console. Failure to include this key will result in API errors and empty responses.

Step 3: Implement Robust Error Handling:

The provided code lacks error handling. The API might fail for various reasons (network issues, rate limits, incorrect API key). Wrap your API call in a try...catch block to handle potential errors gracefully:

try {
    //Your API call and data processing from Step 1 here...
} catch (Exception $e) {
    $botMessage = "Error fetching travel information: " . $e->getMessage();
    // ...send error message to the bot...
}

Step 4: Verify API Response:

Before accessing the data, always check if the API request was successful. Inspect the status field in the JSON response:

if ($dataArray['status'] !== 'OK') {
    $botMessage = "Google Maps API returned an error: " . $dataArray['status'];
    // ...send error message to the bot...
}

:mag: Common Pitfalls & What to Check Next:

  • API Key Restrictions: Ensure your Google Maps API key has the correct permissions and is not restricted by usage limits.
  • Network Connectivity: Check if your server has proper internet access.
  • Rate Limiting: If you’re making many requests, you might be hitting Google Maps API’s rate limits. Implement request throttling or consider using a caching mechanism.
  • Incorrect Origin/Destination: Double-check the origins and destinations parameters in your API request. They must be correctly formatted addresses or place IDs.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Your array syntax is missing quotes around the keys. PHP needs string keys quoted when you’re accessing associative arrays.

Change this:

$travelDistance = $dataArray[rows][0][elements][0][distance][text];
$travelTime = $dataArray[rows][0][elements][0][duration][text];

To this:

$travelDistance = $dataArray['rows'][0]['elements'][0]['distance']['text'];
$travelTime = $dataArray['rows'][0]['elements'][0]['duration']['text'];

Without quotes, PHP thinks these are constants instead of string keys - that’s why you’re getting empty values. You should also add error checking for the API response and make sure you’re including your API key in the request URL since Google Maps API requires authentication.

Had the same problem with PHP bots and APIs. Besides the missing quotes thing others mentioned, you need to debug what’s actually coming back. Log the raw JSON response and the decoded array before you try to grab values. One thing I spotted - you’re missing an API key in your request URL. Google Maps has required auth for ages now, so without it you’ll get weird responses or hit rate limits. Just add &key=YOUR_API_KEY to your URL. Also throw in a quick check like if (isset($dataArray['rows'][0]['elements'][0]['distance']['text'])) before accessing values. APIs love changing their response structure, and this’ll stop your bot from crashing when they do.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.