使用PHP将数据写入文件

Mar*_*ail 22 php post text http

我需要使用下面的代码发布数据到php文件,将其保存在文本文件中.我只是不知道如何创建php文件来接收下面的数据并将其保存在文本文件中.尽可能简单.

try {  
    // Add your data  
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
    nameValuePairs.add(new BasicNameValuePair("stringData", "12345"));  
    nameValuePairs.add(new BasicNameValuePair("stringData", "AndDev is Cool!"));  
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

    // Execute HTTP Post Request  
    HttpResponse response = httpclient.execute(httppost);  
    String responseText = EntityUtils.toString(response.getEntity()); 
    tv.setText(responseText);             
} catch (ClientProtocolException e) {  
    // TODO Auto-generated catch block  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
}  
Run Code Online (Sandbox Code Playgroud)

Ham*_*ish 65

简单如下:

file_put_contents('test.txt', file_get_contents('php://input'));
Run Code Online (Sandbox Code Playgroud)

  • 将第三个参数`FILE_APPEND`添加到`file_put_contents`以将请求数据附加到文件而不是一直覆盖. (8认同)
  • &lt;?php $content = $_POST['content']; $file = "text.txt"; $Saved_File = fopen($file, 'w'); fwrite($Saved_File, $content); fclose($Saved_File); ?&gt; (7认同)
  • 如果你想获得一个特定键的值并保存它,那么是的.如果您只想转储原始POST数据(不必是键值对 - 例如它可能是二进制数据),那么'php:// input'流将读取它.问题很模糊,并要求"尽可能简单"......好吧,它并没有变得简单得多. (3认同)
  • 另外,`file_put_contents`在一次点击中执行fopen,fwrite和fclose--更容易使用和阅读. (3认同)

eki*_*aby 17

1)在PHP中,要从传入请求获取POST数据,请使用$ _POST数组.PHP中的POST数组是关联的,这意味着每个传入参数都是键值对.在开发过程中,了解你在$ _POST中实际获得的内容是有帮助的.您可以使用printf()或var_dump()转储内容,如下所示.

var_dump($_POST);
Run Code Online (Sandbox Code Playgroud)

- 要么 -

printf($_POST);
Run Code Online (Sandbox Code Playgroud)

2)选择一种有用的基于字符串的格式来存储数据.PHP有一个serialize()函数,您可以使用它将数组转换为字符串.将数组转换为JSON字符串也很容易.我建议使用JSON,因为在各种语言中使用这种表示法是很自然的(而使用PHP序列化会在某种程度上将你绑定到将来使用PHP).在PHP 5.2.0及更高版本中,json_encode()函数是内置的.

$json_string = json_encode($_POST);

// For info re: JSON in PHP:
// http://php.net/manual/en/function.json-encode.php
Run Code Online (Sandbox Code Playgroud)

3)将字符串存储在文件中.尝试使用fopen(),fwrite()和fclose()将json字符串写入文件.

$json_string = json_encode($_POST);

$file_handle = fopen('my_filename.json', 'w');
fwrite($file_handle, $json_string);
fclose($file_handle);

// For info re: writing files in PHP:
// http://php.net/manual/en/function.fwrite.php
Run Code Online (Sandbox Code Playgroud)

您需要为使用的文件路径和文件名提供特定的位置和方法.

注意:还可以使用$ HTTP_RAW_POST_DATA直接获取HTTP请求的POST主体.原始数据将进行URL编码,它将是一个可以写入文件的字符串,如上所述.