![]() |
Converting file content to a byte array in PHP is a useful technique for various applications, including file manipulation, data processing, and when working with binary files like images or PDFs. PHP offers multiple ways to read file content and convert it into a byte array, providing flexibility to handle different scenarios effectively. Using file_get_contents() and unpack() FunctionsOne of the simplest ways to convert file content to a byte array in PHP is by using the file_get_contents() function to read the file content as a string, and then using unpack() function to convert the string to a byte array.
Output Array ( [1] => 60 [2] => 115 [3] => 118 [4] => 103 [5] => 32 [6] => 120 [7] => 109 [8] => 108 [9] => 110 [10] => 115 [11] => 61 [12] => 34 [13] => 1... Using fread() and unpack() FunctionsFor larger files, or when you need more control over the reading process (such as reading in chunks), fread in combination with fopen and unpack can be used.
Output
Here, fopen opens the file in binary read mode (‘rb’), filesize gets the size of the file, and fread reads the file content based on the provided size. unpack then converts this content into a byte array. Using File and Array MappingAnother approach involves reading the file into an array of lines with file, then using array_map to convert each character of every line into its corresponding byte value.
Output
Using file and str_split FunctionsAnother efficient way to convert file content to a byte array in PHP involves reading the file into a string using the file_get_contents function, then converting this string to an array of characters using the str_split function. Finally, we use array_map to convert each character to its corresponding byte value. Example: The following example show how to use file_get_contents, str_split, and array_map to convert file content to a byte array in PHP.
Output Array ( [0] => 87 [1] => 101 [2] => 108 [3] => 99 [4] => 111 [5] => 109 [6] => 101 [7] => 32 [8] => 116 [9] => 111 [10] => 32 [11] => 71 [12] => 101 [13] => 101 [14] => 107 [15] => 115 [16] => 102 [17] => 111 [18] => 114 [19] => 71 [20] => 101 [21] => 101 [22] => 107 [23] => 115 [24] => 87 [25] => 101 [26] => 108 [27] => 99 [28] => 111 [29] => 109 [30] => 101 [31] => 32 [32] => 116 [33] => 111 [34] => 32 [35] => 71 [36] => 101 [37] => 101 [38] => 107 [39] => 115 [40] => 102 [41] => 111 [42] => 114 [43] => 71 [44] => 101 [45] => 101 [46] => 107 [47] => 115 [48] => 72 [49] => 101 [50] => 108 [51] => 108 [52] => 111 [53] => 32 [54] => 87 [55] => 101 [56] => 108 [57] => 99 [58] => 111 [59] => 109 [60] => 101 ) |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |