程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP SPL標准庫之文件操作(SplFileInfo和SplFileObject)實例,

PHP SPL標准庫之文件操作(SplFileInfo和SplFileObject)實例,

編輯:關於PHP編程

PHP SPL標准庫之文件操作(SplFileInfo和SplFileObject)實例,


PHP SPL中提供了SplFileInfo和SplFileObject兩個類來處理文件操作。

SplFileInfo用來獲取文件詳細信息:

復制代碼 代碼如下:
$file = new SplFileInfo('foo-bar.txt');
 
print_r(array(
    'getATime' => $file->getATime(), //最後訪問時間
    'getBasename' => $file->getBasename(), //獲取無路徑的basename
    'getCTime' => $file->getCTime(), //獲取inode修改時間
    'getExtension' => $file->getExtension(), //文件擴展名
    'getFilename' => $file->getFilename(), //獲取文件名
    'getGroup' => $file->getGroup(), //獲取文件組
    'getInode' => $file->getInode(), //獲取文件inode
    'getLinkTarget' => $file->getLinkTarget(), //獲取文件鏈接目標文件
    'getMTime' => $file->getMTime(), //獲取最後修改時間
    'getOwner' => $file->getOwner(), //文件擁有者
    'getPath' => $file->getPath(), //不帶文件名的文件路徑
    'getPathInfo' => $file->getPathInfo(), //上級路徑的SplFileInfo對象
    'getPathname' => $file->getPathname(), //全路徑
    'getPerms' => $file->getPerms(), //文件權限
    'getRealPath' => $file->getRealPath(), //文件絕對路徑
    'getSize' => $file->getSize(),//文件大小,單位字節
    'getType' => $file->getType(),//文件類型 file  dir  link
    'isDir' => $file->isDir(), //是否是目錄
    'isFile' => $file->isFile(), //是否是文件
    'isLink' => $file->isLink(), //是否是快捷鏈接
    'isExecutable' => $file->isExecutable(), //是否可執行
    'isReadable' => $file->isReadable(), //是否可讀
    'isWritable' => $file->isWritable(), //是否可寫
));

SplFileObject繼承SplFileInfo並實現RecursiveIterator , SeekableIterator接口 ,用於對文件遍歷、查找、操作

遍歷:
復制代碼 代碼如下:
try {
    foreach(new SplFileObject('foo-bar.txt') as $line) {
        echo $line;
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

查找指定行:
復制代碼 代碼如下:
try {
    $file = new SplFileObject('foo-bar.txt');
    $file->seek(2);
    echo $file->current();
} catch (Exception $e) {
    echo $e->getMessage();
}

寫入csv文件:
復制代碼 代碼如下:
$list  = array (
    array( 'aaa' ,  'bbb' ,  'ccc' ,  'dddd' ),
    array( '123' ,  '456' ,  '7891' ),
    array( '"aaa"' ,  '"bbb"' )
);
 
$file  = new  SplFileObject ( 'file.csv' ,  'w' );
 
foreach ( $list  as  $fields ) {
    $file -> fputcsv ( $fields );
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved