The SplFileObject::fseek() function is an inbuilt function of Standard PHP Library (SPL) in PHP that allows you to move the file pointer to a specified position within a file opened using SplFileObject
. The file pointer is the position where the next read or write operation will occur. This function is used to navigate within a file and read or write data from a specific location.
Syntax:
public SplFileObject::fseek(int $offset, int $whence = SEEK_SET): int
Parameters: This function accepts two parameters that are described below.
- $offset: The offset value represents the number of bytes to move the file pointer. It can be positive or negative, depending on the direction you want to move the pointer.
-
$whence: This is an optional parameter that specifies the starting point for the offset calculation. It can take one of the following values:
SEEK_SET
– Set position equal tooffset
bytes,SEEK_CUR
– Set position to current location plusoffset
,SEEK_END
– Set position to end-of-file plusoffset
.
Program 1: The following program demonstrates the SplFileObject::fseek() function. Save this file name as “output.txt” before running this program.
Line 1: This is the first line of data.
Line 2: This is the second line of data.
Line 3: This is the third line of data.
<?php $file = new SplFileObject( './output.txt' , 'r' );
// Move the file pointer to the 10th byte // from the beginning of the file. $file -> fseek (10, SEEK_SET);
// Read the content from the current position //(10th byte) to the end of the file. $content = $file -> fread ( $file ->getSize() - $file -> ftell ());
echo $content ;
?> |
Output:
is is the first line of data.
Line 2: This is the second line of data.
Line 3: This is the third line of data.
Program 2: The following program demonstrates the SplFileObject::fseek() function. Save this file name as “output.txt” before running this program.
Ram
Seeta
Michael Johnson
Emily Brown
William Davis
<?php $file = new SplFileObject( 'output.txt' , 'r' );
// Move the file pointer to the beginning // of the third line (name) $file -> fseek ( strlen ( "Michael \n" ) * 2, SEEK_SET);
// Read the third name from the current position. $thirdName = trim( $file -> fgets ());
// Output the third name. echo "The third name in the file is: " . $thirdName ;
?> |
Output:
The third name in the file is: Johnson
Reference: https://www.php.net/manual/en/splfileobject.fseek.php