Skip to main content

Testing CSV output in Drupal 8 with BrowserTestBase

In a recent project we were outputting CSV and wanted to test that the file contents were valid.

Read on for a quick tip on how to achieve this with Drupal 8's BrowserTestBase

by Lee Rowlands /

Basically, the easiest way to validate and parse CSV in PHP is with the built in fgetcsv function.

So how do you go about using that inside a functional test - in that instance we're not dealing with a file so its not your ordinary approach for fgetcsv.

The answer is to create a stream wrapper in memory, and use fgetcsv on that.

The code looks something like this:

    $response = $this->getSession()
      ->getDriver()
      ->getContent();
    // Put contents into a memory stream and use fgetcsv to parse.
    $stream = fopen('php://memory', 'r+');
    fwrite($stream, $response);
    rewind($stream);
    $records = [];
    // Get the header row.
    $header = fgetcsv($stream);
    while ($row = fgetcsv($stream)) {
      $records[] = $row;
    }
    fclose($stream);

There you have it, you now have the header in $header and the rows in $rows and can do any manner of asserts that you need to validate the CSV generation works as expected.

Posted by Lee Rowlands
Senior Drupal Developer

Dated

Add new comment

Restricted HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <h4> <h5> <h6>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
Not sure where to start? Try typing "hello" or "help" if you get stuck.