2010-07-18 13 views
6

के साथ तालिका के कक्षों को मुद्रित करने के लिए मेरे पास यह HTML कोड है। मैं अपने स्वयं के PHP स्क्रिप्ट में डेटा को पार्स करने के लिए सरल HTML डोम का उपयोग कर रहा हूं।सरल HTML डोम

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

मैं, उदाहरण के एक सरणी में TDs के अंदर का पाठ प्राप्त करने की आवश्यकता:

$ सरणी [0] = सरणी ('ग्रेग हाउस', 'सेंचुरी सिटी'); $ सरणी [1] = सरणी ('डेक्सटर मॉर्गन', 'मियामी');

मैंने इसे पाने के कई तरीकों की कोशिश की है, लेकिन मैं उनमें से प्रत्येक और हर किसी में विफल हूं। क्या कोई मुझे हाथ दे सकता है?

+0

आपको [डोम और एक्सपैथ] (http://stackoverflow.com/questions/2019422/regex-problem-in-php) – quantumSoup

+0

का उपयोग करना चाहिए सरल HTML डोम का उपयोग करके इसे करने के लिए;) – andufo

उत्तर

11

यह करना चाहिए:

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

पूरी तरह से काम किया। धन्यवाद! – andufo

+0

@ andufo, @ करीम, क्या आप कृपया मुझे बता सकते हैं कि आप वस्तु ऑब्जेक्ट में ऑब्जेक्ट ($ html) कैसे बनाते हैं। तो आपने इसे इस प्रकार उपयोग किया है: - $ table = $ html-> ढूंढें ('# theTable'); – Bajrang

1

@lucia एनआईई

आप इस ऐसा करना चाहिए:

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

यह काम करेगा .. कोशिश इस

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

आप किसी भी एचटीएमएल टैग से डेटा भी प्राप्त कर सकते हैं ...