向右转(尽量每天更新…)

2008-05-07

使用php-js-ext在PHP内解析javascript脚本

Filed under: 转贴 — admin @ 10:31 am

当你在因个人兴趣爱好而开发PHP程序时,面对可以达到你的目的却长达千行以上的js脚本,你有精力去用php重写它么?想用PHP模拟用户行为么?但却 遇到js泛滥的站点……一个不为人所知的php扩展项目可以满足这些需求,这个扩展的目的就是在php内解释javascript。

项目主页 http://aurore.net/projects/php-js/

php-js-ext是mozilla javascript解释器和php之间的一座桥梁,因此我们除了需要下载最后版本为0.1.2的php-js-ext,还需要下载最新版本为1.7.0的mozilla
js,链接如下(php-js-ext 0.1.2发布时是配合js-1.5工作,但经我测试,也可以配合js-1.7工作)

CODE:

wget http://aurore.net/projects/php-js/php-js-ext-0.1.2.tar.bz2
wget http://ftp.mozilla.org/pub/mozilla.org/js/js-1.7.0.tar.gz
系统是CentOS 4.5

1.安装mozilla js

解开js-1.7.0.tar.gz

CODE:

tar zxvf js-1.7.0.tar.gz
cd js/src
开始编译(如不能完成编译见最后说明)

CODE:

make -f Makefile.ref

拷贝libjs.so到/usr/lib

CODE:

cp Linux_All_DBG.OBJ/libjs.so /usr/lib
ldconfig
拷贝头文件到/usr/include

CODE:

cp jsapi.h jscompat.h jslong.h jsosdep.h jsotypes.h jspubtd.h jstypes.h jsproto.tbl jsconfig.h Linux_All_DBG.OBJ/jsautocfg.h /usr/include/

自此mozilla js的安装工作就完成了,下面开始进行php-js-ext的安装

2.安装php-js-ext

解开php-js-ext-0.1.2.tar.bz2

CODE:

tar jxvf php-js-ext-0.1.2.tar.bz2
cd php-js-ext-0.1.2
创造环境并设定扩展版本(如有一个以上的php存在,需要输入phpize的完整路径)

CODE:

/path/phpize

配置并编译安装(如有一个以上的php存在或configure无法找到php的位置,需要在configure的时候指定-with-php-config=/path/php-config)

CODE:

./configure
make && make install
如果一切无误,js.so已经在你的php的lib目录

最后,修改你的php.ini,在相应的位置加入extension=js.so,并确认extension_dir的设定正确。

输出一个phpinfo的结果,以查看js.so是否被正确加载和可能的错误信息。
如果一切无误的话,我们就可以开始使用这个功能了。

这里附上官方网站的使用说明:

QUOTE:

A simple ./configure; make; make install should do the trick. Make sure to add an extension=js.so line to your php.ini/php.d. Note: you need to install libjs first. If you’re using a Redhat-esque system, you can use the SRPM provided above, else, use the TBZ.

Then, just use js_eval to evaluate your JavaScript. js_eval returns the value returned by the JavaScript interpreter to PHP.

For example:

js_eval(”var a = 123;”);
js_eval(”var b = 456;”);

$c = js_eval(”[a, b];”);
echo “a is “.$c[0].”\n”;
echo “b is “.$c[1].”\n”;

js_eval(”var sum = function(x, y) { return x + y; }”);

$d = js_eval(”sum(a, b);”);
echo “The sum of a and b is “.$d.”\n”;

Would produce:

a is 123
b is 456
The sum of a and b is 579

js_eval takes an optional boolean argument, assoc, which returns objects as associative arrays instead of PHP objects.

The php-js execution environment provides two built-in JavaScript system functions:

* print
* gc

print outputs its argument to the php output stream.

gc forces garbage collection within the JavaScript environment.
(非 Redhat的linux发行版可能会在mozilla js的编译过程中产生错误,是因为连接器和内核已经不对a.out提供支持,我们需要用gcc来生成一个共享库而不是ld了。打开 js/src/config/Linux_All.mk,将第50行的 MKSHLIB = $(LD) -shared $(XMKSHLIBOPTS) 更改为 MKSHLIB = $(CC) -shared $(XMKSHLIBOPTS) ,make -f Makefile.ref clean后再次尝试编译。)

来源:SunGod

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress