2014-09-26 39 views
1

我是一個新的Perl,我有一個腳本獲取我的Linux服務器中的所有數據,處理數據並將其形成json字符串。Perl發佈到php

現在的問題是: 如何在另一個域中的我的php代碼中獲取這些數據。我不知道這種方法,我的導師說要把數據從perl發佈到php,我不知道如何。

請指教。 :D

+0

這在Perl的許多部分中都有介紹:http://search.cpan.org/~gaas/HTTP-Message-6.06/lib/HTTP/Request/Common.pm – squiguy 2014-09-26 03:02:05

+0

你可以給出一個關於它是如何工作的概述?只需在下面回答,以便我可以隨時獲得支持。謝謝 – waelhe 2014-09-26 03:05:04

+0

我不知道這種方法的概念。 – waelhe 2014-09-26 03:08:59

回答

2

要將數據發送到服務器,您可以使用libwww這一模塊庫在網絡上進行通信。最好的地方可能是LWP Cookbook,它有一些常用的食譜。您的情況,張貼JSON數據到一個PHP腳本,可以通過使用HTTP::Request創建的請求和發送它使用LWP::UserAgent處理:

use strict; 
use warnings; 
use feature ':5.10'; 
use LWP::UserAgent; 
use JSON; 

# gather your data 
my $data = prepare_data(); 

# Create a POST request with the URL you want your data going to 
my $req = HTTP::Request->new(POST => "http://api.example.com/"); 
# set the content type as JSON 
$req->content_type('application/json'); 
# encode the json, add it to the request 
$req->content(encode_json $data); 

# print out the request object as text 
say $req->as_string; 

# Create a user agent object 
my $ua = LWP::UserAgent->new; 
# send the request using LWP::UserAgent's request method 
my $response = $ua->request($req); 
# see what the response was 
# LWP::UA has a handy is_success method for checking this 
if (! $response->is_success) { 
    die "LWP request failed! " . $response->status_line; 
} 

# print the whole response 
say $response->as_string; 

# get the contents of the response 
my $content = $response->decoded_content; 

這應該給你一個起點,和我以前做的模塊文檔提到更多細節。

+0

感謝很多先生:順便說一下,D – waelhe 2014-09-26 08:28:35

+0

,這是來自PHP的結果? 與設計和其他? – waelhe 2014-09-26 08:31:21

+0

您需要設置您的PHP腳本來處理由perl腳本發送的請求。服務器將處理一些請求(例如,如果您在請求中放置了錯誤的URL,服務器將發回404「未找到」響應),但您可以設置您的PHP腳本以發送適當的數據響應在你的請求。 – 2014-09-26 08:43:59