Spl/files-Phpdoc专题
文件处理
目录
- SplFileInfo — The SplFileInfo class
- SplFileInfo::__construct — 构建一个新的 SplFileInfo 对象
- SplFileInfo::getATime — Gets last access time of the file
- SplFileInfo::getBasename — Gets the base name of the file
- SplFileInfo::getCTime — 获取文件 inode 修改时间
- SplFileInfo::getExtension — Gets the file extension
- SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file
- SplFileInfo::getFilename — Gets the filename
- SplFileInfo::getGroup — Gets the file group
- SplFileInfo::getInode — Gets the inode for the file
- SplFileInfo::getLinkTarget — Gets the target of a link
- SplFileInfo::getMTime — Gets the last modified time
- SplFileInfo::getOwner — Gets the owner of the file
- SplFileInfo::getPath — Gets the path without filename
- SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path
- SplFileInfo::getPathname — Gets the path to the file
- SplFileInfo::getPerms — Gets file permissions
- SplFileInfo::getRealPath — Gets absolute path to file
- SplFileInfo::getSize — Gets file size
- SplFileInfo::getType — Gets file type
- SplFileInfo::isDir — Tells if the file is a directory
- SplFileInfo::isExecutable — Tells if the file is executable
- SplFileInfo::isFile — Tells if the object references a regular file
- SplFileInfo::isLink — Tells if the file is a link
- SplFileInfo::isReadable — Tells if file is readable
- SplFileInfo::isWritable — Tells if the entry is writable
- SplFileInfo::openFile — Gets an SplFileObject object for the file
- SplFileInfo::setFileClass — Sets the class used with SplFileInfo::openFile
- SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
- SplFileInfo::__toString — Returns the path to the file as a string
- SplFileObject — The SplFileObject
class
- SplFileObject::__construct — Construct a new file object
- SplFileObject::current — Retrieve current line of file
- SplFileObject::eof — Reached end of file
- SplFileObject::fflush — Flushes the output to the file
- SplFileObject::fgetc — Gets character from file
- SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
- SplFileObject::fgets — Gets line from file
- SplFileObject::fgetss — Gets line from file and strip HTML tags
- SplFileObject::flock — Portable file locking
- SplFileObject::fpassthru — Output all remaining data on a file pointer
- SplFileObject::fputcsv — Write a field array as a CSV line
- SplFileObject::fread — Read from file
- SplFileObject::fscanf — Parses input from file according to a format
- SplFileObject::fseek — Seek to a position
- SplFileObject::fstat — Gets information about the file
- SplFileObject::ftell — Return current file position
- SplFileObject::ftruncate — Truncates the file to a given length
- SplFileObject::fwrite — Write to file
- SplFileObject::getChildren — No purpose
- SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV
- SplFileObject::getCurrentLine — Alias of SplFileObject::fgets
- SplFileObject::getFlags — Gets flags for the SplFileObject
- SplFileObject::getMaxLineLen — Get maximum line length
- SplFileObject::hasChildren — SplFileObject does not have children
- SplFileObject::key — Get line number
- SplFileObject::next — Read next line
- SplFileObject::rewind — Rewind the file to the first line
- SplFileObject::seek — Seek to specified line
- SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV
- SplFileObject::setFlags — Sets flags for the SplFileObject
- SplFileObject::setMaxLineLen — Set maximum line length
- SplFileObject::__toString — Alias of SplFileObject::fgets
- SplFileObject::valid — Not at EOF
- SplTempFileObject — The
SplTempFileObject class
- SplTempFileObject::__construct — Construct a new temporary file object
SPL 提供 一些与文件相关的类。
简介
The SplFileInfo class offers a high-level object oriented interface to information for an individual file.
类摘要
SplFileInfo
class SplFileInfo {
/* 方法 */
public <span
class="methodname">__construct ( <span
class="methodparam">string $file_name
)
public int <span class="methodname">getATime ( <span class="methodparam">void )
public string
getBasename ([ <span
class="methodparam">string $suffix ]
)
public int <span class="methodname">getCTime ( <span class="methodparam">void )
public string getExtension ( <span class="methodparam">void )
public <span
class="type">SplFileInfo <span
class="methodname">getFileInfo ([ <span
class="methodparam">string
$class_name ] )
public string getFilename ( <span class="methodparam">void )
public int <span class="methodname">getGroup ( <span class="methodparam">void )
public int <span class="methodname">getInode ( <span class="methodparam">void )
public string getLinkTarget ( <span class="methodparam">void )
public int <span class="methodname">getMTime ( <span class="methodparam">void )
public int <span class="methodname">getOwner ( <span class="methodparam">void )
public string getPath ( <span class="methodparam">void )
public <span
class="type">SplFileInfo <span
class="methodname">getPathInfo ([ <span
class="methodparam">string
$class_name ] )
public string getPathname ( <span class="methodparam">void )
public int <span class="methodname">getPerms ( <span class="methodparam">void )
public string getRealPath ( <span class="methodparam">void )
public int <span class="methodname">getSize ( <span class="methodparam">void )
public string getType ( <span class="methodparam">void )
public bool isDir ( <span class="methodparam">void )
public bool isExecutable ( <span class="methodparam">void )
public bool isFile ( <span class="methodparam">void )
public bool isLink ( <span class="methodparam">void )
public bool isReadable ( <span class="methodparam">void )
public bool isWritable ( <span class="methodparam">void )
public <span
class="type">SplFileObject <span
class="methodname">openFile ([ <span
class="type">string $open_mode =
"r" [, <span
class="type">bool $use_include_path =
false [, <span
class="type">resource $context =
null ]]] )
public void
setFileClass ([ <span
class="methodparam">string $class_name<span
class="initializer"> = "SplFileObject" ] )
public void
setInfoClass ([ <span
class="methodparam">string $class_name<span
class="initializer"> = "SplFileInfo" ] )
public string __toString ( <span class="methodparam">void )
}
SplFileInfo::__construct
构建一个新的 SplFileInfo 对象
说明
public <span
class="methodname">SplFileInfo::__construct ( <span
class="methodparam">string $file_name
)
为指定的 file_name 创建一个新的 SplFileInfo 对象,该文件不需要存在或者可读。
参数
file_name
文件路径
范例
示例 #1 SplFileInfo::__construct 示例
<?php
$info = new SplFileInfo('example.php');
if ($info->isFile()) {
echo $info->getRealPath();
}
?>
SplFileInfo::getATime
Gets last access time of the file
说明
public int <span class="methodname">SplFileInfo::getATime ( <span class="methodparam">void )
Gets the last access time for the file.
参数
此函数没有参数。
返回值
Returns the time the file was last accessed.
错误/异常
Throws RunTimeException on error.
参见
- fileatime
SplFileInfo::getBasename
Gets the base name of the file
说明
public string
SplFileInfo::getBasename ([ <span
class="methodparam">string $suffix ]
)
This method returns the base name of the file, directory, or link without path info.
Caution
SplFileInfo::getBasename is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the <span class="function">setlocale function.
参数
suffix
Optional suffix to omit from the base name returned.
返回值
Returns the base name without path information.
范例
示例 #1 SplFileInfo::getBasename example
<?php
$info = new SplFileInfo('file.txt');
var_dump($info->getBasename());
$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename());
$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename('.txt'));
?>
以上例程的输出类似于:
string(8) "file.txt"
string(8) "file.txt"
string(4) "file"
参见
- SplFileInfo::getFilename
SplFileInfo::getCTime
获取文件 inode 修改时间
说明
public int <span class="methodname">SplFileInfo::getCTime ( <span class="methodparam">void )
返回此文件 inode 的修改时间,返回的时间是个 Unix 时间戳。
参数
此函数没有参数。
返回值
返回inode最后一次变更的时间戳。
错误/异常
错误时抛出 RunTimeException。
范例
示例 #1 SplFileInfo::getCTime 例子
<?php
$info = new SplFileInfo(__FILE__);
echo 'Last changed at ' . date('g:i a', $info->getCTime());
?>
以上例程的输出类似于:
Last changed at 1:49 pm
参见
- filectime
SplFileInfo::getExtension
Gets the file extension
说明
public string SplFileInfo::getExtension ( <span class="methodparam">void )
Retrieves the file extension.
参数
此函数没有参数。
返回值
Returns a string containing the file extension, or an empty string if the file has no extension.
范例
示例 #1 SplFileInfo::getExtension example
<?php
$info = new SplFileInfo('foo.txt');
var_dump($info->getExtension());
$info = new SplFileInfo('photo.jpg');
var_dump($info->getExtension());
$info = new SplFileInfo('something.tar.gz');
var_dump($info->getExtension());
?>
以上例程会输出:
string(3) "txt"
string(3) "jpg"
string(2) "gz"
注释
Note:
This method is only available as of PHP 5.3.6. Another way of getting the extension is to use the pathinfo function.
<?php $extension = pathinfo($info->getFilename(), PATHINFO_EXTENSION); ?>
参见
- SplFileInfo::getFilename
- SplFileInfo::getBasename
- pathinfo
SplFileInfo::getFileInfo
Gets an SplFileInfo object for the file
说明
public <span
class="type">SplFileInfo <span
class="methodname">SplFileInfo::getFileInfo ([ <span
class="methodparam">string
$class_name ] )
This method gets an SplFileInfo object for the referenced file.
参数
class_name
Name of an SplFileInfo derived class to
use.
返回值
An SplFileInfo object created for the file.
参见
- SplFileInfo::setInfoClass
SplFileInfo::getFilename
Gets the filename
说明
public string SplFileInfo::getFilename ( <span class="methodparam">void )
Gets the filename without any path information.
参数
此函数没有参数。
返回值
The filename.
范例
示例 #1 SplFileInfo::getFilename example
<?php
$info = new SplFileInfo('foo.txt');
var_dump($info->getFilename());
$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());
$info = new SplFileInfo('http://www.php.net/');
var_dump($info->getFilename());
$info = new SplFileInfo('http://www.php.net/svn.php');
var_dump($info->getFilename());
?>
以上例程的输出类似于:
string(7) "foo.txt"
string(7) "foo.txt"
string(0) ""
string(7) "svn.php"
参见
- SplFileInfo::getBasename
SplFileInfo::getGroup
Gets the file group
说明
public int <span class="methodname">SplFileInfo::getGroup ( <span class="methodparam">void )
Gets the file group. The group ID is returned in numerical format.
参数
此函数没有参数。
返回值
The group id in numerical format.
错误/异常
Throws RuntimeException on error.
范例
示例 #1 SplFileInfo::getGroup example
<?php
$info = new SplFileInfo(__FILE__);
print_r(posix_getgrgid($info->getGroup()));
?>
以上例程的输出类似于:
参见
- posix_getgrgid
SplFileInfo::getInode
Gets the inode for the file
说明
public int <span class="methodname">SplFileInfo::getInode ( <span class="methodparam">void )
Gets the inode number for the filesystem object.
参数
此函数没有参数。
返回值
Returns the inode number for the filesystem object.
错误/异常
Throws RuntimeException on error.
参见
- fileinode
SplFileInfo::getLinkTarget
Gets the target of a link
说明
public string SplFileInfo::getLinkTarget ( <span class="methodparam">void )
Gets the target of a filesystem link.
Note:
The target may not be the real path on the filesystem. Use <span class="methodname">SplFileInfo::getRealPath to determine the true path on the filesystem.
参数
此函数没有参数。
返回值
Returns the target of the filesystem link.
错误/异常
Throws RuntimeException on error.
范例
示例 #1 SplFileInfo::getLinkTarget example
<?php
$info = new SplFileInfo('/Users/bbieber/workspace');
if ($info->isLink()) {
var_dump($info->getLinkTarget());
var_dump($info->getRealPath());
}
?>
以上例程的输出类似于:
string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"
参见
- SplFileInfo::isLink
- SplFileInfo::getRealPath
SplFileInfo::getMTime
Gets the last modified time
说明
public int <span class="methodname">SplFileInfo::getMTime ( <span class="methodparam">void )
Returns the time when the contents of the file were changed. The time returned is a Unix timestamp.
参数
此函数没有参数。
返回值
Returns the last modified time for the file, in a Unix timestamp.
参见
- filemtime
SplFileInfo::getOwner
Gets the owner of the file
说明
public int <span class="methodname">SplFileInfo::getOwner ( <span class="methodparam">void )
Gets the file owner. The owner ID is returned in numerical format.
参数
此函数没有参数。
返回值
The owner id in numerical format.
错误/异常
Throws RuntimeException on error.
范例
示例 #1 SplFileInfo::getOwner example
<?php
$info = new SplFileInfo('file.txt');
print_r(posix_getpwuid($info->getOwner()));
?>
参见
- posix_getpwuid
- SplFileInfo::getGroup
SplFileInfo::getPath
Gets the path without filename
说明
public string SplFileInfo::getPath ( <span class="methodparam">void )
Returns the path to the file, omitting the filename and any trailing slash.
参数
此函数没有参数。
返回值
Returns the path to the file.
范例
示例 #1 SplFileInfo::getPath example
<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPath());
$info = new SplFileInfo('/usr/');
var_dump($info->getPath());?>
以上例程的输出类似于:
string(8) "/usr/bin"
string(4) "/usr"
参见
- SplFileInfo::getRealPath
- SplFileInfo::getFilename
- SplFileInfo::getPathInfo
SplFileInfo::getPathInfo
Gets an SplFileInfo object for the path
说明
public <span
class="type">SplFileInfo <span
class="methodname">SplFileInfo::getPathInfo ([ <span
class="methodparam">string
$class_name ] )
Gets an SplFileInfo object for the parent of the current file.
参数
class_name
Name of an SplFileInfo derived class to
use.
返回值
Returns an SplFileInfo object for the parent path of the file.
范例
示例 #1 SplFileInfo::getPathInfo example
<?php
$info = new SplFileInfo('/usr/bin/php');
$parent_info = $info->getPathInfo();
var_dump($parent_info->getRealPath());
?>
以上例程的输出类似于:
string(8) "/usr/bin"
参见
- SplFileInfo::setInfoClass
SplFileInfo::getPathname
Gets the path to the file
说明
public string SplFileInfo::getPathname ( <span class="methodparam">void )
Returns the path to the file.
参数
此函数没有参数。
返回值
The path to the file.
范例
示例 #1 SplFileInfo::getPathname example
<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPathname());
?>
以上例程的输出类似于:
string(12) "/usr/bin/php"
参见
- SplFileInfo::getRealPath
SplFileInfo::getPerms
Gets file permissions
说明
public int <span class="methodname">SplFileInfo::getPerms ( <span class="methodparam">void )
Gets the file permissions for the file.
参数
此函数没有参数。
返回值
Returns the file permissions.
范例
示例 #1 SplFileInfo::getPerms example
<?php
$info = new SplFileInfo('/tmp');
echo substr(sprintf('%o', $info->getPerms()), -4);
$info = new SplFileInfo(__FILE__);
echo substr(sprintf('%o', $info->getPerms()), -4);
?>
以上例程的输出类似于:
1777
0644
SplFileInfo::getRealPath
Gets absolute path to file
说明
public string SplFileInfo::getRealPath ( <span class="methodparam">void )
This method expands all symbolic links, resolves relative references and returns the real path to the file.
参数
此函数没有参数。
返回值
Returns the path to the file, or false if the file does not exist.
范例
示例 #1 SplFileInfo::getRealPath example
<?php
$info = new SplFileInfo('/..//./../../'.__FILE__);
var_dump($info->getRealPath());
$info = new SplFileInfo('/tmp');
var_dump($info->getRealPath());
$info = new SplFileInfo('/I/Do/Not/Exist');
var_dump($info->getRealPath());
$info = new SplFileInfo('php://output');
var_dump($info->getRealPath());
$info = new SplFileInfo("");
var_dump($info->getRealPath());
?>
以上例程的输出类似于:
string(28) "/private/tmp/phptempfile.php"
string(12) "/private/tmp"
bool(false)
bool(false)
string(12) "/private/tmp"
参见
- SplFileInfo::isLink
- realpath
SplFileInfo::getSize
Gets file size
说明
public int <span class="methodname">SplFileInfo::getSize ( <span class="methodparam">void )
Returns the filesize in bytes for the file referenced.
参数
此函数没有参数。
返回值
The filesize in bytes.
错误/异常
A RuntimeException will be thrown if the file does not exist or an error occurs.
参见
- filesize
SplFileInfo::getType
Gets file type
说明
public string SplFileInfo::getType ( <span class="methodparam">void )
Returns the type of the file referenced.
参数
此函数没有参数。
返回值
A string representing the type of the entry. May be one of file, link, or dir
错误/异常
Throws a RuntimeException on error.
范例
示例 #1 SplFileInfo::getType example
<?php
$info = new SplFileInfo(__FILE__);
echo $info->getType().PHP_EOL;
$info = new SplFileInfo(dirname(__FILE__));
echo $info->getType();
?>
以上例程的输出类似于:
file
dir
SplFileInfo::isDir
Tells if the file is a directory
说明
public bool SplFileInfo::isDir ( <span class="methodparam">void )
This method can be used to determine if the file is a directory.
参数
此函数没有参数。
返回值
Returns true if a directory, false otherwise.
范例
示例 #1 SplFileInfo::isDir example
<?php
$d = new SplFileInfo(dirname(__FILE__));
var_dump($d->isDir());
$d = new SplFileInfo(__FILE__);
var_dump($d->isDir());
?>
以上例程的输出类似于:
bool(true)
bool(false)
SplFileInfo::isExecutable
Tells if the file is executable
说明
public bool SplFileInfo::isExecutable ( <span class="methodparam">void )
Checks if the file is executable.
参数
此函数没有参数。
返回值
Returns true if executable, false otherwise.
范例
示例 #1 SplFileInfo::isExecutable example
<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->isExecutable());
$info = new SplFileInfo('/usr/bin');
var_dump($info->isExecutable());
$info = new SplFileInfo('foo');
var_dump($info->isExecutable());
?>
以上例程的输出类似于:
bool(true)
bool(true)
bool(false)
SplFileInfo::isFile
Tells if the object references a regular file
说明
public bool SplFileInfo::isFile ( <span class="methodparam">void )
Checks if the file referenced by this SplFileInfo object exists and is a regular file.
参数
此函数没有参数。
返回值
Returns true if the file exists and is a regular file (not a
link), false otherwise.
范例
示例 #1 SplFileInfo::isFile example
<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isFile());
$info = new SplFileInfo(dirname(__FILE__));
var_dump($info->isFile());
?>
以上例程的输出类似于:
bool(true)
bool(false)
SplFileInfo::isLink
Tells if the file is a link
说明
public bool SplFileInfo::isLink ( <span class="methodparam">void )
Use this method to check if the file referenced by the SplFileInfo object is a link.
参数
此函数没有参数。
返回值
Returns true if the file is a link, false otherwise.
范例
示例 #1 SplFileInfo::isLink example
<?php
$info = new SplFileInfo('/path/to/symlink');
if ($info->isLink()) {
echo 'The real path is '.$info->getRealPath();
}
?>
参见
- SplFileInfo::getRealPath
SplFileInfo::isReadable
Tells if file is readable
说明
public bool SplFileInfo::isReadable ( <span class="methodparam">void )
Check if the file is readable.
参数
此函数没有参数。
返回值
Returns true if readable, false otherwise.
范例
示例 #1 SplFileInfo::isReadable example
<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isReadable());
$info = new SplFileInfo('foo');
var_dump($info->isReadable());
?>
以上例程的输出类似于:
bool(true)
bool(false)
SplFileInfo::isWritable
Tells if the entry is writable
说明
public bool SplFileInfo::isWritable ( <span class="methodparam">void )
Checks if the current entry is writable.
参数
此函数没有参数。
返回值
Returns true if writable, false otherwise;
SplFileInfo::openFile
Gets an SplFileObject object for the file
说明
public <span
class="type">SplFileObject <span
class="methodname">SplFileInfo::openFile ([ <span
class="methodparam">string $open_mode<span
class="initializer"> = "r" [, <span
class="methodparam">bool
$use_include_path =
false [, <span
class="type">resource $context =
null ]]] )
Creates an SplFileObject <span class="type">object of the file. This is useful because <span class="classname">SplFileObject contains additional methods for manipulating the file whereas SplFileInfo is only useful for gaining information, like whether the file is writable.
参数
open_mode
The mode for opening the file. See the <span
class="function">fopen documentation for descriptions of possible
modes. The default is read only.
use_include_path
值 设为 true 时, 也会在
include_path搜索文件名。
context
上下文(context)的说明请参考手册中的
上下文(context)章节.
返回值
The opened file as an SplFileObject <span class="type">object.
错误/异常
A RuntimeException if the file cannot be opened (e.g. insufficient access rights).
范例
示例 #1 SplFileInfo::openFile example
<?php
$fileinfo = new SplFileInfo('/tmp/foo.txt');
if ($fileinfo->isWritable()) {
$fileobj = $fileinfo->openFile('a');
$fileobj->fwrite("appended this sample text");
}
?>
参见
- SplFileObject
- stream_context_create
- fopen
SplFileInfo::setFileClass
Sets the class used with <span class="methodname">SplFileInfo::openFile
说明
public void
SplFileInfo::setFileClass ([ <span
class="methodparam">string $class_name<span
class="initializer"> = "SplFileObject" ] )
Use this method to set a custom class which will be used when <span class="methodname">SplFileInfo::openFile is called. The class name passed to this method must be <span class="classname">SplFileObject or a class derived from <span class="classname">SplFileObject.
参数
class_name
The class name to use when <span
class="methodname">SplFileInfo::openFile is called.
返回值
没有返回值。
范例
示例 #1 SplFileInfo::setFileClass example
<?php
// Create a class extending SplFileObject
class MyFoo extends SplFileObject {}
$info = new SplFileInfo(__FILE__);
// Set the class to use
$info->setFileClass('MyFoo');
var_dump($info->openFile());
?>
以上例程的输出类似于:
object(MyFoo)#2 (0) { }
参见
- SplFileInfo::openFile
SplFileInfo::setInfoClass
Sets the class used with <span class="methodname">SplFileInfo::getFileInfo and <span class="methodname">SplFileInfo::getPathInfo
说明
public void
SplFileInfo::setInfoClass ([ <span
class="methodparam">string $class_name<span
class="initializer"> = "SplFileInfo" ] )
Use this method to set a custom class which will be used when <span class="methodname">SplFileInfo::getFileInfo and <span class="methodname">SplFileInfo::getPathInfo are called. The class name passed to this method must be <span class="classname">SplFileInfo or a class derived from <span class="classname">SplFileInfo.
参数
class_name
The class name to use when <span
class="methodname">SplFileInfo::getFileInfo and <span
class="methodname">SplFileInfo::getPathInfo are called.
返回值
没有返回值。
范例
示例 #1 SplFileInfo::setFileClass example
<?php
// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo {}
$info = new SplFileInfo('foo');
// Set the class name to use
$info->setInfoClass('MyFoo');
var_dump($info->getFileInfo());
?>
以上例程的输出类似于:
object(MyFoo)#2 (0) { }
参见
- SplFileInfo::getFileInfo
SplFileInfo::__toString
Returns the path to the file as a string
说明
public string SplFileInfo::__toString ( <span class="methodparam">void )
This method will return the file name of the referenced file.
参数
此函数没有参数。
返回值
Returns the path to the file.
范例
示例 #1 SplFileInfo::__toString example
<?php
$info = new SplFileInfo('foo');
var_dump($info->__toString());
echo $info.PHP_EOL;
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->__toString());
echo $info.PHP_EOL;
?>
以上例程的输出类似于:
string(3) "foo"
foo
string(12) "/usr/bin/php"
/usr/bin/php
简介
SplFileObject类为文件提供了一个面向对象接口.
类摘要
SplFileObject
class SplFileObject <span class="ooclass"> extends SplFileInfo implements <span class="interfacename">RecursiveIterator <span class="oointerface">, <span class="interfacename">SeekableIterator {
/* 常量 */
const integer
SplFileObject::DROP_NEW_LINE = 1 ;
const integer
SplFileObject::READ_AHEAD = 2 ;
const integer
SplFileObject::SKIP_EMPTY = 4 ;
const integer
SplFileObject::READ_CSV = 8 ;
/* 方法 */
public <span class="type">stringarray <span class="methodname">current ( <span class="methodparam">void )
public bool eof ( <span class="methodparam">void )
public bool fflush ( <span class="methodparam">void )
public string fgetc ( <span class="methodparam">void )
public array
fgetcsv ([ <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = "\"" [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
public string fgets ( <span class="methodparam">void )
public string
fgetss ([ <span
class="methodparam">string
$allowable_tags ] )
public bool
flock ( <span
class="type">int $operation [, <span
class="methodparam">int &$wouldblock
] )
public int <span class="methodname">fpassthru ( <span class="methodparam">void )
public <span
class="type">intfalse <span
class="methodname">fputcsv ( <span
class="type">array $fields [, <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = '"' [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
public <span
class="type">stringfalse <span
class="methodname">fread ( <span
class="type">int $length )
public mixed
fscanf ( <span
class="type">string $format , <span
class="methodparam">mixed &$vars )
public int <span
class="methodname">fseek ( <span
class="type">int $offset [, <span
class="methodparam">int $whence<span
class="initializer"> = SEEK_SET ] )
public array fstat ( <span class="methodparam">void )
public int <span class="methodname">ftell ( void )
public bool
ftruncate ( <span
class="methodparam">int $size )
public int <span
class="methodname">fwrite ( <span
class="type">string $str [, <span
class="methodparam">int $length ] )
public void getChildren ( <span class="methodparam">void )
public array getCsvControl ( <span class="methodparam">void )
public int <span class="methodname">getFlags ( <span class="methodparam">void )
public int <span class="methodname">getMaxLineLen ( <span class="methodparam">void )
public bool hasChildren ( <span class="methodparam">void )
public int <span class="methodname">key ( void )
public void next ( <span class="methodparam">void )
public void rewind ( <span class="methodparam">void )
public void
seek ( <span
class="type">int $line_pos )
public void
setCsvControl ([ <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = "\"" [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
public void
setFlags ( <span
class="methodparam">int $flags )
public void
setMaxLineLen ( <span
class="methodparam">int $max_len )
public bool valid ( <span class="methodparam">void )
/* 继承的方法 */
public int <span class="methodname">SplFileInfo::getATime ( <span class="methodparam">void )
public string
SplFileInfo::getBasename ([ <span
class="methodparam">string $suffix ]
)
public int <span class="methodname">SplFileInfo::getCTime ( <span class="methodparam">void )
public string SplFileInfo::getExtension ( <span class="methodparam">void )
public <span
class="type">SplFileInfo <span
class="methodname">SplFileInfo::getFileInfo ([ <span
class="methodparam">string
$class_name ] )
public string SplFileInfo::getFilename ( <span class="methodparam">void )
public int <span class="methodname">SplFileInfo::getGroup ( <span class="methodparam">void )
public int <span class="methodname">SplFileInfo::getInode ( <span class="methodparam">void )
public string SplFileInfo::getLinkTarget ( <span class="methodparam">void )
public int <span class="methodname">SplFileInfo::getMTime ( <span class="methodparam">void )
public int <span class="methodname">SplFileInfo::getOwner ( <span class="methodparam">void )
public string SplFileInfo::getPath ( <span class="methodparam">void )
public <span
class="type">SplFileInfo <span
class="methodname">SplFileInfo::getPathInfo ([ <span
class="methodparam">string
$class_name ] )
public string SplFileInfo::getPathname ( <span class="methodparam">void )
public int <span class="methodname">SplFileInfo::getPerms ( <span class="methodparam">void )
public string SplFileInfo::getRealPath ( <span class="methodparam">void )
public int <span class="methodname">SplFileInfo::getSize ( <span class="methodparam">void )
public string SplFileInfo::getType ( <span class="methodparam">void )
public bool SplFileInfo::isDir ( <span class="methodparam">void )
public bool SplFileInfo::isExecutable ( <span class="methodparam">void )
public bool SplFileInfo::isFile ( <span class="methodparam">void )
public bool SplFileInfo::isLink ( <span class="methodparam">void )
public bool SplFileInfo::isReadable ( <span class="methodparam">void )
public bool SplFileInfo::isWritable ( <span class="methodparam">void )
public <span
class="type">SplFileObject <span
class="methodname">SplFileInfo::openFile ([ <span
class="methodparam">string $open_mode<span
class="initializer"> = "r" [, <span
class="methodparam">bool
$use_include_path =
false [, <span
class="type">resource $context =
null ]]] )
public void
SplFileInfo::setFileClass ([ <span
class="methodparam">string $class_name<span
class="initializer"> = "SplFileObject" ] )
public void
SplFileInfo::setInfoClass ([ <span
class="methodparam">string $class_name<span
class="initializer"> = "SplFileInfo" ] )
public string SplFileInfo::__toString ( <span class="methodparam">void )
}
预定义常量
SplFileObject::DROP_NEW_LINE
Drop newlines at the end of a line.
SplFileObject::READ_AHEAD
Read on rewind/next.
SplFileObject::SKIP_EMPTY
Skips empty lines in the file. This requires the READ_AHEAD flag
be enabled, to work as expected.
SplFileObject::READ_CSV
Read lines as CSV rows.
更新日志
| 版本 | 说明 |
|---|---|
| 5.3.9 | SplFileObject::SKIP_EMPTY value changed to 4. Previously, value was 6. |
SplFileObject::__construct
Construct a new file object
说明
public <span
class="methodname">SplFileObject::__construct ( <span
class="methodparam">string $filename
[, string
$open_mode = "r" [, <span
class="methodparam">bool
$use_include_path =
false [, <span
class="type">resource $context ]]] )
Construct a new file object.
参数
filename
The file to read.
小贴士 如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见 <span class="function">fopen。各种 wapper 的不同功能请参见 支持的协议和封装协议,注意其用法及其可提供的预定义变量。
open_mode
The mode in which to open the file. See <span
class="function">fopen for a list of allowed modes.
use_include_path
Whether to search in the
include_path
for filename.
context
A valid context resource created with <span
class="function">stream_context_create.
返回值
没有返回值。
错误/异常
Throws a RuntimeException if the
filename cannot be opened.
Throws a LogicException if the filename
is a directory.
范例
示例 #1 SplFileObject::__construct example
This example opens the current file and iterates over its contents line by line.
<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line_num => $line) {
echo "Line $line_num is $line";
}
?>
以上例程的输出类似于:
Line 0 is <?php
Line 1 is $file = new SplFileObject(__FILE__);
Line 2 is foreach ($file as $line_num => $line) {
Line 3 is echo "Line $line_num is $line";
Line 4 is }
Line 5 is ?>
参见
- SplFileInfo::openFile
- fopen
SplFileObject::current
Retrieve current line of file
说明
public <span class="type">stringarray <span class="methodname">SplFileObject::current ( <span class="methodparam">void )
Retrieves the current line of the file.
参数
此函数没有参数。
返回值
Retrieves the current line of the file. If the
SplFileObject::READ_CSV flag is set, this method returns an array
containing the current line parsed as CSV data.
范例
示例 #1 SplFileObject::current example
<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $k => $line) {
echo ($file->key() + 1) . ': ' . $file->current();
}
?>
以上例程的输出类似于:
1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4: echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>
参见
- SplFileObject::key
- SplFileObject::seek
- SplFileObject::next
- SplFileObject::rewind
- SplFileObject::valid
SplFileObject::eof
Reached end of file
说明
public bool SplFileObject::eof ( <span class="methodparam">void )
Determine whether the end of file has been reached
参数
此函数没有参数。
返回值
Returns true if file is at EOF, false otherwise.
范例
示例 #1 SplFileObject::eof example
<?php
$file = new SplFileObject("fruits.txt");
while ( ! $file->eof()) {
echo $file->fgets();
}
?>
以上例程的输出类似于:
apple
banana
cherry
date
elderberry
参见
- SplFileObject::valid
- feof
SplFileObject::fflush
Flushes the output to the file
说明
public bool SplFileObject::fflush ( <span class="methodparam">void )
Forces a write of all buffered output to the file.
参数
此函数没有参数。
返回值
成功时返回 true, 或者在失败时返回 false。
范例
示例 #1 SplFileObject::fflush example
<?php
$file = new SplFileObject('misc.txt', 'r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>
参见
- SplFileObject::fwrite
SplFileObject::fgetc
Gets character from file
说明
public string SplFileObject::fgetc ( <span class="methodparam">void )
Gets a character from the file.
参数
此函数没有参数。
返回值
Returns a string containing a single character read from the file or
false on EOF.
Warning
此函数可能返回布尔值 false,但也可能返回等同于 false
的非布尔值。请阅读
布尔类型章节以获取更多信息。应使用
=== 运算符来测试此函数的返回值。
范例
示例 #1 SplFileObject::fgetc example
<?php
$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
echo "$char\n";
}
?>
参见
- SplFileObject::fgets
SplFileObject::fgetcsv
Gets line from file and parse as CSV fields
说明
public array
SplFileObject::fgetcsv ([ <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = "\"" [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
Gets a line from the file which is in CSV format and returns an array containing the fields read.
Note:
The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.
参数
delimiter
The field delimiter (one character only). Defaults as a comma or the
value set using <span
class="methodname">SplFileObject::setCsvControl.
enclosure
The field enclosure character (one character only). Defaults as a double
quotation mark or the value set using <span
class="methodname">SplFileObject::setCsvControl.
escape
The escape character (at most one character). Defaults as a backslash
(\*) or the value set using <span
class="methodname">SplFileObject::setCsvControl. An empty string
(""*) disables the proprietary escape mechanism.
Note: Usually an
enclosurecharacter is escpaped inside a field by doubling it; however, theescapecharacter can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape theenclosurecharacter theescapecharacter has no special meaning; it isn't even meant to escape itself.
返回值
Returns an indexed array containing the fields read, or false on
error.
Note:
A blank line in a CSV file will be returned as an array comprising a single
nullfield unless usingSplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.
更新日志
| 版本 | 说明 |
|---|---|
| 7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism. |
范例
示例 #1 SplFileObject::fgetcsv example
<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
var_dump($file->fgetcsv());
}
?>
示例 #2 SplFileObject::READ_CSV example
<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
list($animal, $class, $legs) = $row;
printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>
Contents of animals.csv
crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0
以上例程的输出类似于:
A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs
参见
- SplFileObject::setCsvControl
- SplFileObject::setFlags
- SplFileObject::READ_CSV
- SplFileObject::current
SplFileObject::fgets
Gets line from file
说明
public string SplFileObject::fgets ( <span class="methodparam">void )
Gets a line from the file.
参数
此函数没有参数。
返回值
Returns a string containing the next line from the file, or false
on error.
错误/异常
Throws a RuntimeException if the file cannot be read.
范例
示例 #1 SplFileObject::fgets example
This example simply outputs the contents of file.txt line-by-line.
<?php
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
echo $file->fgets();
}
?>
参见
- fgets
- SplFileObject::fgetss
- SplFileObject::fgetc
- SplFileObject::current
SplFileObject::fgetss
Gets line from file and strip HTML tags
Warning
本函数已自 PHP 7.3.0 起废弃。强烈建议不要使用本函数。
说明
public string
SplFileObject::fgetss ([ <span
class="methodparam">string
$allowable_tags ] )
Identical to SplFileObject::fgets, except that SplFileObject::fgetss attempts to strip any HTML and PHP tags from the text it reads. The function retains the parsing state from call to call, and as such is not equivalent to calling strip_tags on the return value of SplFileObject::fgets.
参数
allowable_tags
Optional parameter to specify tags which should not be stripped.
返回值
Returns a string containing the next line of the file with HTML and PHP
code stripped, or false on error.
范例
示例 #1 SplFileObject::fgetss example
<?php
$str = <<<EOD
<html><body>
<p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents("sample.php", $str);
$file = new SplFileObject("sample.php");
while (!$file->eof()) {
echo $file->fgetss();
}
?>
以上例程的输出类似于:
Welcome! Today is the of .
Text outside of the HTML block.
参见
- fgetss
- SplFileObject::fgets
- SplFileObject::fgetc
- SplFileObject::current
- The string.strip_tags filter
SplFileObject::flock
Portable file locking
说明
public bool
SplFileObject::flock ( <span
class="methodparam">int $operation
[, int
&$wouldblock ] )
Locks or unlocks the file in the same portable way as <span class="function">flock.
参数
operation
operation is one of the following:
-
LOCK_SHto acquire a shared lock (reader). -
LOCK_EXto acquire an exclusive lock (writer). -
LOCK_UNto release a lock (shared or exclusive).
It is also possible to add LOCK_NB as a bitmask to one of the
above operations, if flock should not
block during the locking attempt.
wouldblock
Set to true if the lock would block (EWOULDBLOCK errno condition).
返回值
成功时返回 true, 或者在失败时返回 false。
范例
示例 #1 SplFileObject::flock example
<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
if ($file->flock(LOCK_EX)) { // do an exclusive lock
$file->ftruncate(0); // truncate file
$file->fwrite("Write something here\n");
$file->flock(LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
?>
参见
- flock
SplFileObject::fpassthru
Output all remaining data on a file pointer
说明
public int <span class="methodname">SplFileObject::fpassthru ( <span class="methodparam">void )
Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.
You may need to call <span class="methodname">SplFileObject::rewind to reset the file pointer to the beginning of the file if you have already written data to the file.
参数
此函数没有参数。
返回值
Returns the number of characters read from handle and passed through
to the output.
范例
示例 #1 SplFileObject::fpassthru example
<?php
// Open the file in binary mode
$file = new SplFileObject("./img/ok.png", "rb");
// Send the right headers
header("Content-Type: image/png");
header("Content-Length: " . $file->getSize());
// Dump the picture and end script
$file->fpassthru();
exit;
?>
参见
- fpassthru
SplFileObject::fputcsv
Write a field array as a CSV line
说明
public <span
class="type">intfalse <span
class="methodname">SplFileObject::fputcsv ( <span
class="methodparam">array $fields [,
string
$delimiter = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = '"' [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
Writes the fields array to the file as a CSV line.
参数
fields
An array of values.
delimiter
The optional delimiter parameter sets the field delimiter (one
character only).
enclosure
The optional enclosure parameter sets the field enclosure (one
character only).
escape
The optional escape parameter sets the escape character (at most one
character). An empty string ("") disables the proprietary escape
mechanism.
Note:
If an
enclosurecharacter is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by anescape_char.
返回值
Returns the length of the written string 或者在失败时返回 false.
Returns false, and does not write the CSV line to the file, if the
delimiter or enclosure parameter is not a single character.
错误/异常
An E_WARNING level error is issued if the delimiter or
enclosure parameter is not a single character.
更新日志
| 版本 | 说明 |
|---|---|
| 7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism. |
| 5.5.21, 5.6.5 | Added the escape parameter. |
范例
示例 #1 SplFileObject::fputcsv example
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$file = new SplFileObject('file.csv', 'w');
foreach ($list as $fields) {
$file->fputcsv($fields);
}
?>
The above example will write the following to file.csv:
aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""
参见
- fputcsv
- SplFileObject::fgetcsv
SplFileObject::fread
Read from file
说明
public <span
class="type">stringfalse <span
class="methodname">SplFileObject::fread ( <span
class="methodparam">int $length )
Reads the given number of bytes from the file.
参数
length
The number of bytes to read.
返回值
Returns the string read from the file 或者在失败时返回 false.
范例
示例 #1 SplFileObject::fread example
<?php
// Get contents of a file into a string
$filename = "/usr/local/something.txt";
$file = new SplFileObject($filename, "r");
$contents = $file->fread($file->getSize());
?>
注释
Note:
Note that SplFileObject::fread reads from the current position of the file pointer. Use <span class="methodname">SplFileObject::ftell to find the current position of the pointer and <span class="methodname">SplFileObject::rewind (or <span class="methodname">SplFileObject::fseek) to rewind the pointer position.
参见
- fread
SplFileObject::fscanf
Parses input from file according to a format
说明
public mixed
SplFileObject::fscanf ( <span
class="methodparam">string $format ,
mixed
&$vars )
Reads a line from the file and interprets it according to the specified
format, which is described in the documentation for <span
class="function">sprintf.
Any whitespace in the format string matches any whitespace in the line
from the file. This means that even a tab \t in the format string can
match a single space character in the input stream.
参数
format
The format string is composed of zero or more directives: ordinary
characters (excluding %) that are copied directly to the result and
conversion specifications, each of which results in fetching its own
parameter.
A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.
Argnum
An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.
| Flag | 说明 |
|---|---|
| - | Left-justify within the given field width; Right justification is the default |
| + | Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign. |
| (space) | Pads the result with spaces. This is the default. |
| 0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros. |
| '(char) | Pads the result with the character (char). |
Width
An integer that says how many characters (minimum) this conversion should result in.
Precision
A period . followed by an integer who's meaning depends on the specifier:
- For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
- For g and G specifiers: this is the maximum number of significant digits to be printed.
- For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.
Note: If the period is specified without an explicit value for precision, 0 is assumed.
Note: Attempting to use a position specifier greater than
PHP_INT_MAXwill generate warnings.
| Specifier | 说明 |
|---|---|
| % | A literal percent character. No argument is required. |
| b | The argument is treated as an integer and presented as a binary number. |
| c | The argument is treated as an integer and presented as the character with that ASCII. |
| d | The argument is treated as an integer and presented as a (signed) decimal number. |
| e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). |
| E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2). |
| f | The argument is treated as a float and presented as a floating-point number (locale aware). |
| F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3. |
| g | General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. |
| G | Like the g specifier but uses E and f. |
| o | The argument is treated as an integer and presented as an octal number. |
| s | The argument is treated and presented as a string. |
| u | The argument is treated as an integer and presented as an unsigned decimal number. |
| x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
| X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
Warning The c type specifier ignores padding and width
Warning Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results
Variables will be co-erced to a suitable type for the specifier:
| Type | Specifiers |
|---|---|
| string | s |
| integer | d, u, c, o, x, X, b |
| double | g, G, e, E, f, F |
vars
The optional assigned values.
返回值
If only one parameter is passed to this method, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.
范例
示例 #1 SplFileObject::fscanf example
<?php
$file = new SplFileObject("misc.txt");
while ($userinfo = $file->fscanf("%s %s %s")) {
list ($name, $profession, $countrycode) = $userinfo;
// Do something with $name $profession $countrycode
}
?>
Contents of users.txt
javier argonaut pe
hiroshi sculptor jp
robert slacker us
luigi florist it
参见
- fscanf
- sscanf
- printf
- sprintf
SplFileObject::fseek
Seek to a position
说明
public int <span
class="methodname">SplFileObject::fseek ( <span
class="methodparam">int $offset [,
int $whence<span
class="initializer"> = SEEK_SET ] )
Seek to a position in the file measured in bytes from the beginning of
the file, obtained by adding offset to the position specified by
whence.
参数
offset
The offset. A negative value can be used to move backwards through the
file which is useful when SEEK_END is used as the whence value.
whence
whence values are:
SEEK_SET- Set position equal tooffsetbytes.SEEK_CUR- Set position to current location plusoffset.SEEK_END- Set position to end-of-file plusoffset.
If whence is not specified, it is assumed to be SEEK_SET.
返回值
Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.
范例
示例 #1 SplFileObject::fseek example
<?php
$file = new SplFileObject("somefile.txt");
// Read first line
$data = $file->fgets();
// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>
参见
- fseek
SplFileObject::fstat
Gets information about the file
说明
public array SplFileObject::fstat ( <span class="methodparam">void )
Gathers the statistics of the file. Behaves identically to <span class="function">fstat.
参数
此函数没有参数。
返回值
Returns an array with the statistics of the file; the format of the array is described in detail on the stat manual page.
范例
示例 #1 SplFileObject::fstat example
<?php
$file = new SplFileObject("/etc/passwd");
$stat = $file->fstat();
// Print only the associative part
print_r(array_slice($stat, 13));
?>
以上例程的输出类似于:
Array
(
[dev] => 771
[ino] => 488704
[mode] => 33188
[nlink] => 1
[uid] => 0
[gid] => 0
[rdev] => 0
[size] => 1114
[atime] => 1061067181
[mtime] => 1056136526
[ctime] => 1056136526
[blksize] => 4096
[blocks] => 8
)
参见
- fstat
- stat
SplFileObject::ftell
Return current file position
说明
public int <span class="methodname">SplFileObject::ftell ( <span class="methodparam">void )
Returns the position of the file pointer which represents the current offset in the file stream.
参数
此函数没有参数。
返回值
Returns the position of the file pointer as an integer, or false
on error.
范例
示例 #1 SplFileObject::ftell example
<?php
$file = new SplFileObject("/etc/passwd");
// Read first line
$data = $file->fgets();
// Where are we?
echo $file->ftell();
?>
参见
- ftell
SplFileObject::ftruncate
Truncates the file to a given length
说明
public bool
SplFileObject::ftruncate ( <span
class="methodparam">int $size )
Truncates the file to size bytes.
参数
size
The size to truncate to.
Note:
If
sizeis larger than the file it is extended with null bytes.If
sizeis smaller than the file, the extra data will be lost.
返回值
成功时返回 true, 或者在失败时返回 false。
范例
示例 #1 SplFileObject::ftruncate example
<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");
// Truncate to 5 bytes
$file->ftruncate(5);
// Rewind and read data
$file->rewind();
echo $file->fgets();
?>
以上例程的输出类似于:
Hello
参见
- ftruncate
SplFileObject::fwrite
Write to file
说明
public int <span
class="methodname">SplFileObject::fwrite ( <span
class="methodparam">string $str [,
int $length
] )
Writes the contents of string to the file
参数
str
The string to be written to the file.
length
If the length argument is given, writing will stop after length
bytes have been written or the end of string is reached, whichever
comes first.
返回值
Returns the number of bytes written, or false on error.
更新日志
| 版本 | 说明 |
|---|---|
| 7.4.0 | The function now returns false instead of zero on failure. |
范例
示例 #1 SplFileObject::fwrite example
<?php
$file = new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo "Wrote $written bytes to file";
?>
以上例程的输出类似于:
Wrote 5 bytes to file
参见
- fwrite
SplFileObject::getChildren
No purpose
说明
public void SplFileObject::getChildren ( <span class="methodparam">void )
An SplFileObject does not have children
so this method returns null.
参数
此函数没有参数。
返回值
没有返回值。
参见
- RecursiveIterator::getChildren
SplFileObject::getCsvControl
Get the delimiter, enclosure and escape character for CSV
说明
public array SplFileObject::getCsvControl ( <span class="methodparam">void )
Gets the delimiter, enclosure and escape character used for parsing CSV fields.
参数
此函数没有参数。
返回值
Returns an indexed array containing the delimiter, enclosure and escape character.
更新日志
| 版本 | 说明 |
|---|---|
| 7.4.0 | The escape character can now be an empty string. |
| 5.6.25, 7.0.10 | Added the escape character to the returned array. |
范例
示例 #1 SplFileObject::getCsvControl example
<?php
$file = new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>
以上例程的输出类似于:
Array
(
[0] => ,
[1] => "
[2] => \
)
参见
- SplFileObject::setCsvControl
- SplFileObject::fgetcsv
SplFileObject::getCurrentLine
Alias of SplFileObject::fgets
说明
此方法是该方法的别名: <span class="methodname">SplFileObject::fgets.
SplFileObject::getFlags
Gets flags for the SplFileObject
说明
public int <span class="methodname">SplFileObject::getFlags ( <span class="methodparam">void )
Gets the flags set for an instance of SplFileObject as an <span class="type">int.
参数
此函数没有参数。
返回值
Returns an int representing the flags.
范例
示例 #1 SplFileObject::getFlags example
<?php
$file = new SplFileObject(__FILE__, "r");
if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
echo "Skipping empty lines\n";
} else {
echo "Not skipping empty lines\n";
}
$file->setFlags(SplFileObject::SKIP_EMPTY);
if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
echo "Skipping empty lines\n";
} else {
echo "Not skipping empty lines\n";
}
?>
以上例程的输出类似于:
Not skipping empty lines
Skipping empty lines
参见
- SplFileObject::setFlags
SplFileObject::getMaxLineLen
Get maximum line length
说明
public int <span class="methodname">SplFileObject::getMaxLineLen ( <span class="methodparam">void )
Gets the maximum line length as set by <span class="methodname">SplFileObject::setMaxLineLen.
参数
此函数没有参数。
返回值
Returns the maximum line length if one has been set with <span class="methodname">SplFileObject::setMaxLineLen, default is 0.
范例
示例 #1 SplFileObject::getMaxLineLen example
<?php
$file = new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());
$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>
以上例程的输出类似于:
int(0)
int(20)
参见
- SplFileObject::setMaxLineLen
SplFileObject::hasChildren
SplFileObject does not have children
说明
public bool SplFileObject::hasChildren ( <span class="methodparam">void )
An SplFileObject does not have children
so this method always return false.
参数
此函数没有参数。
返回值
Returns false
参见
- RecursiveIterator::hasChildren
SplFileObject::key
Get line number
说明
public int <span class="methodname">SplFileObject::key ( <span class="methodparam">void )
Gets the current line number.
Note:
This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen is used to read fixed lengths of the file.
参数
此函数没有参数。
返回值
Returns the current line number.
范例
示例 #1 SplFileObject::key example
<?php
$file = new SplFileObject("lipsum.txt");
foreach ($file as $line) {
echo $file->key() . ". " . $line;
}
?>
以上例程的输出类似于:
0. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
1. Duis nec sapien felis, ac sodales nisl.
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
示例 #2 SplFileObject::key example with SplFileObject::setMaxLineLen
<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
echo $file->key() . ". " . $line . "\n";
}
?>
以上例程的输出类似于:
0. Lorem ipsum dolor s
1. it amet, consectetu
2. r adipiscing elit.
3.
4. Duis nec sapien fel
5. is, ac sodales nisl
6. .
7. Lorem ipsum dolor s
8. it amet, consectetu
9. r adipiscing elit.
参见
- SplFileObject::current
- SplFileObject::seek
- SplFileObject::next
- SplFileObject::rewind
- SplFileObject::valid
SplFileObject::next
Read next line
说明
public void SplFileObject::next ( <span class="methodparam">void )
Moves ahead to the next line in the file.
参数
此函数没有参数。
返回值
没有返回值。
范例
示例 #1 SplFileObject::next example
<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!$file->eof()) {
echo $file->current();
$file->next();
}
?>
参见
- SplFileObject::current
- SplFileObject::key
- SplFileObject::seek
- SplFileObject::rewind
- SplFileObject::valid
SplFileObject::rewind
Rewind the file to the first line
说明
public void SplFileObject::rewind ( <span class="methodparam">void )
Rewinds the file back to the first line.
参数
此函数没有参数。
返回值
没有返回值。
错误/异常
Throws a RuntimeException if cannot be rewound.
范例
示例 #1 SplFileObject::rewind example
<?php
$file = new SplFileObject("misc.txt");
// Loop over whole file
foreach ($file as $line) { }
// Rewind to first line
$file->rewind();
// Output first line
echo $file->current();
?>
参见
- SplFileObject::current
- SplFileObject::key
- SplFileObject::seek
- SplFileObject::next
- SplFileObject::valid
SplFileObject::seek
Seek to specified line
说明
public void
SplFileObject::seek ( <span
class="methodparam">int $line_pos )
Seek to specified line in the file.
参数
line_pos
The zero-based line number to seek to.
返回值
没有返回值。
错误/异常
Throws a LogicException if the line_pos
is negative.
范例
示例 #1 SplFileObject::seek example
This example outputs the third line of the script which is found at position 2.
<?php
$file = new SplFileObject(__FILE__);
$file->seek(2);
echo $file->current();
?>
以上例程的输出类似于:
$file->seek(2);
参见
- SplFileObject::current
- SplFileObject::key
- SplFileObject::next
- SplFileObject::rewind
- SplFileObject::valid
SplFileObject::setCsvControl
Set the delimiter, enclosure and escape character for CSV
说明
public void
SplFileObject::setCsvControl ([ <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = "\"" [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
Sets the delimiter, enclosure and escape character for parsing CSV fields.
参数
delimiter
The field delimiter (one character only).
enclosure
The field enclosure character (one character only).
escape
The field escape character (at most one character). An empty string
("") disables the proprietary escape mechanism.
返回值
没有返回值。
更新日志
| 版本 | 说明 |
|---|---|
| 7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism. |
范例
示例 #1 SplFileObject::setCsvControl example
<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl('|');
foreach ($file as $row) {
list ($fruit, $quantity) = $row;
// Do something with values
}
?>
Contents of data.csv
<?php
apples|20
bananas|14
cherries|87
?>
参见
- SplFileObject::getCsvControl
- SplFileObject::fgetcsv
SplFileObject::setFlags
Sets flags for the SplFileObject
说明
public void
SplFileObject::setFlags ( <span
class="methodparam">int $flags )
Sets the flags to be used by the <span class="classname">SplFileObject.
参数
flags
Bit mask of the flags to set. See
SplFileObject constants
for the available flags.
返回值
没有返回值。
范例
示例 #1 SplFileObject::setFlags example
<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $fields) {
var_dump($fields);
}
?>
参见
- SplFileObject::getFlags
SplFileObject::setMaxLineLen
Set maximum line length
说明
public void
SplFileObject::setMaxLineLen ( <span
class="methodparam">int $max_len )
Sets the maximum length of a line to be read.
参数
max_len
The maximum length of a line.
返回值
没有返回值。
错误/异常
Throws DomainException when max_len is
less than zero.
范例
示例 #1 SplFileObject::setMaxLineLen example
<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
echo $line . "\n";
}
?>
Contents of lipsum.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis nec sapien felis, ac sodales nisl.
Nulla vitae magna vitae purus aliquet consequat.
以上例程的输出类似于:
Lorem ipsum dolor s
it amet, consectetu
r adipiscing elit.
Duis nec sapien fel
is, ac sodales nisl
.
Nulla vitae magna v
itae purus aliquet
consequat.
参见
- SplFileObject::getMaxLineLen
SplFileObject::__toString
Alias of SplFileObject::fgets
说明
此方法是该方法的别名: <span class="methodname">SplFileObject::fgets.
更新日志
| 版本 | 说明 |
|---|---|
| 7.2.19, 7.3.6 | Changed from an alias of SplFileObject::current to an alias of SplFileObject::fgets. |
SplFileObject::valid
Not at EOF
说明
public bool SplFileObject::valid ( <span class="methodparam">void )
Check whether EOF has been reached.
参数
此函数没有参数。
返回值
Returns true if not reached EOF, false otherwise.
范例
示例 #1 SplFileObject::valid example
<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while ($file->valid()) {
echo $file->fgets();
}
?>
参见
- SplFileObject::current
- SplFileObject::key
- SplFileObject::seek
- SplFileObject::next
- SplFileObject::rewind
简介
The SplTempFileObject class offers an object oriented interface for a temporary file.
类摘要
SplTempFileObject
class SplTempFileObject <span class="ooclass"> extends SplFileObject implements <span class="interfacename">SeekableIterator <span class="oointerface">, <span class="interfacename">RecursiveIterator {
/* 继承的常量 */
const integer
SplFileObject::DROP_NEW_LINE = 1 ;
const integer
SplFileObject::READ_AHEAD = 2 ;
const integer
SplFileObject::SKIP_EMPTY = 4 ;
const integer
SplFileObject::READ_CSV = 8 ;
/* 方法 */
public <span
class="methodname">__construct ([ <span
class="methodparam">int $max_memory
] )
/* 继承的方法 */
public <span class="type">stringarray <span class="methodname">SplFileObject::current ( <span class="methodparam">void )
public bool SplFileObject::eof ( <span class="methodparam">void )
public bool SplFileObject::fflush ( <span class="methodparam">void )
public string SplFileObject::fgetc ( <span class="methodparam">void )
public array
SplFileObject::fgetcsv ([ <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = "\"" [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
public string SplFileObject::fgets ( <span class="methodparam">void )
public string
SplFileObject::fgetss ([ <span
class="methodparam">string
$allowable_tags ] )
public bool
SplFileObject::flock ( <span
class="methodparam">int $operation
[, int
&$wouldblock ] )
public int <span class="methodname">SplFileObject::fpassthru ( <span class="methodparam">void )
public <span
class="type">intfalse <span
class="methodname">SplFileObject::fputcsv ( <span
class="methodparam">array $fields [,
string
$delimiter = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = '"' [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
public <span
class="type">stringfalse <span
class="methodname">SplFileObject::fread ( <span
class="methodparam">int $length )
public mixed
SplFileObject::fscanf ( <span
class="methodparam">string $format ,
mixed
&$vars )
public int <span
class="methodname">SplFileObject::fseek ( <span
class="methodparam">int $offset [,
int $whence<span
class="initializer"> = SEEK_SET ] )
public array SplFileObject::fstat ( <span class="methodparam">void )
public int <span class="methodname">SplFileObject::ftell ( <span class="methodparam">void )
public bool
SplFileObject::ftruncate ( <span
class="methodparam">int $size )
public int <span
class="methodname">SplFileObject::fwrite ( <span
class="methodparam">string $str [,
int $length
] )
public void SplFileObject::getChildren ( <span class="methodparam">void )
public array SplFileObject::getCsvControl ( <span class="methodparam">void )
public int <span class="methodname">SplFileObject::getFlags ( <span class="methodparam">void )
public int <span class="methodname">SplFileObject::getMaxLineLen ( <span class="methodparam">void )
public bool SplFileObject::hasChildren ( <span class="methodparam">void )
public int <span class="methodname">SplFileObject::key ( <span class="methodparam">void )
public void SplFileObject::next ( <span class="methodparam">void )
public void SplFileObject::rewind ( <span class="methodparam">void )
public void
SplFileObject::seek ( <span
class="methodparam">int $line_pos )
public void
SplFileObject::setCsvControl ([ <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = "\"" [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
public void
SplFileObject::setFlags ( <span
class="methodparam">int $flags )
public void
SplFileObject::setMaxLineLen ( <span
class="methodparam">int $max_len )
public bool SplFileObject::valid ( <span class="methodparam">void )
}
SplTempFileObject::__construct
Construct a new temporary file object
说明
public <span
class="methodname">SplTempFileObject::__construct ([ <span
class="methodparam">int $max_memory
] )
Construct a new temporary file object.
参数
max_memory
The maximum amount of memory (in bytes, default is 2 MB) for the
temporary file to use. If the temporary file exceeds this size, it will
be moved to a file in the system's temp directory.
If max_memory is negative, only memory will be used. If max_memory
is zero, no memory will be used.
返回值
没有返回值。
错误/异常
Throws a RuntimeException if an error occurs.
范例
示例 #1 SplTempFileObject example
This example writes a temporary file in memory which can be written to and read from.
<?php
$temp = new SplTempFileObject();
$temp->fwrite("This is the first line\n");
$temp->fwrite("And this is the second.\n");
echo "Written " . $temp->ftell() . " bytes to temporary file.\n\n";
// Rewind and read what was written
$temp->rewind();
foreach ($temp as $line) {
echo $line;
}
?>
以上例程的输出类似于:
Written 47 bytes to temporary file.
This is the first line
And this is the second.
参见
- SplFileObject
- PHP input/output streams (for php://temp and php://memory)