Question

Page which I need to parse has items with id="item". There are about 10 items on the page. I need to parse them all and show in random order on my page.

require_once 'simple_html_dom.php';
<br>
$data1 = file_get_html('http://linktowebsite.com';
<br>
if($data1->innertext!='' and count($data1->find('.item'))) {
    <br>
    foreach($data1->find('.item') as $a) {
        <br>
        echo $a;
    }
}

this code parses but didn't shows in random order. Help me please to show them in random order.

Was it helpful?

Solution

Collect the items, and then apply randomization.

require_once 'simple_html_dom.php';
$data1 = file_get_html('http://linktowebsite.com';
$items = array();
if($data1->innertext!='' and count($data1->find('.item'))){
    foreach($data1->find('.item') as $a){
        $items[] = $a;
    }
}
shuffle($items); // randomize
print_r($items);

You could also use array_rand or usort with a random sort callback.

usort($items, "rand"); // I think this works
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top