写了一个简单的返回json数据接口。然后用curl 的post、get两种提交方式取得接口的返回数据。
* User: wzx * Date: 2016/7/27 * Time: 11:33 */test/api目录下接口文件名:testapi.php
error_reporting(0);
if(!empty($_GET)){
$cond=$_GET['cond'];
}
if(!empty($_POST)){
$cond=$_POST['cond'];
}
function api($cond){
if($cond=='ok')
{
echo json_encode(array(a=>'y1',b=>'y2',c=>'y3'));
}else
{
echo json_encode(array(na=>'n1',b=>'n2',c=>'n3'));
}
}api($cond);<?php /** * Created by PhpStorm. * User: wxz * Date: 2016/7/27 * Time: 11:57 */ $url = "http://localhost/test/api/testapi.php"; $post_data = array ("cond" => "ok"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // post数据 curl_setopt($ch, CURLOPT_POST, 1); // post的变量 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); $output = curl_exec($ch); curl_close($ch); //打印获得的数据 print_r(json_decode($output,true));<?php /** * Created by PhpStorm. * User: wzx * Date: 2016/7/27 * Time: 11:53 */ error_reporting(0); $url='http://localhost/test/api/testapi.php?cond=ok'; //初始化 $ch = curl_init(); //设置选项,包括URL curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); //执行并获取HTML文档内容 $output = curl_exec($ch); //释放curl句柄 curl_close($ch); //打印获得的数据 print_r($output);