PHP Curl and Loop based on a numeric value

Im using the Twitter API to collect the number of tweets I've favorited, well to be accurate the total pages of favorited tweets.

I use this URL:

I grab the XML element 'favorites_count'

For this example lets assume favorites_count=5

The Twitter API uses this URL to get the favorties: (Must be authenticated)

You can only get the last 20 favorties using this URL, however you can alter the URL to include a 'page' option by adding: ?page=3 to the end of the favorites URL e.g.

So what I need to do is use CURL (I think) to collect the favorite tweets, but using the URL:

?page=1



?page=3

?page=4

etc...

Some kind of loop to visit each URL, and collect the Tweets and then output the cotents.

Can anyone help with this: - Need to use CURL to authenticate - Collect the number of pages of tweets (Already scripted this) - Then use a loop to go through each page URL based on the pages value?


ANSWERS:


Is favorites_count the total number of favorites or the total number of pages?

$twitter = curl_init('');
curl_set_opt($twitter, CUROPT_RETURNTRANSFER, true);

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

$urlTpl = "http://?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.

Now if favorites_count is the total number of favorites and not pages then you need to modify the above to figure out how many pages there are based on how many favorites are on a page. but thats pretty simple.



 MORE:


 ? Background login with OAuth
 ? LinkedIn / Twitter / Facebook as OAuth and OpenId use
 ? Use the Twitter API to run a script every time I post a new tweet
 ? Using the @ symbol to identify users like twitter does
 ? Twitter APIs for blackberry implementation
 ? Problem with twitter API: cannot update status
 ? Using oAuth (Twitter, LinkedIn) for login to a web app
 ? How to do a RETWEET on an iPhone twitter app (MGTwitterEngine)
 ? How to see if a user is following you on Twitter using C# Twitter API wrapper Tweetsharp
 ? Create a new delegate class for each asynchronous image download?