开发者

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?


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);
}


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


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.


Here's a function that reads a csv file and returns an array of items that contain the first two column data values.

This function could read a file of first_name,last_name for example.

function processFile ($filename) {
    $rtn = array();

    if (($handle = fopen($filename, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $item = array();
            $item[] = $data[0];
            $item[] = $data[1];
            $rtn[] = $item;
        }
    }
    return $rtn;
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜