Skip to content
Advertisement

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,johnrn
    2,smithrn
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

Advertisement

Answer

  1. Remove the rn, not needed
  2. Your moving the pointer twice per loop, change to $parsed[] = $data
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement