首页 > 编程技术 > php

PHP抓取网页内容的方法

发布时间:2016-11-25 15:51

PHP抓取网页内容的方法
PHP抓取页面的内容在实际的开发当中是非常有用的,如作一个简单的内容采集器,提取网页中的部分内容等等,抓取到的内容在通过正则表达式做一下过滤就得到了你想要的内容,至于如何用正则表达式过滤,在这里就不做介绍了,有兴趣的同学可以参考板块:http://111cn.net/articles11.shtml,以下就是几种常用的用php教程抓取网页中的内容的方法。
1.file_get_contents
PHP代码

<?php   
$url = "http://www.111cn.net";
$contents = file_get_contents($url);
//如果出现中文乱码使用下面代码
//$getcontent = iconv("gb2312", "utf-8",$contents); 
echo $contents;
?>   

2.curl
PHP代码 <?php   
$url = "http://www.111cn.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.111cn.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:WINDOWSsystem32下;Linux下要安装curl扩展。


方法一

安装cURL

wget http://curl.haxx.se/download/curl-7.17.1.tar.gz

 tar -zxf curl-7.17.1.tar.gz

./configure --prefix=/usr/local/curl

make & make install

安装php

   只要打开开关 --with-curl=/usr/local/curl

   就可以了。

   这个扩展库还是非常棒,是fsockopen等等相关的有效的替代品。

方法二

进入安装原php的源码目录,

cd ext

cd curl

phpize

./configure --with-curl=DIR

make & make install

就会在PHPDIR/ext/curl/moudles/下生成curl.so的文件。

复制curl.so文件到extensions的配置目录,修改php.ini就好了

extension=curl.so

第一种方法试了N遍一直在失败中,于是放弃。

使用第二种方法安装,

phpize提示找不到,其实命令在/usr/local/php/bin/目标下:

# /usr/local/php/bin/phpize

./configure --with-curl=DIR需要指定php的配置路径,应该如下:

# ./configure --with-php-config=/usr/local/php/bin/php-config --with-curl=DIR

注:上面的资料中错把--with-php-config写成了--with-php-php-config

然后就是编译安装:

# make
# make install
到这里会提示生成文件curl.so的路径: /usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/

进入到这个路径下,复制curl到extension_dir目录下(本目录路径可以看phpinfo可是直接看php.int),

修改php.ini

extension=curl.so

# /usr/local/php/bin/php -m
如果看到有curl项表示成功。

重启apache

# /usr/local/apache2/bin/apachectl stop

# /usr/local/apache2/bin/apachectl start

到此成功了,在phpinfo中可以看到CURL的项。

这里提供一款支持中文汉字与英文混合在一起的截取功能,包括对html标签等进来处理,下面我们来看看这款截取函数吧。

 

中英文字符串截取函数(包括html)

function get_word($string, $length, $dot = '..',$charset='gbk') {
if(strlen($string) <= $length) {
return $string;
}
$string = str_replace(array(' ',' ', '&', '"', '<', '>'), array('','','&', '"', '<', '>'), $string);
$strcut = '';
if(strtolower($charset) == 'utf-8') {
$n = $tn = $noc = 0;
while($n < strlen($string)) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif(224 <= $t && $t < 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) {
break;
}
}
if($noc > $length) {
$n -= $tn;
}
$strcut = substr($string, 0, $n);
} else {
for($i = 0; $i < $length; $i++) {
$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
}
}
return $strcut.$dot;
}
$str = "欢迎 visit 简明 nowamagic";
$str_result = get_word($str, 12);
echo $str_result;

PHP Session的生存周期与用法详解


session 是一种服务器端用于存储有关用户会话信息的机制,服务器使用一种类似于散列表的结构(也可能就是使用散列表)来保存信息。

当程序需要为某个客户端的请求创建一个 session 的时候,服务器首先会检查这个客户端是否已经包含了一个 session 标识,这个我们称为 session id(获取方法为 session_id() ),如果已包含一个 session id 则说明此客户端之前已经创建过 session,服务器则按照 session id 把这个 session 中的值检索出来,如果客户端不包含 session id,说明此客户端第一次请求服务器或手动清除过缓存文件,则为此客户端创建一个 session 并且生成一个与此 session 相关联的 session id,一般来说,session id 的值是不会重复的,并且加密的字符串,这个 session id 将被在本次响应中返回给客户端保存。

session 在何时被创建 ?

通常(是指通常)是在浏览器向服务器端第一次请求时被创建,并且它会占用一定的内存空间,因此在不必要的情况下,尽最关闭 session 。

session 何时被删除

通常情况下,session 在会在这几种情况下被删除,一是使用 session_destroy() 重置函数手动删除;二是 session 的上次活动时间距离当前时间的间隔超过了 session 的超时设置的时间;三是服务器进程被停止。

怎么在浏览器关闭时删除 session

理论上来说,是做不到这一点,http是一种无状态协议,因此服务器不知道客户端什么时候关掉的浏览器,并且PHP也没有一个关相的函数来获取此项信息,但这个问题还可以得到解决,就是使用 网页特效 代码 window.oncolose 来监视浏览器的关闭动作,然后用Ajax向服务器端发送一个请求来删除 session ,但这个办法也并不会完全解决问题,原因是在有些情况下比如浏览器崩溃、突然断电、用户死机等这些时候并不能作出反应。


在PHP中有关Session的函数比较多,不过我们最常用到的也就这么几个函数:
session_start(), session_register(),session_unregister(),
session_is_registered(),session_destroy函数.
session_start():启用session机制,在需要用到session的程序文件的最开始调用它.
session_register():注册session变量
session_unregister(): 删除session变量(一个一个删除)
session_is_registered(): 判断session变量是否注册
session_distroy(): 销毁所有session变量(所有session变量销毁)


们来看一下验证程序,假设数据库教程存储的是用户名和 md5 加密后的密码:

<?php教程

// 表单提交后...
$posts = $_POST;
// 清除一些空白符号
foreach ($posts as $key => $value)
{
$posts[$key] = trim($value);
}
$password = md5($posts["password"]);
$username = $posts["username"];

$query = "SELECT `username` FROM `user` WHERE `password` = '$password'";
// 取得查询结果
$userInfo = $DB->getRow($query);

if (!empty($userInfo))
{
if ($userInfo["username"] == $username)
{
// 当验证通过后,启动 Session
session_start();
// 注册登陆成功的 admin 变量,并赋值 true
$_SESSION["admin"] = true;
}
else
{
die("用户名密码错误");
}
}
else
{
die("用户名密码错误");

  我们在需要用户验证的页面启动 Session,判断是否登陆:

<?php
// 防止全局变量造成安全隐患
$admin = false;

// 启动会话,这步必不可少
session_start();

// 判断是否登陆
if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true)
{
echo "您已经成功登陆";
}
else
{
// 验证失败,将 $_SESSION["admin"] 置为 false
$_SESSION["admin"] = false;
die("您无权访问");
}

?>

需要注意下面几个方面:
 1.函数session_start()必须在程序最开始执行,在其前面不能有任何输出内容,否则
    就会出现“Warning:Cannot send session cookie - headers already
   sent"类似这样的警告信息.
 2.函数session_register()用于注册要保存在session中的相关变量,其用法如下:
 <?php
  $val = "session value";
  session_register("val");
 ?>
 val即为要注册的session变量名,在注册时一定不要加上"$"符号,只写其变量名称即可.

 3.函数session_unregister()与上面函数用法完全相同,但功能相反,上面函数是注册
session变量,而其则是删除指定的session变量.
 4.函数session_is_registered()用于判断session变量是否注册.
 5.函数session_destroy()主要用于在系统注销和退出时,销毁所有的session变量,
它没有参数,直接调用即可。

php教程字符串操作函数入门篇
1.字符串的定义与显示
定义:通过””,''来标志
显示:echo()和print(),但print()具有返回值值,1,而echo()没有,但echo比print()要快,print()能用在复合语句中。
2.字符串的格式化
printf(string $format[,mixed$args])
第一参数是格式字符串,$args是要替换进来的值,prinf(“%d”,$num);
说明,如果想打印一个”%”,必须用”%”,浮点数f,八进制用”0”
3.常用的字符串函数
1.计算字符串的长度
strlen(string $string),说明,1个英文长度1个字符,1个汉字长度为2个字符,空格也算一个字符。
2.将字符串改变大小写
转为小写:strtolower()
转为大写:strtoupper()
将第一个字符大写: ucfirst()
将每个单词的第一个字母大写 ucwords()
3.字符串裁剪。
当一个字符串的首尾有多余的空白字符,如空格、制表符等可以用
string trim(string $str[,string $charlist])
string rtrim(string $str[sring $charlist])
string itrim(string $str[,string $charlist])
表4.1 trim、itrim、rtrim函数的默认删除字符
字 符
 ASCII码
 意 义
 
" "
 32(0x20)
 空格
 
"t"
 9(0x09)
 制表符
 
"n"
 10(0x)
 换行
 
"r"
 13(0x0D)
 回车
 
""
 0(0x00)
 空字节
 
"x0B"
 11(0x0B)
 垂直制表符
 

4.字符串的查找
string strstr(string $a, string $b)
说明:strstr()函数用于查找字符串指针$b在字符串$a中出现的位置,
并返回$a字符串中从$b开始到$a字符串结束处的字符串。
如果没有返回值,即没有发现$b,则返回FALSE。strstr()函数还有一个同名函数strchr()。
5.字符串与ASCII码
4.字符串的比较
比较函数有
strcmp() //区分大小写
strcasecmp()//不区分大小写
strncmp() //比较部分
strncasecmp()//不区分大小写,比较部分
5.字符串的替换
str_replace(search,replace,subject)
说明使用新的字符串replace替换字符串subject中的search字符串
<?php
$str="I love you";
$replace="lucy";
$end=str_replace("you",$replace,$str);
echo $end; //输出"I love lucy"
?>
对大小写敏感,还可实现多对一、多对多的替换,但无法实现一对多的替换。
<?php
$str="What Is Your Name";
$array=array("a","o","A","O","e");
echo str_replace($array, "",$str); //多对一的替换,输出"Wht Is Yur Nm"
$array1=array("a","b","c");
$array2=array("d","e","f");
echo str_replace($array1,$array2, "abcdef"); //多对多的替换,输出"defdef"
?>
substr_replace
替换字符串的一部分。
6.字符串与HTML

7.其它字符串函数
1.字符串与数组
a.字符串转化为数组
explode()函数可以用指定的字符串分割另一个字符串,并返回一个数组
<?php
$str="使用 空格 分割 字符串";
array=explode(" ", $str);
pint_r($array);
输出Array ( [0] => 使用 [1] => 空格 [2] => 分割 [3] => 字符串 )
?>
b.数组转化为字符串
implode(string $glue,array $pieces)
$pieces是保存要连接的字符串的数组,$glue是用于连接字符串的连接符。例如:
<?php
$array=array("hello","how","are","you");
$str=implode(",",$array); //使用逗号作为连接符
echo $str; //输出"hello,how,are,you"
?>
c.字符串的加密函数
md5(); crypt(),但这个函数一旦加密后就无法转化为原来的形式。
4.3实例留言薄内容处理
一个留言簿,留言簿上有Email地址和用户的留言,提取客户的Email地址和留言,要求Email地址中@符号前不能有点“.”或逗号“,”。
将Email地址中@符号前的内容作为用户的用户名,并将用户留言中第一人称“我”修改为“本人”。
复制代码 代码如下:
<form name="f1" method="post" action="">
<font face="方正舒体" size=4>您的Email地址:</font><br>
<input type="text" name="Email" size=31><br>
<font face="方正舒体" size=4>您的留言:</font><br>
<textarea name="note" rows=10 cols=30></textarea>
<br><input type="submit" name="bt1" value="提交">
<input type="reset" name="bt2" value="清空">
</form>
<!--以上是留言簿表单-->
<?php
if(isset($_POST['bt1']))
{
$Email=$_POST['Email']; //接收Eamil地址
$note=$_POST['note']; //接收留言
if(!$Email||!$note) //判断是否取得值
echo "<script>alert('Email地址和留言请填写完整!')</script>";
else
{
$array=explode("@", $Email); //分割Email地址
if(count($array)!=2) //如果有两个@符号则报错
echo "<script>alert('Email地址格式错误!')</script>";
else
{
$username=$array[0]; //取得@符号前的内容
$netname=$array[1]; //取得@符号后的内容
//如果username中含有“.”或“,”则报错
if(strstr($username,".") or strstr($username,","))
echo "<script>alert('Email地址格式错误!')</script>";
else
{
$str1= htmlspecialchars("<"); //输出符号“<”
$str2= htmlspecialchars(">"); //输出符号“>”
//将留言中的“我”用“本人”替代
$newnote=str_replace("我","本人",$note);
echo "<font face='黑体' size=4>";
echo "用户". $str1. $username . $str2. "您好! ";
echo "您是". $netname. "网友!<br>";
echo "<br>您的留言是:<br> ".$newnote."<br>";
echo "</font>";
}
}
}
}
?>

函数原型:array explode(string separator,string input);

  explode函数应用非常广泛,其主要作用是对规定的字符串以设定的分隔符进行拆分,并以数组形式返回。其常使用在分割文件名以判断文件类型、切割用户Email等场合。

  PHP字符串分割函数explode处理实例

  1、获取文件扩展名
   
$fileName = "leaps教程oulcn.jpg";
$str = explode(".",$fileName);
print_r($str);

我们知道在PHP文件上传功能中,判断上传文件名是否合法的最基本方法是判断扩展名是否合法,这时候就需要使用PHP字符串函数explode对文件名进行分割处理。在上述代码中explode函数以.为分隔符,对文件名进行分割。输入结果如下
   
Array ( [0] => leapsoulcn [1] => jpg )

2、获取用户Email域名信息
 
$emailInfo = explode("@",$email);


手册

AddSlashes: 字符串加入斜线。
bin2hex: 二进位转成十六进位。
Chop: 去除连续空白。
Chr: 返回序数值的字符。
chunk_split: 将字符串分成小段。
convert_cyr_string: 转换古斯拉夫字符串成其它字符串。
crypt: 将字符串用 DES 编码加密。
echo: 输出字符串。
explode: 切开字符串。
flush: 清出输出缓冲区。
get_meta_tags: 抽出文件所有 meta 标记的资料。
htmlspecialchars: 将特殊字符转成 HTML 格式。
htmlentities: 将所有的字符都转成 HTML 字符串。
implode: 将数组变成字符串。
join: 将数组变成字符串。
ltrim: 去除连续空白。
md5: 计算字符串的 MD5 哈稀。
nl2br: 将换行字符转成 <br>。
Ord: 返回字符的序数值。
parse_str: 解析 query 字符串成变量。
print: 输出字符串。
printf: 输出格式化字符串。
quoted_printable_decode: 将 qp 编码字符串转成 8 位字符串。
QuoteMeta: 加入引用符号。
rawurldecode: 从 URL 专用格式字符串还原成普通字符串。
rawurlencode: 将字符串编码成 URL 专用格式。
setlocale: 配置地域化信息。
similar_text: 计算字符串相似度。
soundex: 计算字符串的读音值
sprintf: 将字符串格式化。
strchr: 寻找第一个出现的字符。
strcmp: 字符串比较。
strcspn: 不同字符串的长度。
strip_tags: 去掉 HTML 及 PHP 的标记。
StripSlashes: 去掉反斜线字符。
strlen: 取得字符串长度。
strrpos: 寻找字符串中某字符最后出现处。
strpos: 寻找字符串中某字符最先出现处。
strrchr: 取得某字符最后出现处起的字符串。
strrev: 颠倒字符串。
strspn: 找出某字符串落在另一字符串遮罩的数目。
strstr: 返回字符串中某字符串开始处至结束的字符串。
strtok: 切开字符串。
strtolower: 字符串全转为小写。
strtoupper: 字符串全转为大写。
str_replace: 字符串取代。
strtr: 转换某些字符。
substr: 取部份字符串。
trim: 截去字符串首尾的空格。
ucfirst: 将字符串第一个字符改大写。
ucwords: 将字符串每个字第一个字母改大写。

php教程设计模式 建造者模式 与Adapter(适配器模式)

适配器模式
*
* 将一个类的接口转换成客户希望的另外一个接口,使用原本不兼容的而不能在一起工作的那些类可以在一起工作

建造者模式
*
* 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示

<?php
/**
* 适配器模式
*
* 将一个类的接口转换成客户希望的另外一个接口,使用原本不兼容的而不能在一起工作的那些类可以在一起工作
*/

// 这个是原有的类型
class OldCache
{
public function __construct()
{
echo "OldCache construct<br/>";
}

public function store($key,$value)
{
echo "OldCache store<br/>";
}

public function remove($key)
{
echo "OldCache remove<br/>";
}

public function fetch($key)
{
echo "OldCache fetch<br/>";
}
}

interface Cacheable
{
public function set($key,$value);
public function get($key);
public function del($key);
}

class OldCacheAdapter implements Cacheable
{
private $_cache = null;
public function __construct()
{
$this->_cache = new OldCache();
}

public function set($key,$value)
{
return $this->_cache->store($key,$value);
}

public function get($key)
{
return $this->_cache->fetch($key);
}

public function del($key)
{
return $this->_cache->remove($key);
}
}

$objCache = new OldCacheAdapter();
$objCache->set("test",1);
$objCache->get("test");
$objCache->del("test",1);

php设计模式 Builder(建造者模式)

 

<?php

/**
* 建造者模式
*
* 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示
*/
class Product
{
public $_type = null;
public $_size = null;
public $_color = null;

public function setType($type)
{
echo "set product type<br/>";
$this->_type = $type;
}

public function setSize($size)
{
echo "set product size<br/>";
$this->_size = $size;
}

public function setColor($color)
{
echo "set product color<br/>";
$this->_color = $color;
}
}

$config = array(
"type"=>"shirt",
"size"=>"xl",
"color"=>"red",
);

// 没有使用bulider以前的处理
$oProduct = new Product();
$oProduct->setType($config['type']);
$oProduct->setSize($config['size']);
$oProduct->setColor($config['color']);


// 创建一个builder类
class ProductBuilder
{
var $_config = null;
var $_object = null;

public function ProductBuilder($config)
{
$this->_object = new Product();
$this->_config = $config;
}

public function build()
{
echo "--- in builder---<br/>";
$this->_object->setType($this->_config['type']);
$this->_object->setSize($this->_config['size']);
$this->_object->setColor($this->_config['color']);
}

public function getProduct()
{
return $this->_object;
}
}

$objBuilder = new ProductBuilder($config);
$objBuilder->build();
$objProduct = $objBuilder->getProduct();

标签:[!--infotagslink--]

您可能感兴趣的文章: