PHP str_getcsv() Function
Topic: PHP String ReferencePrev|Next
Description
The str_getcsv()
function parse a CSV (comma-separated values) string into an array.
The following table summarizes the technical details of this function.
Return Value: | Returns an indexed array containing the CSV fields read. |
---|---|
Changelog: | Since PHP 7.4.0, an empty string ("" ) for escape parameter now disables the proprietary escape mechanism. Previously, an empty string was treated like the default parameter value. |
Version: | PHP 5.3.0+ |
Syntax
The basic syntax of the str_getcsv()
function is given with:
str_getcsv(string, separator, enclosure, escape);
The following example shows the str_getcsv()
function in action.
Example
Run this code »<?php
// Sample CSV string
$str = "Apple,Banana,Orange,Strawberry";
// Parsing CSV string
$arr = str_getcsv($str);
print_r($arr);
?>
Parameters
The str_getcsv()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the string to parse. |
separator | Optional. Specifies the field separator (one character only). Default is comma (, ). |
enclosure | Optional. Specifies the field enclosure character (one character only). Default value is a double quotation mark (" ). |
escape | Optional. Specifies the escape character (one character only). Default is backslash (\ ). An empty string ("" ) disables the proprietary escape mechanism. |
More Examples
Here're some more examples showing how str_getcsv()
function actually works:
The following example shows how a CSV string having field with embedded comma will be parsed:
Example
Run this code »<?php
// Sample CSV string
$str = 'Avatar,2009,"James Cameron","Sci-fi, Action"';
// Parsing CSV string
$arr = str_getcsv($str);
print_r($arr);
?>