我正在嘗試使用Twitter API 1.1與symfony2和樹枝。到目前爲止,我已經成功地將所有推文作爲數組傳遞給模板,但我無法僅獲取最新的推文。使用api 1.1顯示twig和symfony2中的最新tweet
一切工作正常,除了數量或職位,所以我張貼完整的代碼來幫助別人也。
Twitter的功能
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] }}
不工作
如果我想知道怎麼樣,我就已經做到了!如何顯示第5條推文? – Radolino
如果你只想要返回一個,你可以修改它,如https://api.twitter.com/1.1/statuses/user_timeline.json?count=1 - 我想不出一種方法來獲得特定的號碼回來。我會盡快回復你。 –
沒有測試過,但是像這樣:{%if loop.index == 5%} should be working。 –