Example 1. A simple curl gets Baidu HTML crawler (crawler):
spider.php
<? PHP /* get Baidu HTML simple web crawler */$curl//resource (2, Curl)curl_exec ($curl ); Curl_close ($curl);
Visit this page:
Example 2. Download a webpage (Baidu) and replace Baidu in the content with ' PHP ' after output
<?PHP/*Download a webpage (Baidu) and replace Baidu in the content with ' PHP ' after output*/$curl=curl_init (); curl_setopt ($curl, Curlopt_url, ' http://www.baidu.com ');//set the URL to access the Web pagecurl_setopt ($curl, Curlopt_returntransfer,true);//Do not print directly after execution$output= Curl_exec ($curl);//ExecutionCurl_close ($curl);//Turn off CurlEcho Str_replace(' Baidu ', ' PHP ',$output);
Visit this page:
Example 3. Call Wenservice for weather information
WEATHERWS (Http://www.webxml.com.cn/WebServices/WeatherWS.asmx?op=getWeather) provides a variety of ways to get weather information, such as Soap1.1,soap1.2,http Get,http Post.
Now use Curl to simulate HTTP POST to get weather data.
weather.php
<?PHP/*Curl Call WebService Query current weather in Beijing*/$data= ' Thecityname= Beijing ';$curl=curl_init (); curl_setopt ($curl, Curlopt_url, ' Http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName '); curl_setopt ($curl, curlopt_header,0); curl_setopt ($curl, curlopt_returntransfer,1); curl_setopt ($curl, curlopt_post,1);//Post Modecurl_setopt ($curl, Curlopt_postfields,$data);//set the parameters of the postcurl_setopt ($curl, Curlopt_httpheader,Array(' Application/x-www-form-urlencoded;charset=utf-8 ', ' content-length: '.strlen($data)) ; curl_setopt ($curl, Curlopt_useragent, "user-agent:mozilla/5.0 (Windows NT 5.1; rv:24.0) gecko/20100101 firefox/24.0 ");//Fix Error: "Object reference not set to an instance of an object. "$rtn= Curl_exec ($curl);if(!curl_errno ($curl)){ //$info = Curl_getinfo ($curl); Print_r ($info); Echo $rtn;}Else{ Echo' Curl error: '. Curl_error ($curl);} Curl_close ($curl);
Page output:
It can also be used in CMD:
C:\users\administrator>d:d: \>cd practise/php/curld: \practise\php\curl>php-f weather.php > Weather.txt
Save the returned results in a TXT file (if an error occurs, refer to PHP run to see the workaround for call to undefined function curl_init ().
CURL Learning Notes and summaries (2) web crawler, weather forecast