2016-02-11 25 views
0

我有txt文件,其中第一行包含列名。但有些行沒有標題,我想知道是否有任何解決方案將沒有列名的行刪除到我的txt文件中?PHP - 如何刪除沒有標題的列到txt文件

要訪問我的txt文件:

$handleFile= fopen("/opt/lampp/htdocs/ngs/tmp/testfile.txt","r"); 
$dataTestFile=fgetcsv($handleFile,0,"\t"); 

下面是一個例子:

Data1;Data2;;Input;; 
aaaaa;ferfs;;alpha;dfdfd; 

所需的輸出:

Data1;Data2;Input; 
aaaaa;ferfs;alpha; 

第一行是列名,和一些他們沒有任何名字,我需要刪除所有沒有n的列埃姆斯。

謝謝。

+1

最好把一些txt文件的樣本 – FareedMN

+0

@FareedMN。真的,我添加了一個示例 – user979974

回答

0

我會做這樣的事情:

<?php 
$data=file_get_contents("/opt/lampp/htdocs/ngs/tmp/testfile.txt"); 
$array=explode("\n",$data); // putting rows in an array 
$first_line=$array['0']; 
$first_line_array=explode("|",$first_line); 
$removed_columns=array(); 
foreach ($first_line_array as $key=>$value){ 
if(strstr(" ",$value) !== FALSE){ 
    array_push($removed_columns,$key); 
} 
} 
// now we know what columns to remove 
$new_line=''; 
$new_array=array(); 
$new_line_array=array(); 
$old_line_array=array(); 
for($x=0;$x<count($array);$x++){ 
$old_line_array=explode("|",$array[$x]); 
for($y=0;$y<count($old_line_array);$y++){ 
    if(!in_array($y,$removed_columns)){ 
     array_push($new_line_array,$old_line_array[$y]); 
    } 
    } 
    $new_line=join('|',$new_line_array); 

    array_push($new_array,$new_line); 

    $new_line=''; 
    $new_line_array=array(); 
    $old_line_array=array(); 

    } 
    $new_data=join("\n",$new_array); 
    file_put_contents("/opt/lampp/htdocs/ngs/tmp/testfilenew.txt",$new_data) 
    ?> 

在你的文件末尾(testfilenew .txt)其中有你想要的數據

+0

thx這麼多爲您的幫助,但不幸的是,我無法測試您的腳本,我有一個錯誤'未捕獲的錯誤:調用未定義的函數split()'。我正在使用PHP 7. – user979974

+0

以及我正在使用5.2 :)對不起 – FareedMN

+0

我用爆炸代替分裂現在它應該工作 – FareedMN

0

您需要先讀取第1行並將空數據的列號存儲在數組中。

一旦你的陣列可以使用下面的代碼跳過列:

$columns = array(1,3); // columns to skip 

while (($data = fgetcsv($dataTestFile, 1000, "|")) !== FALSE) { 
     echo("<tr>\r\n"); 
     foreach ($data as $index=>$val) { 
       if (!in_array($index+1, $columns)) { 
         echo("\t<td>$val</td>\r\n"); 
       } 
     } 
     echo("</tr>\r\n"); 
} //end while