PHP: 将字节转换为可读值(KB,MB,GB,TB,PB,EB,ZB,YB), Converting bytes to human readable values (KB, MB, GB, TB, PB, EB, ZB, YB) with PHP

PHP: 将字节转换为可读值(KB,MB,GB,TB,PB,EB,ZB,YB), Converting bytes to human readable values (KB, MB, GB, TB, PB, EB, ZB, YB) with PHP
PHP: 将字节转换为可读值(KB,MB,GB,TB,PB,EB,ZB,YB), Converting bytes to human readable values (KB, MB, GB, TB, PB, EB, ZB, YB) with PHP

 

在计算领域,诸如kylobytes,gigabytes等术语用于描述某些存储设备和系统存储器中的空间。通常在Web应用程序中,它们会向用户显示,以描述他们在云中或其他需要以字节为单位进行测量的功能中有多少空间。显然,如果你向他们展示字节数,他们就不会知道文件/空闲空间有多大,相信我,他们只会看到数字。

这就是为什么你需要使用已知的KB,MB,GB等测量符号以特定的符号显示这些信息。在PHP中,这可以通过我们今天在本文中与您分享的两种方法轻松完成。它们(具有相同名称的方法)都希望第一个参数的字节数为整数或字符串,并返回一个字符串,其中包含用户可以读取的字符串。

 

A.基于1024字节的短版本

基于1024的版本假设单个KB具有1024个字节,并且在仅3行代码中,您可以轻松地将多个字节转换为可读符号:

注意

理论上,KB完全由1024组成,这种方法最准确

<?php 

/**
 * Converts a long string of bytes into a readable format e.g KB, MB, GB, TB, YB
 * 
 * @param {Int} num The number of bytes.
 */
function readableBytes($bytes) {
    $i = floor(log($bytes) / log(1024));
    $sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

    return sprintf('%.02F', $bytes / pow(1024, $i)) * 1 . ' ' . $sizes[$i];
}

// "1 KB"
echo readableBytes(1024);

 

该方法可以通过以下方式使用:

<?php 

// "1000 B"
echo readableBytes(1000);

// "9.42 MB"
echo readableBytes(9874321);

// "9.31 GB"
// The number of bytes as a string is accepted as well
echo readableBytes("10000000000");

// "648.37 TB"
echo readableBytes(712893712304234);

// "5.52 PB"
echo readableBytes(6212893712323224);

 

B.基于1000字节的版本

另一个选项提供了将字节转换为可读格式,但计数为1KB等于1000字节,而不是像第一个选项那样1024。这种增加会降低准确度,但与第一种方法的逻辑几乎相同:

<?php 

/**
 * Converts a long string of bytes into a readable format e.g KB, MB, GB, TB, YB
 * 
 * @param {Int} num The number of bytes.
 */
function readableBytes($num) {
    $neg = $num < 0;

    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

    if ($neg){
        $num = -$num;
    }

    if ($num < 1){
        return ($neg ? '-' : '') . $num . ' B';
    }
    
    $exponent = min(floor(log($num) / log(1000)), count($units) - 1);
    
    $num = sprintf('%.02F', ($num / pow(1000, $exponent)));
    
    $unit = $units[$exponent];

    return ($neg ? '-' : '') . $num . ' ' . $unit;
}

 

该方法可以通过以下方式使用:

<?php

// "1 KB"
echo readableBytes(1000);

// "9.87 MB"
echo readableBytes(9874321);

// "10 GB"
// The number of bytes as a string is accepted as well
echo readableBytes("10000000000");

// "712.89 TB"
echo readableBytes(712893712304234);

// "6.21 PB"
echo readableBytes(6212893712323224);

 

 

本文: PHP: 将字节转换为可读值(KB,MB,GB,TB,PB,EB,ZB,YB), Converting bytes to human readable values (KB, MB, GB, TB, PB, EB, ZB, YB) with PHP

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.