W3docs

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

To write a file in UTF-8 encoding with PHP, you can use the fopen, fwrite, and fclose functions.

To write a file in UTF-8 encoding with PHP, you can use the fopen, fwrite, and fclose functions. Here is an example of how you can use these functions to write a string to a file. PHP writes the exact bytes provided, so if the string is already encoded in UTF-8, the file will be saved as UTF-8:

Example of writing a file in UTF-8 format in PHP

<?php

$str = "Hello, world!";

$file = fopen("output.txt", "w");

fwrite($file, $str);

fclose($file);

This will create a new file called "output.txt" and write the string "Hello, world!" to it. Since the string is already valid UTF-8, the file will be saved in UTF-8 encoding.

If your string uses a different encoding, you can convert it to UTF-8 before writing. Note that utf8_encode() is deprecated in PHP 8.2 and only converts ISO-8859-1 to UTF-8. The modern approach is to use mb_convert_encoding(). Here is an example:

Example of specifying the encoding when creating the file in PHP

<?php

$str = "Hello, world!";

$file = fopen("output.txt", "w");

fwrite($file, mb_convert_encoding($str, "UTF-8", "ISO-8859-1"));

fclose($file);

This will create a new file called "output.txt" and write the converted string to it in UTF-8 encoding.