andrebruton
andrebruton

Reputation: 2386

Getting Twitter followers with JSON in PHP?

I can get Tweets of users quite easily using PHP and JSON, but as soon as I use it to get a list of followers, I get errors. Both use JSON to return the values.

The code is:

$jsonurl = "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=mooinooicat";
$contents = file_get_contents($jsonurl);
$results = json_decode($contents, true);

echo "<pre>";
print_r($results);
echo "</pre>";

This gives me the following array:

Array
(
    [next_cursor] => 0
    [ids] => Array
        (
            [0] => 31085924
            [1] => 53633023
            [2] => 18263583
        )

    [previous_cursor] => 0
    [next_cursor_str] => 0
    [previous_cursor_str] => 0
)

How do I get the values of next_cursor and previous_cursor and how do I loop just through the ids array?

I want to parse the results for reading into a database.

Upvotes: 0

Views: 3112

Answers (2)

midaym
midaym

Reputation: 83

you are not using the correct api try something like this

function fetch_twitter_count($user) {
    if ($json = file_get_contents("http://api.twitter.com/1/users/show.json?screen_name=$user")) {
        if(empty($json)) return 0;

        $json = json_decode($json['body'], true);

        return number_format(intval($json['followers_count']));
    }
    return 'API Error';
}

have not tested but should do what you want however keep inmind that you will want to use some sort of caching

Upvotes: 1

andrebruton
andrebruton

Reputation: 2386

Thanks for all the answers without examples...

I finally managed to figure it out using the example from Getting values from a single array

Here is the code:

foreach ( $results as $result ) {
  if ( is_array( $result ) ) {
    foreach ( $result as $sub_result ) {
      // You can store this value in a variable, or output it in your desired format.
      echo $sub_result . "<br />";
    }
  } else {
    echo $result . "<br />";
  }
}

Upvotes: 0

Related Questions