【PHP PhantomJS】特定URLのスクリーンキャプチャを生成する方法
PHPとPhantomJSを使って、特定URLのスクリーンキャプチャを生成する方法です。例えば、ユーザーがフォームにURLを入力すると、自動的にURL先のスクリーンショットが保存でます。最近こういった感じのサービスが増えてる気がしたので、やりかたをまとめます。といっても、めっちゃ簡単です。
» ドキュメント
composerでPHP PhantomJSをインストール
PHP PhantomJSというライブラリを使います。1番定番のライブラリです。composer.jsonを作成して、下記のとおりに記載します。
{
"scripts": {
"post-install-cmd": [
"PhantomInstaller\\Installer::installPhantomJS"
],
"post-update-cmd": [
"PhantomInstaller\\Installer::installPhantomJS"
]
},
"config": {
"bin-dir": "bin"
},
"require": {
"jonnyw/php-phantomjs": "4.*"
}
}
下記のスクリプトでスクリーンショットを保存する
下記をindex.php
とかで保存して、実行すれば完了。まじで簡単ですね。
<?php
require_once( 'vendor/autoload.php' );
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
$request = $client->getMessageFactory()->createCaptureRequest('http://jonnyw.me');
$response = $client->getMessageFactory()->createResponse();
// ファイルの保存先を指定する
$file = 'screenshots/file.jpg';
$request->setOutputFile($file);
$client->send($request, $response);
※P.S:無料メルマガで発信中:過去の僕は「ブログ発信で5億円」を稼ぎました。次は「30億円」を目指します。挑戦しつつ、裏側の思考を「メルマガ」から発信します。不満足なら1秒で解約できます。無料登録は「こちら」です。