【问题标题】:Append data to a .JSON file with PHP使用 PHP 将数据附加到 .JSON 文件
【发布时间】:2011-12-15 06:30:16
【问题描述】:

我有这个 .json 文件:

[
    {
        "id": 1,
        "title": "Ben\\'s First Blog Post",
        "content": "This is the content"
    },
    {
        "id": 2,
        "title": "Ben\\'s Second Blog Post",
        "content": "This is the content"
    }
]

这是我的 PHP 代码:

<?php
$data[] = $_POST['data'];

$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);

问题是,我不确定如何实现它。每次提交表单时,我都会在上面调用此代码,因此我需要增加 ID 并使用[{ 保持有效的 JSON 结构,这可能吗?

【问题讨论】:

  • 我不认为 JSON 是增量格式;您必须对其进行反序列化,添加新记录,然后再次对其进行序列化。
  • 我知道这不是您问题的答案,但这让我想起了我尝试用 XML 做同样事情的时候。目的是存储博客文章,我认为这将是避免需要 MySQL 的一种很酷的方法。然而,事实并非如此。从长远来看,使用数据库而不是文件来存储此类数据更可靠、更好的做法,并且痛苦更少。抱歉,我知道当您提出问题并且有人给出“不要那样做”作为答案时,这非常烦人(这就是我将其发布为评论的原因)。这正是我希望早点被告知的。
  • 将数据附加到 .JSON 文件 [在此处输入链接描述][1] [1]: stackoverflow.com/questions/12290572/…
  • 被解释为数据的文件需要如何格式化才能正常工作?

标签: php json


【解决方案1】:

盲目地向其附加文本会破坏您的 json 数据。 JSON 不是一种可以像这样操作的格式。

您必须加载 json 文本,对其进行解码,操作生成的数据结构,然后重新编码/保存。

<?php

$json = file_get_contents('results.json');
$data = json_decode($json);
$data[] = $_POST['data'];
file_put_contents('results.json', json_encode($data));

假设您的文件中存储了[1,2,3]。您的代码可能会将其转换为 [1,2,3]4,这在语法上是错误的。

【讨论】:

    【解决方案2】:
    $data[] = $_POST['data'];
    
    $inp = file_get_contents('results.json');
    $tempArray = json_decode($inp);
    array_push($tempArray, $data);
    $jsonData = json_encode($tempArray);
    file_put_contents('results.json', $jsonData);
    

    【讨论】:

    • 这不是每次都需要更长的时间吗?当你有一个巨大的 JSON 文件时,它会不会变得很荒谬?我正在处理大量数据。
    • newbie php guy here...如果我使用 file_get_contents('php://input') 获取“发布数据”,我该如何修改上面的答案以使其正常工作?所以基本上第一行对我不起作用。我正在使用 file_get_contents('php://input') 因为我在 JS 中调用 fetch() 来制作 http 帖子。
    【解决方案3】:

    如您的示例所示,如果您想将另一个数组元素添加到 JSON 文件,请打开该文件并搜索到最后。如果文件已经有数据,则向后查找一个字节以覆盖最后一个条目之后的],然后写入,加上新数据减去新数据的初始[。否则,它是您的第一个数组元素,因此只需正常编写您的数组即可。

    抱歉,我对 PHP 了解的不够多,无法发布实际代码,但我已经在 Obj-C 中完成了这项工作,这样我就可以避免先读取整个文件,然后再添加到末尾:

    NSArray *array = @[myDictionary];
    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
    FILE *fp = fopen(fname, "r+");
    if (NULL == fp)
        fp = fopen(fname, "w+");
    if (fp) {
        fseek(fp, 0L, SEEK_END);
        if (ftell(fp) > 0) {
            fseek(fp, -1L, SEEK_END);
            fwrite(",", 1, 1, fp);
            fwrite([data bytes] + 1, [data length] - 1, 1, fp);
        }
        else
            fwrite([data bytes], [data length], 1, fp);
        fclose(fp);
    }
    

    【讨论】:

      【解决方案4】:

      这采用了上面的 c 示例并将其移至 php。这将跳转到文件末尾并添加新数据,而不会将所有文件读入内存。

      // read the file if present
      $handle = @fopen($filename, 'r+');
      
      // create the file if needed
      if ($handle === null)
      {
          $handle = fopen($filename, 'w+');
      }
      
      if ($handle)
      {
          // seek to the end
          fseek($handle, 0, SEEK_END);
      
          // are we at the end of is the file empty
          if (ftell($handle) > 0)
          {
              // move back a byte
              fseek($handle, -1, SEEK_END);
      
              // add the trailing comma
              fwrite($handle, ',', 1);
      
              // add the new json string
              fwrite($handle, json_encode($event) . ']');
          }
          else
          {
              // write the first event inside an array
              fwrite($handle, json_encode(array($event)));
          }
      
              // close the handle on the file
              fclose($handle);
      }
      

      【讨论】:

      • 很好的解决方案!最初对我不起作用。不得不用 $handle == null 替换 $handle === null
      【解决方案5】:

      我用来将额外的 JSON 数组附加到 JSON 文件的示例代码。

      $additionalArray = array(
          'id' => $id,
          'title' => $title,
          'content' => $content
      );
      
      //open or read json data
      $data_results = file_get_contents('results.json');
      $tempArray = json_decode($data_results);
      
      //append additional json to json file
      $tempArray[] = $additionalArray ;
      $jsonData = json_encode($tempArray);
      
      file_put_contents('results.json', $jsonData);   
      

      【讨论】:

        【解决方案6】:
        /*
         * @var temp 
         * Stores the value of info.json file
         */
        $temp=file_get_contents('info.json');
        
        /*
         * @var temp
         * Stores the decodeed value of json as an array
         */
        $temp= json_decode($temp,TRUE);
        
        //Push the information in temp array
        $temp[]=$information;
        
        // Show what new data going to be written
        echo '<pre>';
        print_r($temp);
        
        //Write the content in info.json file
        file_put_contents('info.json', json_encode($temp));
        }
        

        【讨论】:

          【解决方案7】:

          我编写了这段 PHP 代码来将 json 添加到 json 文件中。 代码会将整个文件括在方括号中,并用逗号分隔代码。

          <?php
          
          //This is the data you want to add
          //I  am getting it from another file
          $callbackResponse = file_get_contents('datasource.json');
          
          //File to save or append the response to
          $logFile = "results44.json";
          
          
          //If the above file does not exist, add a '[' then 
          //paste the json response then close with a ']'
          
          
          if (!file_exists($logFile)) {
            $log = fopen($logFile, "a");
            fwrite($log, '['.$callbackResponse.']');
            fclose($log);                      
          }
          
          
          //If the above file exists but is empty, add a '[' then 
          //paste the json response then close with a ']'
          
          else if ( filesize( $logFile) == 0 )
          {
               $log = fopen($logFile, "a");
            fwrite($log, '['.$callbackResponse.']');
            fclose($log);  
          }
          
          
          //If the above file exists and contains some json contents, remove the last ']' and 
          //replace it with a ',' then paste the json response then close with a ']'
          
          else {
          
          $fh = fopen($logFile, 'r+') or die("can't open file");
          $stat = fstat($fh);
          ftruncate($fh, $stat['size']-1);
          fclose($fh); 
          
          $log = fopen($logFile, "a");
            fwrite($log, ','.$callbackResponse. ']');
            fclose($log); 
          
          }
          
              ?>
          

          祝你好运

          【讨论】:

            【解决方案8】:

            使用 PHP 将数据附加到 .json 文件

            • 也保持有效的 json 结构
            • 不追加数组。
            • 将 json 附加到 QuesAns.json 文件中。
            • 覆盖文件中的数据
               $data = $_POST['data'];
               //$data= 
               
               array("Q"=>"QuestThird","A"=>"AnswerThird");
                    
               $inp = file_get_contents('QuesAns.json');
               //$inp='[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"}]';     
              
               /**Convert to array because array_push working with array**/
               $tempArray = json_decode($inp,true);
                    
               array_push($tempArray, $data);
               print_r($tempArray);
               echo'<hr>';
            
               $jsonData = json_encode($tempArray);
            
               file_put_contents('QuesAns.json', $jsonData);
               
               print($jsonData);
            

            输出:

            Array ( [0] => Array ( [Q] => QuestFurst [A] => AnswerFirst ) [1] => Array ( [Q] => Quest second [A] => AnswerSecond ) [2] = > 数组([Q] => QuestThird [A] => AnswerThird))


            [{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"第二个任务","A":"AnswerSecond"},{"Q":"QuestThird", "A":"AnswerThird"}]

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-07-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-10-11
              相关资源
              最近更新 更多