Foros del Web » Programando para Internet » PHP »

Mejor tecnica para mostrar avatares de twitter

Estas en el tema de Mejor tecnica para mostrar avatares de twitter en el foro de PHP en Foros del Web. Hola, Tengo una página donde los usuarios pueden iniciar sesión con twitter y publicar comentarios. Quiero mostrar las imágenes de avatar de twitter en los ...
  #1 (permalink)  
Antiguo 23/03/2012, 07:36
Avatar de IMAC/  
Fecha de Ingreso: octubre-2005
Mensajes: 738
Antigüedad: 18 años, 6 meses
Puntos: 14
Mejor tecnica para mostrar avatares de twitter

Hola,

Tengo una página donde los usuarios pueden iniciar sesión con twitter y publicar comentarios.

Quiero mostrar las imágenes de avatar de twitter en los comentarios y me preguntaba si tenéis conocimiento de las técnicas que se suelen usar para ello porque:

- Usar la API para obtener cada avatar no tiene sentido puesto que solo permite 150 peticiones a la hora o 350 si se usa OAuth.

- Guardar la url del avatar en la base de datos cuando inician sesión por primera vez hace que cuando cambien de avatar se siga mostrando en la página el antiguo.

- Había pensado en usar una función para obtener los datos a través del XML público pero no se si generará un retraso considerable si tengo que cargar, digamos, 20 imágenes o más en cada noticia con comentarios.

El código de esta última opción es este:
Código PHP:
<?php
$username 
"twitter";  // <-- You did not use quotes here?! Typo?
$xml simplexml_load_file("http://twitter.com/users/".$username.".xml");
echo 
$xml->profile_image_url;  // <-- No $xml->user here!
?>
Hay multitud de páginas que muestran el avatar pero no estoy seguro de qué técnica usan para ello. Páginas como la famosa pinterest.com o sistemas de comentarios como LiveFyre o Disqus.

¿Alguna idea?
  #2 (permalink)  
Antiguo 25/03/2012, 05:44
Avatar de ShuyithoKruz  
Fecha de Ingreso: marzo-2012
Ubicación: Tijuana
Mensajes: 40
Antigüedad: 12 años, 1 mes
Puntos: 3
Respuesta: Mejor tecnica para mostrar avatares de twitter

Leyendo un poco en twitter puedes leer esto https://dev.twitter.com/docs/api/1/get/users/profile_image/:screen_name

Y aqui te presento algunos ejemplos faciles de usar
Ejemplo 1: https://api.twitter.com/1/users/profile_image/USERNAME?size=bigger
Ejemplo 2: http://img.tweetimag.es/i/USERNAME
Ejemplo 3: http://api.twitter.com/1/users/profile_image/USERNAME.json?size=bigger

Solo cambiarias el USERNAME por el nombre de usuario.

O ya si quieres hacerlo mediante php aqui te dejo este codigo
Código PHP:
<?php
class twitterImage
{
  var 
$user='';
  var 
$image='';
  var 
$displayName='';
  var 
$url='';
  var 
$format='json';
  var 
$requestURL='http://twitter.com/users/show/';
  var 
$imageNotFound=''//any generic image/avatar. It will display when the twitter user is invalid
  
var $noUser=true;
 
  function 
__construct($user)
  {
    
$this->user=$user;
    
$this->__init();
 
  }
  
/*
   * fetches user info from twitter
   * and populates the related vars
   */
  
private function __init()
  {
    
$data=json_decode($this->get_data($this->requestURL.$this->user.'.'.$this->format)); //gets the data in json format and decodes it
    
if(strlen($data->error)<=0//check if the twitter profile is valid
 
    
{
      
$this->image=$data->profile_image_url;
      
$this->displayName=$data->name;
      
$this->url=(strlen($data->url)<=0)?'http://twitter.com/'.$this->user:$data->url;
      
$this->location=$data->location;
    }
    else
    {
      
$this->image=$this->imageNotFound;
    }
 
 
  }
  
/* creates image tag
   * @params
   * passing linked true -- will return an image which will link to the user's url defined on twitter profile
   * passing display true -- will render the image, else return
   */
  
function profile_image($linked=false,$display=false)
  {
    
$img="<img src='$this->image' border='0' alt='$this->displayName' />";
    
$linkedImg="<a href='$this->url' rel='nofollow' title='$this->displayName'>$img</a>";
    if(!
$linked && !$display//the default case
      
return $img;
 
    if(
$linked && $display)
      echo 
$linkedImg;
 
    if(
$linked && !$display)
      return 
$linkedImg;
 
    if(
$display && !$linked)
      echo 
$img;
 
 
  }
  
/* gets the data from a URL */
 
  
private function get_data($url)
  {
    
$ch curl_init();
    
$timeout 5;
    
curl_setopt($ch,CURLOPT_URL,$url);
    
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    
$data curl_exec($ch);
    
curl_close($ch);
    return 
$data;
  }
 
}
 
/* Example on how to use this class*/
//require_once('twitterImage.php') you will require this line if you are saving the above class in a different file
 
//the two lines are enough to display an image off the twitter
 
//$t=new twitterImage('digimantra'); //pass the twitter username
//$t->profile_image(true,true);  //this will render a linked image
 
/* More info about the params of profile_image function
 * true,true -- will render a linked image
 * true,false -- will return a linked image, will not render
 * false,true -- will render an image without link
 * false,false (or blank) -- will return an image, will not render
 */
?>
El guión es bastante fácil de entender y aplicar. Sólo tienes que copiar el contenido y guardarlo en un archivo PHP. Para mostrar una imagen que usted tiene que escribir sólo las líneas 2, después de incluir la clase anterior en el script.

Código PHP:
require_once('twitterImage.php')  //include the above class
$t=new twitterImage('digimantra'); //create instance of the class and pass the username
$t->profile_image(true,true); //display a linked image 
Puede mostrar una imagen con y sin el enlace. La imagen estará vinculado a la dirección proporcionada por el usuario en la página principal de Twitter, y si el enlace no se proporciona, a continuación, se ligará al perfil de usuario de Twitter por defecto.

Si usted cree que necesita algunos cambios o si quieren añadir más funcionalidad a la secuencia de comandos, hágamelo saber. Estaré encantado de poner al día la secuencia de comandos, dependiendo de la magnitud de la solicitud.
  #3 (permalink)  
Antiguo 25/03/2012, 09:42
Avatar de IMAC/  
Fecha de Ingreso: octubre-2005
Mensajes: 738
Antigüedad: 18 años, 6 meses
Puntos: 14
Respuesta: Mejor tecnica para mostrar avatares de twitter

Básicamente estás usando las tercera alternativa que propuse.
¿Sabes si usar http://twitter.com/users/show/ no es usar la API y por lo tanto no tiene restricciones en cuanto al número de accesos por hora?

Gracias.
  #4 (permalink)  
Antiguo 25/03/2012, 09:55
Avatar de ShuyithoKruz  
Fecha de Ingreso: marzo-2012
Ubicación: Tijuana
Mensajes: 40
Antigüedad: 12 años, 1 mes
Puntos: 3
Respuesta: Mejor tecnica para mostrar avatares de twitter

La API se limita siempre y cuando tengas una app que sobrepase los limites establecidos por twitter pero en este caso no estas usando ninguna API simplemente estas usando una URL como si fuera el mismo twitter asi que por lo que yo creo no veo por el cual haya restricciones

Saludos
  #5 (permalink)  
Antiguo 25/03/2012, 14:43
Avatar de IMAC/  
Fecha de Ingreso: octubre-2005
Mensajes: 738
Antigüedad: 18 años, 6 meses
Puntos: 14
Respuesta: Mejor tecnica para mostrar avatares de twitter

Supongo que tendré que hacer yo mismo la prueba con un bucle.

La API también se accede desde una URL prácticamente igual pero empezando por api.twitter.com

Por eso preguntaba, porque la diferencia es mínima. Y el rate limit está a 150 o 350. Muy poco para un página web normal.

Etiquetas: avatar, limite, tecnica, twitter
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 08:57.