use*_*432 4 html mysql sql html-table
假设我有一个 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>
Run Code Online (Sandbox Code Playgroud)
我需要一个脚本,将 TH 标记中的 COLUMNS 创建到 MySQL 表,然后插入 TD 标记中的数据。怎么做?
这可能很简单,但同时也很有趣。
我建议使用 PHP DOM 解析器。( http://simplehtmldom.sourceforge.net/manual.htm )
太棒了!
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!
}
Run Code Online (Sandbox Code Playgroud)输出(我对此进行了测试):
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')
Run Code Online (Sandbox Code Playgroud)
所以<tr>从 html 文件中删除第一个,因为它是表格标题。