PHP解析CSV字符串转换为数组

fgetcsv的简易替代:

function parse_csv($file, $options = null) { 
    $delimiter = empty($options['delimiter']) ? "," : $options['delimiter']; 
    $to_object = empty($options['to_object']) ? false : true; 
    $expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added 
    $str = $file; 
    $lines = explode("\n", $str); 
    $field_names = explode($delimiter, array_shift($lines)); 
    foreach ($lines as $line) { 
        // Skip the empty line 
        if (empty($line)) continue; 
        $fields = preg_split($expr,trim($line)); // added 
        $fields = preg_replace("/^\"(.*)\"$/","$1",$fields); //added 
        //$fields = explode($delimiter, $line); 
        $_res = $to_object ? new stdClass : array(); 
        foreach ($field_names as $key => $f) { 
            if ($to_object) { 
                $_res->{$f} = $fields[$key]; 
            } else { 
                $_res[$f] = $fields[$key]; 
            } 
        } 
        $res[] = $_res; 
    } 
    return $res; 

4 comments

  1. eng 说道:

    支持一下咯,学习
    妞霞奶上下套动基地 http://www.liuxialai.cn

  2. Feng2084 说道:

    非常感谢! It works!

  3. Val Casale 说道:

    I just want to tell you that I am all new to blogging and site-building and certainly liked you’re web page. Most likely I’m planning to bookmark your blog . You amazingly come with wonderful writings. Cheers for sharing with us your web page.

  4. Felix Laliberte 说道:

    Someone essentially help to make seriously posts I would state. This is the very first time I frequented your web page and thus far? I surprised with the research you made to create this particular publish extraordinary. Magnificent job!

发表评论

电子邮件地址不会被公开。