2012-12-10 30 views
0

我正在使用simplehtmldom從網站中獲取html。然後,我搜索頁面上的所有div,並且 顯示字數大於300的內聯字母。爲此,我使用foreach進行迭代。通過div循環並使用simplehtmldom提取文本

$findDivs = $html->find('div'); 

foreach($findDivs as $findDiv) { 
    $wordCount = explode(' ', $findDiv->outertext); 
    $wordCount = count($wordCount); 
    if($wordCount <= 300) { 
    $findDiv->outertext = ''; 
    } 
    else { 
    echo $findDiv->outertext . '<br />'; 
    } 
} 

我的問題是結果重複了6次。我只能假設它是因爲所有div都在每次迭代循環。但是,我不確定我可以使用什麼技術來確保每個div只評估一次。

+0

迭代的div遞歸,不處理一個div的兒童,如果它包含300多個字。 –

+0

請提供樣本html。否則你不可能得到建設性的幫助。 – pguardiario

回答

0

我不知道爲什麼,但這已解決了我的問題。

我增加了 '1' 參數在$ HTML->找到( 'DIV',1);

所以工作代碼如下所示:

$findDivs = $html->find('div',1); //add a 1 to the divs. this works as the script now only loops once. 

foreach($findDivs as $findDiv) { 
    $wordCount = explode(' ', $findDiv->outertext); 
    $wordCount = count($wordCount); 
    if($wordCount <= 300) { 
    $findDiv->outertext = ''; 
    } 
    else { 
    echo $findDiv->outertext . '<br />'; 
    } 
} 
0

你想innertext,但你的代碼狀態outertext - 我認爲這是重複的原因。

foreach($html->find('div') as $findDiv) { 
    $wordCount = explode(' ', $findDiv->innertext); 
    $wordCount = count($wordCount); 
    if($wordCount > 300) { 
    echo $findDiv->outertext . '<br />'; 
    } 
} 
+0

嗨大衛,謝謝,但我恐怕我嘗試了innertext,outertext和明文,並且每次重複都有相同的結果。 – user1882752