文件处理

目录

SPL 提供 一些与文件相关的类。

简介

The SplFileInfo class offers a high-level object oriented interface to information for an individual file.

类摘要

SplFileInfo

class SplFileInfo {

/* 方法 */

public __construct ( string $file_name )

public int getATime ( void )

public string getBasename ([ string $suffix ] )

public int getCTime ( void )

public string getExtension ( void )

public SplFileInfo getFileInfo ([ string $class_name ] )

public string getFilename ( void )

public int getGroup ( void )

public int getInode ( void )

public string getLinkTarget ( void )

public int getMTime ( void )

public int getOwner ( void )

public string getPath ( void )

public SplFileInfo getPathInfo ([ string $class_name ] )

public string getPathname ( void )

public int getPerms ( void )

public string getRealPath ( void )

public int getSize ( void )

public string getType ( void )

public bool isDir ( void )

public bool isExecutable ( void )

public bool isFile ( void )

public bool isLink ( void )

public bool isReadable ( void )

public bool isWritable ( void )

public SplFileObject openFile ([ string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context = NULL ]]] )

public void setFileClass ([ string $class_name = "SplFileObject" ] )

public void setInfoClass ([ string $class_name = "SplFileInfo" ] )

public string __toString ( void )

}

SplFileInfo::__construct

Construct a new SplFileInfo object

说明

public SplFileInfo::__construct ( string $file_name )

Creates a new SplFileInfo object for the file_name specified. The file does not need to exist, or be readable.

参数

file_name
Path to the file.

范例

示例 #1 SplFileInfo::__construct example

<?php
$info = new SplFileInfo('example.php');
if ($info->isFile()) {
    echo $info->getRealPath();
}
?>

SplFileInfo::getATime

Gets last access time of the file

说明

public int SplFileInfo::getATime ( 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 ([ 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 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 SplFileInfo::getCTime ( 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 ( 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 SplFileInfo SplFileInfo::getFileInfo ([ 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 ( 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 SplFileInfo::getGroup ( 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 SplFileInfo::getInode ( 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 ( void )

Gets the target of a filesystem link.

Note:

The target may not be the real path on the filesystem. Use 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 SplFileInfo::getMTime ( 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 SplFileInfo::getOwner ( 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 ( 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 SplFileInfo SplFileInfo::getPathInfo ([ 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 ( 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 SplFileInfo::getPerms ( 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 ( 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 SplFileInfo::getSize ( 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 ( 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 ( 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 ( 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 ( 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 ( 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 ( 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 ( void )

Checks if the current entry is writable.

参数

此函数没有参数。

返回值

Returns TRUE if writable, FALSE otherwise;

SplFileInfo::openFile

Gets an SplFileObject object for the file

说明

public SplFileObject SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context = NULL ]]] )

Creates an SplFileObject object of the file. This is useful because 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 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 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 SplFileInfo::openFile

说明

public void SplFileInfo::setFileClass ([ string $class_name = "SplFileObject" ] )

Use this method to set a custom class which will be used when SplFileInfo::openFile is called. The class name passed to this method must be SplFileObject or a class derived from SplFileObject.

参数

class_name
The class name to use when 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 SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

说明

public void SplFileInfo::setInfoClass ([ string $class_name = "SplFileInfo" ] )

Use this method to set a custom class which will be used when SplFileInfo::getFileInfo and SplFileInfo::getPathInfo are called. The class name passed to this method must be SplFileInfo or a class derived from SplFileInfo.

参数

class_name
The class name to use when SplFileInfo::getFileInfo and 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 ( 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 extends SplFileInfo implements RecursiveIterator , 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 string|array current ( void )

public bool eof ( void )

public bool fflush ( void )

public string fgetc ( void )

public array fgetcsv ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

public string fgets ( void )

public string fgetss ([ string $allowable_tags ] )

public bool flock ( int $operation [, int &$wouldblock ] )

public int fpassthru ( void )

public int fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )

public string fread ( int $length )

public mixed fscanf ( string $format [, mixed &$... ] )

public int fseek ( int $offset [, int $whence = SEEK_SET ] )

public array fstat ( void )

public int ftell ( void )

public bool ftruncate ( int $size )

public int fwrite ( string $str [, int $length ] )

public void getChildren ( void )

public array getCsvControl ( void )

public int getFlags ( void )

public int getMaxLineLen ( void )

public bool hasChildren ( void )

public int key ( void )

public void next ( void )

public void rewind ( void )

public void seek ( int $line_pos )

public void setCsvControl ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

public void setFlags ( int $flags )

public void setMaxLineLen ( int $max_len )

public bool valid ( void )

/* 继承的方法 */

public int SplFileInfo::getATime ( void )

public string SplFileInfo::getBasename ([ string $suffix ] )

public int SplFileInfo::getCTime ( void )

public string SplFileInfo::getExtension ( void )

public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )

public string SplFileInfo::getFilename ( void )

public int SplFileInfo::getGroup ( void )

public int SplFileInfo::getInode ( void )

public string SplFileInfo::getLinkTarget ( void )

public int SplFileInfo::getMTime ( void )

public int SplFileInfo::getOwner ( void )

public string SplFileInfo::getPath ( void )

public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )

public string SplFileInfo::getPathname ( void )

public int SplFileInfo::getPerms ( void )

public string SplFileInfo::getRealPath ( void )

public int SplFileInfo::getSize ( void )

public string SplFileInfo::getType ( void )

public bool SplFileInfo::isDir ( void )

public bool SplFileInfo::isExecutable ( void )

public bool SplFileInfo::isFile ( void )

public bool SplFileInfo::isLink ( void )

public bool SplFileInfo::isReadable ( void )

public bool SplFileInfo::isWritable ( void )

public SplFileObject SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context = NULL ]]] )

public void SplFileInfo::setFileClass ([ string $class_name = "SplFileObject" ] )

public void SplFileInfo::setInfoClass ([ string $class_name = "SplFileInfo" ] )

public string SplFileInfo::__toString ( 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.9SplFileObject::SKIP_EMPTY value changed to 4. Previously, value was 6.

SplFileObject::__construct

Construct a new file object

说明

public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context ]]] )

Construct a new file object.

参数

filename
The file to read.

小贴士 如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见 fopen。各种 wapper 的不同功能请参见 支持的协议和封装协议,注意其用法及其可提供的预定义变量。

open_mode
The mode in which to open the file. See 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 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 string|array SplFileObject::current ( 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 ( 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 ( 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 ( 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 ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

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 SplFileObject::setCsvControl.

enclosure
The field enclosure character (one character only). Defaults as a double quotation mark or the value set using SplFileObject::setCsvControl.

escape
The escape character (at most one character). Defaults as a backslash (\) or the value set using SplFileObject::setCsvControl. An empty string ("") disables the proprietary escape mechanism.

Note: Usually an enclosure character is escpaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character 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 NULL field unless using SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.

更新日志

版本说明
7.4.0The 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::fgets

Gets line from file

说明

public string SplFileObject::fgets ( 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

This function has been DEPRECATED as of PHP 7.3.0. Relying on this function is highly discouraged.

说明

public string SplFileObject::fgetss ([ 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 ( int $operation [, int &$wouldblock ] )

Locks or unlocks the file in the same portable way as flock.

参数

operation
operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB to not block while locking.

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!";
}
?>

更新日志

版本说明
5.5.22, 5.6.6Added support for the wouldblock parameter on Windows.
5.3.2The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

参见

  • flock

SplFileObject::fpassthru

Output all remaining data on a file pointer

说明

public int SplFileObject::fpassthru ( 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 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 int SplFileObject::fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )

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 enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape_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.0The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.5.21, 5.6.5Added 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 string SplFileObject::fread ( 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 class="methodname">SplFileObject::ftell to find the current position of the pointer and class="methodname">SplFileObject::rewind (or class="methodname">SplFileObject::fseek) to rewind the pointer position.

参见

  • fread

SplFileObject::fscanf

Parses input from file according to a format

说明

public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )

Reads a line from the file and interprets it according to the specified format, which is described in the documentation for 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.
0Only 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_MAX will generate warnings.

Specifiers
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:

TypeSpecifiers
strings
integerd, u, c, o, x, X, b
doubleg, G, e, E, f, F

...
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 SplFileObject::fseek ( int $offset [, int $whence = 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 to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

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 ( void )

Gathers the statistics of the file. Behaves identically to 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 SplFileObject::ftell ( 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 ( int $size )

Truncates the file to size bytes.

参数

size
The size to truncate to.

Note:

If size is larger than the file it is extended with null bytes.

If size is 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 SplFileObject::fwrite ( 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 0 on error.

范例

示例 #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 ( 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 ( 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.0The escape character can now be an empty string.
5.6.25, 7.0.10Added 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

说明

此方法是该方法的别名: SplFileObject::fgets.

SplFileObject::getFlags

Gets flags for the SplFileObject

说明

public int SplFileObject::getFlags ( void )

Gets the flags set for an instance of SplFileObject as an integer.

参数

此函数没有参数。

返回值

Returns an integer 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 SplFileObject::getMaxLineLen ( void )

Gets the maximum line length as set by SplFileObject::setMaxLineLen.

参数

此函数没有参数。

返回值

Returns the maximum line length if one has been set with 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)

参见

  • Classname::Method

SplFileObject::hasChildren

SplFileObject does not have children

说明

public bool SplFileObject::hasChildren ( void )

An SplFileObject does not have children so this method always return FALSE.

参数

此函数没有参数。

返回值

Returns FALSE

参见

  • RecursiveIterator::hasChildren

SplFileObject::key

Get line number

说明

public int SplFileObject::key ( 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 ( 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 ( 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 ( 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 ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

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.0The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.3.0Added the escape parameter.

范例

示例 #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 ( int $flags )

Sets the flags to be used by the 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 ( 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.

参见

  • Classname::Method

SplFileObject::__toString

Alias of SplFileObject::fgets

说明

此方法是该方法的别名: SplFileObject::fgets.

更新日志

版本说明
7.2.19, 7.3.6Changed from an alias of SplFileObject::current to an alias of SplFileObject::fgets.

SplFileObject::valid

Not at EOF

说明

public bool SplFileObject::valid ( 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 extends SplFileObject implements SeekableIterator , 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 __construct ([ int $max_memory ] )

/* 继承的方法 */

public string|array SplFileObject::current ( void )

public bool SplFileObject::eof ( void )

public bool SplFileObject::fflush ( void )

public string SplFileObject::fgetc ( void )

public array SplFileObject::fgetcsv ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

public string SplFileObject::fgets ( void )

public string SplFileObject::fgetss ([ string $allowable_tags ] )

public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )

public int SplFileObject::fpassthru ( void )

public int SplFileObject::fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )

public string SplFileObject::fread ( int $length )

public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )

public int SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] )

public array SplFileObject::fstat ( void )

public int SplFileObject::ftell ( void )

public bool SplFileObject::ftruncate ( int $size )

public int SplFileObject::fwrite ( string $str [, int $length ] )

public void SplFileObject::getChildren ( void )

public array SplFileObject::getCsvControl ( void )

public int SplFileObject::getFlags ( void )

public int SplFileObject::getMaxLineLen ( void )

public bool SplFileObject::hasChildren ( void )

public int SplFileObject::key ( void )

public void SplFileObject::next ( void )

public void SplFileObject::rewind ( void )

public void SplFileObject::seek ( int $line_pos )

public void SplFileObject::setCsvControl ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

public void SplFileObject::setFlags ( int $flags )

public void SplFileObject::setMaxLineLen ( int $max_len )

public bool SplFileObject::valid ( void )

}

SplTempFileObject::__construct

Construct a new temporary file object

说明

public SplTempFileObject::__construct ([ 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.

参见