How to iterate through JSON data in a Telegram bot?

Hey everyone, I’m stuck with my Telegram bot. I’m trying to loop through some JSON data to create a response when a user types a specific command like MENU. Here’s what I’ve got so far:

$menu_data = file_get_contents('menu_url.json');
$menu_items = json_decode($menu_data);

foreach ($menu_items as $item) {
    $output = $item->category;
    $output .= ' ' . $item->dish;
}

The weird thing is, this code works fine outside of my Telegram bot, but when I use it in the bot, it doesn’t loop through all the items. It’s like it’s only grabbing the last item or something. Any ideas what might be going wrong here? I’m totally stumped!

hey, sparklinggem try pushing each item into an array:

$arr[] = $item->category . ' ' . $item->dish;

the next step is to join them with implode. hope it helps!

One thing to consider is the memory limit of your PHP script. When working with large JSON datasets in Telegram bots, you might hit PHP’s memory limit, causing unexpected behavior. Try increasing the memory limit using ini_set(‘memory_limit’, ‘256M’) at the beginning of your script.

Also, ensure you’re not exceeding Telegram’s message length limit (4096 characters). If your menu is extensive, you might need to split it into multiple messages. Here’s a quick way to do that:

$chunk_size = 4000;
$chunks = str_split($output, $chunk_size);
foreach ($chunks as $chunk) {
    $bot->sendMessage($chat_id, $chunk);
}

This will send your menu in digestible chunks, avoiding any truncation issues.

I encountered a similar issue when working with JSON data in my Telegram bot. The problem might be related to how Telegram handles messages. Instead of building the output string directly in the loop, try creating an array of formatted items first:

$menu_items = json_decode($menu_data, true); // Decode as associative array
$formatted_items = [];

foreach ($menu_items as $item) {
    $formatted_items[] = $item['category'] + ': ' + $item['dish'];
}

$output = implode("\n", $formatted_items);

This approach ensures all items are processed before sending the message. Also, make sure your JSON is valid and properly structured. If the issue persists, consider logging the raw JSON data to check if it’s being received correctly by your bot.