71
81

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SplFileObjectでオブジェクト指向らしいファイル操作をしてみる

Last updated at Posted at 2012-12-26

file_get_contents() すごく便利ですが、容量が大きいファイルを扱うときはメモリ消費が心配ですよね。
かと言って fopen() で古めかしいコードを書くのはイヤ!そんなときこそ、SplFileObject クラスの出番です!

ファイルの中身は foreach() で回すだけで取得できる

<?php

$splFileObject = new SplFileObject(__FILE__);

echo 'File name:', PHP_EOL;
echo $splFileObject->getPathname(), PHP_EOL;

echo 'File contents:', PHP_EOL;

foreach ( $splFileObject as $line )
{
	echo $line;
}
実行結果
$ php SplFileObject.php 
File name:
/Users/suin/Desktop/SplFileObject.php
File contents:
<?php

$splFileObject = new SplFileObject(__FILE__);

echo 'File name:', PHP_EOL;
echo $splFileObject->getPathname(), PHP_EOL;

echo 'File contents:', PHP_EOL;

foreach ( $splFileObject as $line )
{
	echo $line;
}

もちろんCSVだって foreach() でできます!

<?php

file_put_contents('foo.csv', "1,2,3\n4,5,6\n7,8,9\n");

$splFileObject = new SplFileObject('foo.csv');

foreach ( $splFileObject as $line )
{
	echo $line;
}

// CSVモードに切り替える
$splFileObject->setFlags(SplFileObject::READ_CSV);

foreach ( $splFileObject as $line )
{
	var_dump($line);
}
実行結果
* php SplFileObject.php 
1,2,3
4,5,6
7,8,9
array(3) {
  [0] =>
  string(1) "1"
  [1] =>
  string(1) "2"
  [2] =>
  string(1) "3"
}
array(3) {
  [0] =>
  string(1) "4"
  [1] =>
  string(1) "5"
  [2] =>
  string(1) "6"
}
array(3) {
  [0] =>
  string(1) "7"
  [1] =>
  string(1) "8"
  [2] =>
  string(1) "9"
}
array(1) {
  [0] =>
  NULL
}

関連

変則的なCSVを処理する - Qiita

71
81
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
71
81

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?