A detailed explanation of Splfileobject and splfileinfo in the PHP file processing class

Source: Internet
Author: User
Tags flock php programming string to file
This article mainly introduced the PHP programming file processing Class Splfileobject and splfileinfo usage, combined with the instance form analysis the file processing class Splfileobject and splfileinfo function, the definition, the use method and the related matters needing attention, A friend you need can refer to the following

This article describes the PHP programming file processing Class Splfileobject and splfileinfo usage. Share to everyone for your reference, as follows:

PHP handles large files in addition to the following methods can also directly call the Linux command

File Processing classes:

Splfileinfo {/* Method */public __construct (String $file _name) public int getatime (void)//Get the last access time of the file public string get Basename ([string $suffix])//Gets the base name of the file without path information, the parameter can be a file suffix, and if there is a parameter returns the base name of the file without that suffix. public int getctime (void)//Returns the timestamp of the last change in the article. public string getextension (void)//Gets the file name extension public splfileinfo getfileinfo ([string $class _name])//Returns the file path and name as an object Pu  Blic string GetFileName (void)//Get file name without path public int getgroup (void)//Get file group, return group Idpublic int getinode (void)  Get File Index node public string getlinktarget (void)//Get file link target public int getmtime (void)//Get last Modified time public int getOwner (void )//Get the owner of the file public string getpath (void)//Get the file path, without the file name and the last slash public Splfileinfo getpathinfo ([string $class _name] )//Return Path object public string getpathname (void)//Get file path public int getperms (void)//Get File Permissions public string Getrealpath (V  OID)//Get the file absolute path, if the file does not exist, return falsepublic int getsize (void)//Return file size, Unit bytes public string getType (void)//return file type, possibly files, Link, dirpublicBOOL Isdir (void)//Determines whether the directory is put back to true otherwise returns falsepublic bool IsExecutable (void)//Determines whether the file can be executed, returns TRUE, otherwise returns falsepublic bool is File (void)//If it is present and is a normal file (not a link), returns true otherwise falsepublic bool Islink (void)///Determines whether the file is a connection, not a return falsepublic bool Isreada ble (void)//Determine whether the file is readable, readable return truepublic bool iswritable (void)///Determine if the file is writable, writable return truepublic splfileobject openFile ([stri  ng $open _mode = "R" [, bool $use _include_path = False [, resource $context = NULL]])//Get file object information public void Setfileclass ([string $class _name = "Splfileobject"]) public void Setinfoclass ([string $class _name = ' splfileinfo ']) public void __tostring (void)//Returns the file path and name in the form of a string}

How to use:

$info = new Splfileinfo ($file _name);

Splfileobject {/* constant */const integer drop_new_line = 1; Const integer READ_AHEAD = 2; Const integer SKIP_EMPTY = 4; const The integer read_csv = 8;/* Method */public String|array current (void)//Returns the contents of the present line of the file public bool eof (void)//detect if the file is to the end, if to the end Returns TRUE, otherwise returns falsepublic bool Fflush (void)///To output buffered content to a file, returns true on success, or FALSE on failure. public string fgetc (void)//read file by character public array fgetcsv ([String $delimiter = "," [, String $enclosure = "\" "[, Stri  ng $escape = "\ \"]])//Read CSV file public string fgets (void)//Read file by row public string Fgetss ([string $allowable _tags]) Read files by line and remove HTML tags public bool flock (int $operation [, int & $wouldblock])//File lock or unlock, return TRUE or false/* parameter: Lock_sh shared lock (read). LOCK_EX exclusive Lock (write). Lock_un release Lock (shared or exclusive).  LOCK_NB (Additional lock) If you do not want flock () to block when locked, you should add a lock after the above lock (not supported on Windows) flock (LOCK_EX+LOCK_NB); Exclusive lock plus additional lock flock (LOCK_UN+LOCK_NB); */public int Fpassthru (void)//output file pointer after all data and characters public int fputcsv (array $fields)//A one-dimensional array is entered as a row in the CSV file, returning the length of the written string or Fals Epublic String Fread ( int $length)//reads the specified number of bytes from the file, returns the read string or Falsepublic mixed fscanf (string $format [, Mixed &$ ...])//reads a line from the file and follows the specified pattern Analysis/* Example: $file = new Splfileobject ("Misc.txt"), while ($userinfo = $file->fscanf ("%s%s") {list ($name, $profession, $  CountryCode) = $userinfo; Do something with $name $profession $countrycode}*/public int fseek (int $offset [, int $whence = Seek_set])//move by Byte The file pointer position,/*seek_set sets the file pointer to the specified byte position (the default is the mode). Seek_cur sets the file pointer to the current position plus the specified byte position.      Seek_end sets the file pointer to the end of the file with the specified byte position (this time the bytes are often negative). Public array fstat (void)//Get file information, return the *//* numeric subscript associated key name as an array (from PHP 4.0.6) description 0 Dev device number-device name 1 ino inode number-inode 2 mode inode protection Mode-inode protected Mode 3 Nlink numb  Er of links-Number of connections 4 UID userid of owner-owner of user id5 gid GroupID of owner-owner group Id6 rdev device type, if Inode device *-device type, if inode devices 7 size size in bytes-bytes of file size 8 atime time of last access (Unix Timestam P)-Last accessed (Unix timestamp) 9 Mtime timeDification (Unix timestamp)-Last modified (Unix timestamp) CTime time (Unix timestamp)-Last changed time (Unix timestamp) 11 Blksize blocksize of filesystem IO *-file system io block size of blocks number of blocks allocated-occupied blocks are always 0 under Windows. *-Valid only on systems that support the st_blksize type. Other systems (such as Windows) return-1. */public int Ftell (void)//Returns the current file position, file pointer position public bool Ftruncate (int $size)//truncates the file to the specified length, if the length is greater than the length of the file is empty (the file open method affects it) public int fwrite (string $str [, int $length])//writes $STR string to file, write $length length only. Put back write bytes or nullpublic array getcsvcontrol (void)//gets the delimiter and enclosure character used for parsing CSV FIELDS.P  ublic int getflags (void)//gets the flags set for a instance of Splfileobject as an integer.public int getmaxlinelen ( void)//Returns the maximum number of bytes read in a row (if set), default is 0public int key (void)//Gets the current line number, if not set. public void Next (void)//move to the next line public void rewind (void)//Return to first line public void seek (int $line _pos)//Navigate to file Specify line public void Setcsvcontrol ([String $delimiter = "," [, String $enclosure ="\" "[, string $escape =" \ \ "]]) public void SetFlags (int. $flags) public void Setmaxlinelen (int $max _len)//Set file read one The maximum number of bytes of the row, if the file has 10 characters per line, but set the maximum read to public bool valid (void)//Check whether the bottom of the file is reached, the bottom is not reached and return TRUE, Arrival returns FALSE.}


$file = new Splfileobject ("Misc.txt", ' r+ '), while (! $file->eof ()) {  echo $file->current ();  $file->next ();} Close File Object $file = null;

Common file processing methods:

/** * Get file specifies the number of rows range data * @param unknown $filename file name * @param number $startLine start line * @param number $endLine End line * @param s Tring $method * @return multitype: */function getfilelines ($filename, $startLine = 1, $endLine = A, $method = ' rb ') {$co  ntent = Array ();  $count = $endLine-$startLine;  $fp = new Splfileobject ($filename, $method); $FP->seek ($startLine-1);    Go to Nth row, the Seek method parameter counts from 0 for ($i = 0; $i <= $count; + + $i) {$content [] = $fp->current ();//current () get the contents of the line $FP->next ();      The next line if ($fp->eof ()) {Array_pop ($content);    Break }} return Array_filter ($content); Array_filter filter: False,null, '}/** * get the last line of the article * @param string $res file path/name */function Get_last_line ($res) {$fp = fopen  ($res, ' R ');  if (false = = $fp) {return ' error ';  } fseek ($fp, -1,seek_end);  $s = ";    while (($c = fgetc ($fp))!== false) {if ($c = = "\ n" && $s) break; $s = $c.    $s;  Fseek ($FP,-2, seek_cur);  } fclose ($FP); return $s;}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.