从逗号或制表符分隔的文本文件中读取

时间:2023-01-16 19:51:18

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.

谢谢。

7 个解决方案

#1


34  

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

#2


9  

You can specify a delimiter for fgetcsv(). This is an example of reading tab-delimited files,

您可以为fgetcsv()指定一个分隔符。这是读取表分隔文件的一个例子,

 while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
    ...
 }

#3


3  

Here is an example that will read mydata.txt CSV fields

下面是一个读取mydata的示例。txt CSV域

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

#4


0  

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.

在这里,您可以包含一个带有任意分隔符的regex。这里没有PHP来测试语句,而是PHP .net ->搜索split()。在那里你也有一个关于regex的评论。

#5


0  

you can try explode

你可以试着爆炸

explode ( string $delimiter , string $string [, int $limit ] );

#6


0  

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()

#7


0  

$filePath = "somefile.txt";
$delimiter = "\t";

$file = new \SplFileObject($filePath);
while (!$file->eof()) {
    $line = $file->fgetcsv($delimiter);
    print_r($line);
}

#1


34  

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

#2


9  

You can specify a delimiter for fgetcsv(). This is an example of reading tab-delimited files,

您可以为fgetcsv()指定一个分隔符。这是读取表分隔文件的一个例子,

 while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
    ...
 }

#3


3  

Here is an example that will read mydata.txt CSV fields

下面是一个读取mydata的示例。txt CSV域

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

#4


0  

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.

在这里,您可以包含一个带有任意分隔符的regex。这里没有PHP来测试语句,而是PHP .net ->搜索split()。在那里你也有一个关于regex的评论。

#5


0  

you can try explode

你可以试着爆炸

explode ( string $delimiter , string $string [, int $limit ] );

#6


0  

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()

#7


0  

$filePath = "somefile.txt";
$delimiter = "\t";

$file = new \SplFileObject($filePath);
while (!$file->eof()) {
    $line = $file->fgetcsv($delimiter);
    print_r($line);
}