プログラミングで飯を食え。腕をあげたきゃ備忘録!

PHP、JavaScript、HTML5、CSS3などWEB系言語を中心に基本テク、備忘録をまとめます。Android、Iphoneアプリ開発についても!

PHPでtableのHTMLをcsvとしてダウンロードする。

function table_tag2csv($buff) {
  $buff = preg_replace("/>[\s]+<",$buff);

  $buff = preg_replace("/^.*<table[^>]*>/Uis","",$buff);
  $buff = preg_replace("/<\/table>.*$/is","",$buff);

  $buff = preg_replace("/<([a-z]+) ([^>]+)>/i","<$1>",$buff);
  $buff = preg_replace("//i","",$buff);
  $buff = preg_replace("/<\/th>/i","",$buff);

  $buff = preg_replace("/<\/?[^(tr|td)<>]+>/i","",$buff);

  $buff = str_replace("\r\n","\n",$buff);
  $buff = preg_replace("/(\r|\n)/","\r\n",$buff);

  $csv = "";
  if(preg_match_all("/(.*)<\/tr>/iU",$buff,$trmatches)){
    foreach($trmatches[1] as $rows){
      if(preg_match_all("/(.*)<\/td>/iU",$rows,$tdmatches)){
        for($i=0;$i<count($tdmatches[1]);$i++){
          if(strpos($tdmatches[1][$i],",")!==false || strpos($tdmatches[1][$i],'"')!==false || strpos($tdmatches[1][$i],"\r\n")!==false){
            $tdmatches[1][$i] = '"'.str_replace('"','""',$tdmatches[1][$i]).'"';
          }
          $tdmatches[1][$i] = htmlspecialchars_decode($tdmatches[1][$i]);
        }
        $csv .= implode(',',$tdmatches[1]);
      }
      $csv .= "\r\n";
    }
  }

  header('Cache-Control: private, max-age=10800, pre-check=10800');
  header('Content-Disposition: attachment; filename="'.date("Y-m-d").'.csv"');
  header('Pragma: no-cache');
  header('Content-Type: text/comma-separated-values');
  header('Content-Length: ' . strlen($csv));

  return $csv;
}

引数にtableのHTMLを突っ込んで、

戻り値をechoすればOKです。