PHP - 迭代文件并分解 JSON 文本 block

标签 php arrays json

我在服务器上有一个文件,我需要解析它并构建一个 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/

相关文章:

ios - 多单元格类型 swift 4.2

javascript - 将 json 对象属性提取到数组中的简单方法?

php - MySQL 使用不存在列中的数组

php - 如何引用其他表列customer_id获取产品价格列的总和

c++ - 没有匹配函数来调用 'make_pair(char [len], int&)

java - 如何获得该数组的标准差

javascript - HTML 表 SBadmin Bootstrap 来自 JSON

mysql - 将 JSON 字符串插入 MySQL 列 UTF-8

php - codeigniter 表单设置值?

php - 试图将 sql 数据库显示到 php 网页中,CSS 没有工作