PHP のスクレイピングで楽に使えそうなライブラリ PHP Simple HTML DOM Parser を使ったときのメモ
PHP Simple HTML DOM Parser だと CSSセレクタで要素指定できるのがありがたい
ライブラリなくてもスクレイピング出来そうだったけどPHPも初心者だったからか xpath が使いづらかった...
PHP Simple HTML DOM Parser の公式のドキュメント?、ライブラリとかのリンク先
実施した環境はこんな感じ
- Windows11
- XAMPP Windows 7.4.27
- PHP Simple HTML DOM Parser v1.9.1
ライブラリ取得・配置
- SourceForge よりダウンロード
https://sourceforge.net/projects/simplehtmldom/ - ダウンロードしたデータより
simple_html_dom.php
を取得 - XAMPP の htdocs の下に配置(フォルダ作っておいてもOK)
※スクレイピングする実行ファイルから読み込むのでこだわりなければ実行ファイルと同じフォルダが楽そう
スクレイピングするファイル作成
simple_html_dom.php
の読込
require_once "simple_html_dom.php"; //ファイルパスは置いた場所にする
html 読込 file_get_html(url)
$html = file_get_html('https://exampl/sample.html');
要素取得して情報表示 $html->find(CSSセレクタ)->取得情報
$html = file_get_html('https://qiita.com/');
// find した1件目の情報表示
$h2text = $html->find('h2')[0]->plaintext;
echo $h2 . '<br>';
// find した全件の情報表示(ループ処理)
foreach($html->find('h2') as $node){
$value = $node->plaintext;
echo $value . '<br>';
}
参考 スクレイピングした結果をJSONで返すAPI
<?php
// simple_html_dom 読込
require_once "simple_html_dom.php";
// html 読込
$html = file_get_html('https://qiita.com/');
// json にする情報の設定 (h2タグとってテキストとリンク設定)
$arrays = array();
foreach($html->find('h2') as $node){
$h2 = $node->plaintext;
$href = $node->firstChild()->href;
array_push($arrays, ['h2'=>$h2, 'href'=>$href]);
}
// JSON レスポンス設定
header("Content-type: application/json; charset=UTF-8; Access-Control-Allow-Origin: *");
echo json_encode($arrays);
?>