ウェブページを解析・パースするための方法4つ

解析方法4つの特徴

ウェブページの解析のうち入手が容易で使い方が手軽な方法として4つあげました。それぞれに特徴があるので、サイトの特性に応じた方法を採用するのが良いと思います。ちなみにわたしはアルファブログ、2ch、Yahoo、OKwave、モバゲーなどの解析をやった経験がありますが、それぞれちがった方法で解析しました。

PHP標準関数 感覚的に構築されてるサイトの解析(一行ずつこつこつ型)
HTML Simple Parser シンプルなHTMLのサイトの解析
HTML DOM Parser divやclassなどの属性多用のするサイトの解析
MagpieRSS RSSなどXMLマークアップが厳格なサイトの解析

PHP標準関数

  • 使い方
$html = file('http://www.yakedo.net/');
foreach ($lines as $line_num => $line) {
  echo $line;
}

$html = file_get_contents('http://www.yakedo.net/');
echo "$html";

HTML Simple Parser

  • ダウンロード

http://sourceforge.net/projects/simplehtmldom/files/

  • 使い方
require_once 'simple_html_dom.php';

$html = file_get_html('http://www.yakedo.net/');
// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';
}
// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';
}

HTML DOM Parser

  • ダウンロード

http://sourceforge.net/projects/php-html/files/

  • 使い方
require_once 'htmlparser.inc';

$parser = HtmlParser_ForURL ('http://www.yakedo.net/');
while ($parser->parse()) {

  # 領域開始
  if ($parser->iNodeAttributes['class']== "xxx" && $parser->iNodeType == NODE_TYPE_ELEMENT){
    $title_flg = true;
  }

  # 領域終了
  if ($parser->iNodeAttributes['class']== "xxx" && $parser->iNodeType == NODE_TYPE_ELEMENT){
    $title_flg = false;
  }

  # データ処理
  if ($title_flg){
    $value = mb_convert_encoding($parser->iNodeValue, 'UTF-8', 'auto');
    $href = $parser->iNodeAttributes['href'];
    echo "$value $href\n";
  }
}

MagpieRSS

  • ダウンロード

http://magpierss.sourceforge.net/

  • 使い方
require_once 'rss_fetch.inc';
require_once 'rss_utils.inc';

$rss = @fetch_rss('http://www.yakedo.net/index.xml');
$site_title = $rss->channel['title'];
$site_link = $rss->channel['link'];
$site_description = $rss->channel['description'];
foreach ($rss->items as $item ) {
  $title = $item['title']
  $link   = $item['link'];
  $about = $item['about'];
  $atom = $item['atom_content'];
  $cont = $item['content'];
  $encd = $cont['encoded'];
  $dc = $item['dc'];
  $date1 = date('Y/m/d', $item['date_timestamp']);
  $date2 = getrssdate($dc['date']);
}
function getrssdate($text){
	$spd = split("T",$text);
	return $spd[0];
}