既存サイトを簡単に Web サービス化する

php の DOMDocument は便利、XML だけでなく、文法があいまいな HTML も読み込んでくれる。つまり、HTML を読み込ませると XML と同様に DOM として扱える。
よって、XHTML でなくてもサイトのページをロードして、DOM や XSLT で加工するだけで簡単に Web サービスっぽくすることも可能なわけです。

<?php
  header('Content-Type: text/html; charset=utf-8');

  $doc = new DOMDocument();

  // http://www.example.com/search?q=test の結果を取得する。
  // 実際には、$_GET の内容を組み立てて渡す。
  $doc->loadHTMLFile('http://www.example.com/search?q=test');
  
  ・・・ここでDOM を操作して整形・・・

  // XSLT で整形
  $docxsl = new DOMDocument();
  $docxsl->load('sample.xsl');
  
  $xslt = new XSLTProcessor();
  $xslt->importStylesheet($docxsl);
  
  print($xslt->transformToXML($doc));
  flush();
?>

ちょっと仕事で考えてたので、具体的なサンプルはなし。

<?php
function getXmlTransFromHtml($id, $content)
{
    $doc = new DOMDocument('1.0', 'UTF-8');
    @$doc->loadHTML($content);
    
    $dom = new DOMDocument('1.0', 'UTF-8');
    $domnode = $dom->importNode($doc->getElementById($id), true);
    $dom->appendChild($domnode);
    
    // XSLT で整形
    $docxsl = new DOMDocument();
    $docxsl->load('html2xml.xsl');
    
    $xslt = new XSLTProcessor();
    $xslt->importStylesheet($docxsl);
    
    print($xslt->transformToXML($dom));
    flush();
}
?>