产品新用户1核2G1M云服务器一年70元
新用户2核4G8M轻量服务器一年70元
立即购买
【腾讯云】轻量应用服务器248 3年上线 只要198元
打开页面
点击248 1年的立即购买之后选择3年
*未买过轻量应用服务器的老用户可买
超具性价比产品,不要错过哦!!
PHP PhantomJS是一个灵活的PHP库,通过PhantomJS无头浏览器加载页面并返回页面响应。它可用于测试需要JavaScript支持的网站,并且还支持屏幕截图和PDF输出
phantomjs代码git地址:https://github.com/jonnnnyw/php-phantomjs
PHP PhantomJS需要运行PHP 5.3.0或更高版本
建议您使用Composer安装PHP PhantomJS。首先,将以下内容添加到项目的composer.json
文件中:
`
#composer.json
"scripts": {
"post-install-cmd": [
"PhantomInstaller\\Installer::installPhantomJS"
],
"post-update-cmd": [
"PhantomInstaller\\Installer::installPhantomJS"
]
}
`
这将确保在您的bin文件夹中为系统安装最新版本的PhantomJS。如果您没有在composer.json中定义bin文件夹,请添加路径:
#composer.json
"config": {
"bin-dir": "bin"
}
require包里添加
"require": { "jonnyw/php-phantomjs": "4.*" },
最后在根目录 运行 composer update
或者 composer require “<code>jonnyw/php-phantomjs:4.*” </code>
默认情况下,PhantomJS库将在bin文件夹中查找相对于脚本运行位置的PhantomJS可执行文件
~/bin/phantomjs
。如果无法找到可执行文件,或者您的PhantomJS可执行文件的路径与默认位置有所不同,例如您已经在全局安装了PhantomJS,则需要手动定义PhantomJS可执行文件的路径。
`$client->getEngine()->setPath('/path/to/phantomjs');`
composer安装好扩展后 windows会在项目本目录下生成一个bin/phantomjs.exe;
linux 会在项目根目录下生成一个bin/phantomjs
当你运行你的程序报错找不到phantomjs脚本时 请指定 ` $client->getEngine()->setPath(‘/path/to/phantomjs’); ` 脚本路径
以下说明如何进行基本的GET请求并输出页面内容:
<?php
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
/**
* @see JonnyW\PhantomJs\Http\Request
**/
$request = $client->getMessageFactory()->createRequest('http://jonnyw.me', 'GET');
/**
* @see JonnyW\PhantomJs\Http\Response
**/
$response = $client->getMessageFactory()->createResponse();
// Send the request
$client->send($request, $response);
if($response->getStatus() === 200) {
// Dump the requested page content
echo $response->getContent();
}
将屏幕截图保存到本地磁盘:
<?php
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
$width = 800;
$height = 600;
$top = 0;
$left = 0;
/**
* @see JonnyW\PhantomJs\Http\CaptureRequest
**/
$request = $client->getMessageFactory()->createCaptureRequest('http://jonnyw.me', 'GET');
$request->setOutputFile('/path/to/save/capture/file.jpg');
$request->setViewportSize($width, $height);
$request->setCaptureDimensions($width, $height, $top, $left);
/**
* @see JonnyW\PhantomJs\Http\Response
**/
$response = $client->getMessageFactory()->createResponse();
// Send the request
$client->send($request, $response);
以PDF格式输出页面:
<?php
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
/**
* @see JonnyW\PhantomJs\Http\PdfRequest
**/
$request = $client->getMessageFactory()->createPdfRequest('http://jonnyw.me', 'GET');
$request->setOutputFile('/path/to/save/pdf/document.pdf');
$request->setFormat('A4');
$request->setOrientation('landscape');
$request->setMargin('1cm');
/**
* @see JonnyW\PhantomJs\Http\Response
**/
$response = $client->getMessageFactory()->createResponse();
// Send the request
$client->send($request, $response);