天道酬勤,学无止境

Reading .csv into a PHP array [duplicate]

I have a PHP routine that reads a .csv file that has been uploaded to my site.

The number of fields in the file may be different from upload to upload.

I want to be able to establish the size of the .csv file (the number of fields) and then store its contents in an array.

This is what I have so far:

//get the csv file 
$file = $_FILES[csv1][tmp_name]; 
$handle = fopen($file,"r"); 

//loop through the csv file and insert into array
$dataline = fgetcsv($handle,1000,",","'");
$fieldnum = count($dataline);

$recordloop = 0;

while ($dataline) 
{ 

    for ($fieldloop=0; $fieldloop <$fieldnum; $fieldloop++)
    {
        //this is the bit that is wrong
        $dataarray[]=array($dataline[$fieldloop]);
    }

    $data = fgetcsv($handle,1000,",","'");
    $recordloop++;
}

If for example, there are 30 fields and 200 records I am trying to get the array to be of the structure $dataarray[200][30].

How do I get the data into the array of this structure?

Example .csv:

Row 1 will be field headings
Name, Gender, Ethnicity, DOB, etc .... the number of fields is not fixed - it could be from 30 to 40 fields in this row

Rows 2 onwards will be the records
John, M, British, 10/04/49, etc
Simon, M, British, 04/03/65, etc

ANSWER - did just what I wanted

$file = $_FILES[csv1][tmp_name]; 
$handle = fopen($file,"r"); 

$matrix = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
$matrix[] = $row;
}

评论

You already have this kind of implementation in PHP:

$csv = array_map('str_getcsv', file('someCSVfile.csv'));

Explanation:

  • str_getcsv() - Parse a CSV string into an array.
  • file() - Reads entire file into an array.
  • array_map(Function, Array)- Returns an array containing all the elements of the array after applying the callback function to each one.

Example output:

//CSV
NAME,CLASS,ROOM
Sally,2018,312
Belinda,2017,148

//OUTPUT:
Array(
       [0] => Array([0] => NAME,    [1] => CLASS, [2] => ROOM), 
       [1] => Array([0] => Sally,   [1] => 2018,  [2] => 312),
       [2] => Array([0] => Belinda, [1] => 2017,  [2] => 148)
)

Associative keys

Two quick functions to parse with associative keys - both based on the array_map method:

METHOD 1: running twice

function assoc_getcsv($csv_path) {
    $r = array_map('str_getcsv', file($csv_path));
    foreach( $r as $k => $d ) { $r[$k] = array_combine($r[0], $r[$k]); }
    return array_values(array_slice($r,1));
}  

METHOD 2: running once

function assoc_getcsv($csv_path) {
    $f = array();
    function parse_csv_assoc($str,&$f){ 
        if (empty($f)) { $f = str_getcsv($str); }
        return array_combine($f, str_getcsv($str));         
    }
    return array_values(array_slice(array_map('parse_csv_assoc', file($csv_path), $f),1));
} 

Example output:

//CSV
NAME,CLASS,ROOM
Sally,2018,312
Belinda,2017,148

//OUTPUT:
Array(
       [0] => Array([NAME] => Sally,   [CLASS] => 2018,  [ROOM] => 312),
       [1] => Array([NAME] => Belinda, [CLASS] => 2017,  [ROOM] => 148)
)

this function will read a CSV and generate a multi-dimensional array

function fromCSVFile( $file) {
    // open the CVS file
    $handle = @fopen( $file, "r");
    if ( !$handle ) {
        throw new \Exception( "Couldn't open $file!" );
    }

    $result = [];

    // read the first line
    $first = strtolower( fgets( $handle, 4096 ) );
    // get the keys
    $keys = str_getcsv( $first );

    // read until the end of file
    while ( ($buffer = fgets( $handle, 4096 )) !== false ) {

        // read the next entry
        $array = str_getcsv ( $buffer );
        if ( empty( $array ) ) continue;

        $row = [];
        $i=0;

        // replace numeric indexes with keys for each entry
        foreach ( $keys as $key ) {
            $row[ $key ] = $array[ $i ];
            $i++;
        }

        // add relational array to final result
        $result[] = $row;
    }

    fclose( $handle );
    return $result;
}

So if your .CSV file looks like this:

Name,Gender,Ethnicity,DOB
John,M,British,10/04/49
Simon,M,British,04/03/65

You will get this:

(
    [0] => Array
        (
            [name] => John
            [gender] => M
            [ethnicity] => British
            [dob] => 10/04/49
        )

    [1] => Array
        (
            [name] => Simon
            [gender] => M
            [ethnicity] => British
            [dob] => 04/03/65
        )

)

1.csv:

Name,Gender,Ethnicity,DOB
John,M,British,10/04/49
Simon,M,British,04/03/65

Use file() to read the csv file into an array, then iterate through this array and get all the fields into an array element with explode() and make your new $array

<?php

$file = '1.csv';
$content = file($file);

$array = array();

for($i = 1; $i < count($content); $i++) {
    $line = explode(',', $content[$i]);
    for($j = 0; $j < count($line); $j++) {
        $array[$i][$j + 1] = $line[$j];
    }   
}   

print_r($array);

?>

Output:

Array
(
    [1] => Array
        (
            [1] => John
            [2] => M
            [3] => British
            [4] => 10/04/49

        )

    [2] => Array
        (
            [1] => Simon
            [2] => M
            [3] => British
            [4] => 04/03/65

        )

)

If you want get record:2 and field:4 you can do this:

echo $array[2][4];

Output:

04/03/65

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • PHP 数组合并,忽略某些重复的键并让它们包含在内部创建的数组中(PHP array merging, ignore certain duplicated keys and let them be included in the inner created arrays)
    问题 我正在将具有相同设置内部数组名称的数组合并在一起,将键值更改为订单号,然后为不与此代码重复的项目创建更多内部数组... function readCSV($csvFile) { $line_of_text = []; $file_handle = fopen($csvFile, 'r'); //skip csv headers //fgetcsv($file_handle); //fgetcsv($file_handle); fgetcsv($file_handle); while (!feof($file_handle)) { $tmp = fgetcsv($file_handle, 1024); if (isset($line_of_text[$tmp[0]])) { foreach ($tmp as $k => $v) { if (array_key_exists($k, $line_of_text[$tmp[0]])) { if (!is_array($line_of_text[$tmp[0]][$k])) { $kVal = $line_of_text[$tmp[0]][$k]; $line_of_text[$tmp[0]][$k] = []; $line_of_text[$tmp[0]][$k][] = $kVal; } $line_of_text[$tmp[0]
  • 将.csv文件读入C中的数组[重复](Reading .csv file into an array in C [duplicate])
    问题 这个问题在这里已经有了答案: 在 C 中读取 .csv 文件(5 个回答) 4年前关闭。 我目前正在尝试将 .csv 文件读入 C 中的数组。我对如何解决这个问题有些犹豫。 我浏览了许多论坛和相关主题,但我仍然无法理解。 如果有人可以向我展示或尽可能简单地分解它。 这将不胜感激。 顺便说一下,.csv文件的内容是这样的。 该数组应仅包含字母和数字。 我正在考虑使用二维数组。 这是一个合适的解决方案吗? A,1 B,2 C,3 .... 回答1 首先定义你的数据结构: struct my_record { char name; int value; }; 然后你可以这样读: FILE* my_file = fopen(...); struct my_record records[100]; size_t count = 0; for (; count < sizeof(records)/sizeof(records[0]); ++count) { int got = fscanf(my_file, "%c,%d", &records[count].name, &records[count].value); if (got != 2) break; // wrong number of tokens - maybe end of file } fclose(my_file)
  • Reading .csv file into an array in C [duplicate]
    This question already has answers here: Read .csv file in C (5 answers) Closed 4 years ago. I am Currently trying to read a .csv file into an array in C. I'm somewhat on the fence on how to approach the problem. I've looked through many forums and related topic but I still can't grasp it. If someone could show me or break it down as simple as possible. That would be greatly appreciated. By the way, the contents of the .csv file is like this. The array should consist of just the alphabet and the number. I was thinking about using a 2-D array. Is that an appropriate solution? A,1 B,2 C,3 ....
  • PHP将csv列读入数组(PHP reading csv column into array)
    问题 我有一个 php 函数可以让我将 csv 列(COLUMN NOT LINE)读入数组或字符串? 先感谢您。 回答1 $csv = array_map("str_getcsv", file("data.csv", "r")); $header = array_shift($csv); // Seperate the header from data $col = array_search("Value", $header); foreach ($csv as $row) { $array[] = $row[$col]; } 回答2 愿这会有所帮助。 http://www.php.net/manual/de/function.fgetcsv.php 只需抓取您想要的列的行位置。 回答3 $arr=array(); $row = -1; if (($handle = fopen("test.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); $row++; for ($c = 0; $c < $num; $c++) { $arr[$row][$c]= $data[$c]; } } fclose($handle); } 回答4
  • 从php中的csv文件读取大数据[重复](Read large data from csv file in php [duplicate])
    问题 这个问题已经在这里有了答案: file_get_contents => PHP致命错误:允许的内存耗尽(4个答案) 1年前关闭。 我正在读取csv并与mysql检查记录是否存在于我的表中或不在php中。 csv大约有25000条记录,当我运行我的代码时,它在2m 10s后显示“服务不可用”错误(加载:2m 10s) 在这里我添加了代码 // for set memory limit & execution time ini_set('memory_limit', '512M'); ini_set('max_execution_time', '180'); //function to read csv file function readCSV($csvFile) { $file_handle = fopen($csvFile, 'r'); while (!feof($file_handle) ) { set_time_limit(60); // you can enable this if you have lot of data $line_of_text[] = fgetcsv($file_handle, 1024); } fclose($file_handle); return $line_of_text; } // Set path to CSV file
  • How do I read a CSV file into an array using d3js v5 [duplicate]
    This question already has answers here: How to return the response from an asynchronous call (42 answers) Closed 3 years ago. I am creating a data dashboard that should allow the user to point to a CSV file on their file system, which is then uploaded into the dashboard to perform all kinds of visualisation actions on it. I am using a nice d3js example for the visualisation, but none of the examples I found include reading the CSV file and I cannot make it work. I can read the CSV file and log the contents to the console, but whatever I do to pass the data into an array (which I can
  • PHP:删除多维数组中的空数组字符串(PHP: remove empty array strings in multidimensional array [duplicate])
    问题 这个问题已经在这里有了答案: 如何从PHP中的多维数组中删除空值? (8个答案) 7年前关闭。 我有这个数组: $aryMain = array(array('hello','bye'), array('',''),array('','')); 它是通过读取一个csv文件形成的,而array('','')是文件末尾的空行。 如何删除它们? 我试过了: $aryMain = array_filter($aryMain); 但这是行不通的:( 非常感谢! 回答1 要添加到Rikesh的答案中: <?php $aryMain = array(array('hello','bye'), array('',''),array('','')); $aryMain = array_filter(array_map('array_filter', $aryMain)); print_r($aryMain); ?> 将他的代码放在另一个array_filter中将摆脱整个数组本身。 Array ( [0] => Array ( [0] => hello [1] => bye ) ) 相比: $aryMain = array_map('array_filter', $aryMain); Array ( [0] => Array ( [0] => hello [1] => bye ) [1] =>
  • PHP reading csv column into array
    I there a php function that enables me to read a csv column (COLUMN NOT LINE) into an array or a string ? thank you in advance.
  • 如何使用PHP解析CSV文件(How to parse a CSV file using PHP [duplicate])
    问题 这个问题已经在这里有了答案: 如何从PHP中的csv文件中提取数据(12个答案) 3年前关闭。 假设我有一个.csv文件,其内容如下: "text, with commas","another text",123,"text",5; "some without commas","another text",123,"text"; "some text with commas or no",,123,"text"; 如何通过PHP解析内容? 回答1 只需使用该功能即可解析CSV文件 http://php.net/manual/zh/function.fgetcsv.php $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); } 回答2 由于PHP> = 5.3.0,答案要短一些:
  • PHP:以OOP方式搜索CSV文件(PHP: Searching through a CSV file the OOP way)
    问题 我需要编写一个脚本来搜索CSV文件,并对该脚本执行某些搜索功能; 在列中查找重复的条目在另一列中找到与禁止条目列表匹配的条目通过正则表达式匹配在指定的列上查找条目 现在,我在程序上进行编码完全没有问题,但是当我进入面向对象编程时,我想使用类和对象实例。 但是,对OOP的思考对我来说还不是很自然,因此我不确定该走哪条路。 我不是在寻找特定的代码,而是关于如何设计脚本的建议。 我目前的想法是这样; 创建一个文件类。 这将处理数据的导入/导出创建一个搜索类。 文件的子类。 这将包含各种搜索方法 它如何在index.php中起作用: 从index.php文件对象中的csv获取数组创建一个循环以遍历数组的值从搜索对象中调用循环中的方法并回显它们 我看到的这种方法的问题是: 我将要指出数组中的不同元素,以查看特定的“列”。 我可以将循环放在函数中并将其作为参数传递,但是这种感觉违反了OOP的观点。 我的搜索方法将以不同的方式工作。 使用嵌套循环来搜索重复项是相当简单的,但是我不需要嵌套循环来进行简单的单词或正则表达式搜索。 我应该这样走吗? 创建一个文件类。 这将处理数据的导入/导出创建循环类文件类的子级。 这将包含处理遍历数组的方法创建一个搜索类。 循环的子类。 这将包含各种搜索方法 我的主要问题是,看来我可能需要多个搜索对象,并在循环类中对其进行迭代。 任何帮助将非常感激。
  • 在php中正确读取.csv文件的数据(Properly reading the data of .csv files in php)
    问题 我有一个工作系统,可以在其中获取两个 .csv 文件的数据。 并将所有数据保存到数组中,然后比较两个 csv 文件中存在的一些数据。 系统运行良好,但后来我发现某些行没有显示在阵列上。 我想我在读取 csv 文件时没有使用正确的代码。 我想编辑/改进系统。 这是我从 csv 文件读取或获取数据的代码。 $thedata = array(); $data = file("upload/payment.csv"); foreach ($data as $deposit){ $depositarray = explode(",", $deposit); $depositlist = $depositarray; $key = md5($depositlist[9] . $depositlist[10]); $thedata[$key]['payment'] = array( 'name' => $depositlist[0], 'email' => $depositlist[1], 'modeofpayment' =>$depositlist[8], 'depositdate' => $depositlist[9], 'depositamount' => number_format($depositlist[10],2) ); } '<pre>',print_r($thedata)
  • Properly reading the data of .csv files in php
    I have a working system on which I get the data of two .csv file. And save all the data into array and then compare some of the data existing on both csv file. The system works well but later I found out that some of the rows doesn't display on the array. I think I don't use the proper code in reading a csv file. I want to edit/improve the system. This is my code on reading or getting the data from csv file. $thedata = array(); $data = file("upload/payment.csv"); foreach ($data as $deposit){ $depositarray = explode(",", $deposit); $depositlist = $depositarray; $key = md5($depositlist[9] .
  • 很长的 PHP 操作:500 内部服务器错误(Very long PHP operation: 500 Internal Server Error)
    问题 我正在阅读 10,000 个 csv 文件,每个文件有 1000 行并删除重复项并创建新文件 为了那个原因 我逐行读取并将数据存储在数组中。 当我在数组中存储新数据时,我检查天气它不是重复的(天气数组已经有数据) 然后使用数组重新创建 csv 另外我在 php.ini 中更改了以下内容 max_execution_time = 30000 max_input_time = 60000 memory_limit = -1 error_log = error_log 但我收到以下错误。 没有错误日志。 php.ini 中是否还有其他配置要更改。 请帮我解决 内部服务器错误服务器遇到内部错误或配置错误,无法完成您的请求。 请联系服务器管理员 webmaster@xxxxxx.com 并告知他们错误发生的时间,以及您所做的可能导致错误的任何事情。 服务器错误日志中可能提供有关此错误的更多信息。 此外,在尝试使用 ErrorDocument 处理请求时遇到 404 Not Found 错误。 回答1 除了检查 Apache 超时之外,您还应该尝试中断此脚本一次并尝试分批运行它,大约为 2000 个 csv 文件。 也有可能是其中一个 CSV 文件中的某些数据导致了此错误,如果您将其分成 2000 个文件并运行,则可以识别该错误。
  • 使用PHP读取大型Excel文件(Reading large excel file with PHP)
    问题 我正在尝试使用PHPExcel1.7.3c读取一个17MB的excel文件(2003年),但是在超过120秒的限制之后,加载文件时它已经崩溃了。 是否有另一个图书馆可以更有效地做到这一点? 我不需要样式,只需要它来支持UTF8。 谢谢你的帮助 回答1 使用PHPExcel时,Filesize并不是一个很好的衡量标准,更重要的是要了解每个工作表中单元格的数量(行数列)。 如果不需要样式,请致电: $objReader->setReadDataOnly(true); 加载文件之前? 如果您不需要访问所有工作表,或者仅访问工作表中的某些单元格,请查看使用 $objReader->setLoadSheetsOnly(array(1,2)) 或者 $objReader->setLoadSheetsOnly(1) 或定义一个readFilter 您正在使用单元缓存吗? 如果是的话,什么方法? 这减慢了加载时间。 回答2 如果您只需要从读取的Excel文件中获取数据,这就是我读取大型Excel文件的方法: 我在服务器上安装了gnumeric,即使用debian / ubuntu:apt-get install gnumeric 然后php调用读取我的excel文件并将其存储到一个二维数据数组中非常简单(尺寸是行和列): system("ssconvert \"$excel_file
  • 将 CSV 文件数据导入 MySQL 表 [重复](Import CSV file data into MySQL table [duplicate])
    问题 这个问题在这里已经有了答案: 使用 PHP 将 CSV 文件数据插入并更新到 MySQL 表中(2 个回答) 6年前关闭。 我正在将记录从 CSV 文件插入到 MySQL 表中; 如果任何记录已存在,则更新该记录并插入其他记录,如果该记录不匹配,则插入所有记录。 这是我的代码 <?php $connect = mysql_connect('localhost','root','root'); if (!$connect) { die('Could not connect to MySQL: ' . mysql_error()); } $cid =mysql_select_db('bizin490_devcredit',$connect); define('CSV_PATH', '/home/ubc/Documents/'); $csv_file = CSV_PATH . "test.csv"; $csvfile = fopen($csv_file, 'r'); $theData = fgets($csvfile); $i = 0; while (!feof($csvfile)) { $csv_data[] = fgets($csvfile, 1024); $csv_array = explode(",", $csv_data[$i]); $insert_csv = array
  • Import CSV file data into MySQL table [duplicate]
    This question already has answers here: Insert and update CSV file data into MySQL table using PHP (2 answers) Closed 6 years ago. I am inserting record from CSV file to MySQL table; if any record already exists update that record and insert other records and if there is no match of the record insert all records. Here is my code <?php $connect = mysql_connect('localhost','root','root'); if (!$connect) { die('Could not connect to MySQL: ' . mysql_error()); } $cid =mysql_select_db('bizin490_devcredit',$connect); define('CSV_PATH', '/home/ubc/Documents/'); $csv_file = CSV_PATH . "test.csv";
  • CSV file upload to handle status update & inserting new records
    While working on a project, hosted locally, I'm stuck at managing CSV uploads. One of tasks require me to upload data on daily basis that has either new entries or updated status for existing entries. There is also an probability that some of the entries (that exists in database) has no updated status. Problem statement; I've created a CSV upload feature that uploads the CSV file to a particular location and imports the information in assigned TABLE. I want to know on what is the best way to verify the database records when I do the CSV upload. It should ideally work as following; if entry
  • Import CSV into MYSQL but ignore header row [duplicate]
    This question already exists: Closed 9 years ago. Possible Duplicate: Read a file from line X to line Y? I know this has been covered before, but all the answers I have found are related to the LOAD DATA INFILE method, which uses IGNORE 1 LINES to ignore the header, I have tried that with my code below but it just throw an error. <?php //database connect info here //check for file upload if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){ //upload directory $upload_dir = "./csv"; //create file name $file_path = $upload_dir . $_FILES['csv_file']['name']; //move
  • 将大量csv文件导入PostgreSQL db的有效方法(Efficient way to import a lot of csv files into PostgreSQL db)
    问题 我看到很多将 CSV 导入 PostgreSQL 数据库的示例,但我需要的是一种将 500,000 个 CSV 导入单个 PostgreSQL 数据库的有效方法。 每个 CSV 有点超过 500KB(总共大约 272GB 的数据)。 CSV 的格式相同,并且没有重复记录(数据是从原始数据源以编程方式生成的)。 我一直在搜索并将继续在线搜索选项,但我希望能以最有效的方式完成这项工作。 我确实对 Python 有一些经验,但会深入研究任何其他似乎合适的解决方案。 谢谢! 回答1 如果您从阅读 PostgreSQL 指南“填充数据库”开始,您会看到几条建议: 在单个事务中加载数据。 如果可能,请使用COPY 。 在加载数据之前删除索引、外键约束等,然后再恢复它们。 PostgreSQL 的 COPY 语句已经支持 CSV 格式: COPY table (column1, column2, ...) FROM '/path/to/data.csv' WITH (FORMAT CSV) 所以看起来你最好根本不使用 Python,或者只使用 Python 来生成所需的COPY语句序列。 回答2 你那里有大量的数据。 我不是 100% 确定 Postgre,但至少 MySQL 提供了一些 SQL 命令,将 csv 直接输入到表中。 这绕过了任何插入检查等
  • Reading CSV file with unescaped enclosures
    I am reading a CSV file but some of the values are not escaped so PHP is reading it wrong. Here is an example of a line that is bad: " 635"," ","AUBREY R. PHILLIPS (1920- ) - Pastel depicting cottages in a steep sided river valley, possibly North Wales, signed and dated 2000, framed, 66cm by 48cm. another of a rural landscape, titled verso "Harvest Time, Somerset" signed and dated '87, framed, 69cm by 49cm. (2) NB - Aubrey Phillips is a Worcestershire artist who studied at the Stourbridge School of Art.","40","60","WAT","Paintings, prints and watercolours", You can see Harvest Time, Somerset