How to tweet with line breaks using Twitter API in PHP

When tweeting using Twitter API in PHP
You can tweet with code like this, but
require __DIR__ . '\vendor\autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
$TW_CK = 'xxxxx';
$TW_CS = 'xxxxx';
$TW_AT = 'xxxxx';
$TW_ATS = 'xxxxx';
// Create an instance of the TwitterOAuth class
$connect = new TwitterOAuth( $TW_CK, $TW_CS, $TW_AT, $TW_ATS );
// If using Twitter API v2.
$connect->setApiVersion('2');
// Tweet text
$tweet = '改行の\nテストです。';
$result = $connect->post(
'tweets',['text' => $tweet],true
);
If you want to add a line break to the tweet text, this won't work.
// Tweet text
$tweet = '改行の\nテストです。';
It will look like this.

Conclusion
Do this.
// Tweet text
$tweet = '改行の'."\n".'テストです。';
Then a line break was added.

Enclose the main text with single quotes `'`
and concatenate the line break enclosed in double quotes `"`.
This is a technique sometimes used in JavaScript and other languages.
By the way, I also tested other patterns, but
// Tweet text
$tweet = "ダブルとシングルを".'\n'."逆にしたパターン";
// Tweet text
$tweet = 'シングルのみの'.'\n'.'パターン';
// Tweet text
$tweet = "ダブルのみの"."\n"."パターン";
In these cases, `\n` was output as is, and it didn't work.
If you found something different in your environment, or know a better way, please let me know in the comments.




If this was helpful, we'd appreciate your support!
Your support will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
Rakuten Ichiba
Yahoo! Shopping
PR