Read a text file


	if (is_file('some_filename.json'))
	{
		$file_contents = 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
	}

 

 

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *