how to Execute PhantomJS from PHP

I want to execute PhantomJS from PHP on localhost.

Can any body explain how to execute PhantomJS from PHP and what package I should download from phantomjs.org?


Solution 1:

  • download the PhantomJS binary, upload it somewhere and make it executable (chmod +x)
  • if you are going to make screenshots, setup fontconfig (this is pretty specific to my config but the goal is to make sure to have at least some fonts on your system)
  • run the following in PHP:
    $response = exec('/path/to/phantomjs myscript.js');

Solution 2:

There's actually a library called PHP PhantomJS, intended to make this easier for you!

PHP PhantomJS is a flexible PHP library to load pages through the PhantomJS headless browser and return the page response. It is handy for testing websites that demand javascript support and also supports screen captures.

Full documentation

Feature list :

  • Load webpages through the PhantomJS headless browser
  • View detailed response data including page content, headers, status code etc.
  • Handle redirects
  • View javascript console errors
  • View detailed PhantomJS debugged information
  • Save screen captures to local disk
  • Set viewport size
  • Define screen capture x, y, width and height parameters
  • Delay page rendering for a specified time
  • Execute PhantomJS with command line options
  • Easily build and run custom PhantomJS scripts

Make sure, though, that your version of PhantomJS is compatible with your version of PHP PhantomJS:

Please Note: Version 4.0 of this library is currently waiting on an unresolved issue with PhantomJS 2.0.

Solution 3:

I recently published a project that gives PHP access to a browser. Get it here: https://github.com/merlinthemagic/MTS. Under the hood it relies on PhantomJS.

After downloading and setup you would simply use the following code:

$myUrl          = "http://www.example.com";
$windowObj      = \MTS\Factories::getDevices()->getLocalHost()->getBrowser('phantomjs')->getNewWindow($myUrl);

//now you can either retrive the DOM and parse it, like this:
$domData    = $windowObj->getDom();

//or take screen shots
$imageData    = $windowObj->screenshot();

//or use the mouse to click buttons:
$windowObj->mouseEventOnElement("[id=searchInput]", 'leftclick');

//or type with the keyboard :
$windowObj->sendKeyPresses("my search words");

//or load and execute custom javascript, fill forms etc, etc.