Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php // http://stackoverflow.com/questions/42208643/write-the-correct-value-of-a-float-to-a-csv-file
- // include __DIR__ .'/__bootstrap__.php';
- /*
- * create test data file in the current directory...
- */
- define('DATA_FILE', 'Q42208643.dat');
- define('DATA_FILE_OUT', 'Q42208643.out.dat');
- /* */
- $f = fopen(DATA_FILE, 'wb');
- fwrite($f, '122222' .';'. time() .';'. '.123'. PHP_EOL);
- fwrite($f, '233333' .';'. time() .';'. '2,345'. PHP_EOL);
- fwrite($f, '344444' .';'. time() .';'. '3.678'. PHP_EOL);
- fclose($f);
- unset($f);
- /* */
- // setup field names and validiation rules
- $headers = ['name', 'timestamp', 'floatValue',];
- $args = array(
- 'sensor_internal_id' => array('filter' => FILTER_VALIDATE_REGEXP,
- 'options' => array('regexp' => '/^[a-zA-Z0-9_:.()\/]*$/'), ),
- 'timestamp' => array('filter' => FILTER_CALLBACK,
- 'options' => 'validateDate', ),
- 'value' => array('filter' => FILTER_VALIDATE_FLOAT),
- );
- if (($handle = fopen(DATA_FILE, "r+")) !== false) {
- $fOut = fopen(DATA_FILE_OUT, "wb");
- while (($fields = fgetcsv($handle, 1024, ";")) !== false) {
- $fields[2] = str_replace(",", ".", $fields[2]); // ensure float string is valid
- $namedFields = array_combine($headers, $fields);
- $result = filter_var_array($namedFields, $args);
- $outLine = correctFloat($fields);
- fwrite($fOut, $outLine . PHP_EOL);
- }
- fclose($handle);
- fclose($fOut);
- }
- // show input / output
- echo 'Input:', PHP_EOL;
- print_r(file_get_contents(DATA_FILE));
- echo 'Output:', PHP_EOL;
- print_r(file_get_contents(DATA_FILE_OUT));
- exit(0);
- function validateDate($date)
- {
- if (!preg_match("/^\d{8}$/", substr($date, 0, 8))) {
- return false;
- }
- if (!checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
- return false;
- }
- if (substr($date, 8, 2) > 23 || substr($date, 10, 2) > 59 || substr($date, 12, 2) > 59) {
- return false;
- }
- return true;
- }
- function correctFloat($fields) {
- $fields[2] = floatval($fields[2]);
- return implode(';', $fields);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement