Front-End & Daily

How to tweet with line breaks using Twitter API in PHP

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.

Twitter API tweet line break \n

Conclusion

Do this.

// Tweet text
$tweet = '改行の'."\n".'テストです。';

Then a line break was added.

Twitter API tweet add line break

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.

Comments

After reviewing the content, we will publish it, omitting any personal information.

Enter your name and email address too

Please enter if you would like a reply by email.

The personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and click 'Send'.

If this was helpful, we'd appreciate your support!
Your support will be used for childcare.

Send support via OFUSE


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

As an Amazon Associate, 'Ken' earns from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark