模拟一个服务器(Client)向另外一个服务器(Serve)发送数据,另外一个服务器接受数据
1. 本地起一个PHP服务(服务器一)
php -S 192.168.0.102:8888 C:\Users\laozhongyi\Desktop\phpService.php
或者写一个bat ,名为 phpService.bat
:: php 启动一个web服务
:: 192.168.0.102 为服务器的IP地址,下面我们用的是自己本地机子作为服务器
start php -S 192.168.0.102:8888 C:\Users\laozhongyi\Desktop\phpService.php
同时在该服务下,写一个接受数据的接口:
<?php
//服务器端接受数据
//将整个文件读入一个字符串
$xmldata = file_get_contents("php://input");
$xmldata = (array)simplexml_load_string($xmldata);
//var_export,函数的第二个参数设置为 TRUE,从而返回变量的表示, 不设置第2个参数,效果则和var_dump()一样,纯是输出
$data = var_export($xmldata,TRUE); //
//file_get_contents: 将一个字符串写入文件。该函数将返回写入到文件内数据的字节数,失败时返回FALSE
$ret = file_put_contents('C:\Users\laozhongyi\Desktop/phpService.log', $data);
if (false == $ret) {
exit("写入失败");
}
echo $data;
exit();
2. 一个服务器发送数据(服务器二), [该服务器向服务器一发送数据]
该代码我们写在一个服务上,请求 http://admin.hotel.test/test/curl 此地址,就执行了下列代码
$xml = '<?xml version="1.0" encoding="utf-8"?>
<profile>
<sha1>adsfadsf</sha1>
<user_id>asdfasdf</user_id>
<album_id>asdf</album_id>
<album_name>asdf</album_name>
<tags>asdfasd</tags>
<title>asdfasdf</title>
<content>asdfadsf</content>
<type>asdfasdf</type>
<copyright>asdfasdf</copyright>
</profile>';
$url = 'http://192.168.0.102:8888';//这里是1 中我们启的一个服务,监听请求的一个接口
$header = ['Content-type: text/xml'];//定义content-type为xml
$ch = curl_init(); //初始化curl
curl_setopt($ch, \CURLOPT_URL, $url);//设置链接
curl_setopt($ch, \CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
curl_setopt($ch, \CURLOPT_HTTPHEADER, $header);//设置HTTP头
curl_setopt($ch, \CURLOPT_POST, 1);//设置为POST方式
curl_setopt($ch, \CURLOPT_POSTFIELDS, $xml);//POST数据
$response = curl_exec($ch);//接收返回信息
if(curl_errno($ch)){//出错则显示错误信息
print curl_error($ch);
}
curl_close($ch); //关闭curl链接
var_dump( $response);//显示返回信息