str_getcsv()替代旧的PHP版本,最后给我一个空数组

时间:2012-11-17 11:27:57

标签: php regex csv

我的托管服务提供商没有支持str_getcsv()的PHP版本,所以我环顾四周找到了这个功能。除了它给了我一个额外的空数组并且它搞砸了我的代码之外,它确实有效。示例" a,b,b"将返回Array ( [0] => a [1] => b [2] => c [3] => )。这是功能:

function _pick_csv_element($x) {
return strlen($x[1]) ? $x[1] : $x[2];
}

function str_getcsv($input) {
preg_match_all(
    '/\G (?: \s*"([^"]*)"\s* | ([^,]*) ) (?:,|$) /x',
    $input, $matches,
    PREG_SET_ORDER
);
return array_map('_pick_csv_element', $matches);
}

3 个答案:

答案 0 :(得分:5)

可能最可靠的解决方法是:

$fh = fopen('php://temp', 'r+');
fwrite($fh, $string);
rewind($fh);

$row = fgetcsv($fh);

fclose($fh);

您继续使用内置CSV功能,只需要从流中读取即可。但是这会有轻微的性能影响,因为需要复制字符串。

答案 1 :(得分:0)

戴夫,

我猜你使用的是PHP 5.2。*。如果您的要求是将整个CSV文件读入多维关联数组,那么下面就像美女一样:

function parse_csv_file($csvfile) {
    $csv = Array();
    $rowcount = 0;
    if (($handle = fopen($csvfile, "r")) !== FALSE) {
        $max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
        $header = fgetcsv($handle, $max_line_length);
        $header_colcount = count($header);
        while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
            $row_colcount = count($row);
            if ($row_colcount == $header_colcount) {
                $entry = array_combine($header, $row);
                $csv[] = $entry;
            }
            else {
                error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
                return null;
            }
            $rowcount++;
        }
        //echo "Totally $rowcount rows found\n";
        fclose($handle);
    }
    else {
        error_log("csvreader: Could not read CSV \"$csvfile\"");
        return null;
    }
    return $csv;
}

答案 2 :(得分:-1)

在这里寻找你的答案,这可能对你有所帮助。

alternate for str_getcsv