Telegram bot not displaying all items from JSON array

I have a telegram bot that should show menu items from a JSON file when someone types a command. The JSON contains multiple food items but my bot only shows the last one instead of all of them.

Here’s my code:

$data = file_get_contents('https://restaurant-api.com/items.json');
$items = json_decode($data);
foreach ($items as $item)
{
   $message = $item->category;
   $message = $message." - ".$item->name;
}

When I run this same code in a regular PHP script it works perfectly and shows all menu items. But inside my telegram bot it only displays one item. How can I make the bot show the complete list of items from the JSON data?

ur just overwriting $message w each loop. init it as empty string b4 the loop: $message = ""; then use $message .= $item->category . " - " . $item->name . "\n"; to keep everything.

Your issue lies with how you’re handling the $message variable within the loop. Since you are overwriting it each time, only the last item is displayed. To fix this, initialize $message as an empty string before the loop starts. Then, use .= to append each item to $message. This way, you’ll construct the full list of menu items, which you can send to your Telegram bot once the loop is complete.

You’re overwriting the same variable each time instead of building up your message. I encountered this exact bug when I made my first bot last year. Set $message = ''; before your loop starts. Then inside the loop, use $message .= $item->category . " - " . $item->name . "\n"; instead. The .= appends to what’s already there rather than wiping it clean. Once the loop finishes, send that built-up $message to Telegram and you’ll get all your items.

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