Simple HTML DOM Parser - Send post variables

rickyduck picture rickyduck · Feb 29, 2012 · Viewed 9.6k times · Source

I have the Simple HTML DOM Parser for PHP, and I am using the following markup:

$html = file_get_html('http://www.google.com');

However how do I send post variables (like a cURL) to that page and get the response? For example

$html = file_get_html('http://www.google.com', array("Item"=>"Value", "Item2"=>"Value2"));

Answer

Another Code picture Another Code · Feb 29, 2012

The documentation doesn't mention it as far as I can see, but after taking a look in the source code I noticed the function you're using accepts a stream context as its third argument. You can create a post request with this PHP feature like this:

$request = array(
'http' => array(
    'method' => 'POST',
    'content' => http_build_query(array(
        'Item' => 'Value',
        'Item2' => 'Value2'
    )),
)
);

$context = stream_context_create($request);

$html = file_get_html('http://www.google.com', false, $context);

If you don't like contexts or would prefer a different method (like the cURL extension) you could also just fetch the page content using that, then feed it to the parser with str_get_html() or $parser->load(); the class itself does pretty much the same internally with the method you're using right now.