php獲取網頁源代碼

正好我也在做標籤的解析,互相探討一下
獲取網頁源碼用file_get_contents($url)就可以了
url如果是要解析網址的話記得加上http://
比如在輸入框內輸入http://www.baidu.com
//以下代碼保存爲catch.php
<?php
if(isset($_POST["url"]))
{
 $url=$_POST["url"];
 $fcont=file_get_contents($url);
 if(eregi('<table(.*)table>',$fcont,$re))
  echo "Yes";
 else
  echo "No";
 echo $re[0];
}
else
{
?>
<form action="catch.php" method="post">
url:<input type="text" size=30 name="url">
<input type="submit" name="submit" value="Catch">
</form>
<?php
}
?>
此外,還有一個現成的解析工具包simplehtmldom,詳見參考資料
提問者評價
說得很詳細,謝謝

參考資料: http://simplehtmldom.sourceforge.net/



以下就是幾種常用的用php抓取網頁中的內容的方法。
1.file_get_contents 
PHP代碼 
代碼如下:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?php 
$url = "http://www.jb51.net"; 
$contents = file_get_contents($url); 
//如果出現中文亂碼使用下面代碼 
//$getcontent = iconv("gb2312", "utf-8",$contents); 
echo $contents; 
?> 

2.curl 
PHP代碼 
代碼如下:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?php 
$url = "http://www.jb51.net"; 
$ch = curl_init(); 
$timeout = 5; 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
//在需要用戶檢測的網頁裏需要增加下面兩行 
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD); 
$contents = curl_exec($ch); 
curl_close($ch); 
echo $contents; 
?> 

3.fopen->fread->fclose 
PHP代碼 
代碼如下:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?php 
$handle = fopen ("http://www.jb51.net", "rb"); 
$contents = ""; 
do { 
$data = fread($handle, 1024); 
if (strlen($data) == 0) { 
break; 
} 
$contents .= $data; 
} while(true); 
fclose ($handle); 
echo $contents; 
?> 

注意: 
1.使用file_get_contents和fopen必須空間開啓allow_url_fopen。方法:編輯php.ini,設置allow_url_fopen = On,allow_url_fopen關閉時fopen和file_get_contents都不能打開遠程文件。 
2.使用curl必須空間開啓curl。方法:windows下修改php.ini,將extension=php_curl.dll前面的分號去掉,而且需要拷貝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安裝curl擴展。
##############至於說哪種方法好,這個不好說,看你要完成的任務有多難來定吧,我一般用CURL比較多....自己去網上搜搜,有很多博客裏有教程,感興趣的事加上聰明的人,一下下就學會了哦..祝你好運.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章