【问题标题】:FILE_SKIP_EMPTY_ELEMENTS not removing empty lineFILE_SKIP_EMPTY_ELEMENTS 不删除空行
【发布时间】:2014-07-31 16:12:19
【问题描述】:

我是 PHP 文件函数的新手,我正在尝试写入 以这种方式归档。数据是从 Instagram 实时发布的 订阅源。该文件似乎总是包含一个空行 通常在前几行收到。

  $x = fopen('activity.log', "r+");
  $myString = file_get_contents('php://input');
  $ALL = $myString."\n";
  file_put_contents('activity.log', $ALL, FILE_APPEND);

所以,我尝试用 FILE_SKIP_EMPTY_LINES 参数创建数组时使用 file() 函数,但是空行(在本例中为第 5 行) 在数组中显示为空元素。

  $x = fopen('activity.log', "r+");
   //put file contents into an array
    $y = file('activity.log', FILE_SKIP_EMPTY_LINES);
   echo "<pre>";print_r($result);"</pre>";  

   Array
  (
    [0] => [{"changed_aspect": "media", "object": "tag", "object_id": "london", "time": 1406820800, "subscription_id": 9720966, "data": {}}]

    [1] => [{"changed_aspect": "media", "object": "tag", "object_id": "london", "time": 1406820802, "subscription_id": 9720966, "data": {}}]

    [2] => [{"changed_aspect": "media", "object": "tag", "object_id": "london", "time": 1406820803, "subscription_id": 9720966, "data": {}}]

    [3] => [{"changed_aspect": "media", "object": "tag", "object_id": "london", "time": 1406820803, "subscription_id": 9720966, "data": {}}]

    [4] =>
)

我还尝试了 array_filter() 来删除空元素,但这不起作用,所以我认为空行实际上并不是空的。什么 我可能会在这里失踪。谢谢。

【问题讨论】:

    标签: php arrays file


    【解决方案1】:

    那是其他的空格,而不仅仅是换行符。
    一个简单的解决方法是使用 preg_grep 过滤它:

      preg_grep("/^\s*$/", file($fn), PREG_GREP_INVERT)
    

    ^\s*$ 检查数组行中是否只有白色的\space,_INVERT 只返回那些没有的行。

    你不需要之前的fopen() btw。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-12
      • 2021-12-22
      • 2010-10-16
      • 2018-12-20
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      相关资源
      最近更新 更多