PHP - cURL implementation to send Get and Post requests

 
 

1. Introduction to cURL

  cURL is a tool that uses URL syntax to transfer files and data, and supports many protocols, such as HTTP, FTP, TELNET, etc. Best of all, PHP also supports the cURL library. This article will introduce some advanced features of cURL and how to use it in PHP.

2. Basic structure

  Before learning more complex functions, let's take a look at the basic steps to make a cURL request in PHP:

  (1) Initialization 

    curl_init()

  (2) Set variables 

    curl_setopt() . Most importantly, all mysteries are here. There is a long list of cURL parameters that can be set, which specify various details of the URL request. It can be difficult to read and understand it all at once, so today we'll just try the more common and useful options.

  (3) Execute and get the result 

    curl_exec()

  (4) Release the cURL handle

    curl_close()

3. cURL implements Get and Post

3.1 Get method implementation

  //initialize
  $ch = curl_init();

  //Set options, including URL
  curl_setopt($ch, CURLOPT_URL, "http://www.nettuts.com");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);

  //Execute and get HTML document content
  $output = curl_exec($ch);

  //Release the curl handle
  curl_close($ch);

  //Print the obtained data
  print_r($output);

3.2 Post method implementation

   $url = "http://localhost/web_services.php";
  $post_data = array ("username" => "bob","key" => "12345");

  $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($output);

  

  以上方式获取到的数据是json格式的,使用json_decode函数解释成数组。

  $output_array = json_decode($output,true);

  如果使用json_decode($output)解析的话,将会得到object类型的数据。


小鸡:

sprintf() 函数把格式化的字符串写入一个变量中。
$txt = sprintf("%s world. Day number %u",$str,$number);

echo $txt;   输出:Hello world. Day number 123


urlencode()函数原理就是首先把中文字符转换为十六进制,然后在每个字符前面加一个标识符%,对字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。

urldecode()函数与urlencode()函数原理相反,用于解码已编码的 URL 字符串,其原理就是把十六进制字符串转换为中文字符。

$url = 'http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sn=%s';
$targetUrl = sprintf($url, $ak, urlencode($location), $output, $sn);



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325797443&siteId=291194637