场景:各种文件的大小以字节形式存储在数据库中.将此大小信息格式化为千字节,兆字节和千兆字节的最佳方法是什么?例如,我有一个Ubuntu显示为"5.2 MB(5445632字节)"的MP3.我如何在网页上显示为"5.2 MB"并且文件小于1兆字节显示为KB并且文件1千兆字节及以上显示为GB?
我在处理大文件时没有经验,所以我不知道该怎么做.我试图使用file_get_contents读取几个大文件; 任务是使用preg_replace()清理和消除它们.
我的代码在小文件上运行良好; 但是,大文件(40 MB)会触发内存耗尽错误:
PHP Fatal error: Allowed memory size of 16777216 bytes exhausted (tried to allocate 41390283 bytes)
Run Code Online (Sandbox Code Playgroud)
我正在考虑使用fread(),但我不确定它是否也能正常工作.这个问题有解决方法吗?
感谢您的输入.
这是我的代码:
<?php
error_reporting(E_ALL);
##get find() results and remove DOS carriage returns.
##The error is thrown on the next line for large files!
$myData = file_get_contents("tmp11");
$newData = str_replace("^M", "", $myData);
##cleanup Model-Manufacturer field.
$pattern = '/(Model-Manufacturer:)(\n)(\w+)/i';
$replacement = '$1$3';
$newData = preg_replace($pattern, $replacement, $newData);
##cleanup Test_Version field and create comma delimited layout. …Run Code Online (Sandbox Code Playgroud) php ×2