PHP でのスクレイピング メモ

手っ取り早くやる方法(要 Tidy)

<?php
//ソースを持ってくる
$src = "hogehoge";

//お行儀が悪いのを整形する
$tidy = new tidy;
$tidy->parseString($src, array('output-xhtml' => true), 'UTF8');
$tidy->cleanRepair();
$declarations = '<?xml version="1.0" encoding="UTF-8"?>';
$declarations .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ';
$declarations .= '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
$src = $declarations . $tidy->html();

//パースする
$xml = @new SimpleXMLElement($src);
$xml->registerXPathNamespace('xmlns', 'http://www.w3.org/1999/xhtml');

//XPath で悠々スクレイピング
$el = $xml->xpath('//xmlns:a');
?>