如何用php在一个文件中写入非ASCII数据

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?

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

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

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