Read a text file
if (is_file('some_filename.json'))
{
$FileContent = file_get_contents('some_filename.json');
}
Read a binary file to an array
Your file may be byte based by PHP works to stop you operating at a raw byte level, so you have to workaround that a bit by using unpack
$filename = "myfile.bin";
if (is_file($filename))
{
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
$byteArray = unpack("C*",$contents); //<<<Warning the outputted array starts from [1] not [0] !!!!!! Bloody PHP...
//N.B. the C* designates unsigned char repeating, but actually unpack can create arrays that are not byte based no problem from teh file...
If your file is very big then get clever with fread etc and only read chunks at a time
Read binary file 1 byte at a time
Using ord() – good for 1 byte at a time
fseek($handle, -100, SEEK_END );
for ($Count = 0; $Count < 100; $Count++)
{
$OurByteValue = ord(fread($handle, 1));
//echo "[" . intval($OurByteValue) . "]"; //Display integer
echo "[" . sprintf("%02X", $OurByteValue) . "]"; //Display hex
}
Using unpack() – better for arrays of bytes really, but works fine for 1 byte at a time too
//Get and display the first 100 bytes of the file, reading 1 byte at a time
fseek($handle, 0, SEEK_SET );
for ($Count = 0; $Count < 100; $Count++)
{
$FileByteArray = unpack("C*", fread($handle, 1)); //<<<Warning the outputted array starts from [1] not [0] !!!!!! Bloody PHP...
//echo "[" . intval($FileByteArray[1]) . "]"; //Display intiger
echo "[" . sprintf("%02X", $FileByteArray[1]) . "]"; //Display hex
}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.