搜索Twitter用户并在自己的页面上显示结果

时间:2016-03-14 12:34:57

标签: php api twitter twitter-oauth

我刚刚在我的页面上实现了Twitter登录,它运行良好。我接下来要做的是为我的用户提供搜索栏,他们可以在这里查找推特用户并发送推文。我正在查看Twitter文档,但还没有找到一个这样的例子。我将不胜感激任何帮助!

1 个答案:

答案 0 :(得分:0)

好的,所以我找到了我自己的问题的解决方案,并想分享给遇到同样问题的每个人。实际上这很简单,我只需要了解JSON原理(仍然是新手)。

所以这是我的(简化)代码:



    session_start();

    require '../twitteroauth/autoload.php';

    use Abraham\TwitterOAuth\TwitterOAuth;

    define('CONSUMER_KEY', ''); // add your app consumer key between single quotes
    define('CONSUMER_SECRET', ''); // add your app consumer secret key between single quotes
    define('OAUTH_CALLBACK', 'http://yourdomain.com/callback.php'); // your app callback URL


    if (!isset($_SESSION['access_token'])) {
        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
        $request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
        $_SESSION['oauth_token'] = $request_token['oauth_token'];
        $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

        $url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
        echo $url;
    } else {
        $access_token = $_SESSION['access_token'];
        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

        $parameters = array('q' => 'chrischaos'); // this is where you put the seach-term

        $users = $connection->get('users/search', $parameters);


        foreach($users as $user) {
            $user = get_object_vars($user);
            echo $user['screen_name'];
        }

    }


干杯!