2014-09-26 57 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