2011-08-24 72 views
1

我想(「年月日」)格式來迎接我的日期獲取日期(「年月日」)如何從dat文件

.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; 
     } 
    } 
+2

你問的是如何讀取文件,或者如何格式化日期?這實際上是兩個不同的問題。 (對於日期,一旦它被讀取,你可以簡單地調用'date('Ymd',$ date)') –

+0

@Michael Mior :)編輯的問題,我想閱讀這種格式,現在我的頁面顯示結果像那177 | RC456456177 | 1314160971 | 129 $ – John

+0

'$ date = date('Ymd',$ results [2])'? –

回答

0

根據您在上面發佈的代碼,這應該是訣竅。

$date = date('Y.m.d', $results[2]) 
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

+0

'$ contents [3]'或'$ contents [2]'? –

+0

$ contents [2]。對不起,愚蠢的錯字。 – Andreas

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雙引號字符串作爲最佳實踐的內部。