有兩種不同的方式,我會這樣做:
\ 1。在ruby中,建立一個只偵聽'::'(或127.0.0.1,如果你不喜歡ipv6)的非HTTP服務器。然後,每當您的PHP腳本需要做某件事時,它都可以連接到服務器並將數據傳遞給它。這將是最快的解決方案,因爲每次PHP需要做某件事時,ruby腳本都不需要啓動。
例紅寶石:
require 'mechanize'
require 'socket'
def do_mechanize_stuff(command, *args)
case command
when 'search_google'
# search google with args.join(' ')
when 'answer_questions_on_stackoverflow'
# answer questions on stackoverflow
# with mechanize
end
'the result to pass to PHP'
end
srv = TCPServer.new '::', 3000
loop do
Thread.new(srv.accept) do |sock|
sock.write(
do_mechanize_stuff *sock.gets.split(' ')
)
sock.close
end
end
例紅寶石客戶端:(你需要這個翻譯成PHP)
require 'socket'
# This is a script that searches google
# and writes the results to stdout.
s = TCPSocket.new 'localhost', 3000
s.puts 'search_google how to use a keyboard'
until (r = s.gets).nil?
print r # a search result.
end
你可以使用像http://god.rubyforge.org/過程看工具,保持服務器運行。
\ 2。使ruby腳本成爲一個命令行工具,並使用PHP中的exec
來調用它。
一個示例命令行腳本:
require 'mechanize'
def do_mechanize_stuff(command, *args)
# ... from previous example
end
do_mechanize_stuff ARGV.shift, ARGV
感謝,我會嘗試 – Rick 2010-07-04 18:46:53