如何解析包含制表符分隔行的txt文件?

问题描述 投票:0回答:3

我无法使用以下代码拆分字符串。

<?php
$i=0;
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "no\t";
fwrite($fh, $stringData);
$stringData = "username \t";
fwrite($fh, $stringData);
$stringData ="password \t";
fwrite ($fh,$stringData);

$newline ="\r\n";
fwrite ($fh,$newline);
$stringData1 = "1\t";
fwrite($fh, $stringData1);
$stringData1 = "srinivas \t";
fwrite($fh, $stringData1);
$stringData1 ="malayappa \t";
fwrite ($fh,$stringData1);


fclose($fh);



?>
$fh = fopen("testFile.txt", "r");
$
while (!feof($fh)) {
$line = fgets($fh);
echo $line;
}

fclose($fh);
$Beatles = array('pmm','malayappa','sreenivas','PHP');

for($i=0;$i<count($Beatles);$i++)
{
if($i==2)
{

echo $Beatles[$i-1];
echo $Beatles[$i-2];

}
}
$pass_ar=array();
$fh = fopen("testFile.txt", "r");
while (!feof($fh)) {
$line = fgets($fh);
echo $line;
$t1=explode(" ",$line);

print_r($t1);
array_push($pass_ar,t1);
}

fclose($fh);
php file text delimited fileparsing
3个回答
1
投票

如果我正确地阅读了代码,您正在编写由 分隔的字符串,但尝试用空格分隔,请使用:

explode("\t", $string);

1
投票

您可以使用 fgetcsv,因为您只是在做一个标准的制表符分隔输入文件。鉴于您的示例文件:

no [tab] username [tab] password
1  [tab] srinivas [tab] malayappa

然后

$lines = array();
$fh = fopen('testfile.txt', 'rb') or die ("can't open testfile.txt");
while($lines[] = fgetcsv($fh, 0, "\t") { // no line length limit, tab delimiter)
   ...
}

会给你

$lines = Array(
    0 => Array(
         0 => 'no ',
         1 => 'username ',
         2 => 'password '
    ),
    1 => Array(
         0 => 1,
         1 => 'srinivas ',
         2 => 'malayappa'
    )
);

0
投票

你在空白处爆炸了。 除非你爆炸的字符串中有空格,否则它不会工作。

尝试使用代码标记使代码更具可读性,以便从人们那里获得更高质量的响应。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.