The League of Extraordinary Packages

Our Packages:

Presented by The League of Extraordinary Packages

Getting Started

Connections Settings

Inserting Records

Selecting Records


Converting Records

Upgrading Guide

Prevents CSV Formula Injection

Available since version 9.1.0

class EscapeFormula
    public function __construct(string $escape = "\t", array $special_chars = [])
    public function __invoke(array $record): array
    public function escapeRecord(array $record): array
    public function getEscape(): string
    public function getSpecialCharacters(): array

The EscapeFormula Formatter formats CSV records to reduce CSV Formula Injection in imported Spreadsheet programs.

Usage with Writer objects

The EscapeFormula class uses the formatter capabilities of the Writer object to escape formula injection.


public function __construct(string $escape = "\t", array $special_chars = [])
public function __invoke(array $record): array

The EscapeFormula::__construct method takes two (2) arguments:


use League\Csv\EscapeFormula;
use League\Csv\Writer;

$writer = Writer::createFromPath('php://temp', 'r+');
$writer->addFormatter(new EscapeFormula());
$writer->insertOne(['2', '2017-07-25', 'Important Client', '=2+5', 240, null]);
//outputting a CSV Document with all CSV Formula Injection escaped
//"2,2017-07-25,\"Important Client\",\"\t=2+5\",240,\n"

Usage with PHP stream resources

You can use the EscapeFormula to format your records before callng fputcsv or SplFileObject::fputcsv.


use League\Csv\EscapeFormula;

$resource = fopen('/path/to/my/file', 'r+');
$formatter = new EscapeFormula("`");
foreach ($iterable_data as $record) {
    fputcsv($resource, $formatter->escapeRecord($record));

Even though we provide the EscapeFormula formatter I must stress out that this is in no way a bulletproof method. This prevention mechanism only works if you know how the CSV export will be consumed. In any other cases, you are better of leaving the filtering to the consuming client and report any found security concern to their respective security channel.