php 从逗号或制表符分隔的文本文件中读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1372223/
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
Reading from comma or tab delimited text file
提问by veli
I need to read the data from a file that can be either comma or tab delimited. I now that there is a function getcsv but it accepts only one possible delimiter.
我需要从逗号或制表符分隔的文件中读取数据。我现在有一个函数 getcsv 但它只接受一个可能的分隔符。
Any ideas how to handle this?
任何想法如何处理这个?
Thanks.
谢谢。
回答by NSSec
Starting from PHP 5.3, you can use str_getcsv()to read individual lines using different delimiters.
从 PHP 5.3 开始,您可以使用str_getcsv()读取使用不同分隔符的单行。
$someCondition = someConditionToDetermineTabOrComma();
$delimiter = $someCondition ? "," : "\t";
$fp = fopen('mydata.csv', 'r');
while ( !feof($fp) )
{
$line = fgets($fp, 2048);
$data = str_getcsv($line, $delimiter);
doSomethingWithData($data);
}
fclose($fp);
回答by ZZ Coder
You can specify a delimiter for fgetcsv(). This is an example of reading tab-delimited files,
您可以为 fgetcsv() 指定分隔符。这是读取制表符分隔文件的示例,
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
...
}
回答by Jignesh Prajapati
Here is an example that will read mydata.txtCSV fields
这是一个将读取mydata.txtCSV 字段的示例
$tab = "\t";
$fp = fopen('mydata.txt', 'r');
while ( !feof($fp) )
{
$line = fgets($fp, 2048);
$data_txt = str_getcsv($line, $tab);
//Get First Line of Data over here
print_r($data_txt);
exit;
}
fclose($fp);
回答by Joe Devine
Here is the function that I added to my utilities library for future use. I derived it from NSSec's answer.
这是我添加到实用程序库中以备将来使用的函数。我是从NSSec 的回答中推导出来的。
This solution allows you to specify whether you want to use the first line as keys for the array. I will probably add the ability to pass an array to be used for keys for the $first_line_keys parameter at some point.
此解决方案允许您指定是否要将第一行用作数组的键。我可能会在某个时候添加传递用于 $first_line_keys 参数键的数组的功能。
/**
* Converts a CSV file into an array
* NOTE: file does NOT have to have .csv extension
*
* $file - path to file to convert (string)
* $delimiter - field delimiter (string)
* $first_line_keys - use first line as array keys (bool)
* $line_lenght - set length to retrieve for each line (int)
*/
public static function CSVToArray($file, $delimiter = ',', $first_line_keys = true, $line_length = 2048){
// file doesn't exist
if( !file_exists($file) ){
return false;
}
// open file
$fp = fopen($file, 'r');
// add each line to array
$csv_array = array();
while( !feof($fp) ){
// get current line
$line = fgets($fp, $line_length);
// line to array
$data = str_getcsv($line, $delimiter);
// keys/data count mismatch
if( isset($keys) && count($keys) != count($data) ){
// skip to next line
continue;
// first line, first line should be keys
}else if( $first_line_keys && !isset($keys) ){
// use line data for keys
$keys = $data;
// first line used as keys
}else if($first_line_keys){
// add as associative array
$csv_array[] = array_combine($keys, $data);
// first line NOT used for keys
}else{
// add as numeric array
$csv_array[] = $data;
}
}
// close file
fclose($fp);
// nothing found
if(!$csv_array){
return array();
}
// return csv array
return $csv_array;
} // CSVToArray()
回答by JupiterN
$filePath = "somefile.txt";
$delimiter = "\t";
$file = new \SplFileObject($filePath);
while (!$file->eof()) {
$line = $file->fgetcsv($delimiter);
print_r($line);
}
回答by StampedeXV
Read the whole file, or line by line and split it using split.
读取整个文件,或逐行读取并使用 split 拆分它。
There you can include a regex with arbitrary delimiters. I have not PHP here to test a statement, but php.net -> search for split(). There you also have a comment relating to regex.
在那里你可以包含一个带有任意分隔符的正则表达式。我这里没有用 PHP 来测试语句,而是在 php.net -> 搜索 split()。您还有一条与正则表达式相关的评论。

