从由php脚本解析的表单输出创建html文件

时间:2019-02-01 03:16:03

标签: php html string variables fwrite

我想使用来自表单的输入来更新html文档

目标是能够输入URL,输入描述,输入创建日期并输出到文件。

我的想法是将HTML文档分解成begin.txt newarticle.txt和end.txt

然后使用fopen和fwrite将其拼凑在一起。

我敢肯定有一种更简单的方法,但这就是我目前正在尝试的方法。

<html>
<body bgcolor="#FFFFFF>
<H1>Add new Article</h1>

<form action="newarticle.php" method="post">
Paste the link address
<input type="text" name="url">
</br>
Paste the description:
<input type="text" name="description">
</br>
Paste the date article was released:
<input type="text" name="date">
<p>

<input type=submit value="Create Article">
</form>
</body>
</html>

newarticle.php

<?php
$v1 = $_POST["url"]; //You have to get the form data
$v2 = $_POST["description"];
$v3 = $_POST["date"];
$file = fopen('newarticle.txt', 'w+'); //Open your .txt file
ftruncate($file, 0); //Clear the file to 0bit
$content = $v1. PHP_EOL .$v2. PHP_EOL .$v3;
fwrite($file , $content); //Now lets write it in there
fclose($file ); //Finally close our .txt
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>

这使我在三行中的输出。

我如何创建一个内容格式化为实际代码段的文件:

<li><a href=$v1>$v2</a></li>
<li>$v3</li>

1 个答案:

答案 0 :(得分:1)

如果您不介意html的格式对于相同的元素集总是完全相同,但是属性值和内部HTML不同,则可以使用heredoc来构建html。基本上是多行字符串。例如:

$v1 = "info from the form";
$v2 = "more info!";

$built = <<<EOF
<li>$v1</li>\n
<li>$v2</li>
EOF;

echo $built;

这将输出:

<li>info from the form</li>
<li>more info!</li>