PuPHPeteer by Johann Pardanaud is PHP bridge for Google Chrome’s Puppeteer headless chrome Node.js API. PuPHPeteer is based on another package by Johann called Rialto, which is a package to manage Node resources from PHP.
Examples
PuPHPeteer has similar PHP examples based on the Puppeteer examples, to get a feel for how you might use the API in PHP.
Here’s an example of navigating to a page and taking a screenshot:
1use Nesk\PuPHPeteer\Puppeteer; 2 3$puppeteer = new Puppeteer; 4$browser = $puppeteer->launch(); 5 6$page = $browser->newPage(); 7$page->goto('https://example.com'); 8$page->screenshot(['path' => 'example.png']); 910$browser->close();
Here’s an example of evaluation a script in the context of a page:
1use Nesk\PuPHPeteer\Puppeteer; 2use Nesk\Rialto\Data\JsFunction; 3 4$puppeteer = new Puppeteer; 5 6$browser = $puppeteer->launch(); 7$page = $browser->newPage(); 8$page->goto('https://example.com'); 910// Get the "viewport" of the page, as reported by the page.11$dimensions = $page->evaluate(JsFunction::create("12 return {13 width: document.documentElement.clientWidth,14 height: document.documentElement.clientHeight,15 deviceScaleFactor: window.devicePixelRatio16 };17"));1819printf('Dimensions: %s', print_r($dimensions, true));2021$browser->close();
Differences
The most significant difference, in my opinion, is that in every method call and getter/setter in PuPHPeteer is synchronous.
Although PuPHPeteer supports the full Node API, there are a few implementation differences. The biggest is creating a new Puppeteer;
instance instead of using require('puppeteer')
in Node. When you create an instance using new Puppeteer;
it creates a new Node process controlled by PHP.
Next, you can pass configuration options to the constructor:
1[ 2 // Node's executable path 3 'executable_path' => 'node', 4 5 // How much time (in seconds) the process can stay inactive before being killed 6 'idle_timeout' => 60, 7 8 // How much time (in seconds) an instruction can take to return a value 9 'read_timeout' => 30,1011 // How much time (in seconds) the process can take to shutdown properly before being killed12 'stop_timeout' => 3,1314 // A logger instance for debugging (must implement \Psr\Log\LoggerInterface)15 'logger' => null,1617 // Enables debugging mode:18 // - adds the --inspect flag to Node's command19 // - appends stack traces to Node exception messages20 'debug' => false,21]
PuPHPeteer requires PHP >= 7.1
and Node >= 8
. Check out the GitHub repo for the full readme and installation instructions. Great job Johann!
Filed in:
Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.