Foros del Web » Programando para Internet » PHP »

Parsear HTML desde un PHP

Estas en el tema de Parsear HTML desde un PHP en el foro de PHP en Foros del Web. Hola necesito parsear este html y obtener los datos, y estos datos crear un xml, pero me cuesta llegar a obtenerlos todos y acomodarlos!!! Estoy ...
  #1 (permalink)  
Antiguo 16/08/2010, 17:31
Avatar de shanshito  
Fecha de Ingreso: noviembre-2008
Mensajes: 40
Antigüedad: 15 años, 5 meses
Puntos: 0
Exclamación Parsear HTML desde un PHP

Hola necesito parsear este html y obtener los datos, y estos datos crear un xml, pero me cuesta llegar a obtenerlos todos y acomodarlos!!!
Estoy usando simplehtmldom y lo bajan de aquí ---> http://simplehtmldom.sourceforge.net/ ;

este es mi HTML el cual necesito convertir en XML

Código HTML:
Ver original
  1. <tr>
  2.         <td valign="top" width="200"><div class="titulos_futuro_fisico">FUTURO</div>
  3.         <div class="div_columnas">
  4.           <div align="center"></div>
  5.           <table border="0" cellpadding="0" cellspacing="0" width="190">
  6.             <tbody><tr>
  7.               <td class="tiutlos_col_cuadro_merc_granos">MERCADO<br></td>
  8.               <td class="tiutlos_col_cuadro_merc_granos" width="50"><div align="center">POS<br>
  9.  
  10.               </div></td>
  11.               <td class="tiutlos_col_cuadro_merc_granos" width="45"><div align="center">U$S<br>
  12.               </div></td>
  13.               <td class="tiutlos_col_cuadro_merc_granos" width="50"><div align="right">VAR U$S<br>
  14.               </div></td>
  15.             </tr>
  16.            
  17.                 <tr>
  18.               <td>CBOT</td>
  19.  
  20.               <td width="50"><div align="center">NOV/10</div></td>
  21.               <td width="45"><div align="center">379,01</div></td>
  22.               <td width="50"><div align="right">
  23.                   <table border="0" cellpadding="0" cellspacing="0" width="100%">
  24.                     <tbody><tr>
  25.                       <td><div align="right"><img src="images/iconos/menos.gif" height="7" width="7"></div></td>
  26.                       <td width="33"><div align="right">-4,23</div></td>
  27.  
  28.                     </tr>
  29.                   </tbody></table>
  30.               </div></td>
  31.             </tr>
  32.                
  33.                 <tr>
  34.               <td>CBOT</td>
  35.               <td width="50"><div align="center">MAY/11</div></td>
  36.               <td width="45"><div align="center">381,03</div></td>
  37.  
  38.               <td width="50"><div align="right">
  39.                   <table border="0" cellpadding="0" cellspacing="0" width="100%">
  40.                     <tbody><tr>
  41.                       <td><div align="right"><img src="images/iconos/menos.gif" height="7" width="7"></div></td>
  42.                       <td width="33"><div align="right">-4,41</div></td>
  43.                     </tr>
  44.                   </tbody></table>
  45.               </div></td>
  46.  
  47.             </tr>
  48.                
  49.                 <tr>
  50.               <td>MATBA         </td>
  51.               <td width="50"><div align="center">NOV/10</div></td>
  52.               <td width="45"><div align="center">272,80</div></td>
  53.               <td width="50"><div align="right">
  54.                   <table border="0" cellpadding="0" cellspacing="0" width="100%">
  55.  
  56.                     <tbody><tr>
  57.                       <td><div align="right"><img src="images/iconos/mas.gif" height="7" width="7"></div></td>
  58.                       <td width="33"><div align="right">1,30</div></td>
  59.                     </tr>
  60.                   </tbody></table>
  61.               </div></td>
  62.             </tr>
  63.                
  64.                 <tr>
  65.  
  66.               <td>MATBA         </td>
  67.               <td width="50"><div align="center">MAY/11</div></td>
  68.               <td width="45"><div align="center">249,90</div></td>
  69.               <td width="50"><div align="right">
  70.                   <table border="0" cellpadding="0" cellspacing="0" width="100%">
  71.                     <tbody><tr>
  72.                       <td><div align="right"><img src="images/iconos/mas.gif" height="7" width="7"></div></td>
  73.  
  74.                       <td width="33"><div align="right">1,60</div></td>
  75.                     </tr>
  76.                   </tbody></table>
  77.               </div></td>
  78.             </tr>
  79.                
  80.           </tbody></table>
  81.         </div></td>
  82.     <td width="10">&nbsp;</td>
  83.  
  84.    
  85.     <td valign="top" width="200"><div class="titulos_futuro_fisico">FISICO</div>
  86.         <div class="div_columnas">
  87.           <table border="0" cellpadding="0" cellspacing="0" width="190">
  88.             <tbody><tr>
  89.               <td class="tiutlos_col_cuadro_merc_granos">MERCADO<br></td>
  90.               <td class="tiutlos_col_cuadro_merc_granos" width="55"><div align="right">PRECIO<br>
  91.               </div></td>
  92.  
  93.             </tr>
  94.             <tr align="center"><td colspan="3" height="100%" valign="middle">Sin Cotización</td></tr>
  95.           </tbody></table>
  96.         </div></td>
  97.     </tr>



aca les dejo el codigo de mi php.

Código PHP:
<?php

//http://simplehtmldom.sourceforge.net/
require("simplehtmldom/simple_html_dom.php");

$url="http://www.fyo.com/includes/cgGetMercadoGranos.asp?grano=1";
$html=file_get_contents($url);

 
/*** a new dom object ***/
    
$dom = new domDocument;

    
/*** load the html into the object ***/
    
$dom->loadHTML($html);

    
/*** discard white space ***/
    
$dom->preserveWhiteSpace false;

    
/*** the table by its tag name ***/
    
$tables $dom->getElementsByTagName('table');

    
/*** get all rows from the table ***/
    
$rows $tables->item(0)->getElementsByTagName('tr');

    
/*** loop over the table rows ***/
    
foreach ($rows as $row)
    {
        
/*** get each column by tag name ***/
        
$cols $row->getElementsByTagName('td');
        
/*** echo the values ***/
        
        
echo '<tr>'.$cols->item(0)->nodeValue.'</tr><br/>';

    }
?>

Aca simplemente lo que hago es porbar que puedo obtner los datos, pero me esta costando darme cuenta como ordenar los datos para que pueda grabarlos o guardarlos como yo quiera. asi me salen todos desarodenados .

Espero que alguien me pueda ayudar! Gracias por la sabiduría y la ayuda que siempre nos brindan a los desarrolladores de INTERNEEEEERRRRDD!!

abrazo!
  #2 (permalink)  
Antiguo 16/08/2010, 21:25
Avatar de ElJavista
Colaborador
 
Fecha de Ingreso: marzo-2007
Ubicación: Lima Perú
Mensajes: 2.231
Antigüedad: 17 años, 1 mes
Puntos: 67
Respuesta: Parsear HTML desde un PHP

INTERNED? qué será eso?

Última edición por ElJavista; 16/08/2010 a las 21:31
  #3 (permalink)  
Antiguo 16/08/2010, 21:56
Avatar de silvanha  
Fecha de Ingreso: marzo-2006
Ubicación: En mi mundo de sueños
Mensajes: 653
Antigüedad: 18 años, 1 mes
Puntos: 65
Respuesta: Parsear HTML desde un PHP

Cita:
Iniciado por ElJavista Ver Mensaje
INTERNED? qué será eso?
Señor ElJavista, no leyó ud. bien, es:

Cita:
Iniciado por shanshito Ver Mensaje
INTERNEEEEERRRRDD!!
jojo, y no tampoco tengo idea

por otro lado, shanshito, podrías ser mas especifico en tu problema??? desordenados como? es decir, podemos ver el código, pero aún así.. que es lo que necesitas??

cómo dirían por ahí, adivinar de repente cuesta trabajo
__________________
●•· No hay nada imposible..
●•· Vico-X.. ;)
  #4 (permalink)  
Antiguo 17/08/2010, 07:35
Avatar de shanshito  
Fecha de Ingreso: noviembre-2008
Mensajes: 40
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Parsear HTML desde un PHP

simple, http://www.fyo.com/includes/cgGetMer...os.asp?grano=1

eso me devuelve un html con datos, necesito parsearlo, y ordenarlos, nose si en un array o en una matriz, pero los necesito, y con esos datos, armar un XML,
Alguien me puede dar una manito? :D
  #5 (permalink)  
Antiguo 17/08/2010, 09:22
 
Fecha de Ingreso: octubre-2009
Mensajes: 240
Antigüedad: 14 años, 6 meses
Puntos: 6
Respuesta: Parsear HTML desde un PHP

Hola, has visto alguna funcion de php para xml ?
Quizas simplexml-import-dom te pueda servir.

http://www.php.net/manual/en/functio...import-dom.php
  #6 (permalink)  
Antiguo 17/08/2010, 09:58
Avatar de shanshito  
Fecha de Ingreso: noviembre-2008
Mensajes: 40
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Parsear HTML desde un PHP

Gracias estoy checando! vamos a ver como sale.
Alguna solucion mas??

Saludos!
  #7 (permalink)  
Antiguo 17/08/2010, 10:10
Avatar de shanshito  
Fecha de Ingreso: noviembre-2008
Mensajes: 40
Antigüedad: 15 años, 5 meses
Puntos: 0
De acuerdo Respuesta: Parsear HTML desde un PHP

Cita:
Iniciado por principianteZF Ver Mensaje
Hola, has visto alguna funcion de php para xml ?
Quizas simplexml-import-dom te pueda servir.

http://www.php.net/manual/en/functio...import-dom.php
Mira, por lo que estoy necesitando, no me sirve, yo necesito pasar el html a xml, o sea, que interprete sus columnas y filas como nodos XML, como hago eso con simplexml??

Si tu sabes como, podrias poner un ejemplo para todos??

gracias!!!!!
  #8 (permalink)  
Antiguo 17/08/2010, 12:56
Avatar de shanshito  
Fecha de Ingreso: noviembre-2008
Mensajes: 40
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Parsear HTML desde un PHP

Bueno, ya estoy cerca, lo que hice fue usar la funcion strim_tags() de esta manera...

Código PHP:
Ver original
  1. $url      = $_REQUEST["url"];
  2.     $fp       = fopen( $url, 'r' );
  3.     $contenido  = "";
  4.     while( !feof( $fp ) ) {
  5.         $buffer = trim( fgets( $fp, 4096 ) );
  6.         $contenido .= strip_tags($buffer,'<img>').'/';
  7.     }
  8.     echo "\n";
  9.     echo strip_tags($contenido,'<img>').'/';
  10.     echo "\n";

Entonces, saco los tags de HTML y lo convierto en string, agregandole el "/" detras de cada palabra y este es lo que me trae -->

Código TEXTO:
Ver original
  1. ///FUTURO/////MERCADO/POS//U$S//VAR U$S/////CBOT/NOV/10/382,69////*/3,67///////CBOT/MAY/11/382,13////*/1,10///////MATBA /NOV/10/272,40////*/S/C///////MATBA /MAY/11/249,40////*/S/C//////// //FISICO////MERCADO/PRECIO///Sin Cotización//////

Tambien deje el atributo <img> para despues extraer el src de la imagen asi puedo obtenerla mas tarde..... estoy intentando parsear y cortar esa cadena para convertirla en un array asi poder hacer lo que quiero con ella, espero que a alguien le sea de ayuda y nos ayudemos todos! :D saludos, voy a ir posteando las soluciones! cheers!
  #9 (permalink)  
Antiguo 17/08/2010, 14:23
Avatar de shanshito  
Fecha de Ingreso: noviembre-2008
Mensajes: 40
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Parsear HTML desde un PHP

bueno, ya logre meter todo en mi array, asi es como lo hago

Código PHP:
Ver original
  1. $url      = $_REQUEST["url"];
  2.     $fp       = fopen( $url, 'r' );
  3.     $contenido  = "";
  4.     while( !feof( $fp ) ) {
  5.         $buffer = trim( fgets( $fp, 4096 ) );
  6.         $contenido .= strip_tags($buffer,'<img>').' ';
  7.     }
  8.     echo "\n";
  9.     $trozos = explode(" ",$contenido);
  10.     foreach($trozos as $key => $value) {
  11.        if($value == "") {
  12.     unset($trozos[$key]);
  13.       }
  14.       }
  15.       $trozo = array_values($trozos);
  16.     print_r($trozo);
  17.      echo "\n";
  18.  
  19.    
  20. ?>


ahora solo me falta extraer antes de convertir en array los datos, el "SRC" de los TAGS <img>, asi puedo usarlas como quiera!!! Saludos, y gracias por el interes a todos lo que dieron un poco de bola CHE, aguanta ARGENTINA MARADONA y a todos los que no quisieron responder, QUE LA SIGAN CHUPANDO! jaja
  #10 (permalink)  
Antiguo 17/08/2010, 14:25
Avatar de shanshito  
Fecha de Ingreso: noviembre-2008
Mensajes: 40
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Parsear HTML desde un PHP

Postdata!!!

INTERNERD es la INTERNET de los NERDS!!!
  #11 (permalink)  
Antiguo 17/08/2010, 16:49
Avatar de silvanha  
Fecha de Ingreso: marzo-2006
Ubicación: En mi mundo de sueños
Mensajes: 653
Antigüedad: 18 años, 1 mes
Puntos: 65
Respuesta: Parsear HTML desde un PHP

Cita:
Iniciado por shanshito Ver Mensaje
Postdata!!!

INTERNERD es la INTERNET de los NERDS!!!


y de lo demás, sorry se me fue el tiempo xD pero que bueno que lo hayas logrado, te das cuenta =O te autorespondiste ;)

suerte y saludos! ^^
__________________
●•· No hay nada imposible..
●•· Vico-X.. ;)

Etiquetas: html, parse
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 14:20.