2016-10-04 54 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倍的減少! –