CURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, such as HTTP, FTP, and TELNET. 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.
Fortunately, 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) initialize curl_init ()
(2) setting the variable curl_setopt () // is the most important. all the mysteries are here. 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 the result curl_exec ()
(4) release curl handle curl_close ()
3. CURL implements Get and Post
1) Get implementation
// Initialize $ ch = curl_init (); // Set options, including URLcurl_setopt ($ ch, curlOPT_URL, "http://www.eer3.com"); 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 );
2) Post implementation
$ Url = "http: // localhost/web_services.php"; $ post_data = array ("username" => "uname", "key" => "123456 "); $ ch = curl_init (); curl_setopt ($ ch, curlOPT_URL, $ url); curl_setopt ($ ch, curlOPT_RETURNTRANSFER, 1); // post data curl_setopt ($ ch, curlOPT_POST, 1); // The 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.