How can the array returned by file() be properly handled and manipulated to replace semicolons with commas in a CSV file in PHP?
The array returned by file() in PHP reads each line of a file into an array element. To replace semicolons with commas in a CSV file, you can loop through each element of the array, use str_replace() to replace semicolons with commas, and then write the modified lines back to the file.
$fileLines = file('example.csv'); // Read file into array
$modifiedLines = array(); // Create an array to store modified lines
foreach ($fileLines as $line) {
$modifiedLines[] = str_replace(';', ',', $line); // Replace semicolons with commas
}
file_put_contents('example.csv', implode("\n", $modifiedLines)); // Write modified lines back to file
Keywords
Related Questions
- How can one optimize the search functionality to improve performance and accuracy?
- How can one ensure compatibility with multiple server configurations when developing an application that requires accessing https pages in PHP?
- What best practices should be followed when using foreach loops with PHP arrays?