如何从dat文件中获取日期(“Y.m.d”)

时间:2011-08-24 05:01:15

标签: php date datetime

我想以(“Y.m.d”)格式

获取日期

.dat文件包含以下数据,此处为

 3rd column is date 
177|RC456456177|1314160971|129$

178|RC456456456|1314167971|177$

179|RC456456456|1314130971|157$

180|RC456456456|1314260971|147$

我用它来获取值

if($_POST['ordernum']==="")
{

$blank="Blank text box detected";
} 

elseif (isset($_POST["ordernum"]))
{

    $file = 'order.dat';

    $searchfor = $_POST["ordernum"];

$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor,'/');

$pattern = "/^$pattern.*$/m";

if(preg_match_all($pattern, $contents, $matches)){
   $result = implode("", $matches[0]);

          $results = explode("|", $result);
          $settings->tid = $results[1];
          //echo $settings->tid;
        }
       else{
           $res="No result found";
          // echo  $res;
        }
    }

3 个答案:

答案 0 :(得分:1)

<?php

    $file = fopen ("whatever.dat", "r");

    while ($line = fgets($file)) {
        $contents = explode('|', $line);
        print date('Y.m.d', $contents[2]).PHP_EOL;
    }

    fclose ($file);
?>

那应该有用。 HTH

答案 1 :(得分:1)

// iterate through the file manually, it actually will be faster than reading
// it into either a long string or an array.
$fl = fopen( $path, 'r' );
$searchfor = $_POST["ordernum"] . '$';
// explode will not be needed because of fgetcsv
// http://php.net/manual/en/function.fgetcsv.php
while( $line = fgetcsv( $fl, 0, '|' ) )
{
    // test the last value
    if( $line[3] == $searchfor ) 
    {
        $settings->tid = date( 'Y-m-d', $results[2]);
        break;
    }
}

作为一个注释(这不适用于我的示例),您通常应该在PHP中的双引号字符串中转义所有$作为最佳实践。

答案 2 :(得分:0)

根据您在上面发布的代码,这应该可以解决问题。

$date = date('Y.m.d', $results[2])