Archive for the ‘ 程式小心得 ’ Category

java & php 的 timestamp 為不同單位

一般以來,我以為 timestamp 應該是要從 1970 年零點零分零秒開始,至目前時刻所經過的「秒」數,才算是 timestamp 。不過後來查了一下 java 的 timestamp 的說明,他是從 1970 年零點零分零秒開始到現在的「微秒」數。所以二者之間相差了 1000 倍。

Java 的 timestamp的說明如下:
long getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

PHP 的 timestamp 說明如下:
int time ( void )
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

所以如果 php & java 要作 web service 的服務的話,記得要處理這部份的轉換。

Java 部份的程式碼:

import java.util.Calendar;
class Time
{
public static void  main(String arg[]) {
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime().getTime());
}
}

結果如下:

whatup@whatup:/tmp$ java Time
1257688227061

PHP 部份的程式碼:

 echo time();

結果如下:

whatup@whatup:/tmp$ php time.php
1257688308

利用 curl 平行抓取多個網頁

如果一次要抓多個網頁,如果使用一個一個 curl 慢慢抓的話,實在是太慢了。假設一個網頁要 0.3 sec 的話,十個網頁需要抓時就要 3 sec 了。利用這個 curl 的 mutli handle 功能,可以同時抓取 N 個網頁,這樣抓取網頁速度會有明顯的提昇。

其實也可以利用這個方法,來試試自已的網頁的存取速度怎麼樣。不過如果一次開 50 個以上,感覺抓取速度會受到影響。所以還是別同時抓取太多網頁比較好。

範例程式碼如下:

 0);

foreach($curl_obs as $curl_ob)
{
  $content = curl_multi_getcontent($curl_ob);
  var_dump(strlen($content));
}
foreach($curl_obs as $curl_ob)
{
  curl_multi_remove_handle($mh, $curl_ob);
}
curl_multi_close($mh);
?>

執行結果:

whatup@whatup:/tmp$ php curl_multi.php
int(222)
int(9490)

google app enging for java 用來跑 PHP

前幾天 google 發布了 google app engine 支援了 java 後,就有聽說有人可以利用 Quercus 專案,來支援 PHP ,這是一個令人興奮的消息啊。像我不太會寫 python 的人,有 PHP 的支援,更可以讓更多的 web developer 快速上手。

幾天後,有一家公司的 blog 上發表了一篇「Run PHP on the Google App Engine」,他們已經成功的在 app engine 上執行 php 了。

他所列的步驟如下:

  1. Register a free account.
  2. Download this file to your computer.
  3. Edit application XML tag in the file war\WEB-INF\appengine-web.xml to the name of the application you have registered.
  4. Finally upload your application. I downloaded Google App Engine SDK for Java and use the following command in windows.

但我在本地端測試的時候,因為少了一些 package 所以沒辦法在本地端執行,你可以到 http://www.codehaus.org/ 下載 jetty package ,並且解壓縮到 app-engine 的 lib 目錄,即可以使用 dev_appserver.sh 這個指令在本地端測試了。Depoy 到 google 的 GAE 上的話,就不用這這個 package 了。

另外他沒有支援 Mysql 之類的關聯性資料庫,所以如果要 port 一些跟資料庫相關的東西的話,應該要自行改寫其資料庫的部份。

jquery 判定 browser 種類

在工作中,有一些需要為 IE 作特別的 hack ,例如像 IE 的 option 不吃 onclick 的事件之類的。但又不想讓他影響到 IE 之外的 browser 。在 jquery 裡面,可以使用下列的參數來判定是不是使用 IE 。

if(jQuery.browser.msie) alert("這個 browser 是 IE");

當然其他的參數也可以判定 browser 的板本與種類,可以參考Utilities/jQuery.browser這份文件。