How can I write a file in UTF-8 format?

How can I write a file in UTF-8 format?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Myth of Automatic UTF-8 Conversion

You cannot simply tell PHP to "save a file in UTF-8" and expect it to happen automatically. The code snippet you are using reads the raw bytes from a file and writes them back to a new location with the Content-Type header set correctly for the browser. However, the actual data inside the file remains unchanged because file_put_contents() is a binary operation by default. It treats the input string as a sequence of bytes and writes them exactly as they are.

If your source files contain characters like é, ñ, or Chinese hieroglyphs encoded in ISO-8859-1 (Latin-1) or Windows-1252, those multi-byte sequences will be interpreted incorrectly by any UTF-8-aware tool later on. You will end up with mojibake—garbled text that looks like é instead of é.

To fix this, you must explicitly convert the character encoding during the write process. This requires understanding how PHP handles strings internally versus how it writes to disk.

Using mb_convert_encoding() for Files

The most robust way to handle this in PHP is to use the mb_convert_encoding() function before writing the file. This function translates the byte sequences from the source encoding into the target UTF-8 format.

Here is how you modify your script:

header('Content-type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');

$fpath = 'folder';
$d = dir($fpath);

while (false !== ($a = $d->read())) {
    if ($a != '.' and $a != '..') {
        $npath = $fpath . '/' . $a;
        
        // Read the file as raw bytes to avoid internal conversion issues
        $data = file_get_contents($npath);

        // Detect source encoding or assume common legacy encodings
        $sourceEncoding = mb_detect_encoding($data, ['ISO-8859-1', 'Windows-1252', 'UTF-8'], true);

        if ($sourceEncoding !== 'UTF-8') {
            $convertedData = mb_convert_encoding(
                $data, 
                'UTF-8', 
                $sourceEncoding
            );
            
            // Write the converted data to the new location
            file_put_contents('tempfolder/' . $a, $convertedData);
        } else {
            // If it's already UTF-8, write as-is to preserve exact content
            file_put_contents('tempfolder/' . $a, $data);
        }
    }
}
$d->close();

In this approach, mb_detect_encoding() attempts to guess the source encoding based on the byte patterns. If it detects a legacy encoding, mb_convert_encoding() rewrites the bytes into valid UTF-8 sequences. This ensures that when you open the file in a modern editor or send it to a browser, the characters render correctly.

Handling Binary Files and Performance

Be extremely careful not to apply this logic to non-text files. If your directory contains images, PDFs, or executable scripts, passing them through mb_convert_encoding() will destroy their integrity. UTF-8 conversion only applies to text content.

If you are processing a large number of files, reading the entire file into memory with file_get_contents() can be inefficient and prone to memory exhaustion errors (fatal errors) if a file is several hundred megabytes in size. For large datasets, consider using stream wrappers. You can read the file in chunks using fopen(), convert each chunk, and write it back incrementally. This keeps memory usage low regardless of file size.

The Limitation of file_put_contents

A common mistake developers make is assuming that setting mb_internal_encoding('UTF-8') changes how file_put_contents() behaves. It does not. That function ignores the internal encoding setting and writes raw bytes. If you want to write a literal UTF-8 byte sequence, you must ensure the string variable holding the data actually contains those bytes (which requires conversion) before passing it to the file system call.

Command-Line Alternatives

If you are dealing with a massive migration of an entire site and don't want to write a custom PHP script, standard Unix utilities offer powerful one-liners. The iconv tool is specifically designed for this task:

find folder -type f \( -name "*.html" -o -name "*.php" \) -exec sh -c 'for f; do iconv -f UTF-8 -t UTF-8 "$f" > "tempfolder/$f"; done' _ {} +

Note: This assumes the source is already UTF-8. If the source is mixed, you need to specify the correct source encoding in the -f flag.

For mixed encodings, recode or specialized scripts using Python's chardet might be more reliable than relying solely on PHP's detection heuristics.

Final Considerations

Once the files are converted, always verify the result. Open a random sample of converted files in a text editor that shows encoding (like VS Code or Sublime Text) and ensure no mojibake exists. Also, remember that changing file content does not automatically update the <meta charset> tag inside HTML files. You may need to use regex within your conversion script to locate and replace legacy meta tags with the correct UTF-8 declaration:

$pattern = '/<meta http-equiv="Content-Type" content="text\/html; charset=[^"]*>/i';
$replacement = '<meta charset="UTF-8">';
$str = preg_replace($pattern, $replacement, $convertedData);

This ensures that browsers correctly interpret the new byte sequences you just generated.

Our network