首先,模拟get请求:
curlget.php
<?php
$url='http://localhost/lianxi/curl/post.php?name=HZD';
$ch = curl_init();// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
$data=curl_exec($ch);
curl_close($ch);
$data=json_decode($data,TRUE);
var_dump($data);
?>
输出结果:
array (size=1) 'name' => 'HZD' (length=3)
curlpost.php
<?php
$curlPost=array(
'name' => 'hzd',
'school' => 'HS'
);
$urlpost='http://localhost/lianxi/curl/post.php';
$ch = curl_init();//初始化curl
curl_setopt($ch,CURLOPT_URL,$urlpost);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
$res1=json_decode($data, TRUE);
var_dump($res1);
?>
输出结果:
array (size=2) 'name' => 'hzd' (length=3) 'school' => 'HS' (length=2)
<?php
$respdata=array();
if ($_POST) {
$respdata['name']=$_POST['name'];
$respdata['school']=$_POST['school'];
echo json_encode($respdata);exit();
}
if ($_GET) {
$respdata['name']=$_GET['name'];
echo json_encode($respdata);exit();
}
$respdata['success']=0;
echo json_encode($respdata);exit();
?>
来源:CSDN
作者:黄志东iOSphp
链接:https://blog.csdn.net/u012890809/article/details/43760655