如何使用 fwrite 将引号写入 .txt 文件

发布于 2024-10-18 23:52:10 字数 289 浏览 1 评论 0原文

我有一个 html 表单,用户可以在其中提交数据。当他们提交时,我将获取该数据并将其写入 .txt 文件。我在数据周围添加引号时遇到问题。 我需要它在写入 txt 文件时执行以下操作。

$name = $_POST['用户'];

$data= "$name"

var Name="$data",

所以如果他用户在表单上输入 John,我需要它来读取: var Name="John",

在我的数据表单上。任何帮助表示赞赏。我尝试过addslashes,但似乎也无法使其正常工作。

I have an html form where users can submit data. When they submit I am taking that data and writing it to a .txt file. I am having trouble adding quotation marks around my data.
I need it to do the following when it writes to the txt file.

$name = $_POST['user'];

$data= "$name"

var Name="$data",

So if he user entered John on the form, I would need it to read:
var Name="John",

On my data form. Any help is appreciated. I have tried addslashes, but can't seem to get that to work correctly either.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的呼吸 2024-10-25 23:52:10

试试这个:

$name = $_POST['user'];
$file_line = 'var Name="'.$name.'",';
fwrite($fh, $file_line);

try this:

$name = $_POST['user'];
$file_line = 'var Name="'.$name.'",';
fwrite($fh, $file_line);
若能看破又如何 2024-10-25 23:52:10

编程中有一些看似奇怪的怪癖,但特别是阻止您这样做的一个事实是您没有将引号 (") 视为字符串。Php 对此进行解释:

$data = "$name";

作为将 $name 转换为 a 的请求string 并将其存储在 $data 中,您想要的是将引号用单引号括起来,以便 php 将它们转换为字符串,然后将它们与您的连接(使用连接运算符,句点 (.) )。 $name 变量,如下所示:

$data = '"'.$name.'"';

$data 现在保存值:“John” 最后,对于您要写入的实际字符串,您可以将新变量与“var Name=”部分连接起来:

$string = 'var Name='.$data;

因此 $string 的值 。现在保存字符串:

var Name="John"

这正是您想要的。

There are quirks in programming that seem strange, but in particular the one preventing you from doing this is the fact that you are not treating the quotation marks (") as strings. Php is interpreting this:

$data = "$name";

As a request to turn $name into a string and store it inside of $data. What you want is to wrap the quotation marks with single quotations, so that php will turn them into a string. Then you concatenate (with the concatenation operator, the period (.) ) those with your $name variable, like so:

$data = '"'.$name.'"';

$data now holds the value: "John". Finally, for the actual string you want to write, you would concatenate your new variable with the 'var Name=' part:

$string = 'var Name='.$data;

So the value of $string now holds the string:

var Name="John"

Which is exactly what you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文