2015-09-08 32 views
3

我正在刮取值的網頁並將它們存儲在一個數組中,此刻我可以全部拉入td.Place值,因爲它具有類。簡單的HTML DOM解析器 - 刮沒有id或類的html內容

注:我使用簡單的HTML DOM解析器

我當前的代碼,工程:

<?php 

include('simple_html_dom.php'); 
$html = file_get_html('http://www...'); 

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

// initialize array to store the cell data from each row 
$rowData3 = arra 

foreach($row->find('td.Place') as $cell) 
{ 

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

} 
// push the row's data array to the 'big' array 
$theData3[] = $rowData3; 

} 

print_r($theData3); 
?> 

有什麼問題?

我想在值 & 拉 - 「梯度 **前兩個TD類=內的」 3在類=奇格勒*。因爲兩個TD值沒有id或class,所以我覺得很難。

這是我目前刮

<tr class="PersonrRow odd"> 
     <td></td> 
     <td class="place">T9</td> 
     <td> 
     <span class="rank"></span>16</td> 
     <td class="Grad">-7 
     </td> 
     <td> 
     100 
     </td> 
     <td> 
     -3 
     </td> 
     <td> 
     712 
     </td> 
     <td> 
     682 
     </td> 
     <td> 
     702 
     </td> 
     <td> 
     68 
     </td> 
     <td class="person large"></td> 
     <td style=""> 
     277 
     </td> 
    </tr> 
+0

我很困惑這裏是你使用php來取消這個或jquery,因爲我看不到jquery在這個問題 –

+0

道歉標記我正在使用php,我會從我的問題標籤中刪除jquery。謝謝 – Helena

+0

我不明白這裏的問題,使其更清晰 – Gtopuria

回答

3

好了的HTML,所以做了一些研究,在這裏我的舊文件後挖是我想出了你。你不會需要任何花哨的插件或任何東西只是PHP的DOMDocument:

PHP

<?php 
    $thedata3 = array(); 
    $rowdata3 = array(); 
    $DOM = new DOMDocument(); 
    $DOM->loadHTMLFile("file path or url"); 

    // get the actual table itself 
    $xpath = new DOMXPath($DOM); 
    $table = $xpath->query('//table[@id="tableID"]')->item(0); 


    $rows = $table->getElementsByTagName("tr"); 

    for ($i = 0; $i < $rows->length; $i++) { 
     $cols = $rows->item($i)->getElementsbyTagName("td"); 
     for ($j = 0; $j < $cols->length; $j++) { 

      //change $cols->item($j) $cols->item('insert column number here') 
      // that will give you the proper column you're after 
      array_push($rowdata3, $cols->item($j)->nodeValue); 
     } 
     array_push($thedata3, $rowdata3); 
     $rowdata3 = array(); //empty the $rowdata3 array for fresh results 
    } 
?> 

這是我可以做的最好的是什麼您提供我,但我希望它能幫助在某種程度上,如果您需要任何幫助,請讓我知道。

爲了便於訪問和可讀性。我會建議像所計劃的那樣將所有內容都投入到關聯數組中,然後在刮掉所有數據之後。操縱陣列數據並從中拉取所需數據。這應該更容易。

引用

PHP.net DOM文檔 http://php.net/manual/en/class.domdocument.php

PHP.net DOMXPath http://php.net/manual/en/class.domxpath.php

此鏈接這裏有DOM文檔和DOMXPath類的所有引用。這將有你需要的一切,讓你開始!

+0

感謝馬克,只是一個簡單的問題,我解析的html頁面是相當大的,你不必在getElementsByTagName中指向class =「Grad」,所以我確保我從該區域獲得正確的值? – Helena

+0

在這裏你去了海倫娜,我已經添加了代碼來解決這個問題。如果你需要其他東西,請告訴我。也請接受這個答案,並upvote,如果它是你正在尋找的解決方案。 –

+0

很好的答案,非常有用,我在運行腳本時似乎遇到錯誤。 PHP致命錯誤:無法使用[]讀取第22行的/testen/tester.php 您在/ var/mail/root中有新郵件 – Helena