Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

Problema cuando utilizo 2 webservices

Estas en el tema de Problema cuando utilizo 2 webservices en el foro de Frameworks y PHP orientado a objetos en Foros del Web. Hola mi problema es el siguiente: Tengo un script php que llama a 2 clases, una que muestra el horoscopo del dia y otra que ...
  #1 (permalink)  
Antiguo 07/01/2009, 15:52
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Pregunta Problema cuando utilizo 2 webservices

Hola mi problema es el siguiente:

Tengo un script php que llama a 2 clases, una que muestra el horoscopo del dia y otra que realiza traducciones.

Este es el script:

Código PHP:
<?php
include "class.ahoroscope.php";
include(
"babelfish.class.php");
$dias = array("Domingo","Lunes""Martes""Miercoles""Jueves","Viernes","Sabado");
$d $dias[date('w')];

print 
"<html><head></head><body>\n";
print 
"<table border='1' ><tr><td colspan='2' align='center'>\n";
print 
"<h2>Conoce tu hor&oacute;scopo para hoy, ".$d.date(' d-m-Y')."</h2>\n";
print 
"</td></tr><tr><td width='250'>\n";
print 
"<br><a href='$PHP_SELF?s=capricorn'>Capricornio (Dic 22 -Ene 19)</a>\n";
print 
"<br><a href='$PHP_SELF?s=aquarius'>Acuario (Ene 21 - Feb 18)</a>\n";
print 
"<br><a href='$PHP_SELF?s=pisces'>Piscis (Feb 19 - Mar 20)</a>\n";
print 
"<br><a href='$PHP_SELF?s=aries'>Aries (Mar 21 - Abr 19)</a>\n";
print 
"<br><a href='$PHP_SELF?s=taurus'>Tauro (Abr 20 - May 20)</a>\n";
print 
"<br><a href='$PHP_SELF?s=gemini'>G&eacute;minis (May 21 - Jun 21)</a>\n";
print 
"<br><a href='$PHP_SELF?s=cancer'>C&aacute;ncer (Jun 22 - Jul 22)</a>\n";
print 
"<br><a href='$PHP_SELF?s=leo'>Leo (Jul 23 - Ago 22)</a>\n";
print 
"<br><a href='$PHP_SELF?s=virgo'>Virgo (Ago 23 - Sept 22)</a>\n";
print 
"<br><a href='$PHP_SELF?s=libra'>Libra (Sept 23 - Oct 22)</a>\n";
print 
"<br><a href='$PHP_SELF?s=scorpio'>Escorpio (Oct 23 - Nov 21)</a>\n";
print 
"<br><a href='$PHP_SELF?s=sagittarius'>Sagitario (Nov 22 - Dic 21)</a>\n";
print 
"</td><td width=450' align='center'>\n";
if(
$sign=$_GET['s']){
    
$hs=new ahoroscope();
    
$h=$hs->getHoroscope($sign);
    print 
"<b>Horoscope for $sign:</b><br>$h";
}else{
 print 
"Este es un script de ejemplo de c&oacute;mo usar la clase ahoroscope. S&oacute;lo\n";
 print 
" click en uno de los links to tener tu hor&oacute;scopo para hoy desde \n";
 print 
" la web <b>http://www.astrology.com/</b>.";
}

print 
"</td></tr></table>\n";
print 
"<table border='1'><tr><td colspan='2' align='center'>\n";
print 
"<h2>Traducci&oacute;n al espa&ntilde;ol de $sign </h2>\n";
print 
"</td></tr><tr><td width='706'>\n";
$tr=new babelfish();
echo 
$tr->translate($h,'english','spanish')."<br>\n";
print 
"</td></tr></table>\n";
print 
"</body></html>\n";
?>
__________________
Gaby :adios:
  #2 (permalink)  
Antiguo 07/01/2009, 15:53
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Pregunta Respuesta: Problema cuando utilizo 2 webservices

La primera clase es:

Código PHP:
<?php
header
('Content-Type: text/html; charset=utf-8');
// class.ahoroscope.php
// version 1.0.0, 6 August, 2005
//
// Ahoroscope is a small class to load the webpage from http://www.astrology.com/
// for the given astrology sign, then extract the horoscope and return
// it as a string. The following are the twelve possible values for the $sign.
//   capricorn
//   aquarius
//   pisces
//   aries
//   taurus
//   gemini
//   cancer
//   leo
//   virgo
//   libra
//   scorpio
//   sagittarius
//
// License
//
// Copyright (C) 2005 George A. Clarke, [email protected], http://gaclarke.com/
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 59 Temple
// Place - Suite 330, Boston, MA 02111-1307, USA.
//

class ahoroscope {
 function 
getHoroscope($sign) {
    
$lnk="http://horoscopes.astrology.com/dailylong".$sign.".html";
    
$pg=file_get_contents($lnk);
   if(
strpos($pg,"iTxt")!==false) {
    
$ii=strpos($pg,"iTxt")+6;
    
$ij=strpos($pg,'<',$ii);
    
$hor=substr($pg,$ii,$ij-$ii);
   }else{
    
$hor="Not found";
   }
return 
htmlentities($hor);
}
}
?>
__________________
Gaby :adios:
  #3 (permalink)  
Antiguo 07/01/2009, 15:54
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Pregunta Respuesta: Problema cuando utilizo 2 webservices

Y la otra clase es:

babel_fish_class

Código PHP:
 <?php
 header
('Content-Type: text/html; charset=utf-8');
 
/*******************************************************************************
 ** Class: babelfish
 ** Purpose: Translate text using Altavista Babelfish
 ** Filename: babelfish.class.php
 ** Author: Vedanta Barooah
 ** Author Email: vedanta . barooah @ gmail . com
 ** Date: June 19 2005
 ** Last Updated: June 27 2007
 **
 ** Other Contributors:[email protected],[email protected],Nikolay Kubarelov <[email protected]>
 ********************************************************************************/
 
 /* if ! PHP5 */
 
if (!function_exists('http_build_query')) {
    function 
http_build_query($formdata$numeric_prefix "")
    {
        
$arr = array();
        foreach (
$formdata as $key => $val)
          
$arr[] = urlencode($numeric_prefix.$key)."=".urlencode($val);
        return 
implode($arr"&");
    }
 }
 
/* translate text using altavista babelfish */
 
class babelfish{
     
/* array to store language names */
     
var $languages      =   NULL;
     
/* stores the altavista babelfish url*/
     
var $babel_url      =   NULL;
     
/* stores the search regex  (see readme for details) */
     
var $search_regex   =   NULL;
     
/* stores the data to be posted in an array (see readme for details) */
     
var $post_data      =   NULL;
     
/* stores the supported translation combination(s) */
     
var $valid_translate   =   NULL;
 
     
/* proxy support
     **
     */
     
var $useProxy           =    FALSE;
     var 
$proxyServer       =    NULL;
     var 
$proxyPort           =    NULL;
     var 
$timeOut           =    NULL;
 
     
/* class constructor */
     
function babelfish($url=NULL,$postdata=NULL,$regex=NULL){
 
         
/* list of languages */
         
$this->languages    =       array(
                                         
'en'    =>    'english',
                                         
'zh'    =>    'chinese',
                                         
'zt'    =>    'chinese-traditional',
                                         
'nl'    =>    'dutch',
                                         
'fr'    =>    'french',
                                         
'de'    =>    'german',
                                         
'el'    =>    'greek',
                                         
'it'    =>    'italian',
                                         
'ja'    =>    'japanese',
                                         
'ko'    =>    'korean',
                                         
'pt'    =>    'portuguese',
                                         
'ru'    =>    'russian',
                                         
'es'    =>    'spanish'
                                 
);
         
/* list of valid translations */
         
$this->valid_translate=array(
             
'zt_en','en_zh','en_zt','en_nl','en_fr',
             
'en_de','en_el','en_it','en_ja','en_ko',
             
'en_pt','en_ru','en_es','nl_en','nl_fr',
             
'fr_en','fr_de','fr_el','fr_it','fr_pt',
             
'fr_nl','fr_es','de_en','de_fr','el_en',
             
'el_fr','it_en','it_fr','ja_en','ko_en',
             
'pt_en','pt_fr','ru_en','es_en','es_fr'
         
);
 
         
/* babelfish service url */
         
if($url!=NULL)
             
$this->babel_url=$url;
         else
             
$this->babel_url="http://babelfish.yahoo.com/translate_txt";
         
/* data that is posted to the babelfish site */
         
if($postdata!=NULL)
             
$this->post_data=$postdata;
         else
             
$this->post_data=array(
                         
'doit'=>'done',
                         
'intl'=>'1',
                         
'tt'=>'urltext',
                         
'trtext'=>NULL,
                         
'lp'=>NULL
             
);
         
/* search for the translated text using this regex */
         
if($regex!=NULL)
             
$this->search_regex=$regex;
         else
              
#$this->search_regex='/<td bgcolor=white class=s><div style=padding:10px;>(.*)<\/div><\/td>/';
              #$this->search_regex='/<td bgcolor=white class=s><div style=padding:10px;>(.*)<\/div><\/td>/sm';
 
              
$this->search_regex='/<div id="result"><div style="padding:0.6em;">(.*)<\/div><\/div>/';
              
#$this->search_regex='/<input type=\"hidden\" name=\"p\" value=\"(.*)\">/sm';
              #$this->search_regex='/<td bgcolor=white class=s><div style=padding:10px;>(.*)<\/div><\/td>/sm';
     
}
 
     
/* set proxy settings */
     
function setProxy($proxyServer$proxyPort$timeOut=15){
         
$this->useProxy true;
         
$this->proxyServer $proxyServer;
         
$this->proxyPort $proxyPort;
         
$this->timeOut $timeOut;
     }
 
     
/* perform babelfish translation */
     
function translate($text,$from_language,$to_language,$forceUTF8=true){
         
$f=array_search(strtolower($from_language),$this->languages);
         if(!
$f){die("***error: source language not found");}
         
$t=array_search(strtolower($to_language),$this->languages);
         if(!
$t){die("***error: result language not found");}
         
$l=$f.'_'.$t;
         if(!
in_array($l,$this->valid_translate)){die("***error: cant translate with given combination ($l)");}
         
$this->post_data['trtext']=$text;
         
$this->post_data['lp']=$l;
         
$query=http_build_query($this->post_data);
         
$ch=curl_init();
         
curl_setopt($chCURLOPT_FOLLOWLOCATION1);
         
curl_setopt($chCURLOPT_URLtrim($this->babel_url));
         
curl_setopt($chCURLOPT_RETURNTRANSFER1);
         
curl_setopt($chCURLOPT_POST1);
         
curl_setopt($chCURLOPT_POSTFIELDS$query);
         
curl_setopt($chCURLOPT_USERAGENT"Mozilla/5.0 (babelfish.class.php)");
         
curl_setopt($ch,CURLOPT_ENCODING "UTF-8");
         
/* use proxy if required */
         
if($this->useProxy){
             
curl_setopt($ch,CURLOPT_PROXY,$this->proxyServer.":".$this->proxyPort);
             
curl_setopt($ch,CURLOPT_TIMEOUT,$this->timeOut);
         }
         
$output curl_exec($ch);
         
curl_close($ch);
         
$result=preg_match($this->search_regex,$output,$match);
         if(
$result == 1){
             return 
htmlentities(strip_tags($match[0]));
         }else{
             return 
'** error : babelfish.class.php returned nothing';
         }
     }
 }
 
/* end of class  */
 
?>

Ojalá se den un tiempo y puedan revisar el código para ver qué es lo q estoy haciendo mal.

Gracias
__________________
Gaby :adios:
  #4 (permalink)  
Antiguo 07/01/2009, 15:59
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Problema cuando utilizo 2 webservices

¿Cual es el error?, recuerda que si quieres que te podamos ayudar, debes de especificar claramente que es lo que te falla.

Saludos
  #5 (permalink)  
Antiguo 07/01/2009, 21:26
Avatar de enriqueplace  
Fecha de Ingreso: mayo-2005
Ubicación: Uruguay / Argentina
Mensajes: 1.102
Antigüedad: 18 años, 11 meses
Puntos: 32
Respuesta: Problema cuando utilizo 2 webservices

Gabyweb, y si subes el código fuente de toda la aplicación, el dump de la base de datos y el cd para instalar el servidor?

Ironías aparte, así no logras ayudar a nadie, menos a ti, tienes que ser más concreto y especificar el error, cuando ocurre, donde es que se inicia, etc.

Como dicen por ahí, si tú no te tomas el tiempo para explicarnos el problema, esperas que nosotros tomemos el tiempo para entenderlo y buscarte una solución?
__________________
Blog phpsenior.com Cursos a Distancia surforce.com
  #6 (permalink)  
Antiguo 08/01/2009, 08:13
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Pregunta Respuesta: Problema cuando utilizo 2 webservices

Hola,

Gracias por sus respuestas, por poner el código olvidé detallar el problema.
La aplicación no trabaja con base de datos.

El problema está cuando debe mostrarse la traducción del horóscopo que está en inglés en español. En estas líneas de la clase babelfish:

Código PHP:
$result=preg_match($this->search_regex,$output,$match);
        if(
$result == 1){
             return 
htmlentities(strip_tags($match[0]));
         }else{
             return 
'** error : babelfish.class.php returned nothing';
         } 
Por algún motivo el $result me retorna 0 por eso que me devuelve el mensaje del else.

Gracias
__________________
Gaby :adios:
  #7 (permalink)  
Antiguo 08/01/2009, 08:26
Avatar de enriqueplace  
Fecha de Ingreso: mayo-2005
Ubicación: Uruguay / Argentina
Mensajes: 1.102
Antigüedad: 18 años, 11 meses
Puntos: 32
Respuesta: Problema cuando utilizo 2 webservices

Alguna vez funcionó o dejó de hacerlo?
__________________
Blog phpsenior.com Cursos a Distancia surforce.com
  #8 (permalink)  
Antiguo 08/01/2009, 09:35
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Problema cuando utilizo 2 webservices

Debug, debug, es lo mejor, ve que contenido tiene $output para que veas si hay algo o si te esta regresando otra cosa.

Saludos.
  #9 (permalink)  
Antiguo 08/01/2009, 09:44
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Respuesta: Problema cuando utilizo 2 webservices

Por separado sí funcionan correctamente.

Con respecto al debug, ya lo hice, el $output sí tiene valores, lo que no está funcionando es el preg_match($this->search_regex,$output,$match)) ya que me devuelve el valor del $match como 0, o sea que no encuentra ninguna coincidencia.

No entiendo el constructor en donde se almacena el valor para $this->search_regex... por ahí es la cosa creo.
__________________
Gaby :adios:
  #10 (permalink)  
Antiguo 08/01/2009, 10:09
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Problema cuando utilizo 2 webservices

Pues antes del preg_match haz el debug, imprime $this->search_regex y $output y ve que salida te da, con eso te puedes dar una idea donde esta el problema.

Saludos
  #11 (permalink)  
Antiguo 08/01/2009, 10:23
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Respuesta: Problema cuando utilizo 2 webservices

Hola GatorV,

hice lo que me dijiste y me muestra esto:

/
(.*)<\/div><\/div>/

y la traduccion de Yahoo Babelfish en castellano.

O sea sí lo llega a traducir, pero por algún motivo no encuentra la coincidencia.

Lo has probado?
__________________
Gaby :adios:
  #12 (permalink)  
Antiguo 08/01/2009, 10:54
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Problema cuando utilizo 2 webservices

Haz un var_dump($result) y ve que tregresa preg_match.

Saludos.
  #13 (permalink)  
Antiguo 08/01/2009, 11:12
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Respuesta: Problema cuando utilizo 2 webservices

Retorna 0, es decir $result=0.

__________________
Gaby :adios:
  #14 (permalink)  
Antiguo 08/01/2009, 11:19
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Problema cuando utilizo 2 webservices

En ese caso es que el texto que estas enviando no pasa por la expresion regular, revisa con un editor de expresiones regulares si te hace el match que quieres, ya que de ahi viene tu error, la cadena es incorrecta.

Saludos.
  #15 (permalink)  
Antiguo 08/01/2009, 12:04
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
Respuesta: Problema cuando utilizo 2 webservices

Si pongo texto en duro sí funciona, o sea que la expresión regular está ok.
__________________
Gaby :adios:
  #16 (permalink)  
Antiguo 08/01/2009, 12:09
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Problema cuando utilizo 2 webservices

Mmm muy raro, ve si te esta devolviendo algo extra en $output, por eso te decia hacer el var_dump() es probable que por ahi este un caracter o algo de más que rompe con la expresión regular.

Saludos.
  #17 (permalink)  
Antiguo 08/01/2009, 12:52
Avatar de gabyweb  
Fecha de Ingreso: enero-2002
Ubicación: Lima
Mensajes: 364
Antigüedad: 22 años, 3 meses
Puntos: 0
A ver, cuando hago var_dump($this->search_regex); me devuelve:

string(65) "/
(.*)<\/div><\/div>/"

var_dump($match); //devuelve array(0) { }

var_dump($result); // int(0)

var_dump($output); Devuelve string(25612) " más el contenido de esta url http://babelfish.yahoo.com/translate_txt con el texto en español.

Ya encontré la solución:

$this->search_regex='/<div id="result"><div style="padding:0.6em;">(.*)<\/div><\/div>/sm';

Sólo tenía que añadir lo marcado con rojo, así sí funciona el preg_match.

Gracias GatorV por tu ayuda.
__________________
Gaby :adios:

Última edición por GatorV; 08/01/2009 a las 13:28
  #18 (permalink)  
Antiguo 09/06/2009, 14:32
 
Fecha de Ingreso: diciembre-2007
Mensajes: 38
Antigüedad: 16 años, 4 meses
Puntos: 0
Respuesta: Problema cuando utilizo 2 webservices

Hola a todos...
Voy a utilizar este tema aprovechando q se encuentra el mismo codigo en el cual tengo un problema.
Es en la primera clase q expone gabyweb
Me sale este error en cada uno de los signos del zodico
Cita:
Notice: Undefined variable: PHP_SELF in "RUTA" on line 18
.
.
. on line 32
Sè que tengo que utilizar $_SERVER['PHP_SELF']; en realidad ya lo he intentado pero no se como colocarlo en ese enlace. Me funcionò colocando mi resgistrer_globals en On pero de verdad prefiero seguir utilizandolo en Off.

Cualquier sugerencia se las agradezco....
Hasta pronto.
  #19 (permalink)  
Antiguo 09/06/2009, 15:57
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Problema cuando utilizo 2 webservices

Pues tal como lo indicas debes de usar $_SERVER['PHP_SELF'] en lugar de $PHP_SELF.

Saludos.
  #20 (permalink)  
Antiguo 14/06/2009, 18:21
 
Fecha de Ingreso: diciembre-2007
Mensajes: 38
Antigüedad: 16 años, 4 meses
Puntos: 0
Respuesta: Problema cuando utilizo 2 webservices

Bueno, para cualquiera que tenga este mismo problema las lineas van asi:

Cita:
print "<br><a href='".$_SERVER["PHP_SELF"]."?s=capricorn'>Capricornio (22 Dic - 19 Ene)</a>\n";
Y asi sucesivamente, la solucion era bien facil.
GatorV, aunque no me sirvio de mucho tu respuesta, gracias por responder.
Hasta luego....
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 04:44.