PHP reading file
I am trying to read a formatted file
name
(read this into variable)
10 10
(read into separate variables)
the rest into array
line
line
line
line
to clarify this is for an upload script which i already finished when a user uplo开发者_开发知识库ads a file formatted like that it reads it in the way described above
$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
}
will this help
Not 100% sure what you're asking for but maybe this can get you started:
$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
}
It assumes all input lines are well formatted of course.
$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;
I never tested this, but it should work if your files are constant. The while loop maybe off, and need some re-working if it doesn't work, keeping in mind that fgets returns false if an error occurs or is unable to read the file.
$lines
already contains almost what you need, just pull out the relevant pieces.
$fname = 'test.txt';
$lines = file("$fname", "r");
$name = $lines[0];
list($height, $width) = explode(' ', $lines[1]);
$lines = array_slice($lines, 2);
Note this doesn't have any error checking, so you might want to add some.
As suggested in the comments you can also do this using 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.
精彩评论