dtgv52982
2012-04-09 18:52
浏览 64
已采纳

使用附加的fopen创建PHP数组

I am having trouble figuring out how to write to a file using fopen "a" append mode.

the file itself is a simple PHP array:

$array = array(
  "entry1"   => "blah blah",
  "entry2"   => "forbarbaz",
);   

simple enough. So using fopen with the 2nd arg set to "a" should allow me to append the file using fputs.... the problem is the opening and closing lines, ie $array = array( and );

so now the file should look like this:

  "entry1"   => "blah blah",
  "entry2"   => "forbarbaz",

how would I rebuild this data into a working PHP array assuming it is just a txt file with a list of entries without the opening and closing lines? Sorry if this is not clear, its a little complicated. No I am not going to store these values in a DB, I need the speed advantage by holding these particular values in a file array.

So the questions really is how would i go about constructing the usable PHP array from a txt file with a line by line list like this?

To clarify:

how do i pull in a txt file with lines like this:

  "entry1"   => "blah blah",
  "entry2"   => "forbarbaz",

and have a workable $php_array()????

图片转代码服务由CSDN问答提供 功能建议

我无法确定如何使用fopen“a”追加模式写入文件。

文件本身是一个简单的PHP数组:

  $ array = array(
“entry1”=>“blah blah”,
  “entry2”=>“forbarbaz”,
);  
   
 
 

足够简单。 所以使用fopen将第二个arg设置为“a”应该允许我使用fputs附加文件....问题是开始和结束行,即 $ array = array();

所以现在文件应如下所示:

 “entry1”=>  “blah blah”,
“entry2”=>  “forbarbaz”,
   
 
 

我将如何将这些数据重建为一个有效的PHP数组,假设它只是一个txt文件,其中包含没有开始和结束行的条目列表 ? 对不起,如果不清楚,有点复杂。 不,我不会将这些值存储在数据库中,我需要通过将这些特定值保存在文件数组中来获得速度优势。

所以问题实际上是我将如何构建 来自txt文件的可用PHP数组是否有这样的逐行列表?

为了澄清:

我如何引入txt文件 使用这样的行:

 “entry1”=>  “blah blah”,
“entry2”=>  “forbarbaz”,
   
 
 

并且有一个可行的$ php_array()????

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dpsx99068 2012-04-09 18:58
    已采纳

    Try this.

    File format (at the beginning of work with it):

    <?php
    $array = array();
    

    Now it's correct php-file.

    Then simply add new rows like as follows:

    $f = fopen('myarray.php', 'a');
    fputs($f, PHP_EOL.'$array["entry1"] = "value1";');
    fclose($f);
    

    And use it by simply include('myarray.php');

    点赞 打赏 评论
  • dongxing4643 2012-04-09 18:55

    Why not json_encode the array when you store it in the file and then json_decode the JSON into an array when you extract it from the file?

    json_encode
    json_decode

    点赞 打赏 评论
  • dongzhashou0116 2012-04-09 18:57

    Untested. Try this:

    $data = file_get_contents('./data.txt', true);
    $array = eval("array(".$data.")");
    

    FYI, shiplu.mokadd.im's solution is the easiest.

    点赞 打赏 评论
  • dqq22391 2012-04-09 19:02

    Maybe you're looking for the fseek function: http://se.php.net/fseek

    When opening a file in r+ mode, the file pointer is at the beginning of the file. Sounds like you want to place it at the end of the file minus a few bytes, then write your new data.

    点赞 打赏 评论

相关推荐 更多相似问题