PHP读取文件
我正在尝试读取格式化文件PHP读取文件,php,file,Php,File,我正在尝试读取格式化文件 name(将其读入变量) 10(读入单独的变量) 其余的都排成一列 line line line line 为了澄清这一点,我已经完成了一个上传脚本,当用户上传一个格式化为这样的文件时,它会以上面描述的方式读取它 $fname = 'test.txt'; $lines = file("$fname", "r"); while($lines as $currenline){ I am trying to put the name, width, hei
name
(将其读入变量)
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
}
这会有帮助吗?
$lines
已经包含了您所需要的几乎所有内容,只需拉出相关部分即可
$fname = 'test.txt';
$lines = file("$fname", "r");
$name = $lines[0];
list($height, $width) = explode(' ', $lines[1]);
$lines = array_slice($lines, 2);
注意,这没有任何错误检查,因此您可能需要添加一些错误检查
正如评论中所建议的,您也可以使用array\u 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.
不是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
}
当然,它假设所有的输入行都有良好的格式
$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。再次阅读问题后,我认为Mark E的答案就是您要寻找的。如果您使用
数组移位($line)
代替$line[0]
和$line[1]
,您可以去掉数组切片()
。您还可以使用数组移位操作数组3次,而不是一次。@smack0007-我访问数组两次,操作数组一次,而不是操作数组3次…@Mark E不,我的意思是使用数组移位可以做到这一点。我支持你的方法@Mark E我是将此代码放入while lopp还是删除while循环