1. cURL Introduction
CURL is a tool that uses URL syntax to transmit files and data. It supports many protocols, such as HTTP, FTP, and TELNET. The best thing is that PHP also supports the cURL library. This article describes 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 for creating cURL requests in PHP:
(1) initialization
Curl_init ()
(2) set variables
Curl_setopt (). This is the most important thing. There is a long string of cURL parameters that can be set. They can specify the details of URL requests. It may be difficult to read and understand all at once, so today we will only try out the more common and useful options.
(3) execute and obtain results
Curl_exec ()
(4) release the cURL handle
Curl_close ()
3. cURL implements Get and Post
3.1 Get implementation
Copy codeThe Code is as follows:
// Initialization
$ Ch = curl_init ();
// Set options, including URL
Curl_setopt ($ ch, CURLOPT_URL, "http://www.jb51.net ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_HEADER, 0 );
// Execute and obtain the HTML document content
$ Output = curl_exec ($ ch );
// Release the curl handle
Curl_close ($ ch );
// Print the obtained data
Print_r ($ output );
3.2 Post Implementation
Copy codeThe Code is as follows:
$ 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 Data
Curl_setopt ($ ch, CURLOPT_POST, 1 );
// Post variable
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data );
$ Output = curl_exec ($ ch );
Curl_close ($ ch );
// Print the obtained data
Print_r ($ output );
The data obtained in the preceding method is in json format and is interpreted as an Array Using the json_decode function.
$ Output_array = json_decode ($ output, true );
If json_decode ($ output) is used for parsing, data of the object type will be obtained.