2010-07-18 2 views
6

이 html 코드가 있습니다. 나 자신의 PHP 스크립트로 데이터를 구문 분석하는 간단한 HTML Dom을 사용하여.간단한 html dom을 사용하여 테이블의 셀을 인쇄하는 방법

<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] = 배열 ​​('그렉 하우스', '센추리 시티'); $ array [1] = 배열 ​​('Dexter Morgan', 'Miami');

나는 그것을 얻기 위해 몇 가지 방법을 시도했지만, 나는 그들 모두 모두에게 실패했다. 누군가 나에게 손을 줄 수 있습니까?

+0

[DOM and Xpath] (http://stackoverflow.com/questions/2019422/regex-problem-in-php)를 사용해야합니다. – quantumSoup

+0

있습니다. Simple HTML Dom을 사용하여 수행) – 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, @ Karim, dom 객체에 object ($ html)를 만드는 방법을 알려주시겠습니까? 그래서 그것을 다음과 같이 사용했습니다 : - $ table = $ html-> find ('# 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); 
시도

당신은 어떤 HTML 태그에서도 데이터를 얻을 수 있습니다 ...