前回の解析ジョイントは、サイトの新着情報などから、HTMLのヘディングを取得する、というかなり苦しい状況を想定しました。そのため、どの記事のリンクも同じになってしまいますし、公開時間が取得時間になってしまってます。
同じHTMLのみのサイトでも、もう少し構造的な情報が提供されていれば、RSSと遜色ないデータ取得が可能です。
そのサンプルとして作ったのが、Linkhtml という解析ジョイントです。d3pipes最新版には含まれています。
取得したい情報はやはり以下の4つです。それを正規表現でなんとか見つけ出します。
'heading' : 見出し
'pubtime' : yyyy-mm-dd等の表記であれば、それを自動的にUnixTimestampに変換します
'link' : 見出しを囲む<a>タグからリンクを抽出します。
'fingerprint' : ここではlinkと同じです。
Linkhtmlを使ったパイプの構成例はこんな感じになります。
0 外部から取得 snoopy (対象ページのURI)
10 コード変換(UTF8へ) mbstring (対象ページのエンコーディング)
20 XML解析 linkhtml #([0-9/]{10}).*href=\"([^"]+)\" \>(.*)\</a\>#iU
30 コード変換(UTF8から) mbstring EUC-JP (内部エンコーディング)
40 ローカル保存 moduledb 86400
<?php
require_once dirname(dirname(__FILE__)).'/D3pipesParseAbstract.class.php' ;
class D3pipesParseLinkhtml extends D3pipesParseAbstract {
function execute( $html_source , $max_entries = '' )
{
$items = array() ;
$result = preg_match_all( $this->option , $html_source , $matches , PREG_SET_ORDER ) ;
if( ! $result ) {
$this->errors[] = 'Invalid pattern for this Parser' ;
}
foreach( $matches as $match ) {
if( preg_match( '#[0-9]{2,4}[/.-][0-9]{1,2}[/.-][0-9]{1,2}#' , $match[1] , $regs ) ) {
$pubtime = strtotime( $regs[0] ) ;
$link = $match[2] ;
$headline = $match[3] ;
} else if( preg_match( '#[0-9]{2,4}[/.-][0-9]{1,2}[/.-][0-9]{1,2}#' , $match[3] , $regs ) ) {
$pubtime = strtotime( $regs[0] ) ;
$link = $match[1] ;
$headline = $match[2] ;
} else {
$pubtime = time() ;
$link = $match[1] ;
$headline = $match[2] ;
}
$items[] = array(
'headline' => $headline ,
'pubtime' => $pubtime ,
'link' => $link ,
'fingerprint' => $link ,
) ;
}
return $items ;
}
}
?>