Search code examples
phptwitter-oauth

How to print tweet's hyperlink in TwitterOAuth


I am using TwitterOAuth to tweet from my own PHP code. everything is working fine. I just want to know how can I echo tweet's hyperlink that user has just tweeted through my PHP app. Here is my code that I am using for tweet posting:

<?php

//LOADING LIBRARY
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;


$consumer_key = '';
$consumer_secret = '';
$access_token = "";
$access_token_secret = "";


$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
$content = $connection->get("account/verify_credentials");

$statues = $connection->post("statuses/update", array("status" => "hello world"));

if ($connection->getLastHttpCode() == 200) {
    echo 'Tweet posted succesfully';

} else {
    echo 'Handle error case';
}

?>

Solution

  • The response that Twitter statuses/update gives out after you post a Tweet is documented here.
    For me, it looks something like this -

    Array
    (
        [id_str] => 662128569695383552
        ...
        [user] => stdClass Object
            (
                [screen_name] => couchthomas
                ...
    

    The id_str and the screen_name can be used to build the Tweet url.

    https://twitter.com/<screen_name>/status/<id_str>
    

    So, if you get a response like the one above, it would look something like this -

    $id_str = $statues["id_str"];
    $screen_name = $statues["user"]->screen_name;
    $tweet_url = "https://twitter.com/$screen_name/status/$id_str";
    

    Try var_dumping the $statues variable and build it accordingly.

    EDIT Now that I've the OP output, clarifying this answer.
    The output looks like this -

    object(stdClass)#7 (23) { 
        ["created_at"]=> string(30) "Thu Nov 05 12:17:43 +0000 2015" 
        ["id"]=> int(662242385318014977) 
        ["id_str"]=> string(18) "662242385318014977" 
        ...
        ["user"]=> object(stdClass)#22 (40) 
            { 
                ...
                ["name"]=> string(8) "Eggs Lab" 
                ["screen_name"]=> string(7) "EggsLab" 
    

    So, accordingly, you can fetch the id_str of the tweet(which is a direct key statues) and the user's screen_name(which is a nested in the obj user inside $statues) by -

    $id_str = $statues->id_str;
    $screen_name = $statues->user->screen_name;
    

    and create the tweet url as explained above.