使用php代码修改文本文件

时间:2015-05-20 13:35:36

标签: php json self-modifying

我有一个格式错误的JSON文件(doc1.json):

{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}

我必须改变它:

{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}

我可以在PHP文件中执行此操作吗?

2 个答案:

答案 0 :(得分:1)

//Get the contents of file
    $fileStr = file_get_contents(filelocation);

//Make proper json
    $fileStr = str_replace('}{', '},{', $fileStr);

//Create new json    
    $fileStr = '{"u":[' . $fileStr . ']}';

//Insert the new string into the file
    file_put_contents(filelocation, $fileStr);

答案 1 :(得分:0)

我会从文件中构建您想要的数据结构:

$file_path = '/path/to/file';
$array_from_file = file($file_path);

// set up object container
$obj = new StdClass;
$obj->u = array();

// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
    $line_obj = json_decode($json);
    if(is_null($line_obj)) {
        throw new Exception('We have some bad JSON here.');
    } else {
        $obj->u[] = $line_obj;
    }
}

// encode to JSON
$json = json_encode($obj);

// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);

这假设原始文件中的每个JSON对象代表都在一个单独的行上。

我更喜欢这种方法而不是字符串操作,因为您可以在内置检查中解码JSON以查看输入是否是可以反序列化的有效JSON格式。如果脚本成功运行,这可以保证调用者能够将输出反序列化到脚本中。