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

时间:2012-04-25 05:55:13

标签: php codeigniter

如果我使用以下代码我在文本文件中获取数据

{"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); 

1 个答案:

答案 0 :(得分:3)

在这里使用php file_put_content()更多信息http://php.net/manual/en/function.file-put-contents.php

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

$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
}
相关问题