php請求API介面方法
執法丶大隊發表於2020-04-06
thinkphp下直接放入公共函式即可.
-
-
-
-
-
-
function get_url($url)
-
{
-
$ch = curl_init();
-
curl_setopt($ch, CURLOPT_URL,$url);
-
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
-
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
-
$result = curl_exec($ch);
-
curl_close ($ch);
-
return $result;
-
}
-
-
-
-
-
-
-
function post_url($url, $data)
-
{
-
$curl = curl_init();
-
curl_setopt($curl, CURLOPT_URL, $url);
-
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
-
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
-
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
-
-
-
curl_setopt($curl, CURLOPT_POST, 1);
-
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
-
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
-
curl_setopt($curl, CURLOPT_HEADER, 0);
-
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
-
-
$tmpInfo = curl_exec($curl);
-
if(curl_errno($curl))
-
{
-
echo 'Errno'.curl_error($curl);
-
}
-
curl_close($curl);
-
return $tmpInfo;
-
}
-
-
-
-
-
-
function object_to_array($obj){
-
$_arr = is_object($obj) ? get_object_vars($obj) :$obj;
-
foreach ($_arr as $key=>$val){
-
$val = (is_array($val) || is_object($val)) ? object_to_array($val):$val;
-
$arr[$key] = $val;
-
}
-
return $arr;
-
}
-
-
-
-
-
-
function arrayToXml($arr)
-
{
-
$xml = "<xml>";
-
foreach ($arr as $key=>$val)
-
{
-
if (is_numeric($val))
-
{
-
$xml.="<".$key.">".$val."</".$key.">";
-
-
}
-
else
-
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
-
}
-
$xml.="</xml>";
-
return $xml;
-
}
-
-
-
-
-
-
-
-
function get_api($apiurl, $param, $format = 'array', $method = 'get'){
-
if (is_array($param)) {
-
$string = '?';
-
foreach ($param as $key => $val){
-
$string .= $key.'='.$val.'&';
-
}
-
$param = substr($string, 0, -1);
-
}
-
$url = $apiurl.$param;
-
switch (strtolower($method)){
-
case '':$json = get_url($url);break;
-
case 'get':$json = get_url($url);break;
-
case 'g':$json = get_url($url);break;
-
case 'post':$json = post_url($apiurl,$param);break;
-
case 'p':$json = post_url($apiurl,$param);break;
-
default:$json = get_url($url);break;
-
}
-
$start = strpos($json, '{');
-
$end = -1*(strlen(strrchr($json, '}'))-1);
-
if ($end) {
-
$json = substr($json, $start, $end);
-
}else {
-
$json = substr($json, $start);
-
}
-
$obj = json_decode($json);
-
$array = object_to_array($obj);
-
$xml = arrayToXml($array);
-
switch ($format){
-
case 'array':$data = $array;break;
-
case 'arr':$data = $array;break;
-
case 'obj':$data = $obj;break;
-
case 'object':$data = $obj;break;
-
case 'json':$data = $json;break;
-
default:$data = $array;
-
}
-
return $data;
-
}