LoginSignup
5
6

More than 5 years have passed since last update.

Composer経由でphpQueryをインストール

Last updated at Posted at 2018-11-12

phpでwebスクレイピングするときに使用するライブラリにphpQueryというものがあります。
zipでダウンロードできるようですが、今回はcomposer経由でインストールしたいと思います。

環境

  • macOS Mojave 10.14.1
  • Composerインストール済み

1. 作業するディレクトリでcomposer init

$ composer init

対話式でconfig設定する画面になりますが、今回はすべてスキップします。
すると、作業ディレクトリ内にcomposer.jsonが作られていると思います。

2. phpQueryを検索

今回はcomposerでphpQueryがインストールできるか検索しただけなので、スキップしても問題ありません。
パッケージ検索はcomposer search {検索するパッケージ}

$  composer search phpQuery
electrolinux/phpquery phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library
jaeger/querylist Simple, elegant, extensible PHP Web Scraper (crawler/spider),Use the css3 dom selector,Based on phpQuery! 简洁、优雅、可扩展的PHP采集工具(爬虫),基于phpQuery。
foolz/sphinxql-query-builder A PHP query builder for SphinxQL. Uses MySQLi to connect to the Sphinx server.
(略)
atofighi/phpquery phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library
ridaamirini/phpquerybuilder An fast, small SQL Builder based on FluentPDO

ちゃんとありますね。

3. phpQueryインストール

それではインストールしていきましょう。
composer経由でパッケージインストールする際は、composer require {パッケージ名}

$ composer require electrolinux/phpquery
Using version ^0.9.6 for electrolinux/phpquery
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing electrolinux/phpquery (0.9.6): Downloading (100%)         
Writing lock file
Generating autoload files

composer.lockファイルと、vendorディレクトリが生成されていると思います。

4. インストールされたか確認

$ composer info
electrolinux/phpquery 0.9.6 phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library

ちゃんと入っていますね。

サンプルコード

こんな感じで使用します。

<?php

require './vendor/autoload.php';

$html = file_get_contents('取得したいURL');
// h1要素を取得して出力
echo phpQuery::newDocument($html)->find("h1")->text();
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6