我在服务器上有一个文件,需要解析并构建一个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 obj / array中,以进行解析。并相应地分配每个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);
我只是无法“想”在将文件分成几块时循环浏览。
我通过以下方式获得文件内容:
$statusFile = '/location/to/my/data/file';
ob_start();
include( $statusFile );
$statusFileContent = ob_get_contents();
ob_end_clean();
答案 0 :(得分:2)
我为您提供了一个优雅的解决方案。您不需要循环,只需执行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);
答案 1 :(得分:1)
您需要完成3件事:
这是我放在一起的一小段代码,它们说明了您可以采用的方法。我在PHP Fiddle上进行了测试,但是无法弄清楚如何共享链接。
<?php
// File path to load
// $file = "/path/to/file.txt";
$file = "https://pastebin.com/raw/gu2AC7qy";
// Flag indicating we are inside of a "block"
$inBlock = false;
// Name/Key of current "block"
$blockName = null;
// Container for our data
$data = [];
// Open for reading
$handle = fopen($file, 'r');
// If we opened it (you should add better error handling)
if ($handle) {
// Grab each line one at a time
while(($line = fgets($handle)) !== false) {
// Cleanup line
$line = trim($line);
// Throw away useless lines (comments, empty, etc.)
if (empty($line)) {
// Skip blank lines
continue;
}
if (substr($line, 1) == '#') {
// Skip comments
continue;
}
// Check if start of "block"
if (substr($line, -1) == '{') {
// Set the flag
$inBlock = true;
// Get the block name
$blockName = trim(str_replace('{', '', $line));
// Create new data section
$data[$blockName] = [];
// Get next line
continue;
}
// If currently inside block
if ($inBlock === true && ! empty($blockName)) {
// Get a data attribute
$dataRow = trim($line);
// Parse as key/value
$dataRowParts = explode("=", $dataRow);
$key = isset($dataRowParts[0]) ? trim($dataRowParts[0]) : null;
$value = isset($dataRowParts[1]) ? trim($dataRowParts[1]) : "";
// Store in current block's data
if ($key !== null) {
$data[$blockName][$key] = $value;
}
// Get next line
continue;
}
// Check if end of "block"
if (substr($line, -1) == '}') {
// Clear flag
$inBlock = false;
// Unset block name
$blockName = null;
// Get next line
continue;
}
}
// Close the file
fclose($handle);
}
// Output data as JSON
echo json_encode($data);
?>
理想情况下,您应该将此逻辑放在类和方法中,因此它不是一堆庞大的代码-当然,要添加适当的错误处理。祝你好运!
答案 2 :(得分:1)
您可以利用以下事实:这几乎是.ini文件。
移除顶部并将括号中的组转换为ini部分
$sections = preg_replace(['/#.*/', '/(\S+) \{/', '/}/'], ['', '[$1]', ''], $file_contents);
然后是一个.ini字符串。
$result = parse_ini_string($sections, true);
echo json_encode($result);