繁体   English   中英

PHP:将表格行添加到 HTML 文件

[英]PHP: Add table row to HTML file

我正在尝试将在 PHP 中生成的表格行添加到 HTML 文件中。 实际上我已经用一个简单的 HTML 表单和一些 PHP 代码完成了这项工作,但是我希望将新行添加到表格的顶部,而不是底部......(这将是一个待办事项列表用于我的作业,但没有复选框。)

这是PHP代码:

<?php
$file = fopen("index.php","a+") or exit("Unable to open file!");
$since = $_POST["since"];
$since2 = "<tr><td class=\"since\">$since</td>";
$due = $_POST["due"];
$due2 = "<td class=\"due\">$due</td></tr>\n";
$user = $_POST["user"];
$user2 = "<td class=\"content\">$user</td>";

if ($_POST["since"] <> "");
{
    fwrite ($file,"$since2$user2$due2");
}

fclose($file);
?>

谁能帮我? (是的,我知道代码不干净,因为这是我第一次尝试编写 PHP。)

这是使用代码制作的tr示例:

<tr><td class="since">Thu 22th  Nov</td><td class="content">example</td><td class="due">Tue 27th  Nov</td></tr>

我的主要观点是在顶部添加一个新的tr 真的很感激任何帮助! (我环顾四周,希望这个问题还没有被问到。)

有点短,但这应该可以解决问题(未经测试)

<?php
if (!emtpy($_POST['since']))//check using empty, it checks if postvar is set, and if it's not empty
{//only open the file if you're going to use it
    $file = fopen('index.php','a');//no need for read access, you're not reading the file ==> just 'a' will do
    $row = '<tr><td class="since"'.$_POST['since'].'</td>
            <td class="due">'.$_POST['due'].'</td>
            <td class="content">'.$_POST['user'].'</td></tr>';//don't forget to close the row
    fwrite ($file,$row);
    fclose($file);
}
?>

顺便说一句,你的if语句并没有完全削减它:

if ($_POST["since"]  <> "");
{

在 PHP 中!=!==是您要查找的运算符(也不相等),并且 if 语句后不跟分号。
您还为一个新变量分配了很多 post 变量,只是为了将它们连接成一个字符串,绝对没有必要这样做:

$newString = 'Concat '.$_POST['foo'].'like I did above';
$newString = "Same ".$_POST['trick'].' can be used with double quotes';
$newString = "And to concat an array {$_POST['key']}, just do this";//only works with double quotes, though

更新:
在下面的评论中回答您的问题:这是解析 html 并附加/添加所需元素所需的内容:

$document = new DOMDocument();
$document->loadHTML(file_get_contents('yourFile.html'));
//edit dom here
file_put_contents('yourFile.html',$document->saveHTML());

花一些时间在这里了解如何在 DOM 中添加/创建/更改任意数量的元素。 您可能感兴趣的方法是: createDocumentFragmentcreateElement和所有类似 JavaScript 的方法: getElementByIdgetElementsByTagName等...

要将其添加到文件的开头,您可以读取其内容,将其添加到新行的末尾,然后将整个内容写回文件。

// read the original file
$original_list = file_get_contents("index.php");

// use the writing mode to overwrite the file
$file = fopen("index.php","w") or exit("Unable to open file!");

$since = $_POST["since"];
$since2 = "<tr><td class=\"since\">$since</td>";

$user = $_POST["user"];
$user2 = "<td class=\"content\">$user</td>";

$due = $_POST["due"];
$due2 = "<td class=\"due\">$due</td></tr>\n";

if ($_POST["since"] <> "");
{
    fwrite($file,"$since2$user2$due2$original_list");
}

fclose($file);

这不是构建待办事项列表的最佳方式,但我们对您的家庭作业和进一步改进答案的要求知之甚少。

另一个提示:避免使用无意义的变量名,如$since2$due2 ,即使它们本质上是临时的。 通过使用更好的名称,例如$since_cell$due_cell ,即使没有注释,代码$due_cell变得更容易理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM