1.编写curl类,进行网页内容抓取
<BR>class CurlUtil <BR>{ <BR>private $curl; <BR>private $timeout = 10; <BR>/** <BR>* 初始化curl对象 <BR>*/ <BR>public function __construct() <BR>{ <BR>$this->curl = curl_init(); <BR>curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); <BR>curl_setopt($this->curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); <BR>curl_setopt($this->curl, CURLOPT_HEADER, false); //设定是否显示头信息 <BR>curl_setopt($this->curl, CURLOPT_NOBODY, false); //设定是否输出页面内容 <BR>curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, $this->timeout); <BR>curl_setopt($this->curl, CUR<mark>6来源gaodaimacom搞#^代%!码网</mark><strong>搞gaodaima代码</strong>LOPT_FOLLOWLOCATION, true); <BR>curl_setopt($this->curl, CURLOPT_AUTOREFERER, true); <BR>} <BR>/** <BR>* 注销函数 关闭curl对象 <BR>*/ <BR>public function __destruct() <BR>{ <BR>curl_close($this->curl); <BR>} <BR>/** <BR>* 获取网页的内容 <BR>*/ <BR>public function getWebPageContent($url) <BR>{ <BR>curl_setopt($this->curl, CURLOPT_URL, $url); <BR>return curl_exec($this->curl); <BR>} <BR>} <BR>
2.创建curl对象
<BR>$CurlUtil = new CurlUtil(); <BR>
3.抓取yahoo搜索结果
<BR>function getYahooSearch(CurlUtil $curl, $key) <BR>{ <BR>$key = urlencode($key); <BR>$searchUrl = "http://boss.yahooapis.com/ysearch/web/v1/$key?appid=你的雅虎appid&lang=tzh®ion=hk&abstract=long&count=20&format=json&start=0&count=10"; <BR>$josnStr = $curl->getWebPageContent($searchUrl); <BR>$searchDataInfo = json_decode($josnStr, true); <BR>$searchData = $searchDataInfo['ysearchresponse']['resultset_web']; <BR>$returnArray = array(); <BR>if (!empty($searchData)) { <BR>foreach ($searchData as $data) { <BR>$returnArray[] = array("url" => $data['url'], "date" => $data['date'], 'title' => strip_tags($data['title']), 'description' => strip_tags($data['abstract'])); <BR>} <BR>} <BR>return $returnArray; <BR>} <BR>
4.测试结果
var_dump(getYahooSearch($CurlUtil, “百度”));