如何使用PHP和fgetcsv函数从CSV文件创建数组

Tho*_*mas 91 php csv arrays

有人可以使用fgetcsv提供从CSV文件创建数组的代码吗?

我使用以下代码从一个简单的CSV文件创建一个数组,但是当我的一个字段有多个逗号(例如地址)时,它无法正常工作.

$lines =file('CSV Address.csv');

foreach($lines as $data)
{
list($name[],$address[],$status[])
= explode(',',$data);
}
Run Code Online (Sandbox Code Playgroud)

*此外,我的托管服务不支持str_getcsv.

以上代码不适用于以下CSV文件示例.第一列是名称,第二列是地址,第三列是婚姻状态.

Scott L. Aranda,"123 Main Street, Bethesda, Maryland 20816",Single
Todd D. Smith,"987 Elm Street, Alexandria, Virginia 22301",Single
Edward M. Grass,"123 Main Street, Bethesda, Maryland 20816",Married
Aaron G. Frantz,"987 Elm Street, Alexandria, Virginia 22301",Married
Ryan V. Turner,"123 Main Street, Bethesda, Maryland 20816",Single
Run Code Online (Sandbox Code Playgroud)

Dav*_*ong 165

就像你在标题中所说,fgetcsv是要走的路.它非常易于使用.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);
Run Code Online (Sandbox Code Playgroud)

如果fopen()失败,您将需要在其中放置更多错误检查,但这可以逐行读取CSV文件并将该行解析为数组.

  • @Thomas如果你需要一系列的名字,地址和状态,你可以做你上面所做的事:`list($ names [],$ addresses [],$ statuses [])= $ line;` (6认同)

Ali*_*xel 50

我认为str_getcsv()语法更清晰,它也不需要将CSV存储在文件系统中.

$csv = str_getcsv(file_get_contents('myCSVFile.csv'));

echo '<pre>';
print_r($csv);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

或者逐行解决方案:

$csv = array();
$lines = file('myCSVFile.csv', FILE_IGNORE_NEW_LINES);

foreach ($lines as $key => $value)
{
    $csv[$key] = str_getcsv($value);
}

echo '<pre>';
print_r($csv);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

或者对于没有str_getcsv()的逐行解决方案:

$csv = array();
$file = fopen('myCSVFile.csv', 'r');

while (($result = fgetcsv($file)) !== false)
{
    $csv[] = $result;
}

fclose($file);

echo '<pre>';
print_r($csv);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

  • 谨防!str_getcsv存在一个错误,它会忽略行结尾:https://bugs.php.net/bug.php?id = 55763&edit = 1 (4认同)
  • 仅供参考:str_getcsv()仅适用于PHP 5.3.0.我正在研究的项目错过了1版DOH!(我们使用5.2.9 atm). (2认同)

kna*_*ode 17

我创建了一个将csv字符串转换为数组的函数.该函数知道如何转义特殊字符,它可以使用或不使用机箱字符.

我用你的csv样本尝试了它,它按预期工作!

$dataArray = csvstring_to_array( file_get_contents('Address.csv'));
Run Code Online (Sandbox Code Playgroud)


Man*_*ath 13

老问题,但仍然与PHP 5.2用户相关.str_getcsv可从PHP 5.3获得.我编写了一个与fgetcsv本身一起使用的小函数.

以下是我的功能来自https://gist.github.com/4152628:

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;
}
Run Code Online (Sandbox Code Playgroud)

返回

开始阅读CSV

Array
(
    [0] => Array
        (
            [vid] => 
            [agency] => 
            [division] => Division
            [country] => 
            [station] => Duty Station
            [unit] => Unit / Department
            [grade] => 
            [funding] => Fund Code
            [number] => Country Office Position Number
            [wnumber] => Wings Position Number
            [title] => Position Title
            [tor] => Tor Text
            [tor_file] => 
            [status] => 
            [datetime] => Entry on Wings
            [laction] => 
            [supervisor] => Supervisor Index Number
            [asupervisor] => Alternative Supervisor Index
            [author] => 
            [category] => 
            [parent] => Reporting to Which Position Number
            [vacant] => Status (Vacant / Filled)
            [index] => Index Number
        )

    [1] => Array
        (
            [vid] => 
            [agency] => WFP
            [division] => KEN Kenya, The Republic Of
            [country] => 
            [station] => Nairobi
            [unit] => Human Resources Officer P4
            [grade] => P-4
            [funding] => 5000001
            [number] => 22018154
            [wnumber] => 
            [title] => Human Resources Officer P4
            [tor] => 
            [tor_file] => 
            [status] => 
            [datetime] => 
            [laction] => 
            [supervisor] => 
            [asupervisor] => 
            [author] => 
            [category] => Professional
            [parent] => 
            [vacant] => 
            [index] => xxxxx
        )
) 
Run Code Online (Sandbox Code Playgroud)


小智 10

$arrayFromCSV =  array_map('str_getcsv', file('/path/to/file.csv'));
Run Code Online (Sandbox Code Playgroud)


cle*_*lem 6

要获得具有正确键的数组,您可以尝试以下操作:

// Open file
$file = fopen($file_path, 'r');

// Headers
$headers = fgetcsv($file);

// Rows
$data = [];
while (($row = fgetcsv($file)) !== false)
{
    $item = [];
    foreach ($row as $key => $value)
        $item[$headers[$key]] = $value ?: null;
    $data[] = $item;
}

// Close file
fclose($file);
Run Code Online (Sandbox Code Playgroud)


Dee*_*ran 5

尝试这个..

function getdata($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}


// Set path to CSV file
$csvFile = 'test.csv';

$csv = getdata($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';

Array
(
    [0] => Array
        (
            [0] => Project
            [1] => Date
            [2] => User
            [3] => Activity
            [4] => Issue
            [5] => Comment
            [6] => Hours
        )

    [1] => Array
        (
            [0] => test
            [1] => 04/30/2015
            [2] => test
            [3] => test
            [4] => test
            [5] => 
            [6] => 6.00
        ));
Run Code Online (Sandbox Code Playgroud)