Tag: url - Webeame Snippets


Añadir snippet

Tag: url



Twitter API PHP

// introduce aquí la descripción Aqui esta mi API PHP, para que puedas conectarla con twitter. Esta super facil de usar ademas de tener algo de documentacion interior. Tiene dependencias de XPath para PHP y libreria CURL. Saludos
  1. <?php
  2. /*
  3. Ejemplo de instancia
  4. */
  5.  
  6. require_once('class/twitter.class.php');
  7.  
  8. /* Metodo Constructor para Twitter */
  9. $twitter = new Twitter('miusuario','mipass');
  10.  
  11. // Ejemplo :)
  12. echo "<h1>Todos los mensajes de Fayerwayer</h1>";
  13. echo "<pre>";
  14. print_r($twitter->lineaTiempo('fayerwayer'));
  15. echo "</pre>";
  16.  
  17. // Quieres realmente postear este mensaje? Descomentalo
  18. //$twitter->postearMensaje('Mi mensaje de pruebas desde API PHP para Twitter por framirez');
  19.  
  20. // Todos mis seguidores
  21. echo "<h1>Todos mis seguidores</h1>";
  22. echo "<pre>";
  23. print_r($twitter->seguidores());
  24. echo "</pre>";
  25.  
  26. // Ahora quiero ver todos mis mensajes
  27. echo "<h1>Todos mis mensajes</h1>";
  28. echo "<pre>";
  29. foreach($twitter->lineaTiempo() as $mensajes):
  30. echo "<p>Mensaje: " . $mensajes['mensaje'] . " posteado a las " . $mensajes['hora'] . " desde " . $mensajes['desde'] ."</p>";
  31. endforeach;
  32. echo "</pre>";
  33.  
  34. <?php
  35. /*
  36.  
  37. @author: Fabian Ramirez Sepulveda
  38. @email : framirez(ARROB)gurunet.cl
  39. @web : http://www.gurunet.cl/framirez
  40.  
  41. @desc: Proyecto para tener una API desde PHP mas accesible y facil para usuarios no avanzados.
  42.  
  43. @metodos:
  44. lineaTiempo( $nickNameAmigo=opcional) - "Nos retorna todos los ultimos 10 mensajes que nuestro amigo o nosotros hemos posteado"
  45. tomarMensaje($idmensaje) - "Nos retorna el detalle completo del mensaje"
  46. postearMensaje($mensaje) - "Posteamos en tiempo real el mensaje desde PHP"
  47. seguidores() - "Nos retorna todos nuestros amigos que nos siguen"
  48. */
  49.  
  50. // Libreria necesaria para procesar Xpath
  51. require_once('XPath.class.php');
  52.  
  53. class Twitter {
  54.  
  55. var $usuario='';
  56. var $password='';
  57.  
  58. // Headers de nuestro cliente
  59. var $agente = 'Twitter PHP Class by framirez';
  60. var $headers = array('X-Twitter-Client: Twitter PHP by framirez',
  61. 'X-Twitter-Client-Version: 1.0',
  62. 'X-Twitter-Client-URL: http://www.gurunet.cl/framirez');
  63.  
  64. // Curl
  65. var $ch;
  66.  
  67. // Respuesta
  68. var $respuesta;
  69.  
  70. var $xml;
  71.  
  72. function Twitter($usuario=null, $password=null) {
  73. $this->usuario = $usuario;
  74. $this->password = $password;
  75.  
  76. // Metodo constructor automaticamente llama a Xpath
  77. $this->xml = new XPath();
  78. }
  79. /*
  80. @desc: Retornamos el maximo de 10 mensajes de amigos o mios
  81. */
  82. function lineaTiempo($nick = null) {
  83.  
  84. if(empty($nick)):
  85. $this->ch = curl_init("http://twitter.com/statuses/user_timeline.xml");
  86. $this->xml->importFromString($this->setearOpcionesCurl());
  87. else:
  88. $this->ch = curl_init("http://twitter.com/statuses/user_timeline/" . $nick . ".xml");
  89. $this->xml->importFromString($this->setearOpcionesCurl());
  90. endif;
  91.  
  92. // Xpath Match
  93. $id = $this->xml->match('//id');
  94. $nickname = $this->xml->match('//screen_name');
  95. $texto = $this->xml->match('//text');
  96. $hora = $this->xml->match('//created_at');
  97. $desde = $this->xml->match('//location');
  98. $deDonde = $this->xml->match('//source');
  99.  
  100. // Variables Temporales
  101. $i=0;
  102. $arregloMensajes = array();
  103.  
  104. // Recorro el arreglo
  105. for($i=0;$i<count($texto);$i++):
  106. $arregloMensajes[$i]['id'] = $this->xml->getData($id[$i]);
  107. $arregloMensajes[$i]['usuario'] = $this->xml->getData($nickname[$i]);
  108. $arregloMensajes[$i]['mensaje'] = $this->xml->getData($texto[$i]);
  109. $arregloMensajes[$i]['hora'] = $this->xml->getData($hora[$i]);
  110. $arregloMensajes[$i]['desde'] = $this->xml->getData($desde[$i]);
  111. $arregloMensajes[$i]['donde_proviene'] = $this->xml->getData($deDonde[$i]);
  112. $i++;
  113. endfor;
  114.  
  115. $this->xml->reset();
  116. return $arregloMensajes;
  117. }
  118.  
  119. function tomarMensaje($id) {
  120. $this->ch = curl_init("http://twitter.com/statuses/user_timeline.xml");
  121. $this->xml->importFromString($this->setearOpcionesCurl());
  122.  
  123. // Xpath Match
  124. $id = $this->xml->match('//id');
  125. $nickname = $this->xml->match('//screen_name');
  126. $texto = $this->xml->match('//text');
  127. $hora = $this->xml->match('//created_at');
  128. $desde = $this->xml->match('//location');
  129. $deDonde = $this->xml->match('//source');
  130.  
  131. // Variables Temporales
  132. $arregloMensajes = array();
  133.  
  134. // Recorro el arreglo
  135. $arregloMensajes['id'] = $this->xml->getData($id[0]);
  136. $arregloMensajes['usuario'] = $this->xml->getData($nickname[0]);
  137. $arregloMensajes['mensaje'] = $this->xml->getData($texto[0]);
  138. $arregloMensajes['hora'] = $this->xml->getData($hora[0]);
  139. $arregloMensajes['desde'] = $this->xml->getData($desde[0]);
  140. $arregloMensajes['donde_proviene'] = $this->xml->getData($deDonde[0]);
  141.  
  142. $this->xml->reset();
  143. return $arregloMensajes;
  144. }
  145.  
  146. function postearMensaje($mensaje) {
  147.  
  148. if(empty($mensaje)):
  149. die("Debes pasar como parametro el mensaje");
  150. else:
  151. $this->ch = curl_init("http://twitter.com/statuses/update.xml");
  152. $this->xml->importFromString($this->setearOpcionesCurl('status=' . urlencode($mensaje)));
  153. $this->xml->reset();
  154. endif;
  155.  
  156. return true;
  157. }
  158.  
  159. function seguidores() {
  160. $this->ch = curl_init("http://twitter.com/statuses/followers.xml");
  161. $this->xml->importFromString($this->setearOpcionesCurl());
  162. // Xpath Match
  163. $id = $this->xml->match('//id');
  164. $nickname = $this->xml->match('//screen_name');
  165. $nombre = $this->xml->match('//name');
  166. $desde = $this->xml->match('//location');
  167. $web = $this->xml->match('//url');
  168. $foto = $this->xml->match('//profile_image_url');
  169. $descripcion = $this->xml->match('//description');
  170.  
  171. // Variables Temporales
  172. $i=0;
  173. $arregloMensajes = array();
  174.  
  175. // Recorro el arreglo
  176. for($i=0;$i<count($nickname);$i++):
  177. $arregloMensajes[$i]['id'] = $this->xml->getData($id[$i]);
  178. $arregloMensajes[$i]['nombre'] = $this->xml->getData($nombre[$i]);
  179. $arregloMensajes[$i]['desde'] = $this->xml->getData($desde[$i]);
  180. $arregloMensajes[$i]['usuario'] = $this->xml->getData($nickname[$i]);
  181. $arregloMensajes[$i]['web'] = $this->xml->getData($web[$i]);
  182. $arregloMensajes[$i]['foto'] = $this->xml->getData($foto[$i]);
  183. $arregloMensajes[$i]['descripcion'] = $this->xml->getData($descripcion[$i]);
  184. $i++;
  185. endfor;
  186.  
  187. $this->xml->reset();
  188. return $arregloMensajes;
  189. }
  190.  
  191.  
  192. function setearOpcionesCurl($post=false) {
  193. // Autentificamos
  194. curl_setopt($this->ch, CURLOPT_USERPWD, $this->usuario.':'.$this->password);
  195.  
  196. if(!empty($post)){
  197. curl_setopt($this->ch, CURLOPT_POST, true);
  198. curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
  199. }
  200.  
  201. curl_setopt($this->ch, CURLOPT_VERBOSE, 1);
  202. curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
  203. curl_setopt($this->ch, CURLOPT_USERAGENT, $this->agente);
  204.  
  205. // Setamos la respuesta
  206. $respuesta = curl_exec($this->ch);
  207. curl_close($this->ch);
  208.  
  209. unset($this->ch);
  210.  
  211. return $respuesta;
  212. }
  213.  
  214. }
  215.  
  216.  
  217. ?>

En PHP twitter php componente php5 curl xpath por framirez hace on 20/2/08 | Comentarios



Obtener encabezados de una dirección web

Devuelve las cabeceras de una dirección web
  1. /**
  2. * function getHeaders (string $url, boolean $formato = true)
  3. *
  4. * Devuelve las cabeceras de una dirección web
  5. * Solo acepta HTTP como metodo
  6. *
  7. * Si $formato es true devuelve un array asociativo,
  8. * de lo contrario, un array de claves simples
  9. *
  10. * return array
  11. */
  12. function getHeaders ($url, $formato = true) {
  13. if (function_exists('get_headers')) {
  14. return @get_headers($url, $formato);
  15. }
  16.  
  17. $partes = @parse_url($url);
  18.  
  19. if (empty($partes['host'])) {
  20. return false;
  21. }
  22.  
  23. if (empty($partes['path'])) {
  24. $path = '/';
  25. } else {
  26. $path = $partes['path'];
  27. }
  28.  
  29. if (!empty($partes['query'])) {
  30. $path .= '?'.$partes['query'];
  31. }
  32.  
  33. $partes['port'] = isset($partes['port'])?$partes['port']:80;
  34.  
  35. $socket = fsockopen($partes['host'], $partes['port'], $errno, $errstr, 30);
  36.  
  37. if (!$socket) {
  38. return false;
  39. }
  40.  
  41. $header = 'HEAD '.$path.' HTTP/1.1'."\r\n"
  42. .'Host: '.$partes['host'].(empty($partes['port'])?'':(':'.$partes['port']))."\r\n"
  43. .'Connection: Close'."\r\n\r\n";
  44.  
  45. fwrite($socket, $header);
  46.  
  47. $datos = array();
  48. $fin = false;
  49.  
  50. while (!feof($socket) or ($fin == true)) {
  51. if ($header = fgets($socket, 1024)) {
  52. if ($header == "\r\n") {
  53. $fin = true;
  54. break;
  55. } else {
  56. $header = trim($header);
  57. }
  58.  
  59. if ($formato == 1) {
  60. $key = explode(':', $header);
  61. $key = array_shift($key);
  62.  
  63. if ($key == $header) {
  64. $datos[] = $header;
  65. } else {
  66. $datos[$key] = substr($header,strlen($key)+2);
  67. }
  68.  
  69. unset($key);
  70. } else {
  71. $datos[] = $header;
  72. }
  73. }
  74. }
  75.  
  76. fclose($socket);
  77.  
  78. return $datos;
  79. }

En PHP encabezados cabeceras url por Lito hace on 4/2/08 | Comentarios



Texto simple para URL

Cambia todo tipo de carácteres extraños por letras o símbolos equivalentes para poder usarlo como complemento en las URL's
  1. /**
  2. * function palabra_simple (string $texto, boolean $min, boolean $html = false)
  3. *
  4. * Cambia las letras con tildes, eñes o caracteres raros por su concordancia natural.
  5. * En caso de que min sea true devolvera el texto en minúsculas.
  6. *
  7. * @$min: true/false para devolver el resultado en minúsculas
  8. * @$html: true/false si la cadena de texto que recibe está formateada con htmlentities
  9. *
  10. * return string
  11. */
  12. function palabra_simple ($texto, $min = true, $html = false) {
  13. if (!$html) {
  14. $texto = htmlentities($texto, ENT_QUOTES, 'ISO-8859-1');
  15. }
  16.  
  17. $texto = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/i', '$1', $texto);
  18. $texto = html_entity_decode($texto, ENT_QUOTES, 'ISO-8859-1');
  19.  
  20. $texto = preg_replace(array('/[^a-z0-9_-]/i', '/-+/', '/^-/', '/-$/',), array('-', '-', '', ''), $texto);
  21.  
  22. return $min?strtolower($texto):$texto;
  23. }

En PHP url texto simple por Lito hace on 4/2/08 | Comentarios



Descargar el contenido de una URL con cURL

  1. function abrir($url)
  2. {
  3. $sesion = curl_init($url);
  4.  
  5. curl_setopt($sesion, CURLOPT_RETURNTRANSFER, 1);
  6. curl_setopt($sesion, CURLOPT_FOLLOWLOCATION, 1);
  7. curl_setopt($sesion, CURLOPT_TIMEOUT, 5);
  8. curl_setopt($sesion, CURLOPT_CONNECTTIMEOUT, 5);
  9.  
  10. // Nos hacemos pasar por el Firefox
  11. curl_setopt($sesion, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
  12.  
  13. $resultado = curl_exec($sesion);
  14.  
  15. curl_close($sesion);
  16.  
  17. return $resultado;
  18. }

En PHP curl por jape hace on 1/2/08 | Comentarios



Función para generar cadenas para URLs

Recibe una cadena de texto, por ejemplo el título de un artículo y lo convierte a un formáto válido para utilizarlo en URLs amigables.
  1. function slug($slug)
  2. {
  3. $slug = strtolower($slug);
  4. $slug = explode(" ", $slug);
  5.  
  6. $temp = "";
  7. foreach ($slug as $token)
  8. {
  9. if (strlen($token) >= 3 || is_numeric($token))
  10. $temp .= $token." ";
  11. }
  12.  
  13. $slug = trim($temp);
  14. $slug = str_replace("á", "a", $slug);
  15. $slug = str_replace("é", "e", $slug);
  16. $slug = str_replace("í", "i", $slug);
  17. $slug = str_replace("ó", "o", $slug);
  18. $slug = str_replace("ú", "u", $slug);
  19. $slug = str_replace("ñ", "n", $slug);
  20. $slug = str_replace("ü", "u", $slug);
  21. $slug = str_replace("è", "e", $slug);
  22. $slug = preg_replace("/[^a-zA-Z0-9 ]/", "", $slug); // only take alphanumerical characters
  23. $slug = str_replace(" ", "-", $slug); // replace spaces by dashes
  24. $slug = substr($slug, 0, 90);
  25. $slug = trim($slug, '-');
  26.  
  27. return $slug;
  28.  
  29. }

En PHP url friendly rewrite por admin hace on 30/1/08 | Comentarios