如何使用php将数组数据放入文本文件

如何使用php将数组数据放入文本文件,php,codeigniter,Php,Codeigniter,如果我使用下面的代码,我会在文本文件中获取数据 {"title":"sankas","description":"sakars","code":"sanrs"} {"title":"test","description":"test","code":"test"} 但我的代码正在运行 {"title":"sankas","description":"sakars","code":"sanrs"} 因此,我无法添加更多行。我要更改这些行以获得正确的结果 $info =

如果我使用下面的代码,我会在文本文件中获取数据

{"title":"sankas","description":"sakars","code":"sanrs"}    
{"title":"test","description":"test","code":"test"}
但我的代码正在运行

{"title":"sankas","description":"sakars","code":"sanrs"}
因此,我无法添加更多行。我要更改这些行以获得正确的结果

        $info = array();
    $folder_name = $this->input->post('folder_name');
    $info['title'] = $this->input->post('title');
    $info['description'] = $this->input->post('description');
    $info['code'] = $this->input->post('code');
    $json = json_encode($info);
    $file = "./videos/overlay.txt";
    $fd = fopen($file, "a"); // a for append, append text to file

    fwrite($fd, $json);
    fclose($fd); 

使用php的
文件\u put\u content()
此处提供更多信息

更新: 假设正确地传递了数据。这是你能做的

$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
//using the FILE_APPEND flag to append the content.
file_put_contents ($file, $json, FILE_APPEND);
更新2:

如果要从文本文件访问回该值。overlay.txt以下是您可以执行的操作

$content = file_get_contents($file);
如果要分别获取标题、代码和描述。如果字符串是json格式的,那么首先需要使用将其转换为数组

//this will convert the json data back to array
$data = json_decode($json);
要访问单个值,如果只有一行,可以这样做

echo $data['title'];
echo $data['code'];
echo $data['description'];
如果有多行,那么可以使用php foreach循环

foreach($data as $key => $value)
{
    $key contains the key for example code, title and description
    $value contains the value for the correspnding key
}
希望这对你有帮助

更新3:

像这样做

$jsonObjects = file_get_contents('./videos/overlay.txt');
$jsonData = json_decode($jsonObjects);
foreach ($jsonData as $key => $value) {
    echo $key . $value;
    //$key contains the key (code, title, descriotion) and $value contains its corresponding value
}

我在用我的代码问正确答案。在我的代码中使用file_put_contents()。$string=introde($json);文件内容(“./videos/overlay.txt”,$string);这是不可能的working@SankarMvs我做到了。这应该行得通。如果我理解您的意思是正确的,那么您希望在文件末尾追加json字符串,对吗?您已经在使用json_encode将数组转换为json。您想将其转换为字符串吗?如何检索此值{“title”:“asd”,“description”:“asd”,“code”:“asd”}{“title”:“sad”,“description”:“sadd”,“code”:“sadd”}