2010-11-06 166 views
1

我想读一个格式化的文件PHP读取文件

name(读取到这个变量)

10 10(读成独立的变量)

,其余为阵列

line 

line 

line 

line 

来澄清这是一个上传脚本,我已经完成了,当用户上传一个格式化的文件时,它以上述方式读取它

$fname = 'test.txt'; 

$lines = file("$fname", "r"); 

while($lines as $currenline){ 

I am trying to put the name, width, height into variables 
    then the rest into the array 

} 

将这种帮助

回答

0

$lines已经几乎包含了你所需要的,只是拉了相关作品。

$fname = 'test.txt'; 
$lines = file("$fname", "r"); 
$name = $lines[0]; 
list($height, $width) = explode(' ', $lines[1]); 
$lines = array_slice($lines, 2); 

请注意,这没有任何错误检查,因此您可能需要添加一些。

正如意见建议,你也可以做到这一点使用array_shift

$fname = 'test.txt'; 
$lines = file("$fname", "r"); 
$name = array_shift($lines); 
list($height, $width) = explode(' ', array_shift($lines)); 
// $lines now contains only the rest of the lines in the file. 
+0

如果你使用'array_shift($线)'代替'$行[0]'和'$线[1]',你可以摆脱'array_slice()'的。 – 2010-11-06 15:43:34

+0

您还使用array_shift操作数组3次而不是一次。 – smack0007 2010-11-06 15:45:28

+0

@ smack0007 - 我正在访问数组两次,并操纵它一次,而不是操纵它3次... – 2010-11-06 15:46:34

0

不是100%肯定你问什么,但也许这可以让你开始:

$fname = 'test.txt'; 

$lines = file("$fname", "r"); 

foreach($lines as $line) { 
    $parts = explode(' ', $line); 
    $name = $parts[0]; 
    $width = $parts[1]; 
    $height = $parts[2]; 

    // Do whatever you want with the line data here 
} 

它假设所有输入行格式正确。

+0

再次阅读问题后,我认为Mark E的答案就是您要找的答案。 – smack0007 2010-11-06 15:43:28

0
$fh = fopen($fname, 'r'); 

$name = fgets($fh); 
$dimensions = split(' ', fgets($fh)); 
$length = $dimensions[0]; 
$width = $dimensions[1]; 

$lines = array(); 

while ($line = fgets($fh) $lines[] = $line; 

我从来没有测试过,但它应该工作,如果你的文件是恒定的。 while循环可能关闭,如果它不起作用需要重新工作,请记住,如果发生错误或无法读取文件,则fgets将返回false。