PHP将文件从输入写入txt

时间:2013-02-21 09:43:44

标签: php

我在这个网站上搜索了一个答案,但找不到任何答案。

我有一个表单,我想将输入的内容写入txt文件。为了简单起见,我只写了一个简单的表单和一个脚本,但它一直让我得到一个空白页面。这是我得到的

<html>
<head>
    <title></title>
</head>
<body>
    <form>
        <form action="myprocessingscript.php" method="post">
        <input name="field1" type="text" />
        <input name="field2" type="text" />
        <input type="submit" name="submit" value="Save Data">
    </form>
    <a href='data.txt'>Text file</a>
</body>

这是我的PHP文件

<?php
$txt = "data.txt"; 
$fh = fopen($txt, 'w+'); 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
   $txt=$_POST['field1'].' - '.$_POST['field2']; 
   file_put_contents('data.txt',$txt."\n",FILE_APPEND); // log to data.txt 
   exit();
}
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
    ?>

5 个答案:

答案 0 :(得分:38)

您的表单应如下所示:

<form action="myprocessingscript.php" method="POST">
    <input name="field1" type="text" />
    <input name="field2" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>

和PHP

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

我写信给/tmp/mydata.txt,因为这样我确切地知道它在哪里。使用data.txt写入当前工作目录中的该文件,我在您的示例中一无所知。

file_put_contents打开,为您写入和关闭文件。不要乱用它。

进一步阅读: file_put_contents

答案 1 :(得分:5)

您遇到的问题是因为您拥有额外的<form>,您的数据采用GET方式,并且您使用PHP访问POST中的数据

<body>
<!--<form>-->
    <form action="myprocessingscript.php" method="POST">

答案 2 :(得分:0)

可能的解决方案:

<?php
$txt = "data.txt"; 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
}
?>

您在关闭de file之前关闭了脚本。

答案 3 :(得分:0)

如果您使用file_put_contents,则无需执行fopen - &gt; fwrite - &gt; fclose,file_put_contents为你完成所有这些。您还应该检查Web服务器是否在您尝试编写“data.txt”文件的目录中具有写权限。

根据您的PHP版本(如果它是旧版本),您可能没有file_get / put_contents函数。检查您的网络服务器日志,看看执行脚本时是否出现任何错误。

答案 4 :(得分:0)

使用fwrite()代替file_put_contents()

相关问题