php

How to Use str_getcsv() Function in PHP

In the world of PHP programming, there are numerous built-in functions that assist developers in manipulating and processing data efficiently. One such function is the str_getcsv() function. This powerful function is designed specifically for parsing CSV (Comma-Separated Values) strings, allowing developers to extract and work with structured data stored in this popular format.

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:

str_getcsv(string,separator,enclosure,escape)

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:

<?php
$string = 'UK,Canada,Germany,Italy,Turkey';
$data = str_getcsv($string);
var_dump($data);
?>

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:

<?php
$csv = array_map('str_getcsv', file('data.csv'));
// displaying the result array
echo "<pre>";
print_r($csv);
echo "</pre>";
?>

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.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.