PHP採集代碼
採集http://www.01job.cn/asp/itjob.asp該頁面中職位列表頭三條的記錄
看了很多的PHP採集教程了 還是不會寫 所以這裡請教了....
以下是My Code,運行時了錯:
include("function.php");
$url="http://www.01job.cn/asp/itjob.asp";
$ft["title"]["begin"]="
";
$rs=pick($url,$ft,$th);
echo $rs["title"];
echo "
內容:".$rs["content"];
?>
function.php
//擷取網頁內容
Function fetch_urlpage_contents($url){
$c=file_get_contents($url);
return $c;
}
//擷取匹配內容
Function fetch_match_contents($begin,$end,$c)
{
$begin=change_match_string($begin);
$end=change_match_string($end);
if(@preg_match("/{$begin}(.*?){$end}/i",$c,$rs))
{return $rs[1];}
else {return "";}
}
//轉義Regex字串
Function change_match_string($str){
//注意,以下只是簡單轉義
$old=array("/","$");
$new=array("\/","\$");
$str=str_replace($old,$new,$str);
return $str;
}
//採集網頁
Function pick($url,$ft,$th)
{
$c=fetch_urlpage_contents($url);
foreach($ft as $key => $value)
{
$rs[$key]=fetch_match_contents($value["begin"],$value["end"],$c);
if(is_array($th[$key]))
{ foreach($th[$key] as $old => $new)
{
$rs[$key]=str_replace($old,$new,$rs[$key]);
}
}
}
return $rs;
}
?>
------解決方案--------------------
//擷取網頁內容
Function fetch_urlpage_contents($url){
for($i=0;$i<10;$i++)
{
[email protected]_get_contents($url);
if(trim($c) != "")break;
}
//print($c);
return $c;
}
//擷取匹配內容
Function fetch_match_contents($begin,$end,$c)
{
$beginPos = strpos($c,$begin);
$endPos = strpos($c,$end);
if($beginPos > 0 && $endPos > 0 && $endPos > $beginPos)
{
$result = substr($c,$beginPos+strlen($begin),$endPos - $beginPos-strlen($begin));
return $result;
}
else
{
return "";
}
}
//採集網頁
Function pick($url,$ft,$th)
{
$c=fetch_urlpage_contents($url);
foreach($ft as $key => $value)
{
$rs[$key]=fetch_match_contents($value["begin"],$value["end"],$c);
if(is_array($th[$key]))
{ foreach($th[$key] as $old => $new)
{
$rs[$key]=str_replace($old,$new,$rs[$key]);
}
}
}
return $rs;
}
?>
caiji
$url="http://www.01job.cn/asp/itjob.asp";
$ft["title"]["begin"]=""; <br />$ft["title"]["end"]="";
$rs=pick($url,$ft,$th);
print_r($rs);
?>
------解決方案--------------------
寫個例子。。
PHP code
$content = file_get_contents('http://www.01job.cn/asp/itjob.asp');preg_match_all('/(.*)<\/a>/',$content,$arr);print_r($arr);