Rick's Tech Talk

All Tech Talk, Most of the Time

Getting Twitter User IDs with PHP

When using the Twitter API's "Streaming API", you often have to pass in Twitter User IDs as arguments, rather than Twitter usernames (aka "screen name"). I wrote a small command-line PHP program that obtains Twitter User IDs from Twitter usernames. This is what it looks like when you run it:

$ php getuserid.php rickumali yomamali
21111241 => Ranniel Umali (yomamali)
16067265 => Rick Umali (rickumali)
I liked writing this little program. There's one line (line 2 below) that reminded me of Perl, for its quirky keyword:

  1. unset($argv[0]); # Removes the program from the argument array list
  2. $lookup .= implode(',',$argv); # Comma separate the arguments
In Perl, you'd use join (with the same arguments) to achieve this (though in PHP the argument array contains the command in the 0th index. I unset this variable in line 1.)

Another thing that was interesting was PHP's "built-in" JSON support. In general, you should be using JSON to interact with the Twitter API, and you should hope for JSON to be in your PHP already. In my code, I have this:

  1. $data = json_decode($json);
  2. if (is_array($data)) {
  3.   foreach ($data as $user) {
  4.     print $user->{'id'} . " => " . $user->{'name'} . " (" . $user->{'screen_name'} . ")\n";
  5.     $id_list[] = $user->{'id'};
  6.   }
  7. }
I reference the elements (line 4) inside the $user object with the arrow operator because json_decode(), by default, returns objects (not arrays). If I had specified json_decode($json, TRUE), then the user object is a PHP array, and I could then use $user['id'] to obtain the id value.