2013-07-11 26 views
0

我需要從在線時間表(針對學校)中提取教程到數組中。所以我可以將數據插入到我的數據庫中。在線時間表(網址:roosters-hd.stenden.com)看起來像這樣:將HTML表格元素提取到數組中

在左邊我們看到時間,並在頂部的學生(Mo,Tu,We,Th,Fr)。非常基本。

每課包含6個我需要獲取的值。

除此之外,我還需要獲取[startDate]和[endDate]。時間基於課程單元所在的行以及它的行數。日期可以通過將列號添加到開始日期(打印在頂部)來計算。 那麼到底該數組將是這個樣子:

[0] => Array 
     (
      [0] => Array 
       (
        [Name] => Financiering 
        [Type] => WC 
        [Code] => DECBE3 
        [Classroom] => E2.053 - leslokaal 
        [Teacher] => Verboeket, Erik (E) 
        [Class] => BE1F, BE1B, BE1A 
        [StartDate] => 04/06/2013 08:30:00 
        [EndDate] => 04/06/2013 10:00:00 
       ) 
       etc. 

因爲我缺乏在取數據的經驗,我會適當地被非常低效和不靈活的解決方案告終。像我應該使用XML解析器?或正則表達式?關於如何解決這個問題的任何想法?

+0

請** **不是正則表達式! http://stackoverflow.com/a/1732454/2170192 –

+0

是不是正則表達式,正則表達式是用於解析字符串,它是非常強大的,但它仍然不應該用於這種解析。還鏈接你發佈返回400個不好的請求。這將是很好的看到現場的例子,你可以把它放在jsfiddle.net –

+0

固定鏈接。 我現在沒有任何例子,因爲我不知道我應該從哪裏開始。我的意思是,提取數據的正確有效方法。 – JasperJ

回答

2

正則表達式的方法:

<pre><?php 
$html = file_get_contents('the_url.html'); 

$clean_pattern = <<<'LOD' 
~ 
    # definitions 
    (?(DEFINE) 
     (?<start>   <!--\hSTART\hOBJECT-CELL\h-->     ) 
     (?<end>   (?>[^<]++|<(?!!--))*<!--\hEND\hOBJECT-CELL\h--> ) 

     (?<next_cell>  (?>[^<]++|<(?!td\b))*<td[^>]*+> ) 
     (?<cell_content> [^<]*+       ) 
    ) 

    # pattern 
    \g<start> 
     \g<next_cell>  (?<Name>  \g<cell_content> ) 
     \g<next_cell>  (?<Type>  \g<cell_content> ) 
     \g<next_cell>  (?<Code>  \g<cell_content> ) 

     \g<next_cell>  (?<Classroom> \g<cell_content> ) 
     \g<next_cell> 

     \g<next_cell>  (?<Teacher> \g<cell_content> ) 
     \g<next_cell>  
     \g<next_cell>  (?<Class>  \g<cell_content> ) 
    \g<end> 
~x 
LOD; 

preg_match_all($clean_pattern, $html, $matches, PREG_SET_ORDER); 

foreach ($matches as $match) { 
    echo <<<LOD 
    Name: {$match['Name']} 
    Type: {$match['Type']} 
    Code: {$match['Code']} 
    Classroom: {$match['Classroom']} 
    Teacher: {$match['Teacher']} 
    Class: {$match['Class']}<br/><br/> 
LOD; 
} 

的DOM/XPath的方式:

$doc = new DOMDocument(); 
@$doc->loadHTMLFile('the_url.html'); 
$xpath = new DOMXPath($doc); 
$elements = $xpath->query("//*[comment() = ' START OBJECT-CELL ']"); 
$fields = array('Name', 'Type', 'Code', 'Classroom', 'Teacher', 'Class'); 
$not_needed = array(10,8,6,1,0);  
foreach ($elements as $element) { 
    $temp = explode("\n", $element->nodeValue); 
    foreach ($not_needed as $val) { unset($temp[$val]); } 
    array_walk($temp, function (&$item){ $item = trim($item); }); 
    $result[] = array_combine($fields, $temp); 
} 
print_r ($result); 
+0

我在Rubular中嘗試了您的原始圖案,但它似乎不匹配任何東西。 http://rubular.com/r/xwfwYKy13S。 – JasperJ

+1

@JasperJ:ruby不是用於Ruby的ruby,你可以做的最好的測試是在你的代碼中!否則,您可以使用專爲PHP設計的http://regex.larsolavtorvik.com/。 –

+0

對,愚蠢的我。我嘗試了preg_match_all($ raw_pattern,$ data,$ out);數據是來自url的file_get_content。但仍然沒有成功(PHP 5.3.26)。但我會等待更新。 – JasperJ