Home > Article > Backend Development > How to Remove BOM Encoding from CSV Files in PHP?
When importing .csv files, the presence of a Byte Order Mark (BOM) can cause encoding issues. Here's a comprehensive solution to remove the BOM from imported .csv files:
Issue:
Struggling to remove BOM using preg_replace or str_replace.
Code Attempt:
<code class="php">$filepath = get_bloginfo('template_directory')."/testing.csv"; // ... $file = fopen($filepath, "r") or die("Error opening file"); // ...</code>
Solution:
<code class="php">// Read the file contents $content = file_get_contents($filepath); // Remove the BOM $content = str_replace("\xEF\xBB\xBF",'', $content); // Overwrite the file with the updated content file_put_contents($filepath, $content);</code>
<code class="php">function removeBomUtf8($s){ if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){ return substr($s,3); }else{ return $s; } }</code>
Note:
The FILE_PUT_CONTENTS function automatically closes the file, so there's no need to manually close it with fclose().
By implementing these solutions, you can successfully remove the BOM from imported .csv files and ensure correct data parsing.
The above is the detailed content of How to Remove BOM Encoding from CSV Files in PHP?. For more information, please follow other related articles on the PHP Chinese website!