2010-07-18 62 views
6

tengo este código html. Estoy usando Simple HTML Dom para analizar los datos en mi propio script php.cómo imprimir las celdas de una tabla con html dom simple

<table> 
    <tr> 
     <td class="header">Name</td> 
     <td class="header">City</td> 
    </tr> 
    <tr> 
     <td class="text">Greg House</td> 
     <td class="text">Century City</td> 
    </tr> 
    <tr> 
     <td class="text">Dexter Morgan</td> 
     <td class="text">Miami</td> 
    </tr> 
</table> 

que necesita para obtener el texto dentro de las anotaciones en una matriz, ejemplo:

$ array [0] = array ('Greg House', 'Century City'); $ array [1] = array ('Dexter Morgan', 'Miami');

He intentado varias formas de conseguirlo pero he fallado en todos y cada uno de ellos. ¿Alguien puede darme una mano?

+0

Debe usar [DOM y Xpath] (http://stackoverflow.com/questions/2019422/regex-problem-in-php) – quantumSoup

+0

tengo para hacerlo usando Simple HTML Dom;) – andufo

Respuesta

11

Esto debería hacer:

// get the table. Maybe there's just one, in which case just 'table' will do 
$table = $html->find('#theTable'); 

// initialize empty array to store the data array from each row 
$theData = array(); 

// loop over rows 
foreach($table->find('tr') as $row) { 

    // initialize array to store the cell data from each row 
    $rowData = array(); 
    foreach($row->find('td.text') as $cell) { 

     // push the cell's text to the array 
     $rowData[] = $cell->innertext; 
    } 

    // push the row's data array to the 'big' array 
    $theData[] = $rowData; 
} 
print_r($theData); 
+0

funcionó perfectamente. ¡Gracias! – andufo

+0

@ andufo, @ Karim, ¿Puedes decirme cómo haces object ($ html) en el objeto dom? Entonces lo has usado como: - $ table = $ html-> find ('# theTable'); – Bajrang

1

NIE @lucia

usted debe hacer esto por lo que:

// initialize empty array to store the data array from each row 
$theData = array(); 

// loop over rows 
foreach($html->find('#theTable tr') as $row) { 

// initialize array to store the cell data from each row 
$rowData = array(); 
foreach($row->find('td.text') as $cell) { 

    // push the cell's text to the array 
    $rowData[] = $cell->innertext; 
} 

// push the row's data array to the 'big' array 
$theData[] = $rowData; 
} 
print_r($theData); 
3

que va a funcionar .. probar este

include('simple_html_dom.php'); 
$html = file_get_html('mytable.html'); 
foreach($html->find('table tr td') as $e){ 
    $arr[] = trim($e->innertext); 
    } 

print_r($arr); 

También puede obtener datos de cualquier etiqueta html incluso atributos ...

Cuestiones relacionadas