Foros del Web » Programando para Internet » PHP »

Undefined offset en host pero no en localhost

Estas en el tema de Undefined offset en host pero no en localhost en el foro de PHP en Foros del Web. Hola foreros y maestros del php, hace rato tomé un codigo llamado last rss, el código al subirlo a mi web http://manganimemas.com me trae los ...
  #1 (permalink)  
Antiguo 12/07/2010, 18:45
Avatar de memoadian
Colaborador
 
Fecha de Ingreso: junio-2009
Ubicación: <?php echo 'México'?>
Mensajes: 3.696
Antigüedad: 14 años, 9 meses
Puntos: 641
Undefined offset en host pero no en localhost

Hola foreros y maestros del php, hace rato tomé un codigo llamado last rss, el código al subirlo a mi web http://manganimemas.com me trae los ultimos posts de mi blog de blogger (el cual no dejo por que me hace la vida muy facil) y funciona bien pero me lanza un notice

Notice: Undefined offset: 1 in /var/www/vhosts/manganimemas.com/httpdocs/lastRSS.php on line 155

no cacho la verdad el problema, ya revise esas lineas, se supone que el aviso lo da cuando tomamos valores de un array que no existe, entonces puse el archivo en mi localhost, y ahi no me dice nada, verifiqué el display errors de mi php.ini y esta en On asi que no entiendo el problema, soy bastante novaton, alguien podría hecharme un cable, dejo el código de last RSS por si quieren checarlo, si no pues no se apuren, seguro puedo hacer algo pero ya me duele la cabeza.

Código PHP:
Ver original
  1. <?php
  2. class lastRSS {
  3.     // -------------------------------------------------------------------
  4.     // Public properties
  5.     // -------------------------------------------------------------------
  6.     var $default_cp = 'UTF-8';
  7.     var $CDATA = 'nochange';
  8.     var $cp = '';
  9.     var $items_limit = 0;
  10.     var $stripHTML = False;
  11.     var $date_format = '';
  12.  
  13.     // -------------------------------------------------------------------
  14.     // Private variables
  15.     // -------------------------------------------------------------------
  16.     var $channeltags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs');
  17.     var $itemtags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source');
  18.     var $imagetags = array('title', 'url', 'link', 'width', 'height');
  19.     var $textinputtags = array('title', 'description', 'name', 'link');
  20.  
  21.     // -------------------------------------------------------------------
  22.     // Parse RSS file and returns associative array.
  23.     // -------------------------------------------------------------------
  24.     function Get ($rss_url) {
  25.         // If CACHE ENABLED
  26.         if ($this->cache_dir != '') {
  27.             $cache_file = $this->cache_dir . '/rsscache_' . md5($rss_url);
  28.             $timedif = @(time() - filemtime($cache_file));
  29.             if ($timedif < $this->cache_time) {
  30.                 // cached file is fresh enough, return cached array
  31.                 $result = unserialize(join('', file($cache_file)));
  32.                 // set 'cached' to 1 only if cached file is correct
  33.                 if ($result) $result['cached'] = 1;
  34.             } else {
  35.                 // cached file is too old, create new
  36.                 $result = $this->Parse($rss_url);
  37.                 $serialized = serialize($result);
  38.                 if ($f = @fopen($cache_file, 'w')) {
  39.                     fwrite ($f, $serialized, strlen($serialized));
  40.                     fclose($f);
  41.                 }
  42.                 if ($result) $result['cached'] = 0;
  43.             }
  44.         }
  45.         // If CACHE DISABLED >> load and parse the file directly
  46.         else {
  47.             $result = $this->Parse($rss_url);
  48.             if ($result) $result['cached'] = 0;
  49.         }
  50.         // return result
  51.         return $result;
  52.     }
  53.    
  54.     // -------------------------------------------------------------------
  55.     // Modification of preg_match(); return trimed field with index 1
  56.     // from 'classic' preg_match() array output
  57.     // -------------------------------------------------------------------
  58.     function my_preg_match ($pattern, $subject) {
  59.         // start regullar expression
  60.         preg_match($pattern, $subject, $out);
  61.  
  62.         // if there is some result... process it and return it
  63.         if(isset($out[1])) {
  64.             // Process CDATA (if present)
  65.             if ($this->CDATA == 'content') { // Get CDATA content (without CDATA tag)
  66.                 $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  67.             } elseif ($this->CDATA == 'strip') { // Strip CDATA
  68.                 $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  69.             }
  70.  
  71.             // If code page is set convert character encoding to required
  72.             if ($this->cp != '')
  73.                 //$out[1] = $this->MyConvertEncoding($this->rsscp, $this->cp, $out[1]);
  74.                 $out[1] = iconv($this->rsscp, $this->cp.'//TRANSLIT', $out[1]);
  75.             // Return result
  76.             return trim($out[1]);
  77.         } else {
  78.         // if there is NO result, return empty string
  79.             return '';
  80.         }
  81.     }
  82.  
  83.     // -------------------------------------------------------------------
  84.     // Replace HTML entities &something; by real characters
  85.     // -------------------------------------------------------------------
  86.     function unhtmlentities ($string) {
  87.         // Get HTML entities table
  88.         $trans_tbl = get_html_translation_table (HTML_ENTITIES, ENT_QUOTES);
  89.         // Flip keys<==>values
  90.         $trans_tbl = array_flip ($trans_tbl);
  91.         // Add support for &apos; entity (missing in HTML_ENTITIES)
  92.         $trans_tbl += array('&apos;' => "'");
  93.         // Replace entities by values
  94.         return strtr ($string, $trans_tbl);
  95.     }
  96.  
  97.     // -------------------------------------------------------------------
  98.     // Parse() is private method used by Get() to load and parse RSS file.
  99.     // Don't use Parse() in your scripts - use Get($rss_file) instead.
  100.     // -------------------------------------------------------------------
  101.     function Parse ($rss_url) {
  102.         // Open and load RSS file
  103.         if ($f = @fopen($rss_url, 'r')) {
  104.             $rss_content = '';
  105.             while (!feof($f)) {
  106.                 $rss_content .= fgets($f, 4096);
  107.             }
  108.             fclose($f);
  109.  
  110.             // Parse document encoding
  111.             $result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content);
  112.             // if document codepage is specified, use it
  113.             if ($result['encoding'] != '')
  114.                 { $this->rsscp = $result['encoding']; } // This is used in my_preg_match()
  115.             // otherwise use the default codepage
  116.             else
  117.                 { $this->rsscp = $this->default_cp; } // This is used in my_preg_match()
  118.  
  119.             // Parse CHANNEL info
  120.             preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel);
  121.             foreach($this->channeltags as $channeltag)
  122.             {
  123.                 $temp = $this->my_preg_match("'<$channeltag.*?>(.*?)</$channeltag>'si", $out_channel[1]);
  124.                 if ($temp != '') $result[$channeltag] = $temp; // Set only if not empty
  125.             }
  126.             // If date_format is specified and lastBuildDate is valid
  127.             if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !==-1) {
  128.                         // convert lastBuildDate to specified date format
  129.                         $result['lastBuildDate'] = date($this->date_format, $timestamp);
  130.             }
  131.  
  132.             // Parse TEXTINPUT info
  133.             preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);
  134.                 // This a little strange regexp means:
  135.                 // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beggining tag)
  136.             if (isset($out_textinfo[2])) {
  137.                 foreach($this->textinputtags as $textinputtag) {
  138.                     $temp = $this->my_preg_match("'<$textinputtag.*?>(.*?)</$textinputtag>'si", $out_textinfo[2]);
  139.                     if ($temp != '') $result['textinput_'.$textinputtag] = $temp; // Set only if not empty
  140.                 }
  141.             }
  142.             // Parse IMAGE info
  143.             preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo);
  144.             if (isset($out_imageinfo[1])) {
  145.                 foreach($this->imagetags as $imagetag) {
  146.                     $temp = $this->my_preg_match("'<$imagetag.*?>(.*?)</$imagetag>'si", $out_imageinfo[1]);
  147.                     if ($temp != '') $result['image_'.$imagetag] = $temp; // Set only if not empty
  148.                 }
  149.             }
  150.             // Parse ITEMS
  151.             preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items);
  152.             $rss_items = $items[2];
  153.             $i = 0;
  154.             $result['items'] = array(); // create array even if there are no items
  155.             foreach($rss_items as $rss_item) {
  156.                 // If number of items is lower then limit: Parse one item
  157.                 if ($i < $this->items_limit || $this->items_limit == 0) {
  158.                     foreach($this->itemtags as $itemtag) {
  159.                         $temp = $this->my_preg_match("'<$itemtag.*?>(.*?)</$itemtag>'si", $rss_item);
  160.                         if ($temp != '') $result['items'][$i][$itemtag] = $temp; // Set only if not empty
  161.                     }
  162.                     // Strip HTML tags and other bullshit from DESCRIPTION
  163.                     if ($this->stripHTML && $result['items'][$i]['description'])
  164.                         $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description'])));
  165.                     // Strip HTML tags and other bullshit from TITLE
  166.                     if ($this->stripHTML && $result['items'][$i]['title'])
  167.                         $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title'])));
  168.                     // If date_format is specified and pubDate is valid
  169.                     if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !==-1) {
  170.                         // convert pubDate to specified date format
  171.                         $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp);
  172.                     }
  173.                     // Item counter
  174.                     $i++;
  175.                 }
  176.             }
  177.  
  178.             $result['items_count'] = $i;
  179.             return $result;
  180.         }
  181.         else // Error in opening return False
  182.         {
  183.             return False;
  184.         }
  185.     }
  186. }
  187.  
  188. ?>

Bueno vi que se puede deshabilitar el php notice, no se que tan bueno sea, pero no parece muy malo :S

Última edición por memoadian; 12/07/2010 a las 19:59
  #2 (permalink)  
Antiguo 12/07/2010, 21:37
 
Fecha de Ingreso: septiembre-2008
Mensajes: 350
Antigüedad: 15 años, 6 meses
Puntos: 31
Respuesta: Undefined offset en host pero no en localhost

Hola, prueba a cambiar esto $rss_items = $items[2]; en la linea 152
por esto $rss_items = isset($items[2]) ? $items[2] : "";



-
__________________
╬-----╬
║☺₧☻║
╬-----╬
  #3 (permalink)  
Antiguo 12/07/2010, 21:46
Avatar de memoadian
Colaborador
 
Fecha de Ingreso: junio-2009
Ubicación: <?php echo 'México'?>
Mensajes: 3.696
Antigüedad: 14 años, 9 meses
Puntos: 641
Respuesta: Undefined offset en host pero no en localhost

MUchas gracias amigo esta de maravilla. un abrazo.
  #4 (permalink)  
Antiguo 12/07/2010, 22:36
 
Fecha de Ingreso: septiembre-2008
Mensajes: 350
Antigüedad: 15 años, 6 meses
Puntos: 31
Respuesta: Undefined offset en host pero no en localhost

De nada
una notice de esas se puede apagar solo en esa linea usando un @
antes de una variable ej: @$noEsCorrecto = 'txt'; pero si se puede solucionar
es mejor hacerlo.
esa Noticia de Undefined offset puede suceder de un loop en un while, for etc.
por ejemplo si se le pide que entregue 5 valores(o automáticamente) y solo encuentra 3 seguro que dará
Undefined offset 4, Undefined offset 5. serian copias null en la memoria de php
__________________
╬-----╬
║☺₧☻║
╬-----╬
  #5 (permalink)  
Antiguo 13/07/2010, 06:38
Avatar de memoadian
Colaborador
 
Fecha de Ingreso: junio-2009
Ubicación: <?php echo 'México'?>
Mensajes: 3.696
Antigüedad: 14 años, 9 meses
Puntos: 641
Respuesta: Undefined offset en host pero no en localhost

Ah ya asi que eso era, muchas gracias por la info, siempre es bueno saber esas cosas. creo que ya te di karma, si no, me dices, pocos en este foro, dan ese tipo de soluciones, han perdido la facultad de ayudar por ayudar. gracias.

Etiquetas: localhost, offset, undefined, hosts
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 00:04.