PHP SPL標準庫之檔案操作(SplFileInfo和SplFileObject)執行個體_php執行個體

來源:互聯網
上載者:User

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 );
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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