我在服务器上有一个文件,我需要解析它并构建一个 JSON 对象以返回。我正在使用 PHP。
文件内容如下所示:
########################################
# NOTES FILE
#
# THIS FILE IS AUTOMATICALLY GENERATED
# DO NOT MODIFY THIS FILE!
########################################
info {
created=1552596653
version=4.4.3
last_update_check=1552554585
update_available=0
last_version=4.4.3
new_version=4.4.3
}
programstatus {
modified_host_attributes=0
modified_service_attributes=0
pid=11523
daemon_mode=1
program_start=1552593834
last_log_rotation=0
...
理想情况下,我想抓取每个段(例如:“info”、“programstatus”等),并在解析时将它们添加到 JSON 对象/数组中。每个attribute = value
都被相应地分配。
所以类似:
$data = array();
// Loop here for each segment
$data['info'] = array(
"created" => "1552596653",
"version" => "4.4.3",
etc...
)
// Then wrap it up with something like
return json_encode($data);
我只是无法“思考”循环遍历文件,同时将其分成 block 。
我通过以下方式获取文件内容:
$statusFile = '/location/to/my/data/file';
ob_start();
include( $statusFile );
$statusFileContent = ob_get_contents();
ob_end_clean();
最佳答案
我为你做了一个优雅的解决方案。不需要循环,5行代码就可以搞定。只需使用正则表达式并转换您拥有的文件即可。
$file = "Your file as a string";
//Get the titles like 'info' and put it around quotion marks
$titles_changed = preg_replace('/(.*)\{/', '"$1":{', $file, -1 );
//Get strings like created=1552596653 and transform to "created"="1552596653",
$values_changed = preg_replace('/(.*)=(.*)/', '"$1":"$2",', $titles_changed );
//Remove spaces from the string
$no_spaces = preg_replace('/\s/s', '', $values_changed);
//Fix all that became ",}" from the second replacement and transforms it into "},"
$limits_fixed = preg_replace('/\,\}/', '},', $no_spaces);
//Remove a "," that lasts on the end of the file and put all string around brakets
$json = "{". rtrim($limits_fixed, ',') . "}";
$object = json_decode($json);
关于PHP - 迭代文件并分解 JSON 文本 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172143/