PHP Script to parse nagios.dat

Please add your own error-handling:

#!/usr/bin/php
<?php

function NagiosParser($file)
{
        $status = file_get_contents($file);

        $current = null;
        $parsed = array();

        foreach (explode("\n", $status) as $line)
        {
                if (preg_match('/^([a-z]+) {$/', $line, $matches))              // Block start
                {
                        $block = array();
                        $current = $matches[1];
                }
                else if (preg_match('/}$/', $line, $matches))                   // Block stop
                {
                        $parsed[$current][] = $block;
                        $current = null;
                        unset($block);
                }
                else if (preg_match('/([a-z_]+)=(.+)/', $line, $matches))       // Not null value
                        if ($current == null)
                                die("Parse error: Value outside of block!");
                        else
                                $block[$matches[1]] = $matches[2];
        }
        return $parsed;
}
print_r(NagiosParser("status.dat"));
Dette indlæg blev udgivet i Nagios, PHP. Bogmærk permalinket.