Skip to content

Instantly share code, notes, and snippets.

@mkoppanen
Created August 18, 2010 15:02
Show Gist options
  • Save mkoppanen/535024 to your computer and use it in GitHub Desktop.
Save mkoppanen/535024 to your computer and use it in GitHub Desktop.
<?php
define("PARSING_HEADER", 1);
define("PARSING_DEFINITION", 2);
define("PARSING_DATA", 3);
define("PARSING_END", 4);
$fp = fopen("file.txt", "r");
$state = 0;
$done = false;
$header = array();
$definition = array();
$data = array();
if ($fp) {
while (!feof($fp)) {
$line = fgets($fp, 4096);
$line = trim($line);
if ($line[0] === '#' && $line[strlen($line) - 1] === '#') {
$section = substr($line, 1, -1);
if (!defined("PARSING_{$section}")) {
echo "Unknown parser state: PARSING_{$section}\n";
break;
}
$state = constant("PARSING_{$section}");
continue;
}
if (empty($line))
continue;
switch ($state) {
case PARSING_HEADER:
if (preg_match("~^Version : (\d+)$~", $line, $matches)) {
$header['version'] = $matches[1];
}
else if (preg_match("~^EOF : '(.)'$~", $line, $matches)) {
$header['eof'] = $matches[1];
}
else if (preg_match("~^EOR : '(.)'$~", $line, $matches)) {
$header['eor'] = $matches[1];
}
else {
echo "Unknown header line: {$line}\n";
}
break;
case PARSING_DEFINITION:
$definition = explode($header['eof'], $line);
break;
case PARSING_DATA:
$data[] = explode($header['eof'], $line);
break;
case PARSING_END:
$done = true;
break;
}
if ($done)
break;
}
}
var_dump($header, $definition, $data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment