Reputation: 1293
I'm attempting to parse a text file but I'm not sure of the best approach and practice to do so. Using PHP I thinking of loading the entire file into a string or should I do it line by line? Im comfortable with a JavaScript method as well just not as familiar!
Should I search for the the needle inside the haystack using strstr? Or what other methods are good for parsing a simple text file that is consistent.
Note the only data I want out of the text file(temp_log.txt) is:
Date: 07/07/2013 Time: 00:57:00.208 21 C
Date: 07/07/2013 Time: 00:57:02.029 25 C
temp_log.txt:
=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:00.208
DEVICE
INTRTD01 21 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>
=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:02.029
DEVICE
INTRTD01 25 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>
Upvotes: 1
Views: 166
Reputation: 142631
Example how to get Date and Time and Temperature with ReGex in PHP
<?php
$text =
"=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:00.208
DEVICE
INTRTD01 21 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>
=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:02.029
DEVICE
INTRTD01 25 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>";
// split text to lines
$lines = explode("\n", $text);
// find date, time and temperature
$all = array();
$date = "";
$time = "";
foreach( $lines as $line ) {
$number = preg_match('#Date: ([^ ]+).*Time: ([^ ]+)#', $line, $result);
if( $number > 0 ) {
$date = $result[1];
$time = $result[2];
}
$number = preg_match('# (\d+) C#', $line, $result);
if( $number > 0 ) {
$all[] = array($date, $time, $result[1]);
}
}
// print all results
foreach($all as $element) {
echo "Date: ", $element[0], " Time: ", $element[1], " ", $element[2], " C", PHP_EOL;
}
?>
Upvotes: 2