简体   繁体   English

用php代码修改文本文件

[英]Modify text file with php code

I have a JSON file badly formatted (doc1.json): 我有一个格式错误的JSON文件(doc1.json):

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

And I have to change it in this: 我必须对此进行更改:

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

Can I do this in a PHP file? 我可以在PHP文件中执行此操作吗?

//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);

I would build the data structure you want from the file: 我将从文件中构建所需的数据结构:

$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);

This assumes each of the JSON object repsentations in your original file are on a separate line. 假定原始文件中的每个JSON对象表示都位于单独的行上。

I prefer this approach over string manipulation, as you can then have built in checks where you are decoding JSON to see if the input is valid JSON format that can be de-serialized. 与字符串操作相比,我更喜欢这种方法,因为这样您就可以在检查JSON的位置进行内置检查,以查看输入是否为可以反序列化的有效JSON格式。 If the script operates successfully, this guarantees that your output will be able to be de-serialized by the caller to the script. 如果脚本成功运行,则可以保证您的输出将被调用者反序列化为脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM