php 如何在PHP中从csv文件中提取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2805427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:43:38  来源:igfitidea点击:

How to extract data from csv file in PHP

phpcsvsplit

提问by liysd

I have a csv file which looks like this

我有一个看起来像这样的 csv 文件

$lines[0] = "text, with commas", "another text", 123, "text",5;
$lines[1] = "some without commas", "another text", 123, "text";
$lines[2] = "some text with commas or no",, 123, "text";

And I would like to have a table:

我想要一张桌子:

$t[0] = array("text, with commas", "another text", "123", "text","5");
$t[1] = array("some without commas", "another text", "123", "text");
$t[2] = array("some text, with comma,s or no", NULL , "123", "text");

If I use split($lines[0],",")I'll get "text" ,"with commas" ...Is there any elegant way to do it?

如果我使用split($lines[0],",")我会得到"text" ,"with commas" ...有没有什么优雅的方法来做到这一点?

回答by Matt

You can use fgetcsvto parse a CSV file without having to worry about parsing it yourself.

您可以使用fgetcsv来解析 CSV 文件,而不必担心自己解析它。

Example from PHP Manual:

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

回答by Gordon

In addition to Matt's suggestion, you can also use SplFileObjectto read in the file:

除了马特的建议,您还可以使用SplFileObject读取文件:

$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(',', '"', '\'); // this is the default anyway though
foreach ($file as $row) {
    list ($fruit, $quantity) = $row;
    // Do something with values
}

source: http://de.php.net/manual/en/splfileobject.setcsvcontrol.php

来源:http: //de.php.net/manual/en/splfileobject.setcsvcontrol.php

回答by Prabhu M

here is also a simple method to get read csv file.

这里也是一个简单的方法来读取 csv 文件。

$sfp = fopen('/path/to/source.csv','r'); 
$dfp = fopen('/path/to/destination.csv','w'); 
while ($row = fgetcsv($sfp,10000,",","")) { 
 $goodstuff = ""; 
 $goodstuff = str_replace("|",",",$row[2]); 
 $goodstuff .= "\n"; 
 fwrite($dfp,$goodstuff); 
} 
fclose($sfp); 
fclose($dfp);

回答by Liz Eipe C

you can read the data using the following function.

您可以使用以下函数读取数据。

  function readCSV() {
    $csv = array_map('str_getcsv', file('data.csv'));
    array_shift($csv); //remove headers


}

http://www.pearlbells.co.uk/how-to-sort-a1a2-z9z10aa1aa2-az9az10-using-php/

http://www.pearllbells.co.uk/how-to-sort-a1a2-z9z10aa1aa2-az9az10-using-php/

回答by arraksis

Maybe my code solves your problem:

也许我的代码解决了你的问题:

// Parse all content from csv file and generate array from line.
function csv_content_parser($content) {
  foreach (explode("\n", $content) as $line) {
    // Generator saves state and can be resumed when the next value is required.
    yield str_getcsv($line);
  }
}
// Get content from csv file.
$content = file_get_contents('your_file.csv');
// Create one array from csv file's lines.
$data = array();
foreach (csv_content_parser($content) as $fields) {
  array_push($data, $fields);
}

In result you have an array with all values from csv. It would be something like:

结果你有一个包含来自 csv 的所有值的数组。它会是这样的:

Array
(
    [0] => Array
        (
            [0] => text, with commas
            [1] => another text
            [2] => 123
            [3] => text
            [4] => 5
        )

    [1] => Array
        (
            [0] => some without commas
            [1] => another text
            [2] => 123
            [3] => text
        )

    [2] => Array
        (
            [0] => some text, with comma,s or no
            [1] =>  NULL 
            [2] => 123
            [3] => text
        )

)

回答by Harikesh Yadav

Suppose you have a create a function for same things, Then it should look like

假设你有一个为同样的事情创建一个函数,那么它应该看起来像

function csvtoarray($filename='', $delimiter){

    if(!file_exists($filename) || !is_readable($filename)) return FALSE;
    $header = NULL;
    $data = array();

    if (($handle = fopen($filename, 'r')) !== FALSE ) {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {   
            if(!$header){
                $header = $row;
            }else{
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    if(file_exists($filename)) @unlink($filename);

    return $data;
}

$data = csvtoarray('file.csv', ',');

print_r($data);

回答by Emil M

You could use something like https://github.com/htmlburger/carbon-csvthat allows column mapping:

您可以使用允许列映射的类似https://github.com/htmlburger/carbon-csv 的内容

$csv = new \Carbon_CSV\CsvFile('path-to-file/filename.csv');
$csv->set_column_names([
    0 => 'first_name',
    1 => 'last_name',
    2 => 'company_name',
    3 => 'address',
]);
foreach ($csv as $row) {
    print_r($row);
}

The result of the below code would be something like:

以下代码的结果类似于:

Array
(
    [0] => Array
        (
            [first_name] => John
            [last_name] => Doe
            [company_name] => Simple Company Name
            [address] => Street Name, 1234, City Name, Country Name
        )
    [1] => Array
        (
            [first_name] => Jane
            [last_name] => Doe
            [company_name] => Nice Company Name
            [address] => Street Name, 5678, City Name, Country Name
        )
)

Another library that does the same thing(and much more) is http://csv.thephpleague.com/9.0/reader/

另一个做同样事情(以及更多)的图书馆是http://csv.thephpleague.com/9.0/reader/

回答by powtac

When you want to keep the index (first line) for multidimensional result array, you can use:

当要保留多维结果数组的索引(第一行)时,可以使用:

$delim      = ';';
$csvFile    = file($csv_file);
$firstline  = str_getcsv($csvFile[0], $delim);
$data       = array();
foreach ($csvFile as $line) {
    $line   = str_getcsv($line, $delim);
    $data[] = array_combine($firstline, $line);
}

回答by Riss

I've built an application to extract data from a CSV file , this php application was used to show a daily quote for users.

我已经构建了一个应用程序来从 CSV 文件中提取数据,这个 php 应用程序用于向用户显示每日报价。

The full project on github: 365-quotes-php-csv.

github 上的完整项目:365-quotes-php-csv

Also this is the class Code for the application i've built

这也是我构建的应用程序的类代码

  <?php
/*
Main Class 
please note :
1- the CSV file must be comma separated (,) and each line must End with (;).
2- Feel free to edit the all.CSV file and add all of your 366 New Quotes.
3- don't change any thing specially the CSV file Location.
---------------------------------------------------------------------------
RISS.WORK all copy rights reserved 2018
please Don't Remove
Github/RissWork
Email : [email protected]
*/
class Quote{

    //properties
        private $_quote,$_allQuotes;
        private static $_instance = null;

    //Constructor
        private function __construct(){
            //Day Count
            $dayCount = date(z);

            if($this->readCsvAndGetQuote($dayCount)){
                return $this->getQuote();
            }else{
                echo 'Error Cannot open the .CSV File';
            }
        }





    //Methods

    //get Instance
    public function getInstance(){
            if(!isset(self::$_instance)){
                self::$_instance = new Quote();
            }
            return self::$_instance;
        }//end of get Instance




    //get daily Quote   
    public function getQuote(){
            return $this->_quote;
        }//end of get Quote




    //Read CSV
    private function readCsvAndGetQuote($dayCount = 1 ){

        if(($handel = fopen("csv/all.csv" , "r")) !== false){
            $this->_allQuotes = fgetcsv($handel,1000000,';');
            $this->_quote = explode(',',$this->_allQuotes[$dayCount]);
            return true;
        }
        return false;

    }//end of read CSV



}//end of Class

回答by Matoeil

Return a php mapping array with the column of interests :

返回一个带有兴趣列的 php 映射数组:

public function extractCSVDatas($file_uri) {
    $AliasToSystemPathMappingArray = [];
    if (($handle = fopen($file_uri, "r")) !== FALSE) {
      $csv = array_map('str_getcsv', file($file_uri));

      //remove header and choose columns among the list:
      foreach((array_slice($csv,1)) as $line) {
        list($id, $alias, $systemPath) = explode(';',$line[0]);
        $AliasToSystemPathMappingArray[] = [$alias, $systemPath];
      }
      fclose($handle);
    }
    return $AliasToSystemPathMappingArray;
  }