phpiofgetcsv

php://memory IO stream and fgetcsv()


I want to parse csv-like string so I can emulate csv and assert it into a test case.

// init CSV-like string
$str = <<<EOD
    1,john\r\n
    2,smith\r\n
EOD;

// Open file Handler, puts the CSV-like string, rewind the file pointer
$fp = fopen('php://memory','r+');
fputs($fp,$str);
rewind($fp);

// Parse the CSV-like string
$parsed = [];
while (($data = fgetcsv($fp, 2048)) !== FALSE) {
    $parsed[] = fgetcsv($fp);
}

var_dump($parsed);

But it won't parse into arrays. This is the output:

array (size=2)
  0 => 
    array (size=1)
      0 => null
  1 => boolean false

Solution

    1. Remove the \r\n, not needed
    2. Your moving the pointer twice per loop, change to $parsed[] = $data