PHP writeUTF implementation

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).

	public static function writeUTF($string) {
		$utfString = utf8_encode($string);
		$length = strlen($utfString);
		print(pack("n", $length));
		print($utfString);
		flush();
	}

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.

Advertisements

1 Comment »

  1. Lok said

    The reason is that java’s readUTF expects the first two bytes to be the length of packet. That is why pre-pending the length works!

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: