2014-02-18 60 views
-1

我想通過php dom解析器讀取這個HTML表格的特定值。我希望我的代碼只讀取「td width」標籤並僅從表中輸出這些項目,如下所示:簡單的DOM html解析器讀取html表格

「WAITLIST,91630,ACCY 2001,10,Intro Financial Accounting,3.00,Zou,Y, Duques酒店251,9:35 AM-10:50AM,01/13/14-04/28/14「

下面是HTML表格:

<table width="100%" border="0" cellspacing="1" cellpadding="0" bgcolor="#006699"> 
           <tr align="center" class="tableRow1Font"> 
            <td width="7%">WAITLIST</td> 
            <td width="5%">91630</td> 
            <td width="11%"> 
       ACCY <A HREF="http://www.gwu.edu/~bulletin/ugrad/accy.html#2001" target="_blank">2001</A> 
            </td> 
            <td width="5%">10</td> 
            <td width="16%">Intro Financial Accounting</td> 
            <td width="6%">3.00</td> 
            <td width="8%"> Zou, Y</td> 
            <td width="8%"><A HREF="http://www.gwu.edu/~map/building.cfm?BLDG=DUQUES" target="_blank" >DUQUES</a> 251</td> 
            <td width="13%">TR<br>09:35AM - 10:50AM</td> 
            <td width="14%"> 
             01/13/14 - 04/28/14 
            </td> 
            <td width="7%"> 

            </td> 
           </tr> 
                </table 

這是我的PHP代碼,其抓住整個表,其中一些元素我不想在我的輸出中重複輸出多次:

// Retrieve the DOM from a given URL 
$html = file_get_html('testdata.html'); 

foreach($html->find('table') as $e){ 
foreach($html->find('td') as $f){ 
    echo $f->innertext . '<br>'; 
    } 
    } 

我該如何更改我的代碼才能獲取並輸出這些元素: 「WAITLIST,91630,ACCY 2001,10,Intro Financial Accounting,3.00,Zou,Y,Duques 251,9:35 AM-10:50AM,01/13/14-04/28/14"

回答

1
// Retrieve the DOM from a given URL 
$html = file_get_html('testdata.html'); 

foreach($html->find('table') as $e){ 
    foreach($e->find('td') as $f){ 
     echo strip_tags($f->innertext) . '<br>'; 
    } 
} 

你是八九不離十已經...

忘記了標記。看看strip_tags是否適合你。

http://us3.php.net/strip_tags

+0

老兄,你搖滾!這個伎倆。謝謝! –