Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import CSV using zend

How do I import CSV files using zend framework? Should I use zend_file_transfer or is there any special class that I have to look into? Also if I use zend_file_transfer is there any special validator for CSV?

like image 308
JABD Avatar asked Jun 13 '11 18:06

JABD


3 Answers

you don't have to use any zend libraries to import csv files, you can just use native php functions, take a look at fgetcsv

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
like image 105
Kenrick Buchanan Avatar answered Nov 03 '22 23:11

Kenrick Buchanan


You could also use SplFileObject for reading CSV files.

From the php manual:

<?php
    $file = new SplFileObject("animals.csv");
    $file->setFlags(SplFileObject::READ_CSV);
    foreach ($file as $row) {
        list($animal, $class, $legs) = $row;
        printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
    }
?> 

http://php.net/manual/en/splfileobject.fgetcsv.php

like image 9
Maghiel Dijksman Avatar answered Nov 03 '22 21:11

Maghiel Dijksman


There is currently no way to do this with the Zend Framework. How can one be sure?

For example, Zend_Translate supports translation with CSV files, but if you check the the source code of the respective adapter (Zend_Translate_Adapter_Csv), you can verify it uses fgetcsv, and not a specific Zend class. Besides, this CSV adapter comes with the following warning:

Note: Beware that the Csv Adapter has problems when your Csv files are encoded differently than the locale setting of your environment. This is due to a Bug of PHP itself which will not be fixed before PHP 6.0 (http://bugs.php.net/bug.php?id=38471). So you should be aware that the Csv Adapter due to PHP restrictions is not locale aware.

which is related with the problems of the fgetcsv function.

like image 1
faken Avatar answered Nov 03 '22 22:11

faken