phpuser-agentsimpledom

How can I randomise User Agent for file_get_html?


I'm scraping a website (nothing dodgy) with simple_html_dom and need to randomise my user agent.

Tried to multiple array content but keep getting the first one.

$opts = array(
     'http'=>array(
       'header'=>"User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53\r\n"
     )
   );
$context = stream_context_create($opts);
$html = file_get_html($webpage, false, $context);

Solution

  • Add this code above your and use $header in opts

    $headers = [
        'User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53\r\n',
        'header 2',
        'header n'
    ];
    $header = $headers[array_rand($headers)];