PHP str_getcsv() Function
The PHP str_getcsv() function parses a CSV string and returns an array containing the fields read.
Note: The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.
Syntax
str_getcsv(string, separator, enclosure, escape)
Parameters
string |
Required. Specify the string to parse. |
separator |
Optional. Specify the field delimiter (one single-byte character only). Default is comma ( , ) |
enclosure |
Optional. Specify the field enclosure character (one single-byte character only). Default is ". |
escape |
Optional. Specify the field escape character (at most one single-byte character). Default is backslash (\). An empty string ("") disables the proprietary escape mechanism. |
Return Value
Returns an indexed array containing the fields read.
Example: parsing a CSV string by rows
Lets assume that we have a CSV file called data.csv. This file contains following content:
The example below shows how to use the str_getcsv() function to parse this CSV file by rows.
<?php //getting the CSV string $csvStr = file_get_contents('data.csv'); //displaying the CSV string echo $csvStr; //parsing the CSV string by rows $csvArr = str_getcsv($csvStr, "\n"); echo "\n"; //displaying the result array print_r($csvArr); ?>
The output of the above code will be:
EmpID,Name,Age,Salary 1,John,25,3000 2,Marry,24,2750 3,Jo,27,2800 4,Kim,30,3100 5,Ramesh,28,3000 Array ( [0] => EmpID,Name,Age,Salary [1] => 1,John,25,3000 [2] => 2,Marry,24,2750 [3] => 3,Jo,27,2800 [4] => 4,Kim,30,3100 [5] => 5,Ramesh,28,3000 )
Example: parsing a CSV file into an array
If the field contains line-breaks, this below example can be used to parse the CSV file into an array.
<?php $csv = array_map('str_getcsv', file('data.csv')); //displaying the result array print_r($csv); ?>
The output of the above code will be:
Array ( [0] => Array ( [0] => EmpID [1] => Name [2] => Age [3] => Salary ) [1] => Array ( [0] => 1 [1] => John [2] => 25 [3] => 3000 ) [2] => Array ( [0] => 2 [1] => Marry [2] => 24 [3] => 2750 ) [3] => Array ( [0] => 3 [1] => Jo [2] => 27 [3] => 2800 ) [4] => Array ( [0] => 4 [1] => Kim [2] => 30 [3] => 3100 ) [5] => Array ( [0] => 5 [1] => Ramesh [2] => 28 [3] => 3000 ) )
❮ PHP String Reference