Ver Mensaje Individual
  #1 (permalink)  
Antiguo 10/08/2011, 16:16
Avatar de reborn
reborn
 
Fecha de Ingreso: febrero-2010
Mensajes: 440
Antigüedad: 14 años, 2 meses
Puntos: 1
Problema al extraer title con file_get_contents()

Buenas...

Quiero extraer el title de una url con file_get_contents().

En un principio hice esto:
Código PHP:
Ver original
  1. <?php
  2.  
  3. function extraer_title($filtro) {
  4.  
  5. $param = "|<[s]*title[s]*>([^<]+)<[s]*/[s]*title[s]*>|Ui";
  6.  
  7. if( preg_match($param, $filtro, $result) ) {
  8.  
  9.                return $result[1];
  10.  
  11. }else{
  12.  
  13.                return false;
  14.  
  15. }
  16.  
  17. }
  18.  
  19. $url= "http://www.url.com";
  20.  
  21. $recorrer = file_get_contents($url);
  22.  
  23. $title = extraer_title($recorrer);
  24.  
  25. echo $title;

...funcionaba bien pero tenia el problema de q algunas paginas bloqueaban el uso de file_get... y con unos ejemplos del user abimaelrc llegue a esto:


Código PHP:
Ver original
  1. function extraer_title($filtro) {
  2.  
  3. $param = "|<[s]*title[s]*>([^<]+)<[s]*/[s]*title[s]*>|Ui";
  4.  
  5. if( preg_match($param, $filtro, $result) ) {
  6.  
  7.                return $result[1];
  8.  
  9. }else{
  10.  
  11.                return false;
  12.  
  13. }
  14.  
  15. }
  16.  
  17. $options = array('http' =>
  18.                     array( 'header' => 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6' . PHP_EOL )
  19.                     );
  20.                    
  21.                     $context = stream_context_create($options);
  22.  
  23.                     $page = file_get_contents('http://www.url.com', false, $context);
  24.  
  25.                     $title = extraer_title($page);
  26.                                        
  27. echo $title;


....luego surgio el problema de q mi pagina web, al hacer uso de esa funcion y de file_get... me cargaba muy lenta y ahi es donde me quede.

Lo ultimo q hice es esto:

Código PHP:
Ver original
  1. $options = array('http' =>
  2.     array( 'header' => 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6' . PHP_EOL )
  3. );
  4.  
  5. $context = stream_context_create($options);
  6.  
  7. $page = file_get_contents('http://www.url.com', false, $context);
  8.  
  9. $doc = new DOMDocument();
  10. @$doc->loadHTML($page);
  11. $nodes = $doc->getElementsByTagName('title');
  12.  
  13. $title = $nodes->item(0)->nodeValue;
  14.  
  15. echo $title;

...pero sigue cargando muy lento todo.

Como lo puedo solucionar?

Gracias.

Saludos.