2016-10-04 53 views
5

我有一个整数写二进制数据到文件,从字面上

Array 
(
    [0] => Array 
     (
      [0] => 1531412763 
      [1] => 1439959339 
      [2] => 76 
      [3] => 122 
      [4] => 200 
      [5] => 4550 
      [6] => 444 
     ) 
... 

等等,我想,如果我看着它,仿佛它是一个数据库的阵列 - 在最外层数组的元素是行内部数组的元素是列。

我想将这些信息保存到一个文件中,以便稍后能够检索它,但我想将它保存为二进制数据以节省空间。基本上,如果我将示例1531412763中的第一个整数写入文件,它将占用10个字节,但如果我可以将它保存为有符号整数,则它将占用4个字节。

我看了一些其他答案,所有建议使用fwrite,我不明白如何使用这种方式?

+0

[包(http://php.net/manual/en/function.pack.php)? – Zimmi

+0

如果你真的需要节省空间,为什么不压缩数据呢?在这一点上可能也是如此。 – Andrew

+0

@Zimmi是的,这正是我需要的,但是我需要为每个单独的值调用'pack'还是有更简单的方法? –

回答

3

要将二进制数据写入文件,可以使用函数pack()unpack()。 Pack会产生一个二进制字符串。由于结果是一个字符串,您可以将这些整数串联到一个字符串中。然后将此字符串作为一行写入您的文件。

通过这种方式,您可以使用file()轻松阅读,这会将文件放入一行数组中。然后每行只有unpack(),并且你有你的原始数组。

像这样:

$arr = array(
    array (1531412763, 1439959339), 
    array (123, 456, 789), 
); 

$file_w = fopen('binint', 'w+'); 

// Creating file content : concatenation of binary strings 
$bin_str = ''; 
foreach ($arr as $inner_array_of_int) { 
    foreach ($inner_array_of_int as $num) { 
     // Use of i format (integer). If you want to change format 
     // according to the value of $num, you will have to save the 
     // format too. 
     $bin_str .= pack('i', $num); 
    } 

    $bin_str .= "\n"; 
} 

fwrite($file_w, $bin_str); 
fclose($file_w); 


// Now read and test. $lines_read will contain an array like the original. 
$lines_read = []; 
// We use file function to read the file as an array of lines. 
$file_r = file('binint'); 

// Unpack all lines 
foreach ($file_r as $line) { 
    // Format is i* because we may have more than 1 int in the line 
    // If you changed format while packing, you will have to unpack with the 
    // corresponding same format 
    $lines_read[] = unpack('i*', $line); 
} 

var_dump($lines_read); 
+1

如果每一行都包含完全相同数量的元素,甚至不需要换行,那么只需计算转换为二进制时的行长度,然后使用'fread($ handle,$ length)'。 –

+0

绝对!并按照您在上次对该问题的评论中的建议优化格式。 – Zimmi

+0

使用这种方法,而不是存储纯文本,我设法保存了一些空间。从'2.72GB'降到'400MB',这是一个6.8倍的减少! –