1. 程式人生 > >PHP中使用cURL實現Get和Post請求的方法

PHP中使用cURL實現Get和Post請求的方法

data print str close arr 設置 高級特性 post數據 decode

cURL 是一個利用URL語法規定來傳輸文件和數據的工具,支持很多協議,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 庫。本文將介紹 cURL 的一些高級特性,以及在PHP中如何運用它。
cURL實現Get和Post
Get方式實現

//初始化
  $ch = curl_init();
  //設置選項,包括URL
  curl_setopt($ch, CURLOPT_URL, "http://www.jb51.net");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  
//執行並獲取HTML文檔內容   $output = curl_exec($ch);   //釋放curl句柄   curl_close($ch);   //打印獲得的數據   print_r($output);

Post方式實現

 $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類型的數據。

PHP中使用cURL實現Get和Post請求的方法