1.cURL Introduction
CURL is a tool that uses URL syntax to transfer files and data, and supports many protocols, such as HTTP, FTP, Telnet, and so on. Best of all, PHP also supports CURL libraries. This article will introduce some of the advanced features of CURL and how to use it in PHP.
2. Basic structure
Before you learn more complex features, take a look at the basic steps in creating a Curl request in PHP:
(1) initialization
Curl_init ()
(2) Set Variable
curl_setopt (). Most important, all the occult are here. There is a long string of curl parameters that can be set to specify the details of the URL request. It may be difficult to read it all at once and understand it, so today we'll just try the more common and useful options.
(3) Execute and obtain the result
Curl_exec ()
(4) Release curl handle
Curl_close ()
3.cURL implement GET and post
3.1 Get Mode implementation
Copy Code code as follows:
Class
$ch = Curl_init ();
Setting options, including URLs
curl_setopt ($ch, Curlopt_url, "http://www.jb51.net");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 0);
Execute and get the contents of the HTML document
$output = curl_exec ($ch);
Release Curl handle
Curl_close ($ch);
Print the obtained data
Print_r ($output);
3.2 Post Method implementation
Copy Code code 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's 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 above method is in JSON format and the Json_decode function is used to interpret the array.
$output _array = Json_decode ($output, true);
If you use Json_decode ($output) parsing, you will get data of type object.