We currently have an application in Groovy/Grails/Java that we're slowly porting to PHP (for more affordable hosting costs).
We encountered a problem when we needed to convert one of our routines for writing out a binary file. We were using Java's DataOutputStream.writeUTF(String) method and had a hard time trying to write binary data in PHP.
After much research on the web, we found a method in PHP called
pack(). Below is our PHP implementation of Java's DOS.writeUTF(String).
[sourcecode language='php']
public static function writeUTF($string) {
$utfString = utf8_encode($string);
$length = strlen($utfString);
print(pack("n", $length));
print($utfString);
flush();
}
[/sourcecode]
We don't claim this to be the exact equivalent of the method, but it gets the job done and the receiving end of the file was able to parse the binary file properly with the new PHP implementation with no modifications to the client code.
Please checkout the
pack() documentation for more details.