ホームページを作成しています。
以下のように一番左の列に問題番号が入っているテーブルがあるのですが
ここからphpで問題番号を抜き出してきて問題数分optionを生成しselectのバリューと名前のところにselect.htmlのように入力されるようにしたいのですがどのようにすればいいでしょうか?
hoge.html
***********************
<html>
<body>
<select>
<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>
***********************
select.html
***********************
<select name="問題番号">
<option value="01">01</option>
<option value="03">03</option>
<option value="05">05</option>
<option value="10">10</option>
</select>
***********************
ファイルはたくさんあるでしょうからサブルーチンにしました。
<?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>
すいません
2013/09/12 05:33:00hoge の部分に日本語が入っていると動作しなくなるのですが
どこを変更すればいいのでしょうか?
#uis の部分を #is に替えてみてください。
2013/09/12 06:06:17