如何使用laravel从twitter API获取所有可用的用户搜索记录

时间:2016-03-07 06:23:38

标签: php json laravel twitter laravel-5

我正在开发twitter API(https://api.twitter.com/1.1/users/search.json)。当我使用GET请求请求用户记录时,我只获得了json前20条记录中的第一页记录,但我想要输入任何特定名称的所有记录。如何扩展请求并将它们存储在数据库中

public function getTwitter() {
    $settings = array(
        'oauth_access_token'        => "xxxxxxxxxxxxxx",
        'oauth_access_token_secret' => "xxxxxxxxxxxxxxxx",
        'consumer_key'              => "xxxxxxxxxxxxxxxxxxxxx",
        'consumer_secret'           => "xxxxxxxxxxxxxxxxxxxxxxx",

    );


    $url           = 'https://api.twitter.com/1.1/users/search.json';
    $getfield      = '?q=name to search';
    $requestMethod = 'GET';

    $twitter = new TwitterAPIExchange($settings);
    $users   = $twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)
        ->performRequest();

    $users = json_decode($users, true);
    // var_dump($users);die();
    for ($i = 0; $i <= 19; $i++) {
        $twitter           = new twitter_user();
        $twitter->user_id  = $users[$i]['id'];
        $twitter->name     = $users[$i]['name'];
        $twitter->sname    = $users[$i]['screen_name'];
        $twitter->location = $users[$i]['location'];
        $twitter->save();

    }

    echo "Data saved";
}

我使用这个循环直到19,因为它给了我20条记录,我想动态访问所有可用记录。

1 个答案:

答案 0 :(得分:2)

 public function full_Record($page){  

    $settings = array(
        'oauth_access_token' => "xxxxxxxxxxxxxxxxxxxxxxx",
        'oauth_access_token_secret' => "xxxxxxxxxxxxxxxxxxxx",
        'consumer_key' => "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
        'consumer_secret' => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        );   
    $url = 'https://api.twitter.com/1.1/users/search.json';
    $getfield = '?q=john&page='. $page;
    $requestMethod = 'GET';

    $twitter = new TwitterAPIExchange($settings);
    $users =  $twitter->setGetfield($getfield)
            ->buildOauth($url, $requestMethod)
            ->performRequest();

    $users = json_decode($users,true);
    if(empty($users)){


        echo "Data saved less data available";
    }
    else{

            for($i=0;$i<=19;$i++){

                $twitter=new twitter_user();
                $twitter->user_id=$users[$i]['id'];
                $twitter->name=$users[$i]['name'];
                $twitter->sname=$users[$i]['screen_name'];
                $twitter->location=$users[$i]['location'];
                $twitter->save();

            }

                $page++;
                $this->full_Record($page);                  

            else{
                echo "Data Saved ok";
            }

    }

本规范按要求运作