Twitter API: Url search for Username

后端 未结 2 747
梦毁少年i
梦毁少年i 2021-01-17 04:56

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\'

2条回答
  •  感情败类
    2021-01-17 05:34

    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 to true so that you won't get Objects in the resulting array:

    $result = json_decode($result, true);
    

    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:

    function array_key_exists_r($needle, $haystack) {
        $result = array_key_exists($needle, $haystack);
    
        if ($result) return $result;
    
        foreach ($haystack as $v) {
            if (is_array($v)) {
                 $result = array_key_exists_r($needle, $v);
            }
            if ($result) return $result;
        }
    
        return $result;
    }
    

    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.

    $result = json_decode($result, true);
    
    if ( array_key_exists_r('screen_name', $result ) ) {
        if ( $result[0]['user']['screen_name'] == $username ) {
            // The username exists
        }
    } else {
        // The username doesn't exist
    }
    

    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?

提交回复
热议问题