str_pad str_split pack unpack

这些函数对处理指定的格式字符很有帮助。

下面是一个将xml转化为二进制格式的例子。

<?php
//$str = file_get_contents( 'D:/12181331779587.xml' );
//$str = base64_encode($str);
//file_put_contents( 'D:/12181331779587_cp.xml', $str );

$file1 = 'D:/12181332227753_exp.xml';
$file2 = 'D:/12181331779587_encode.xml';
$file3 = 'D:/12181331779587_decode.xml';

$size = filesize($file1);

echo '文件大小为:'.$size;
echo "\n<br>转化为二进制 ...";

$content = file_get_contents($file1);
//$content = gzcompress($content);
//$size = strlen($content);
//echo 'gz后文件大小为:'.$size;
//
//$content = base64_encode($content);
//$size = strlen($content);
//echo 'base后文件大小:'.$size;

$content = bstr2bin($content);


$fp = fopen($file2, 'w');
fwrite($fp, $content);
fclose($fp);

$size2 = filesize($file2);

echo '转化成二进制后文件大小为:'.$size2;

$content = bin2bstr($content);

$fp = fopen($file3, 'w');
fwrite($fp, $content);
fclose($fp);


function bin2bstr($input)
// Convert a binary expression (e.g., "100111") into a binary-string
{
    if (!is_string($input)) return null; // Sanity check

    // Pack into a string
    $input = str_split($input, 4);
    $str = '';
    foreach ($input as $v)
    {
        $str .= base_convert($v, 2, 16);
    }

    $str =  pack('H*', $str);

    return $str;
}

function bstr2bin($input)
// Binary representation of a binary-string
{
    if (!is_string($input)) return null; // Sanity check

    // Unpack as a hexadecimal string
    $value = unpack('H*', $input);

    // Output binary representation
    $value = str_split($value[1], 1);
    $bin = '';
    foreach ($value as $v)
    {
        $b = str_pad(base_convert($v, 16, 2), 4, '0', STR_PAD_LEFT);

        $bin .= $b;
    }

    return $bin;
}
?>

你可能感兴趣的:(PHP,职场,格式转换,常用函数,休闲)