27
votes

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.

Any ideas how to handle this?

Thanks.

7

7 Answers

42
votes

Starting from PHP 5.3, you can use str_getcsv() to read individual lines using different delimiters.

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

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

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

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

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

Read the whole file, or line by line and split it using 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.

0
votes

you can try explode

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

Here is the function that I added to my utilities library for future use. I derived it from NSSec's answer.

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.

/**
*   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()
0
votes
$filePath = "somefile.txt";
$delimiter = "\t";

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