首頁  >  文章  >  後端開發  >  PHP中使用cURL實作Get和Post請求的方法

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

PHP中文网
PHP中文网原創
2017-07-29 14:37:2627179瀏覽

    1.curl介紹 

    curl 是一個利用url語法規定來傳輸檔案和資料的工具,支援許多協議,如http、ftp、telnet等。最爽的是,php也支援 curl 函式庫。本文將介紹 curl 的一些高階特性,以及在php中如何運用它。

    2.基本結構

    在學習更複雜的功能之前,先來看看在php中建立curl請求的基本步驟:

    (1)初始化    curl_init()

    (2)設定變數  curl_setopt() 

    最為重要,一切玄妙均在此。有一長串curl參數可供設置,它們能指定url請求的各個細節。要一次全部看完並理解可能比較困難,所以今天我們只試試那些更常用、更有用的選項。

    (3)執行並取得結果  curl_exec()

    (4) 釋放curl句柄    curl_close() 

    3.curl實作get和post

    3.1 get方式實作

//初始化
  $ch = curl_init();
  //设置选项,包括url
  curl_setopt($ch, curlopt_url, "http://www.learnphp.cn");
  curl_setopt($ch, curlopt_returntransfer, 1);
  curl_setopt($ch, curlopt_header, 0);
  //执行并获取html文档内容
  $output = curl_exec($ch);
  //释放curl句柄
  curl_close($ch);
  //打印获得的数据
  print_r($output);

    3.2 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請求的方法的內容,更多相關內容請關注php中文網(www.php.cn)!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn