2010-07-18 14 views
6

Ho questo codice html. Sto usando Simple HTML Dom per analizzare i dati nel mio script php.come stampare le celle di una tabella con dom html semplice

<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> 

ho bisogno di ottenere il testo all'interno delle TDs in un array, ad esempio:

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

Ho provato diversi modi per ottenerlo, ma ho fallito in ognuno di loro. Qualcuno può darmi una mano?

+0

Dovresti usare [DOM e Xpath] (http://stackoverflow.com/questions/2019422/regex-problem-in-php) – quantumSoup

+0

ho per farlo usando Simple HTML Dom;) – andufo

risposta

11

Questo dovrebbe fare:

// 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

ha funzionato perfettamente. Grazie! – andufo

+0

@ andufo, @ Karim, puoi dirmi come fai l'oggetto ($ html) nell'oggetto dom. Quindi lo hai usato come: - $ table = $ html-> find ('# theTable'); – Bajrang

1

@lucia nie

Si dovrebbe fare questo in modo da:

// 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

funzionerà .. provare questo

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); 

Puoi anche ottenere dati da qualsiasi tag html anche gli attributi ...

Problemi correlati