How to set user agent for file_get_html() in dom.php

The problem with file_get_html ()

I really like the Simple HTML DOM Parser for PHP cause of its simplicity but today I encountered the problem of grabbing different HTML for different devices, so I checked the docs but couldn’t find any option how to do it.

So, I dugg into the lib code myself, ready for some manual patching, when I found out that there is actually a way to do this the proper way.

The solution

Let’s assume, you open a connection like this:

$html = file_get_html ($url);

In order to set a user agent for iPhone 5 for example, simply do this:

$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($url, false, $context);

As you can see, you can even set more headers if you want.

Damn, that was easy, wasn’t it? :-)

Follow me on social media

2 thoughts on “How to set user agent for file_get_html() in dom.php

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.