PHP函数库里面,提到CURL,恐怕很多人都会翘起大拇指吧,确实,这个函数库太牛叉了
CURL其实是调用的CURL的lib,随着PHP版本的升高,curl所需的lib版本也随之提高。
关于CURL所必须的类库和安装说明,手册上有详细介绍:
XML/HTML代码
- Requirements
-
- In order to use PHP's cURL functions you need to install the libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
-
- Installation
-
- To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the "include" directory there should be a folder named "curl" which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the "lib" directory. Beginning with PHP 4.3.0 you can configure PHP to use cURL for URL streams --with-curlwrappers.
-
- Note to Win32 Users: In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH.
- You don't need libcurl.dll from the cURL site.
然后在使用的时候也很方便,只需要初始化一下,设置一下postfields或者GET啥啥的,最后exec一下就行了。关键是别忘了close.
例子代码如下:
PHP代码
- $ch = curl_init("http://www.example.com/");
- $fp = fopen("example_homepage.txt", "w");
-
- curl_setopt($ch, CURLOPT_FILE, $fp);
- curl_setopt($ch, CURLOPT_HEADER, 0);
-
- curl_exec($ch);
- curl_close($ch);
- fclose($fp);
以上例子代码有点特殊,是因为他把网页内容进行了下载,同时生成一个文件。这是默认调用GET的方法。
其实,CURL更多的是用来处理POST数据、上传文件等功能
例子如下:
PHP代码
- <?
-
-
-
-
-
-
- $url = 'http://www.ericgiguere.com/tools/http-header-viewer.html';
-
-
- function disguise_curl($url)
- {
- $curl = curl_init();
-
-
-
- $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
- $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
- $header[] = "Cache-Control: max-age=0";
- $header[] = "Connection: keep-alive";
- $header[] = "Keep-Alive: 300";
- $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
- $header[] = "Accept-Language: en-us,en;q=0.5";
- $header[] = "Pragma: ";
-
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
- curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
- curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
- curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
- curl_setopt($curl, CURLOPT_AUTOREFERER, true);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_TIMEOUT, 10);
-
- $html = curl_exec($curl);
- curl_close($curl);
-
- return $html;
- }
-
-
- $text = disguise_curl($url);
- echo $text;
- ?>
上面是一个比较完整的实现。特别需要注意的是header头部的发送,最初看手册的时候,我一以为CURLOPT_HTTPHEADER所需的数组是键值对应的,即:
PHP代码
- $header = array('Keep-Alive'=>'300');
现实的残酷告诉我,不应该这么用,而是象上面的例子那样,每条header为数组的一个记录。
切记切记啊
原文地址:http://www.phpv.net/html/1639.html,作者:手气不错
未删节版本
开门见山,考虑下面的代码(原文连接有详细的解释)
PHP代码
- <html>
- <body>
- <?php
- if (isset($_REQUEST['submitted']) && $_REQUEST['submitted'] == '1') {
- echo "Form submitted!";
- }
- ?>
- <form action="<?php echo $_SERVER['PHP_SELF']; ?>">
- <input type="hidden" name="submitted" value="1" />
- <input type="submit" value="Submit!" />
- </form>
- </body>
- </html>
看似准确无误的代码,但是暗藏着危险。让我们将其保存为 foo.php ,然后放到 PHP 环境中使用
foo.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E%3Cfoo
访问,会发现弹出个 Javascript 的 alert -- 这很明显又是个 XSS 的注入漏洞。究其原因,发现是在
echo $_SERVER['PHP_SELF'];
这条语句上直接输出了未过滤的值。追根数源,我们看下 PHP 手册的描述
'PHP_SELF'
The filename of the currently executing script, relative to the document root.
For instance, $_SERVER['PHP_SELF'] in a script at the address
http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__
constant contains the full path and filename of the current (i.e. included) file.
If PHP is running as a command-line processor this variable contains the script
name since PHP 4.3.0. Previously it was not available.
原因很明确了,原来是 $_SERVER['PHP_SELF'] 虽然“看起来”是服务器提供的环境变量,但这的确和 $_POST 与 $_GET 一样,是可以被用户更改的。
其它类似的变量有很多,比如 $_COOKIE 等(如果用户想“把玩”他们的 cookie,那我们也是没有办法)。解决方案很简单,使用 strip_tags、htmlentities 等此类函数过滤或者转义。
echo htmlentities($_SERVER['PHP_SELF']);
-- Split --
上述的例子让我们需要时刻保持谨慎 coding 的心态。Chris Shiflett 在他的 Blog 总结的相当直白,防止 XSS 的两个基本的安全思想就是
Filter input
Escape output
我将上面翻译成 “过滤输入,转义输出”。详细的内容,可以参考他 Blog 的这篇文章,此处略。
很少看到介绍SPL的文章,难得看到一篇,转摘,记录一下,原文地址:http://www.phpobject.net/blog/read.php/140.htm
PHP SPL笔记
目录
第一部分 简介
1. 什么是SPL?
2. 什么是Iterator?
第二部分 SPL Interfaces
3. Iterator界面
4. ArrayAccess界面
5. IteratorAggregate界面
6. RecursiveIterator界面
7. SeekableIterator界面
8. Countable界面
第三部分 SPL Classes
9. SPL的内置类
10. DirectoryIterator类
11. ArrayObject类
12. ArrayIterator类
13. RecursiveArrayIterator类和RecursiveIteratorIterator类
14. FilterIterator类
15. SimpleXMLIterator类
16. CachingIterator类
17. LimitIterator类
18. SplFileObject类
第一部 简介
1. 什么是SPL?
SPL是Standard PHP Library(PHP标准库)的缩写。
根据官方定义,它是“a collection of interfaces and classes that are meant to solve standard problems”。但是,目前在使用中,SPL更多地被看作是一种使object(物体)模仿array(数组)行为的interfaces和 classes。
2. 什么是Iterator?
SPL的核心概念就是Iterator。这指的是一种Design Pattern,根据《Design Patterns》一书的定义,Iterator的作用是“provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.”
wikipedia中说,"an iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation".……"the iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation".
通俗地说,Iterator能够使许多不同的数据结构,都能有统一的操作界面,比如一个数据库的结果集、同一个目录中的文件集、或者一个文本中每一行构成的集合。
如果按照普通情况,遍历一个MySQL的结果集,程序需要这样写:
PHP代码
-
- $result = mysql_query("SELECT * FROM users");
-
- while ( $row = mysql_fetch_array($result) ) {
-
- }
读出一个目录中的内容,需要这样写:
PHP代码
-
- $dh = opendir('/home/harryf/files');
-
- while ( $file = readdir($dh) ) {
-
- }
读出一个文本文件的内容,需要这样写:
PHP代码
-
- $fh = fopen("/home/hfuecks/files/results.txt", "r");
-
- while (!feof($fh)) {
- $line = fgets($fh);
-
- }
上面三段代码,虽然处理的是不同的resource(资源),但是功能都是遍历结果集(loop over contents),因此Iterator的基本思想,就是将这三种不同的操作统一起来,用同样的命令界面,处理不同的资源。
第二部分 SPL Interfaces
3. Iterator界面
SPL规定,所有部署了Iterator界面的class,都可以用在foreach Loop中。Iterator界面中包含5个必须部署的方法:
* current()
This method returns the current index’s value. You are solely
responsible for tracking what the current index is as the
interface does not do this for you.
* key()
This method returns the value of the current index’s key. For
foreach loops this is extremely important so that the key
value can be populated.
* next()
This method moves the internal index forward one entry.
* rewind()
This method should reset the internal index to the first element.
* valid()
This method should return true or false if there is a current
element. It is called after rewind() or next().
下面就是一个部署了Iterator界面的class示例:
PHP代码
-
-
-
-
-
- class ArrayReloaded implements Iterator {
-
-
-
- private $array = array();
-
-
-
- private $valid = FALSE;
-
-
-
-
- function __construct($array) {
- $this->array = $array;
- }
-
-
-
-
- function rewind(){
- $this->valid = (FALSE !== reset($this->array));
- }
-
-
-
- function current(){
- return current($this->array);
- }
-
-
-
- function key(){
- return key($this->array);
- }
-
-
-
-
- function next(){
- $this->valid = (FALSE !== next($this->array));
- }
-
-
-
- function valid(){
- return $this->valid;
- }
- }
使用方法如下:
PHP代码
-
- $colors = new ArrayReloaded(array ('red','green','blue',));
-
- foreach ( $colors as $color ) {
- echo $color."\n";
- }
你也可以在foreach循环中使用key()方法:
PHP代码
-
- foreach ( $colors as $key => $color ) {
- echo "$key: $color";
- }
除了foreach循环外,也可以使用while循环,
PHP代码
-
- $colors->rewind();
-
- while ( $colors->valid() ) {
- echo $colors->key().": ".$colors->current()."
- ";
- $colors->next();
- }
根据测试,while循环要稍快于foreach循环,因为运行时少了一层中间调用。
4. ArrayAccess界面
部署ArrayAccess界面,可以使得object像array那样操作。ArrayAccess界面包含四个必须部署的方法:
* offsetExists($offset)
This method is used to tell php if there is a value
for the key specified by offset. It should return
true or false.
* offsetGet($offset)
This method is used to return the value specified
by the key offset.
* offsetSet($offset, $value)
This method is used to set a value within the object,
you can throw an exception from this function for a
read-only collection.
* offsetUnset($offset)
This method is used when a value is removed from
an array either through unset() or assigning the key
a value of null. In the case of numerical arrays, this
offset should not be deleted and the array should
not be reindexed unless that is specifically the
behavior you want.
下面就是一个部署ArrayAccess界面的实例:
PHP代码
-
-
-
- class Article implements ArrayAccess {
- public $title;
- public $author;
- public $category;
- function __construct($title,$author,$category) {
- $this->title = $title;
- $this->author = $author;
- $this->category = $category;
- }
-
-
-
-
-
-
-
- function offsetSet($key, $value) {
- if ( array_key_exists($key,get_object_vars($this)) ) {
- $this->{$key} = $value;
- }
- }
-
-
-
-
-
-
- function offsetGet($key) {
- if ( array_key_exists($key,get_object_vars($this)) ) {
- return $this->{$key};
- }
- }
-
-
-
-
-
-
- function offsetUnset($key) {
- if ( array_key_exists($key,get_object_vars($this)) ) {
- unset($this->{$key});
- }
- }
-
-
-
-
-
-
- function offsetExists($offset) {
- return array_key_exists($offset,get_object_vars($this));
- }
- }
使用方法如下:
PHP代码
-
- $A = new Article('SPL Rocks','Joe Bloggs', 'PHP');
-
- echo 'Initial State:';
- print_r($A);
- echo "\n";
-
- $A['title'] = 'SPL _really_ rocks';
-
- $A['not found'] = 1;
-
- unset($A['author']);
-
- echo 'Final State:';
- print_r($A);
- echo "\n";
运行结果如下:
Initial State:
Article Object
(
[title] => SPL Rocks
[author] => Joe Bloggs
[category] => PHP
)
Final State:
Article Object
(
[title] => SPL _really_ rocks
[category] => PHP
)
可以看到,$A虽然是一个object,但是完全可以像array那样操作。
你还可以在读取数据时,增加程序内部的逻辑:
PHP代码
- function offsetGet($key) {
- if ( array_key_exists($key,get_object_vars($this)) ) {
- return strtolower($this->{$key});
- }
- }
5. IteratorAggregate界面
但是,虽然$A可以像数组那样操作,却无法使用foreach遍历,除非部署了前面提到的Iterator界面。
另一个解决方法是,有时会需要将数据和遍历部分分开,这时就可以部署IteratorAggregate界面。它规定了一个getIterator()方法,返回一个使用Iterator界面的object。
还是以上一节的Article类为例:
PHP代码
- class Article implements ArrayAccess, IteratorAggregate {
-
-
-
-
-
- function getIterator() {
- return new ArrayIterator($this);
- }
使用方法如下:
PHP代码
- $A = new Article('SPL Rocks','Joe Bloggs', 'PHP');
-
- echo 'Looping with foreach:';
- foreach ( $A as $field => $value ) {
- echo "$field : $value";
- }
- echo '';
-
- echo "Object has ".sizeof($A->getIterator())." elements";
显示结果如下:
Looping with foreach:
title : SPL Rocks
author : Joe Bloggs
category : PHP
Object has 3 elements
6. RecursiveIterator界面
这个界面用于遍历多层数据,它继承了Iterator界面,因而也具有标准的current()、key()、next()、 rewind()和valid()方法。同时,它自己还规定了getChildren()和hasChildren()方法。The getChildren() method must return an object that implements RecursiveIterator.
7. SeekableIterator界面
SeekableIterator界面也是Iterator界面的延伸,除了Iterator的5个方法以外,还规定了seek()方法,参数是元素的位置,返回该元素。如果该位置不存在,则抛出OutOfBoundsException。
下面是一个是实例:
PHP代码
- class PartyMemberIterator implements SeekableIterator
- {
- public function __construct(PartyMember $member)
- {
-
- }
- public function seek($index)
- {
- $this->rewind();
- $position = 0;
- while ($position < $index && $this->valid()) {
- $this->next();
- $position++;
- }
- if (!$this->valid()) {
- throw new OutOfBoundsException('Invalid position');
- }
- }
-
-
- }
8. Countable界面
这个界面规定了一个count()方法,返回结果集的数量。
第三部分 SPL Classes
9. SPL的内置类
SPL除了定义一系列Interfaces以外,还提供一系列的内置类,它们对应不同的任务,大大简化了编程。
查看所有的内置类,可以使用下面的代码:
PHP代码
-
- foreach(spl_classes() as $key=>$value)
- {
- echo $key.' -> '.$value.'';
- }
10. DirectoryIterator类
这个类用来查看一个目录中的所有文件和子目录:
PHP代码
- try{
-
- foreach ( new DirectoryIterator('./') as $Item )
- {
- echo $Item.'';
- }
- }
-
- catch(Exception $e){
- echo 'No files Found!';
- }
查看文件的详细信息:
PHP代码
- foreach(new DirectoryIterator('./' ) as $file )
- {
- if( $file->getFilename() == 'foo.txt' )
- {
- echo ' getFilename() '; var_dump($file->getFilename()); echo ' ';
- echo ' getBasename() '; var_dump($file->getBasename()); echo ' ';
- echo ' isDot() '; var_dump($file->isDot()); echo ' ';
- echo ' __toString() '; var_dump($file->__toString()); echo ' ';
- echo ' getPath() '; var_dump($file->getPath()); echo ' ';
- echo ' getPathname() '; var_dump($file->getPathname()); echo ' ';
- echo ' getPerms() '; var_dump($file->getPerms()); echo ' ';
- echo ' getInode() '; var_dump($file->getInode()); echo ' ';
- echo ' getSize() '; var_dump($file->getSize()); echo ' ';
- echo ' getOwner() '; var_dump($file->getOwner()); echo ' ';
- echo ' $file->getGroup() '; var_dump($file->getGroup()); echo ' ';
- echo ' getATime() '; var_dump($file->getATime()); echo ' ';
- echo ' getMTime() '; var_dump($file->getMTime()); echo ' ';
- echo ' getCTime() '; var_dump($file->getCTime()); echo ' ';
- echo ' getType() '; var_dump($file->getType()); echo ' ';
- echo ' isWritable() '; var_dump($file->isWritable()); echo ' ';
- echo ' isReadable() '; var_dump($file->isReadable()); echo ' ';
- echo ' isExecutable( '; var_dump($file->isExecutable()); echo ' ';
- echo ' isFile() '; var_dump($file->isFile()); echo ' ';
- echo ' isDir() '; var_dump($file->isDir()); echo ' ';
- echo ' isLink() '; var_dump($file->isLink()); echo ' ';
- echo ' getFileInfo() '; var_dump($file->getFileInfo()); echo ' ';
- echo ' getPathInfo() '; var_dump($file->getPathInfo()); echo ' ';
- echo ' openFile() '; var_dump($file->openFile()); echo ' ';
- echo ' setFileClass() '; var_dump($file->setFileClass()); echo ' ';
- echo ' setInfoClass() '; var_dump($file->setInfoClass()); echo ' ';
- }
- }
除了foreach循环外,还可以使用while循环:
PHP代码
-
- $it = new DirectoryIterator('./');
-
- while($it->valid())
- {
- echo $it->key().' -- '.$it->current().' ';
-
- $it->next();
- }
如果要过滤所有子目录,可以在valid()方法中过滤:
PHP代码
-
- $it = new DirectoryIterator('./');
-
- while($it->valid())
- {
-
- if($it->isDir())
- {
-
- echo $it->key().' -- '.$it->current().'';
- }
-
- $it->next();
- }
11. ArrayObject类
这个类可以将Array转化为object。
PHP代码
-
- $array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
-
- $arrayObj = new ArrayObject($array);
-
- for($iterator = $arrayObj->getIterator();
-
- $iterator->valid();
-
- $iterator->next())
- {
-
- echo $iterator->key() . ' => ' . $iterator->current() . '';
- }
增加一个元素:
$arrayObj->append('dingo');
对元素排序:
$arrayObj->natcasesort();
显示元素的数量:
echo $arrayObj->count();
删除一个元素:
$arrayObj->offsetUnset(5);
某一个元素是否存在:
if ($arrayObj->offsetExists(3))
{
echo 'Offset Exists';
}
更改某个位置的元素值:
$arrayObj->offsetSet(5, "galah");
显示某个位置的元素值:
echo $arrayObj->offsetGet(4);
12. ArrayIterator类
这个类实际上是对ArrayObject类的补充,为后者提供遍历功能。
示例如下:
PHP代码
-
- $array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
- try {
- $object = new ArrayIterator($array);
- foreach($object as $key=>$value)
- {
- echo $key.' => '.$value.'';
- }
- }
- catch (Exception $e)
- {
- echo $e->getMessage();
- }
-
- rayIterator类也支持offset类方法和count()方法:
-
-
- $array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
- try {
- $object = new ArrayIterator($array);
-
- if($object->offSetExists(2))
- {
-
- $object->offSetSet(2, 'Goanna');
- }
-
- foreach($object as $key=>$value)
- {
-
- if($object->offSetGet($key) === 'kiwi')
- {
-
- $object->offSetUnset($key);
- }
- echo ''.$key.' - '.$value.''."\n";
- }
- }
- catch (Exception $e)
- {
- echo $e->getMessage();
- }
?>
13. RecursiveArrayIterator类和RecursiveIteratorIterator类
ArrayIterator类和ArrayObject类,只支持遍历一维数组。如果要遍历多维数组,必须先用 RecursiveIteratorIterator生成一个Iterator,然后再对这个Iterator使用 RecursiveIteratorIterator。
PHP代码
- $array = array(
- array('name'=>'butch', 'sex'=>'m', 'breed'=>'boxer'),
- array('name'=>'fido', 'sex'=>'m', 'breed'=>'doberman'),
- array('name'=>'girly','sex'=>'f', 'breed'=>'poodle')
- );
- foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key=>$value)
- {
- echo $key.' -- '.$value.'';
- }
14. FilterIterator类
FilterIterator类可以对元素进行过滤,只要在accept()方法中设置过滤条件就可以了。
示例如下:
PHP代码
-
- $animals = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'NZ'=>'kiwi', 'kookaburra', 'platypus');
- class CullingIterator extends FilterIterator{
-
- public function __construct( Iterator $it ){
- parent::__construct( $it );
- }
-
- function accept(){
- return is_numeric($this->key());
- }
- }
- $cull = new CullingIterator(new ArrayIterator($animals));
- foreach($cull as $key=>$value)
- {
- echo $key.' == '.$value.'';
- }
- ?>
-
-
- class PrimeFilter extends FilterIterator{
-
- public function __construct(Iterator $it){
- parent::__construct($it);
- }
-
- function accept(){
- if($this->current() % 2 != 1)
- {
- return false;
- }
- $d = 3;
- $x = sqrt($this->current());
- while ($this->current() % $d != 0 && $d < $x)
- {
- $d += 2;
- }
- return (($this->current() % $d == 0 && $this->current() != $d) * 1) == 0 ? true : false;
- }
- }
-
- $numbers = range(212345,212456);
-
- $primes = new primeFilter(new ArrayIterator($numbers));
- foreach($primes as $value)
- {
- echo $value.' is prime.';
- }
15. SimpleXMLIterator类
这个类用来遍历xml文件。
示例如下:
原文的XML在就是变型的,或者说在解释的时候已经坏掉了,所以。我删除了,直接看方法吧:by 膘叔
PHP代码
-
- try {
-
- $it = new SimpleXMLIterator($xmlstring);
-
- foreach(new RecursiveIteratorIterator($it,1) as $name => $data)
- {
- echo $name.' -- '.$data.'';
- }
- }
- catch(Exception $e)
- {
- echo $e->getMessage();
- }
new RecursiveIteratorIterator($it,1)表示显示所有包括父元素在内的子元素。
显示某一个特定的元素值,可以这样写:
PHP代码
- try {
-
- $sxi = new SimpleXMLIterator($xmlstring);
- foreach ( $sxi as $node )
- {
- foreach($node as $k=>$v)
- {
- echo $v->species.'';
- }
- }
- }
- catch(Exception $e)
- {
- echo $e->getMessage();
- }
相对应的while循环写法为:
PHP代码
- try {
- $sxe = simplexml_load_string($xmlstring, 'SimpleXMLIterator');
- for ($sxe->rewind(); $sxe->valid(); $sxe->next())
- {
- if($sxe->hasChildren())
- {
- foreach($sxe->getChildren() as $element=>$value)
- {
- echo $value->species.'';
- }
- }
- }
- }
- catch(Exception $e)
- {
- echo $e->getMessage();
- }
最方便的写法,还是使用xpath:
PHP代码
- try {
-
- $sxi = new SimpleXMLIterator($xmlstring);
-
- $foo = $sxi->xpath('animal/category/species');
-
- foreach ($foo as $k=>$v)
- {
- echo $v.'';
- }
- }
- ch(Exception $e)
- {
- echo $e->getMessage();
- }
下面的例子,显示有namespace的情况:
PHP代码
-
- try {
-
- $sxi = new SimpleXMLIterator($xmlstring);
- $sxi-> registerXPathNamespace('spec', 'http://www.exampe.org/species-title');
-
- $result = $sxi->xpath('//spec:name');
-
- foreach($sxi->getDocNamespaces('animal') as $ns)
- {
- echo $ns.'';
- }
-
- foreach ($result as $k=>$v)
- {
- echo $v.'';
- }
- }
- catch(Exception $e)
- {
- echo $e->getMessage();
- }
增加一个节点:
PHP代码
- try {
-
- $sxi = new SimpleXMLIterator($xmlstring);
-
- $sxi->addChild('animal', 'Tiger');
-
- $new = new SimpleXmlIterator($sxi->saveXML());
-
- foreach($new as $val)
- {
- echo $val.'';
- }
- }
- catch(Exception $e)
- {
- echo $e->getMessage();
- }
增加属性:
PHP代码
- try {
-
- $sxi = new SimpleXMLIterator($xmlstring);
-
- $sxi->addAttribute('id:att1', 'good things', 'urn::test-foo');
-
- $sxi->addAttribute('att2', 'no-ns');
- echo htmlentities($sxi->saveXML());
- }
- catch(Exception $e)
- {
- echo $e->getMessage();
- }
16. CachingIterator类
这个类有一个hasNext()方法,用来判断是否还有下一个元素。
示例如下:
PHP代码
-
- $array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
- try {
-
- $object = new CachingIterator(new ArrayIterator($array));
- foreach($object as $value)
- {
- echo $value;
- if($object->hasNext())
- {
- echo ',';
- }
- }
- }
- catch (Exception $e)
- {
- echo $e->getMessage();
- }
17. LimitIterator类
这个类用来限定返回结果集的数量和位置,必须提供offset和limit两个参数,与SQL命令中limit语句类似。
示例如下:
PHP代码
-
- $offset = 3;
-
- $limit = 2;
- $array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
- $it = new LimitIterator(new ArrayIterator($array), $offset, $limit);
- foreach($it as $k=>$v)
- {
- echo $it->getPosition().'';
- }
另一个例子是:
PHP代码
-
- $array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
- $it = new LimitIterator(new ArrayIterator($array));
- try
- {
- $it->seek(5);
- echo $it->current();
- }
- catch(OutOfBoundsException $e)
- {
- echo $e->getMessage() . "";
- }
18. SplFileObject类
这个类用来对文本文件进行遍历。
示例如下:
PHP代码
- try{
-
- foreach( new SplFileObject("/usr/local/apache/logs/access_log") as $line)
-
- echo $line.'';
- }
- catch (Exception $e)
- {
- echo $e->getMessage();
- }
返回文本文件的第三行,可以这样写:
PHP代码
- try{
- $file = new SplFileObject("/usr/local/apache/logs/access_log");
- $file->seek(3);
- echo $file->current();
- }
- catch (Exception $e)
- {
- echo $e->getMessage();
- }
[参考文献]
1. Introduction to Standard PHP Library (SPL), By Kevin Waterson
2. Introducing PHP 5's Standard Library, By Harry Fuecks
3. The Standard PHP Library (SPL), By Ben Ramsey
4. SPL - Standard PHP Library Documentation
PHP的模版里,smarty一直就是让人又爱又恨的,功能太强大了,以致于美工们看到他也会感觉头疼,毕竟是又要学一门新的语言了。
这么多年,smarty都是在2.x版本里面徘徊,如今,终于要出3了。
以下是官方的change log:
10/6/2008
- completed compilation of {include} tag, variable scoping same as in smarty2
- added compilation of {capture} tag.
- added error message on none existing template files.
10/4/2008
- added comments in the parser definition y file.
- added array of $smarty_token_names to lexer for use in trigger_template_error function
- change handling of none smarty2 style tags like {if}, {for}....
- lexer/parser optimization
10/3/2008
- create different compiled template files depending if caching and/or security is enabled
- cleaned up compiler
- lexer/parser optimization
10/2/2008
- new method trigger fatal error, displays massage and terminates smarty
- compile error status flag added
The compiler will in case of error continue to parse the template(s) to display all errors. No compiled
templates will be written, Smarty terminates after the compiler exits.
- added error message to function __call in Smarty.class.php