PHP5.2.1でCSVを扱うとき、フィールドにカンマが含まれていたら

「a,b,"cde,fg",e」
こんなCSVPHPで扱おうとすると、結構面倒くさい。

ここの人と同じように結構悩んだ。
結論だけ書く。

http://php.benscom.com/manual/ja/function.strtok.php
ここにサンプルがあったので、これを改変してこんな感じで。

test.php


<?php

$fh=fopen("test.csv",'r');

while(!feof($fh)){
    $buffer = fgets($fh,4096);
    $buffer = chop($buffer);
    $values = tokenizeQuoted($buffer,",");
    print_r($values);


}

fclose($fh);




//split a string into an array of space-delimited tokens, taking double-quoted strings into account
function tokenizeQuoted($string,$delimitar)
{
  for($tokens=array(), $nextToken=strtok($string, $delimitar); $nextToken!==false; $nextToken=strtok($delimitar))
  {
    if($nextToken{0}=='"')
      $nextToken = $nextToken{strlen($nextToken)-1}=='"' ?
      substr($nextToken, 1, -1) : substr($nextToken, 1) . $delimitar . strtok('"');
    $tokens[] = $nextToken;
  }
  return $tokens;
}
?>

サンプル

nobody@localhost$ cat test.csv
a,b,"cde,fg",e
nobody@localhost$ php ./test.php
Array
(
  [0] => a
  [1] => b
  [2] => cde,fg
  [3] => e
)
nobody@localhost$