Write file php utf8

Как записать файл в формате UTF-8?

У меня есть куча файлов, которые не входят в кодировку UTF-8, и я конвертирую сайт в кодировку UTF-8.

Я использую простой скрипт для файлов, которые я хочу сохранить в utf-8, но файлы сохраняются в старой кодировке:

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; $data=file_get_contents($npath); file_put_contents('tempfolder/'.$a, $data); >> 

Как сохранить файлы в кодировке utf-8?

file_get_contents / file_put_contents не будут магически конвертировать кодировку.

Вы должны явно преобразовать строку; например, с помощью iconv() или mb_convert_encoding() .

$data = file_get_contents($npath); $data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING'); file_put_contents('tempfolder/'.$a, $data); 

Или, альтернативно, с фильтрами потока PHP:

$fd = fopen($file, 'r'); stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING'); stream_copy_to_stream($fd, fopen($output, 'w')); 

Добавить спецификацию: UTF-8

file_put_contents($myFile, "\xEF\xBB\xBF". $content); 

В Unix / Linux простая команда оболочки может использоваться альтернативно для преобразования всех файлов из заданного каталога:

Может быть запущен через PHPs exec ().

//add BOM to fix UTF-8 in Excel fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) )); 

Я получил эту строку от Cool

Если вы хотите использовать recode рекурсивно и фильтровать для типа, попробуйте следующее:

find . -name "*.html" -exec recode L1..UTF8 <> \; 
$f=fopen($filename,"w"); # Now UTF-8 - Add byte order mark fwrite($f, pack("CCC",0xef,0xbb,0xbf)); fwrite($f,$content); fclose($f); 

Я собрал все вместе и получил простой способ конвертировать текстовые файлы ANSI в «UTF-8 No Mark»:

function filesToUTF8($searchdir,$convdir,$filetypes) < $get_files = glob($searchdir.'*', GLOB_BRACE); foreach($get_files as $file) < $expl_path = explode('/',$file); $filename = end($expl_path); $get_file_content = file_get_contents($file); $new_file_content = iconv(mb_detect_encoding($get_file_content, mb_detect_order(), true), "UTF-8", $get_file_content); $put_new_file = file_put_contents($convdir.$filename,$new_file_content); >> 

Использование: filesToUTF8 (‘C: / Temp /’, ‘C: / Temp / conv_files /’, ‘php, txt’);

  1. Откройте свои файлы в ноутбуке Windows
  2. Измените кодировку как кодировку UTF-8
  3. Сохраните файл
  4. Попробуй еще раз! : О)

Источник

fwrite

fwrite() writes the contents of data to the file stream pointed to by stream .

Parameters

A file system pointer resource that is typically created using fopen() .

The string that is to be written.

If length is an int , writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Return Values

fwrite() returns the number of bytes written, or false on failure.

Errors/Exceptions

fwrite() raises E_WARNING on failure.

Changelog

Examples

Example #1 A simple fwrite() example

$filename = ‘test.txt’ ;
$somecontent = «Add this to the file\n» ;

// Let’s make sure the file exists and is writable first.
if ( is_writable ( $filename ))

// In our example we’re opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that’s where $somecontent will go when we fwrite() it.
if (! $fp = fopen ( $filename , ‘a’ )) echo «Cannot open file ( $filename )» ;
exit;
>

// Write $somecontent to our opened file.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo «Cannot write to file ( $filename )» ;
exit;
>

echo «Success, wrote ( $somecontent ) to file ( $filename )» ;

> else echo «The file $filename is not writable» ;
>
?>

Notes

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>

Note:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with ‘b’ included in fopen() mode parameter.

Note:

If stream was fopen() ed in append mode, fwrite() s are atomic (unless the size of data exceeds the filesystem’s block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite() ; all of the data will be written without interruption.

Note:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

$fp = fopen ( ‘data.txt’ , ‘w’ );
fwrite ( $fp , ‘1’ );
fwrite ( $fp , ’23’ );
fclose ( $fp );

Читайте также:  Bootstrap tooltip with css

// the content of ‘data.txt’ is now 123 and not 23!
?>

See Also

  • fread() — Binary-safe file read
  • fopen() — Opens file or URL
  • fsockopen() — Open Internet or Unix domain socket connection
  • popen() — Opens process file pointer
  • file_get_contents() — Reads entire file into a string
  • pack() — Pack data into binary string

User Contributed Notes 33 notes

After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php’s fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.

Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.

This means the example fwrite_stream() code from the docs, as well as all the «helper» functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.

Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.

// BROKEN function — infinite loop when fwrite() returns 0s
function fwrite_stream ( $fp , $string ) <
for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) <
$fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) <
return $written ;
>
>
return $written ;
>
?>

if you need a function that writes all data, maybe try

/**
* writes all data or throws
*
* @param mixed $handle
* @param string $data
* @throws \RuntimeException when fwrite returned * @return void
*/
/*private static*/ function fwrite_all ( $handle , string $data ): void
$original_len = strlen ( $data );
if ( $original_len > 0 ) $len = $original_len ;
$written_total = 0 ;
for (;;) $written_now = fwrite ( $handle , $data );
if ( $written_now === $len ) return;
>
if ( $written_now < 1 ) throw new \ RuntimeException ( "could only write < $written_total >/ < $original_len >bytes!» );
>
$written_total += $written_now ;
$data = substr ( $data , $written_now );
$len -= $written_now ;
// assert($len > 0);
// assert($len === strlen($data));
>
>
>

Читайте также:  Java foreach двумерный массив

$handles can also be used to output in console like below example

fwrite(STDOUT, «Console Output»);

Источник

fopen

fopen() binds a named resource, specified by filename , to a stream.

Parameters

If filename is of the form «scheme://. «, it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers ) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

A list of possible modes for fopen() using mode
mode Description
‘r’ Open for reading only; place the file pointer at the beginning of the file.
‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+’ Open for reading and writing; otherwise it has the same behavior as ‘w’ .
‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’ Create and open for reading and writing; otherwise it has the same behavior as ‘x’ .
‘c’ Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’ ), nor the call to this function fails (as is the case with ‘x’ ). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock() ) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
‘c+’ Open the file for reading and writing; otherwise it has the same behavior as ‘c’ .
‘e’ Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Note:

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems (Mac OS Classic) used \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will «look funny».

Windows offers a text-mode translation flag ( ‘t’ ) which will transparently translate \n to \r\n when working with the file. In contrast, you can also use ‘b’ to force binary mode, which will not translate your data. To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

The default translation mode is ‘b’ . You can use the ‘t’ mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the ‘b’ in all other cases.

If you specify the ‘t’ flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note:

For portability, it is also strongly recommended that you re-write code that uses or relies upon the ‘t’ mode so that it uses the correct line endings and ‘b’ mode instead.

Note: The mode is ignored for php://output , php://input , php://stdin , php://stdout , php://stderr and php://fd stream wrappers.

The optional third use_include_path parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.

Читайте также:  Dynamic Scaling Example

Источник

Оцените статью