0

I must write a binary file with php, but I think that I don't use the correct method.

I use this function:

$ptr = fopen("file.txt", 'wb');
fwrite($ptr, $Str);
fclose($ptr); 

I write this string (chaotic representation of 0 and 1):

$Str="00000001001110000000000100000100000000000000001000000010000000010000001100000101000000000000010000000001000000000000010100000";

I thought that opening the file with OpenOffice I would not have seen the text of zeros and ones, but instead I was sure I saw a chaotic sequence of characters. Why I see the zeros and ones in open office? How can I do to write the raw data with php?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • It seems to work for me... Perhaps it is an issue with your OpenOffice... have you tried it with http://www.libreoffice.org/? – Lix May 14 '12 at 16:51

2 Answers2

1

If you write text in a file, even when open in binary mode, you will get text in the file. Your 0 is not stored as a zero bit, but as the ASCII representation of the 0 caracter.

Use the binary format for numbers in PHP, for instance:

$var = OxFF; // equals to 1111 1111 in binary.

More in the manual

adrien
  • 4,399
  • 26
  • 26
1

You can write any character with the chr() function.

Alternatively, you can do something like "\x0A" (that's a newline character).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • thanks, but i want write a raw file, non ascii file. I would like write some data each one of 8 bit, surely i must write all data without separator, knowing the length of the data that is constant 8-bit I can read any data. That way I can write and retrieve a lot of data by reducing the space in the file than to write it in ascii. – Maurizio Petrini May 14 '12 at 20:58