【问题标题】:Storing a value of a variable in a text file将变量的值存储在文本文件中
【发布时间】:2015-06-01 12:14:17
【问题描述】:

我创建了一个简单的机制来获取一个人的名字和姓氏(这当然是非常基本的代码)。但是我想将变量的值写入文本文件。我使用了一些 php,但它似乎不起作用:

<?php $handle = fopen("log.txt", "a");
foreach($_GET as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>

因此,我想知道是否有任何代码可以用来将这些信息放入文本文件中?感谢您的帮助。

初始代码:

<head>
<script>

      function getDetails()
      {
        var firstName = document.getElementById("firstName");
	var nameElement = document.getElementById("lastName");
        var theName = firstName.value;
	var theLastName = lastName.value;
        document.getElementById("someDiv").innerHTML += theName += theLastName;
	

 	}
  </script>
</head>

<html>

  <div id="someDiv">
   Details:
  </div>

  <br><br>

  <input id="firstName" type="text">
	<input id="lastName" type="text">
  <input type="button" value="Go!" onClick="getDetails();">

  <br>    
</html>

不过我更喜欢 Javascript。

【问题讨论】:

  • 你是指 Java 还是 JavaScript?
  • Javascript :-) @khelwood

标签: javascript php html variables storage


【解决方案1】:

要通过 php 写入文件,可以使用 file_put_content() 函数。

这是一个简单的代码示例:

// The file where to write
$file = 'db.txt';
// The content
$file_content = $your_variable;
// Write the content
file_put_contents($file, $file_content);

您还可以将内容附加到文件中:

// The file where to write
$file = 'db.txt';
// Old content
$file_content = file_get_contents($file);
// Old + new content
$file_content .= $your_variable;
// Write the content
file_put_contents($file, $file_content);

您还可以附加到文件 file_put_contents 标志:

// The file where to write
$file = 'db.txt';
// New content
$file_content = $your_variable;
// Write the content
file_put_contents($file, $file_content, FILE_APPEND | LOCK_EX);
// FILE_APPEND: used to append the new contents at the end of the file
// LOCK_EX : used to avoid another user to write on the same file at the same time

【讨论】:

  • 是的,在我看来,file_put_content() 对于初学者来说更容易使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 2015-10-13
  • 2016-10-25
  • 1970-01-01
  • 2022-01-09
相关资源
最近更新 更多