Skip to content

Instantly share code, notes, and snippets.

@notasausage
Forked from banksy89/gist:3334259
Last active December 20, 2015 10:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notasausage/6115639 to your computer and use it in GitHub Desktop.
Save notasausage/6115639 to your computer and use it in GitHub Desktop.
Return the profile image (avatar) of a Twitter user using their RSS feed (no API call necessary).
<?php
function getTwitterAvatar( $username, $size = "normal" ) {
// mini = 24px, normal = 48px, bigger = 73px
$sizes = array( "mini", "normal", "bigger" );
// Check for size, default to normal
if( in_array( $size, $sizes ) ) {
$variant = $size;
} else {
$variant = "normal";
}
// Get the user's profile image from their RSS feed
$rawxml = simplexml_load_file( "http://twitter.com/users/{$username}.xml" );
$imageurl = $rawxml->profile_image_url;
// Return the image's url with the size requested
if( $variant == "normal" ) {
return $imageurl;
} else {
return str_replace( "normal", $variant, $imageurl );
}
}
?>
@jeffbyrnes
Copy link

@notasausage, an excellent hack! Two things:

  1. I think if you add the opening <?php tag, you'll get syntax highlighting, which is nice.
  2. Line 13, you could just write as: $rawxml = simplexml_load_file( "http://twitter.com/users/{$username}.xml" );
    • Technically, interpolation is faster than concatenation. As a matter of opinion, to me, this way is easier to read w/ syntax highlighting.

@notasausage
Copy link
Author

Thanks for the input, @jeffbyrnes. I've updated this accordingly.

@jeffbyrnes
Copy link

@notasausage you're welcome. Only thing I'd also encourage here would be some kind of local caching. You might check out phpFlickr for an example of some caching that might be able to be borrowed for you needs.

@notasausage
Copy link
Author

That's my plan, @jeffbyrnes. Didn't feel like putting that in a Gist though, trying to keep it simple enough for anyone to implement however they'd like.

@notasausage
Copy link
Author

I should also note that the php.ini on your server must have allow_url_fopen = on in order for this to work, otherwise PHP will throw an error on the simplexml_load_file() function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment