2010-03-30 28 views
0

即時通訊使用Twitter API收集我已經收藏的推文數量,以及準確計算出收藏推文的總頁數。基於數值的PHP捲曲和循環

我用這個網址:http://api.twitter.com/1/users/show/username.xml

我搶了XML元素 'favorites_count'

對於這個例子讓我們假設favorites_count = 5

Twitter的API使用這個網址來獲得favorties :http://twitter.com/favorites.xml(必須經過身份驗證)

您只能使用此URL獲取最後20個優惠,但是您可以更改要包含的網址通過在收藏夾網址的末尾添加:?page=3來創建「網頁」選項。

http://twitter.com/favorites.xml?page=2

所以我需要做的是使用捲曲(我認爲),收集喜歡的鳴叫,但使用的網址:

http://twitter.com/favorites.xml?page=1 

http://twitter.com/favorites.xml?page=2 

http://twitter.com/favorites.xml?page=3 

http://twitter.com/favorites.xml?page=4 

etc... 

一些類型的循環來訪問每個URL,並收集推文,然後輸出cotents。

任何人都可以在這方面幫助: - 需要使用curl驗證 - 收集的鳴叫(已腳本本)的頁數 - 然後使用一個循環都要經過基於網頁值的每個頁面的網址?

回答

0

是favorites_count收藏夾總數還是總頁數?

$twitter = curl_init('http://api.twitter.com/1/users/show/username.xml'); 
curl_set_opt($twitter, CUROPT_RETURNTRANSFER, true); 

$userInfo = curl_exec($twitter); 
$userObj = new SimpleXmlElement($userInfo); 
$nbFaves = $userObj->favorites_count; // (string) 5 

$urlTpl = "http://http://twitter.com/favorites.xml?page=%s"; 
$favorites = array(); // this will be the data for output 

for($i =0; $i < $nbFaves; $i++) { 
    $pageUrl = sprintf($urlTpl, $i+1); // notice the +1 to move from 0 indexed to 1 indexed 
    curl_set_opt($twitter, CURLOPT_URL, $pageUrl); 
    $faves = curl_exec($twitter); 
    $faves = new SimpleXmlElement($faves); 

    foreach($faves->favorite as $fave) { 
    $data = array(); 
    /* here you assign the diferent child values/attributes 
     * from the favorite node to the $data array 
     */ 
    $favorites[] = $data; // push the data array into $favorites 
    } 

    unset($faves); // just some cleanup 

} 

// now you would loop through $favorites and output the data as html. 

現在,如果favorites_count是收藏夾的總數,而不是網頁,那麼你需要修改上面找出多少頁有基於多少最喜歡的是一個頁面上。但那很簡單。

+0

favorites_count返回收藏夾的數量,但我除以20並將數字向上捨去以獲得總頁數。 – CLiown 2010-03-30 19:33:53

+0

試過它調用未定義的函數。 – CLiown 2010-03-30 19:41:27

+0

在什麼行/函數調用? – prodigitalson 2010-03-30 20:32:00