ファイルはたくさんあるでしょうからサブルーチンにしました。
<?php # 変換関数 function table2select( $f ) { $s = ''; $html = @file_get_contents( $f ); $b = strip_tags( $html, '<tr><td>'); if ( preg_match_all("#<tr[^<]+?<td[^>]*?>(.+?)</td.+?<td[^>]*?>(.+?)</td[^<]+?#uis", $b, $ms , PREG_SET_ORDER) ) { $s = '<select name="問題番号">' . "\n"; foreach( $ms as $m ) { $s .= '<option value="' . $m[1] . '">' . $m[1] . ' ' . $m[2] . '</option>' . "\n"; } $s .= '</select>' . "\n"; $html = str_replace( 'phpコード', $s, $html ); } return ( $html ); } # メイン #$filename = "ファイル名もしくはURL"; $filename = "hoge.html"; echo table2select( $filename );
なお、ファイル名にURLを用いることができるかどうかは、
php.ini で allow_url_fopen が許可されているかどうかによります。
ーーーーー 追加
二列目(三列目以降も可能)も出力したほうが良いように思うので改良版を載せておきます。
列の値は下記のようにして取り出せます。
$tds[0][1] が一列目
$tds[1][1] が二列目
$tds[n][1] がn列目
<?php # 変換関数 function table2select2( $f ) { $s = ''; $html = @file_get_contents( $f ); $b = strip_tags( $html, '<tr><td>'); if ( preg_match_all("#<tr[^<]+?(.+?)</tr#uis", $b, $trs , PREG_SET_ORDER) ) { $s = '<select name="問題番号">' . "\n"; foreach( $trs as $tr ) { if ( preg_match_all("#<td[^<]+?(.+?)</td#uis", $tr[1], $tds , PREG_SET_ORDER) ) { $s .= '<option value="' . $tds[0][1] . '">' . $tds[0][1] . ' ' . $tds[1][1] . '</option>' . "\n"; } } $s .= '</select>' . "\n"; $html = str_replace( 'phpコード', $s, $html ); } return ( $html ); } # メイン #$filename = "ファイル名もしくはURL"; $filename = "hoge.html"; echo table2select2( $filename );
ーーーーーコメント補足への対応
<html> <body> <?php $s = ''; $b = strip_tags( @file_get_contents( __FILE__ ), '<tr><td>'); if ( preg_match_all("#<tr[^<]+?<td[^>]*?>(.+?)</td.+?<td[^>]*?>(.+?)</td[^<]+?#uis", $b, $ms , PREG_SET_ORDER) ) { $s = '<select name="問題番号">' . "\n"; foreach( $ms as $m ) { $s .= '<option value="' . $m[1] . '">' . $m[1] . '</option>' . "\n"; } $s .= '</select>' . "\n"; } echo ( $s ); ?> <TABLE> <tr> <td>01</td> <td>hoge</td> <td>hoge</td> </tr><tr> <td>03</td> <td>hoge</td> <td>hoge</td> </tr> <tr> <td>05</td> <td>hoge</td> <td>hoge</td> </tr> <tr> <td>10</td> <td>hoge</td> <td>hoge</td> </tr> </TABLE> </body> </html>