"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Remove BOM from Imported CSV Files?

How to Remove BOM from Imported CSV Files?

Published on 2024-11-08
Browse:331

How to Remove BOM from Imported CSV Files?

Removing BOM from Imported CSV Files

When importing a .csv file, it's common to encounter a BOM (Byte Order Mark), which can interfere with data processing. This issue can be resolved by removing the BOM from the file.

One method to remove the BOM is using regular expressions:

$new_file = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $file);

However, this method may not always be reliable. An alternative approach using the file_get_contents function is recommended:

$content = file_get_contents($filepath);
file_put_contents($filepath, str_replace("\xEF\xBB\xBF", '', $content));

This approach overwrites the file with the BOM-removed data, allowing you to continue processing the file without BOM interference.

However, using file_put_contents closes the file, which may disrupt your existing script. To resolve this, use fopen to reopen the file after writing:

$file = fopen($filepath, "r") or die("Error opening file");

By implementing these techniques, you can effectively remove the BOM from imported .csv files and ensure smooth data processing within your script.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3