In PHP, what are some best practices for handling CSV data manipulation, such as converting character sets and selecting specific columns?

When handling CSV data manipulation in PHP, it is important to consider issues such as converting character sets and selecting specific columns. To convert character sets, you can use functions like mb_convert_encoding(). To select specific columns, you can read the CSV file line by line and extract the desired columns based on their position.

// Example of converting character sets and selecting specific columns from a CSV file

// Specify the input and output character sets
$inputCharset = 'ISO-8859-1';
$outputCharset = 'UTF-8';

// Open the CSV file for reading
$csvFile = fopen('data.csv', 'r');

// Loop through each line of the CSV file
while (($data = fgetcsv($csvFile)) !== false) {
    // Convert character sets for each column
    foreach ($data as $key => $value) {
        $data[$key] = mb_convert_encoding($value, $outputCharset, $inputCharset);
    }
    
    // Select specific columns (e.g., columns 0 and 2)
    $selectedData = array($data[0], $data[2]);
    
    // Process the selected data
    print_r($selectedData);
}

// Close the CSV file
fclose($csvFile);