Horde_Data_Csv::getCsv PHP Method

getCsv() public static method

Empty lines will be skipped. If the 'length' parameter is provided, all rows are filled up with empty strings up to this length, or stripped down to this length.
public static getCsv ( resource $file, array $params = [] ) : array | boolean
$file resource A file pointer.
$params array Optional parameters. Possible values: - escape: The escape character. - length: The expected number of fields. - quote: The quote character. - separator: The field delimiter.
return array | boolean A row from the CSV file or false on error or end of file.
    public static function getCsv($file, array $params = array())
    {
        $params += array('escape' => '\\', 'quote' => '"', 'separator' => ',');
        // fgetcsv() throws a warning if the quote character is empty.
        if (!strlen($params['quote']) && $params['escape'] != '\\') {
            $params['quote'] = '"';
        }
        // Detect Mac line endings.
        $old = ini_get('auto_detect_line_endings');
        ini_set('auto_detect_line_endings', 1);
        do {
            $row = strlen($params['quote']) ? fgetcsv($file, 0, $params['separator'], $params['quote'], $params['escape']) : fgetcsv($file, 0, $params['separator']);
        } while ($row && is_null($row[0]));
        ini_set('auto_detect_line_endings', $old);
        if ($row) {
            $row = strlen($params['quote']) && strlen($params['escape']) ? array_map(create_function('$a', 'return str_replace(\'' . str_replace('\'', '\\\'', $params['escape'] . $params['quote']) . '\', \'' . str_replace('\'', '\\\'', $params['quote']) . '\', $a);'), $row) : array_map('trim', $row);
            if (!empty($params['length'])) {
                $length = count($row);
                if ($length < $params['length']) {
                    $row += array_fill($length, $params['length'] - $length, '');
                } elseif ($length > $params['length']) {
                    array_splice($row, $params['length']);
                }
            }
        }
        return $row;
    }

Usage Example

Esempio n. 1
0
 protected function readCsv($file, $conf = array())
 {
     $fp = fopen(__DIR__ . '/fixtures/getcsv/' . $file, 'r');
     $data = array();
     while ($res = Horde_Data_Csv::getCsv($fp, $conf)) {
         $data[] = $res;
     }
     return $data;
 }