Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

前端 未结 14 2466
盖世英雄少女心
盖世英雄少女心 2020-11-21 17:37

Because of the Twitter API 1.0 retirement as of June 11th 2013, the script below does not work anymore.

// Create curl resource 
$ch = curl_init(); 
// Set u         


        
14条回答
  •  野的像风
    2020-11-21 18:06

    Go to dev.twitter.com and create an application. This will provide you with the credentials you need. Here is an implementation I've recently written with PHP and cURL.

    $value){
                $r[] = "$key=" . rawurlencode($value);
            }
            return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
        }
    
        function buildAuthorizationHeader($oauth) {
            $r = 'Authorization: OAuth ';
            $values = array();
            foreach($oauth as $key=>$value)
                $values[] = "$key=\"" . rawurlencode($value) . "\"";
            $r .= implode(', ', $values);
            return $r;
        }
    
        $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
    
        $oauth_access_token = "YOURVALUE";
        $oauth_access_token_secret = "YOURVALUE";
        $consumer_key = "YOURVALUE";
        $consumer_secret = "YOURVALUE";
    
        $oauth = array( 'oauth_consumer_key' => $consumer_key,
                        'oauth_nonce' => time(),
                        'oauth_signature_method' => 'HMAC-SHA1',
                        'oauth_token' => $oauth_access_token,
                        'oauth_timestamp' => time(),
                        'oauth_version' => '1.0');
    
        $base_info = buildBaseString($url, 'GET', $oauth);
        $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
        $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature'] = $oauth_signature;
    
        // Make requests
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          //CURLOPT_POSTFIELDS => $postfields,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => $url,
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);
    
        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        curl_close($feed);
    
        $twitter_data = json_decode($json);
    
    //print it out
    print_r ($twitter_data);
    
    ?>
    

    This can be run from the command line:

    $ php .php
    

提交回复
热议问题