昨天有個朋友在問我說,php怎麼抓取網頁某個div區塊的內容。像funp推推王那樣每次推文都會顯示文章內的圖片,提供縮圖撰擇,又是怎麼做到的?其實這語法出乎意料的簡短…
1.
取得指定網頁內的所有圖片:測試
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/');
//取得所有img標籤,並儲存至二維陣列match
preg_match_all('#]*>#i',
$text, $match);
//印出match
print_r($match);
?>
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/');
//取得所有img標籤,並儲存至二維陣列match
preg_match_all('#]*>#i', $text, $match);
//印出match
print_r($match);
?>
2.
取得指定網頁內的第一張圖片:測試
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/');
//取得第一個img標籤,並儲存至陣列match(regex語法與上述同義)
preg_match('/]*>/Ui',
$text, $match);
//印出match
print_r($match);
?>
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/');
//取得第一個img標籤,並儲存至陣列match(regex語法與上述同義)
preg_match('/]*>/Ui', $text, $match);
//印出match
print_r($match);
?>
3.
取得指定網頁內的特定div區塊(藉由id判斷):測試
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');
//去除換行及空白字元(序列化內容才需使用)
//$text=str_replace(array("\r","\n","\t","\s"), '',
$text);
//取出div標籤且id為PostContent的內容,並儲存至陣列match
preg_match('/
/si',$text,$match);
//印出match[0]
print($match[0]);
?>
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');
//去除換行及空白字元(序列化內容才需使用)
//$text=str_replace(array("\r","\n","\t","\s"), '', $text);
//取出div標籤且id為PostContent的內容,並儲存至陣列match
preg_match('/
//印出match[0]
print($match[0]);
?>
4.
上述2及3的結合:測試
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');
//取出div標籤且id為PostContent的內容,並儲存至陣列match
preg_match('/
/si',$text,$match);
//取得第一個img標籤,並儲存至陣列match2
preg_match('/]*>/Ui',
$match[0], $match2);
//印出match2[0]
print_r($match2[0]);
?>
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');
//取出div標籤且id為PostContent的內容,並儲存至陣列match
preg_match('/
//取得第一個img標籤,並儲存至陣列match2
preg_match('/]*>/Ui', $match[0], $match2);
//印出match2[0]
print_r($match2[0]);
?>
後記:用正規表達式Regex來做真的很方便,但老實說我規則常會忘掉,記錄一下幾篇文章好了(Regular Expression
Details | PCRE Functions | Introduction to PHP
Regex)
From[http://xiaoniba.net/html/jiaocheng/PHPjiaocheng/2009/0428/464.html]