LoginSignup
14
14

More than 5 years have passed since last update.

phpQueryでHTMLのtitle要素を抜き出す

Last updated at Posted at 2014-01-03

はじめに

phpQueryを使うと、PHPでjQueryみたいなことができる。スクレイピングに使おう。
Webサイトはこちら。
https://code.google.com/p/phpquery/

phpQuery準備

上記WebサイトのDownloadsから、phpQuery-0.9.5.386.zipをダウンロードして展開。
Webサーバーの /var/www/html/ に配置する。

wget https://code.google.com/p/phpquery/downloads/detail?name=phpQuery-0.9.5.386.zip
unzip phpQuery-0.9.5.386.zip
mv phpQuery /var/www/html/

これでアクセスすると、Cent OSだと

PHP Fatal error: Class 'DOMDocument' not found in ****

とか出るので、php-mbstringとphp-xmlをyumでインストールする。

yum install php-mbstring php-xml -y

加えて、後で使うためにGoogleトップページをダウンロードしておく。

wget http://www.google.co.jp/

title要素を抜き出す

先ほどダウンロードしたGoogleのHTMLに書かれているtitle要素を抜き出す。
手順は、
1. phpQueryのスクリプト読み込み
2. phpQueryのメソッドをコールしてindex.html解析
3. title要素抜き出して表示
の順。

test.php
require_once('phpQuery/phpQuery.php');

phpQuery::newDocumentFile('index.html');
print pq('title')->text();

test.phpに保存し、Webブラウザでアクセスすると、
キャプチャ.PNG
と表示される。

さいごに

phpQueryを使ってHTMLのtitle要素を抜き出してみた。色々と使えそう。

14
14
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
14
14