What is str_getcsv() in PHP?
The str_getcsv() is a built-in function in PHP that allows developers to parse and extract data from CSV (Comma-Separated Values) strings. The function takes a CSV string as input and returns an array containing the individual values. This function handles various scenarios, such as handling quoted strings, custom delimiters, and escaping special characters. Whether you need to import/export data or perform data analysis tasks, you will need the str_getcsv() service at some point.
Syntax
The syntax of str_getcsv() is given below:
The str_getcsv() function accepts one compulsory parameter, string, and three optional parameter separator, enclosure, and escape.
- string: The string specifies the string to be parsed.
- separator: The separator is an optional parameter that specifies the field separator, and the default is a comma.
- enclosure: The enclosure is the field enclosure character, and the default is “.
- escape: The character that specifies the escape character, and the default is a backslash (\).
The str_getscv() function returns the CSV field in an array.
Example 1
In the following example, we have initialized the string and used the str_getscv() function to get the array of strings. We then stored the array in the variable data and displayed it on the console:
Example 2
You can also parse the CSV file in PHP using the str_getcsv() function. We have a CSV file named data saved on the device with the following details:
The following code is used to parse the above CSV file data using the str_getcsv() function. The data is displayed on the browser as a multidimensional array:
Bottom Line
The str_getcsv() is a built-in PHP function that simplifies the parsing of CSV strings, enabling efficient extraction and manipulation of structured data stored in this widely used format. With its ability to handle various scenarios like quoted strings, custom delimiters, and special character escaping, str_getcsv() empowers developers to import/export data and perform data analysis tasks effortlessly.