假设我有一个 HTML 表格。
<html>
<body>
<table border="1">
<tr>
<th>Username</th>
<th>Password</th>
</tr>
<tr>
<td>User_1</td>
<td>Password_1</td>
</tr>
<tr>
<td>User_2</td>
<td>Password_2</td>
</tr>
</table>
</body>
</html>
我需要一个脚本来将 TH 标记中的 COLUMNS 创建到 MySQL 表,然后插入 TD 标记中的数据。如何做到这一点?
这既简单又有趣。
我建议使用 PHP DOM 解析器。 ( http://simplehtmldom.sourceforge.net/manual.htm )
- 在 MySQL 中手动创建包含列(id、用户名、密码)的表。
- 将 html 文件(带有 html 表格)放在网络服务器上。
- 将 PHP DOM 解析器类放在网络服务器上 (http://sourceforge.net/projects/simplehtmldom/files/)
- ???
太棒了!
require_once ('simple_html_dom.php');
$table = file_get_html('table.html');
foreach($table ->find('tr') as $tr){ // Foreach row in the table!
$username = $tr->find('td', 0)->plaintext; // Find the first TD (starts with 0)
$password= $tr->find('td', 1)->plaintext; // Find the second TD (which will be 1)
echo "INSERT INTO users (id, username, password) VALUES (NULL, '$username', '$password') <br />"; // Do your insert query here!
}
输出(我测试过这个):
INSERT INTO users (id, username, password) VALUES (NULL, '', '')
INSERT INTO users (id, username, password) VALUES (NULL, 'User_1', 'Password_1')
INSERT INTO users (id, username, password) VALUES (NULL, 'User_2', 'Password_2')
所以删除第一个<tr>
来自 html 文件,因为它是表格标题。