raw snippet

Snippet: Parse CSV with PHP

Robert Eisele

A function to parse CSV contents with multiline support in PHP

<?php

// Copyright Robert Eisele 2016
function parseCSV($cont, $sep = ';', $quot = '"') {
    $field = "";
    $inStr = false;
    $row = array();
    $ret = array();

    $len = strlen($cont);
    for ($i = 0; $i < $len; $i++) {

        $c = $cont[$i];

        if ($inStr) {

            if ($c === $quot) {
                $inStr = false;
            } else {
                $field .= $c;
            }

            if ($i == $len - 1 && ($row !== array() || $field !== "")) {
                $row[] = trim($field);
                $field = "";
                $ret[] = $row;
                $row = array();
            }

        } else if ($c === $quot) {
            $inStr = true;
        } else if ($c === $sep) {
            $row[] = trim($field);
            $field = "";
        } else if ($c === "\n" || $c === "\r" || $i == $len - 1) {
            if ($row !== array() || $field !== "") {
                $row[] = trim($field);
                $field = "";
                $ret[] = $row;
                $row = array();
            }
        } else {
            $field .= $c;
        }
    }
    return $ret;
}