Written by Manabu Bannai

【PHP PhantomJS】特定URLのスクリーンキャプチャを生成する方法

PHP PROGRAMMING

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);