LM-Sensors-JSON/index.php

68 lines
1.5 KiB
PHP

<?php
$sensor_data = explode("\n", shell_exec('sensors'));
function get_lines($data) {
$lines = array();
$new_line = '';
$first = TRUE;
foreach ($data as $line) {
if($line != '' && $line[0] == " ")
$new_line .= $line;
else {
if(!$first) {
$lines[] = explode('(', str_replace(' ', '', $new_line))[0];
} else {
$first = FALSE;
}
$new_line = $line;
}
}
return $lines;
}
function get_blocks($lines) {
$blocks = array();
$new_block = array();
foreach ($lines as $line) {
if($line == '') {
$blocks[] = $new_block;
$new_block = array();
}
else {
if(str_contains($line, ':'))
$new_block[] = explode(':', $line);
else
$new_block[] = $line;
}
}
return $blocks;
}
function generate_json($blocks) {
$json_array = array();
foreach ($blocks as $block) {
$block_json_array = array();
$block_title = '';
foreach($block as $item) {
if(gettype($item) == 'array') {
$block_json_array[$item[0]] = $item[1];
}
else {
$block_title = $item;
}
}
$json_array[$block_title] = $block_json_array;
reset($block_json_array);
}
return json_encode($json_array);
}
header('Content-Type: application/json');
echo generate_json(get_blocks(get_lines($sensor_data)));