2016-02-14 119 views
3

我使用PHP HTML DOM解析器從其他站點獲取數據。首先,我在本網站上獲得了我的交易的網址,並且我在每個交易網址上發送了另一個請求以獲得評論。我想要發表一系列評論,以便稍後對它們進行排序。爲什麼我不能創建數組?如何在foreach循環中創建數組?

它看起來像這樣

include_once('simple_html_dom.php'); 
$result = array(); 
$html = file_get_html('http://csgolounge.com/profile?id='.$steamid); 

foreach($html->find('div.tradepoll') as $trade) 
    { 
    $tradeid = $trade->find('.tradeheader')[0]->find('a')[0]->href; 
    $html = file_get_html('http://csgolounge.com/'.$tradeid);  

     foreach($html->find('div.message') as $message) 
     { 

     if($message->find('p',0)){} 

     else 
      {      
      $left = $message->find('.msgleft')[0]; 
      $right = $message->find('.msgright')[0]; 

      //information about comments 
      $time = trim(strip_tags_content($left->innertext)); 
      $text = $left->find('.msgtxt')[0]; 

      $result[$time]['time'] = $time; 
      $result[$time]['text'] = $text;      
      } 

     } 

    } 

    echo json_encode($result); 

二HTML看起來像這樣http://paste.ofcode.org/kudYfjCigYL247cftQMeSf

如果我回聲$時間或$文字我總是得到的數據成功。

+0

那麼是什麼問題? '$ result'是你想要的數組。不是嗎?我有點困惑。 –

+0

是的,我想在帶有註釋的foreach循環中創建數組。問題是,回聲json_encode($結果);什麼也不返回 – ToniD

+0

如果你'var_dump($ result);'是你期望的?也許json_encode在非UTF-8編碼上下降了。 – Progrock

回答

0

我發現是什麼問題。

簡單的HTML DOM解析器不會在每次調用file_get_html或str_get_html時清除DOM中的內存,因此每次完成當前DOM時都需要執行明確性。

所以我添加了$ html-> clear();在循環結束時。

Credits:electrictoolbox.com