Unlikely Teacher

1. Share Everything* [Programming Gotchas, Technology News, Insights on Living and Everything in Between]

PHP writeUTF implementation

May 12th, 2009 · No Comments · Java, PHP

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.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • StumbleUpon
  • Tumblr
  • Twitter

Tags: ·

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment