How to add new lines in Telegram bot messages using PHP

I’m working on a PHP Telegram bot and having trouble with line breaks in my messages. When I try to use regular newline characters like \n or \r\n, they don’t create actual line breaks. Instead, they show up as underscore characters _ in the final message.

I need to send a message that has multiple lines but can’t figure out the right way to format it. The message should display properly with actual line breaks between different parts of the text.

Here’s what I’m trying to do:

$message = 'Welcome to our service! We hope you enjoy your stay here.';
$message .= "\n";
$message .= 'You will receive daily updates around 7 PM local time with interesting content.';

But this doesn’t work as expected. The newline character shows as an underscore instead of creating a proper line break in the Telegram message.

What’s the correct way to format line breaks in Telegram bot messages when using PHP? I’ve tried different approaches but none seem to work properly.

oh yeah this bugged me for ages too! turns out telegram can be picky about encoding. try htmlspecialchars() on your message first, then use regular \n - works like 90% of the time for me. also make sure youre not accidently url encoding twice, that messes things up bad

Had the exact same issue when I started working with Telegram bots. The underscore problem usually happens when you’re using HTML parse mode but mixing it with regular newlines incorrectly. Try using %0A instead of \n in your message string - this is the URL-encoded newline character that Telegram expects. Alternatively, if you’re using sendMessage with parse_mode set to HTML, make sure you’re using
tags or just regular \n should work fine. The key thing is making sure your parse_mode parameter matches how you’re formatting the message. I’ve found that using %0A is the most reliable method across different scenarios, especially when dealing with URL encoding in API calls.

This underscore issue caught me off guard too when I first encountered it. The problem typically occurs when there’s a mismatch between your message encoding and what Telegram expects. Double newlines often work better than single ones - try using “\n\n” instead of just “\n”. Also check if you’re accidentally setting parse_mode to Markdown, because in Markdown mode underscores have special meaning and can interfere with line breaks. I’ve had success using PHP_EOL constant instead of hardcoded newline characters, as it handles different server environments better. Another thing to verify is your Content-Type header when making the API request - make sure it’s set to application/json if you’re sending JSON data.