我正在尝试将 Twitter API 1.1 与 symfony2 和 twig 一起使用。到目前为止,我已成功将所有推文作为数组传递给模板,但我无法仅获取最新推文。
除了数字或帖子外,一切正常,所以我发布了完整的代码来帮助其他人。
推特功能
public function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
public function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
public function twitter_latest(){
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "***";
$oauth_access_token_secret = "***";
$consumer_key = "***";
$consumer_secret = "***";
$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 = $this->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($this->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);
return $twitter_data;
}
控制器:
/**
* Index page
*
*/
public function indexAction()
{
$twitters = $this->twitter_latest();
return $this->render('mwwqTestBundle:Main:index.html.twig', array("twitters" => $twitters));
}
树枝模板:
<div id="mainTwitter">
<ul id="twitter_update_list">
{% for twitter in twitters %}
{{ twitter.text }}
{% endfor %}
</ul>
</div>
{{ twitter.text[0] }}, {{ twitter[0].text }}, {{ twitter.text.[0] }}
不工作