This page contains some common examples of how to use the PHP PhantomJS library.
- Setup
- Basic Request
- POST Request
- Other Request Methods
- Custom Headers
- Response Data
- Screen Captures
- Output To PDF
- Set Viewport Size
- Set Background Color
- Custom Timeout
- Delay Page Render
- On Load Finished
- PhantomJS Options
- Exceptions
For more advanced customization or to load your own PhantomJS scripts, see the custom scripts section.
Setup
By default the PhantomJS library will look for the PhantomJS executable in the bin folder relative to where your script is running ~/bin/phantomjs
. If the executable cannot be found or if the path to your PhantomJS executable differs from the default location, for example you have installed PhantomJS globally, you will need to define the path to your PhantomJS executable manually.
Note
The path must include the name of the PhantomJS executable in it, not just a path to the directory containing the executable.
Basic Request
A basic GET request:
You can also set the URL, request method and timeout period when creating a new request instance through the message factory:
POST Request
A basic POST request:
Other Request Methods
The PHP PhantomJS library supports the following request methods:
- OPTIONS
- GET
- HEAD
- POST
- PUT
- DELETE
- PATCH
The request method can be set when creating a new request instance through the message factory:
Or on the request instance itself:
Custom Headers
Custom headers can be added to the request.
For example: when you want to request an authentication protected page with Laravel 5:
Response Data
A standard response object gives you access to the following interface:
Accessor | Description | Return Type |
---|---|---|
getHeaders() | Returns an array of all response headers. | Array |
getHeader(header) | Returns the value for a specific response header e.g. Content-Type. | Mixed |
getStatus() | The response status code e.g. 200. | Integer |
getContent() | The raw page content of the requested page. | String |
getContentType() | The content type of the requested page. | String |
getUrl() | The URL of the requested page. | String |
getRedirectUrl() | If the response was a redirect, this will return the redirect URL. | String |
isRedirect() | Will return true if the response was a redirect or false otherwise. | Boolean |
getConsole() | Returns an array of any javascript errors on the requested page along with a stack trace. | Array |
Note
If the response ever contains a status code of 0, chances are the request failed. Check the request debug log for more detailed information about what may have gone wrong.
Screen Captures
You can save screen captures of a page to your local disk by creating a screen capture request and setting the path you wish to save the file to:
You will need to make sure the directory that you are saving the file to exists and is writable by your application.
You can also set the width, height, x and y axis for your screen capture:
Note
Sometimes you may want to wait for all the resources on the page to load before saving a capture to disk. This can be achieved by either delaying the page render or waiting for all resources to load.
Output To PDF
You can output a page to PDF by creating a PDF request and setting the path you wish to save the document to.
You can set an optional repeating header and/or footer to the PDF output.
The setRepeatingHeader
and setRepeatingFooter
methods take an optional second parameter that allows you to set the height of the header and/or footer. This defaults to 1cm
. You may also use the %pageNum%
and %pageTotal%
placeholders to output the current page and total page count for each. Inline styles can be applied to the injected header and footer tags allowing you to define the look and feel.
You can set the paper size and margin of the PDF.
If you prefer, you can set a standard paper format such as A4 instead of paper size.
Along with the paper orientation.
Note
Sometimes you may want to wait for all the resources on the page to load before outputting to PDF. This can be achieved by either delaying the page render or waiting for all resources to load.
Set Viewport Size
You can easily set the viewport size for a request:
Set Background Color
You can force the background color of the requested page by setting a backgroundColor
body style:
The setBodyStyles
method can be used to set any valid CSS styles on the body tag; it is not limited to just background color.
Custom Timeout
By default, each request will timeout after 5 seconds. You can set a custom timeout period (in milliseconds) for each request:
Delay Page Render
Sometimes when saving a page to local disk you may want to wait until the page is completely loaded first. In this instance you can set a page render delay (in seconds) for the request:
On Load Finished
Another way of delaying the page render is to wait until all the resources on the page have finished loading. This includes things like images, AJAX requests etc. This can be achieved by telling the client to lazy load the request.
Note
It is recommended that you set a timeout on the request when lazy loading. This guarantees that the request will return content after a period of time even if page resources are still loading. Without this you may run into issues on pages that poll resources at short intervals.
PhantomJS Options
The PhantomJS API contains a range of command line options that can be passed when executing the PhantomJS executable. These can also be passed in via the client before a request:
You can also set a path to a JSON configuration file that contains multiple PhantomJS options:
See the PhantomJS Documentation for a full list of command line options.
Exceptions
The following offers an explanation of the exceptions that may be raised by the PhantomJS library.
Exception | Description |
---|---|
InvalidExecutableException | The path to the PhantomJS executable is invalid or is not executable. |
InvalidMethodException | The request method is invalid. It must be one of OPTIONS, GET, HEAD, POST, PUT, DELETE or PATCH. |
InvalidUrlException | The URL you are requesting is an invalid format. |
NotExistsException | A file could not be found or does not exist. |
NotWritableException | A file could not be written. |
ProcedureFailedException | A PhantomJS script failed to execute successfully. |
RequirementException | A PhantomJS script is missing a required element e.g. phantom.exit(1); . |
SyntaxException | A PhantomJS script contains a javascript syntax error. |