I have a list of websites where I want to see if they have twitter accounts. I was curious if there is a url search for username in the API, or something of this nature. I've been reading and looking around; however, I've come up short. I would hate to have to do this manually when I could run a function to do the work for me. Would greatly appreciate some feedback on this topic.
Good day!
As explained in the comment above, version 1 of the twitter API is deprecated and will soon be removed completely. This means that simple requests will not work any more once it has been removed, which is real soon!
Basically, from then on, in order to get any sort of data from twitter, you need to make authenticated requests using their version 1.1 api.
I wrote a post here which explains, with pretty pictures for those who need them, the exact steps required to make calls to their version 1.1 api using PHP.
Here's what you want to do, after you have read the above post thoroughly.
I'm going to assume you know a little PHP. This is how you would use the twitter v1.1 api to check if a username exists or not.
Take a look at the docs for getting a user's timeline. The docs state you can use a screen_name parameter. You also know it requires a GET request.
Armed with the above information, and my class, you can perform a request for a user pretty easily.
Okay, so the result is now stored in the
$result
variable. You can do what you want here. You want to check the user exists, sovar_dump()
the result and look for how to figure out if the user exists or not. Clearly it won't contain an actual user, it may containfalse
ornull
.As I don't know off the top of my head, lets say
$result->user
is equal tofalse
. You would simply do this:... or, short-hand style (I like adding little things like this to my posts)
Do a little research, using:
Here's my code that checks if the user does exist, based on Jimbo's very useful PHP class as detailed above.
First, use json_decode to convert
$result
into a PHP array. Make sure to set the second parameter totrue
so that you won't get Objects in the resulting array:Now you have to check if the
screen_name
array key exists, but array_key_exists doesn't recursively look through multidimensional arrays. So you'll need a new function as found here:And below is the final piece of code that makes it all work. Note where I'm pointing to in the
$result
array. I'm basically looking at the screen_name of the user who posted the first tweet, since the Twitter API returns the timeline of the user as specified in $username.I'm not sure if there's a better way to check if the username exists. Maybe just use check for an error code instead?