Search code examples
phparraysforeachsimple-html-dom

How to create array in foreach loop?


I am using PHP HTML DOM Parser to get data from another site. First i get URLs of my trades on this site and than i send another request on each trade url to get comments .I want to make an array of comments so i can sort them later. Why i cant create array ?

It looks like this

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);

If i echo $time or $text i always get data successfully.


Solution

  • I found what was the problem.

    The Simple HTML DOM Parser does not clean up memory in the DOM each time file_get_html or str_get_html is called so it needs to be done explicity each time you have finished with the current DOM.

    So I added $html->clear(); at the end of the loop.

    Credits: electrictoolbox.com