【问题标题】:How to append data to file using file_put_contents()?如何使用 file_put_contents() 将数据附加到文件中?
【发布时间】:2016-08-09 13:22:32
【问题描述】:

我有一个从 okhttp3 发送多个数据的 android 应用程序,但我找不到记录在 php 中发送的所有数据的方法。我当前的日志只包含最后一条记录(如下所示)。我最好的猜测是,直到最后一条记录,php 文件数据都被覆盖了。如何记录所有发送的数据?是的,所有数据都从 android 应用程序发出...

index.php

if (isset($_POST))
 {
file_put_contents("post.log",print_r($_POST,true));
}

示例 post.log

 Array
(
    [date] =>  02 Aug, 12:22
    [company] => Assert Ventures
    [lattitude] => 32.8937542
    [longitude] => -108.336584
    [user_id] => Malboro
    [photo_id] => 1
)

我想要什么

(
   [date] =>  02 Aug, 12:22
   [company] => Three Ventures
   [lattitude] => 302.8937542
   [longitude] => -55.336584
   [user_id] => Malboro
   [photo_id] => 1
),
(
   [date] =>  02 Aug, 12:22
   [company] => Two Ventures
   [lattitude] => 153.8937542
   [longitude] => -88.336584
   [user_id] => Malboro
   [photo_id] => 1
),
(
    [date] =>  02 Aug, 12:22
    [company] => Assert Ventures
    [lattitude] => 32.8937542
    [longitude] => -108.336584
    [user_id] => Malboro
    [photo_id] => 1
)

【问题讨论】:

  • 你是如何使用 fopen(w 或 a 模式)的?
  • @coder 他没见过file_put_contents()
  • @coder 默认不需要..file_put_contents 'fopens'、'fwrites' 和 'fcloses'
  • @RiggsFolly 我的坏事
  • @Aeonia 未来RT?M its all in there

标签: php android loops foreach


【解决方案1】:

需要传递第三个参数FILE_APPEND

所以你的 PHP 代码看起来像这样,

if (isset($_POST))
 {
file_put_contents("post.log",print_r($_POST,true),FILE_APPEND);
}

FILE_APPEND 标志有助于将内容附加到 文件而不是覆盖内容。

【讨论】:

  • 完美运行..谢谢
  • @Aeonia 不要忘记选择 Alok 的答案,因为它解决了您的问题。
【解决方案2】:

我认为你应该添加 FILE_APPEND 标志。

<?php
$file = 'post.log';
// Add data to the file
$addData = print_r($_POST,true);
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $addData, FILE_APPEND | LOCK_EX);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2018-07-16
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多