【问题标题】:How can i read a text file which contains a proper array in php?如何在 php 中读取包含正确数组的文本文件?
【发布时间】:2015-05-20 02:32:27
【问题描述】:

我用这个将数组写入文本文件:

$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($newStrings, TRUE));
fclose($fp);

现在我想在 php 中读取它,就像读取普通数组一样?我该怎么做?我对此很陌生,我目前正在最后期限内获得与此相关的东西,请帮助。

【问题讨论】:

    标签: php arrays robots.txt


    【解决方案1】:

    var_export() 将是有效的 PHP 代码,然后您可以使用 include 并且比 print_r() 工作得更好,但我建议使用 JSON / json_encode()serialize() 也可以与 JSON 类似,但不可移植。

    写:

    file_put_contents('file.txt', json_encode($newStrings));
    

    阅读:

    $newStrings = json_decode(file_get_contents('file.txt'), true);
    

    【讨论】:

      【解决方案2】:

      使用 PHP serializeunserialize 来执行此操作。

      写入文件:

      $myArray = ['test','test2','test3'];
      $fp = fopen('file.txt', 'w');
      fwrite($fp, serialize($myArray));
      fclose($fp);
      

      或者更苗条:

      file_put_contents('file.txt',serialize($myArray));
      

      再读一遍:

      $myArray = unserialize(file_get_contents('file.txt'));
      

      【讨论】:

        【解决方案3】:

        在写入数据时对数据使用 json_encode() 或 serialize(),然后在读取数据时对数据使用 json_decode() 或 unserialize()。

        要查看差异,请检查以下问题: JSON vs. Serialized Array in database

        【讨论】:

          猜你喜欢
          • 2016-10-05
          • 2021-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多