手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆

PHP5的 SPL [转摘]

首页 > PHP >

很少看到介绍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代码
  1. // Fetch the "aggregate structure"  
  2. $result = mysql_query("SELECT * FROM users");  
  3. // Iterate over the structure  
  4. while ( $row = mysql_fetch_array($result) ) {  
  5.    // do stuff with the row here  
  6. }  


读出一个目录中的内容,需要这样写:

PHP代码
  1. // Fetch the "aggregate structure"  
  2. $dh = opendir('/home/harryf/files');  
  3. // Iterate over the structure  
  4. while ( $file = readdir($dh) ) {  
  5.    // do stuff with the file here  
  6. }  



读出一个文本文件的内容,需要这样写:

PHP代码
  1. // Fetch the "aggregate structure"  
  2. $fh = fopen("/home/hfuecks/files/results.txt""r");  
  3. // Iterate over the structure  
  4. while (!feof($fh)) {  
  5.    $line = fgets($fh);  
  6.    // do stuff with the line here  
  7. }  


上面三段代码,虽然处理的是不同的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代码
  1. /** 
  2. * An iterator for native PHP arrays, re-inventing the wheel 
  3. * 
  4. * Notice the "implements Iterator" - important! 
  5. */  
  6. class ArrayReloaded implements Iterator {  
  7.    /** 
  8.    * A native PHP array to iterate over 
  9.    */  
  10.  private $array = array();  
  11.    /** 
  12.    * A switch to keep track of the end of the array 
  13.    */  
  14.  private $valid = FALSE;  
  15.    /** 
  16.    * Constructor 
  17.    * @param array native PHP array to iterate over 
  18.    */  
  19.  function __construct($array) {  
  20.    $this->array = $array;  
  21.  }  
  22.    /** 
  23.    * Return the array "pointer" to the first element 
  24.    * PHP's reset() returns false if the array has no elements 
  25.    */  
  26.  function rewind(){  
  27.    $this->valid = (FALSE !== reset($this->array));  
  28.  }  
  29.    /** 
  30.    * Return the current array element 
  31.    */  
  32.  function current(){  
  33.    return current($this->array);  
  34.  }  
  35.    /** 
  36.    * Return the key of the current array element 
  37.    */  
  38.  function key(){  
  39.    return key($this->array);  
  40.  }  
  41.    /** 
  42.    * Move forward by one 
  43.    * PHP's next() returns false if there are no more elements 
  44.    */  
  45.  function next(){  
  46.    $this->valid = (FALSE !== next($this->array));  
  47.  }  
  48.    /** 
  49.    * Is the current element valid? 
  50.    */  
  51.  function valid(){  
  52.    return $this->valid;  
  53.  }  
  54. }  

使用方法如下:

PHP代码
  1. // Create iterator object  
  2. $colors = new ArrayReloaded(array ('red','green','blue',));  
  3. // Iterate away!  
  4. foreach ( $colors as $color ) {  
  5.  echo $color."\n";  
  6. }  

你也可以在foreach循环中使用key()方法:

PHP代码
  1. // Display the keys as well  
  2. foreach ( $colors as $key => $color ) {  
  3.  echo "$key: $color";  
  4. }  

除了foreach循环外,也可以使用while循环,

PHP代码
  1. // Reset the iterator - foreach does this automatically  
  2. $colors->rewind();  
  3. // Loop while valid  
  4. while ( $colors->valid() ) {  
  5.    echo $colors->key().": ".$colors->current()." 
  6. ";  
  7.    $colors->next();  
  8. }  

根据测试,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代码
  1. /** 
  2. * A class that can be used like an array 
  3. */  
  4. class Article implements ArrayAccess {  
  5.  public $title;  
  6.  public $author;  
  7.  public $category;   
  8.  function __construct($title,$author,$category) {  
  9.    $this->title = $title;  
  10.    $this->author = $author;  
  11.    $this->category = $category;  
  12.  }  
  13.  /** 
  14.  * Defined by ArrayAccess interface 
  15.  * Set a value given it's key e.g. $A['title'] = 'foo'; 
  16.  * @param mixed key (string or integer) 
  17.  * @param mixed value 
  18.  * @return void 
  19.  */  
  20.  function offsetSet($key$value) {  
  21.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  22.      $this->{$key} = $value;  
  23.    }  
  24.  }  
  25.  /** 
  26.  * Defined by ArrayAccess interface 
  27.  * Return a value given it's key e.g. echo $A['title']; 
  28.  * @param mixed key (string or integer) 
  29.  * @return mixed value 
  30.  */  
  31.  function offsetGet($key) {  
  32.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  33.      return $this->{$key};  
  34.    }  
  35.  }  
  36.  /** 
  37.  * Defined by ArrayAccess interface 
  38.  * Unset a value by it's key e.g. unset($A['title']); 
  39.  * @param mixed key (string or integer) 
  40.  * @return void 
  41.  */  
  42.  function offsetUnset($key) {  
  43.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  44.      unset($this->{$key});  
  45.    }  
  46.  }  
  47.  /** 
  48.  * Defined by ArrayAccess interface 
  49.  * Check value exists, given it's key e.g. isset($A['title']) 
  50.  * @param mixed key (string or integer) 
  51.  * @return boolean 
  52.  */  
  53.  function offsetExists($offset) {  
  54.    return array_key_exists($offset,get_object_vars($this));  
  55.  }  
  56. }  

使用方法如下:

PHP代码
  1. // Create the object  
  2. $A = new Article('SPL Rocks','Joe Bloggs''PHP');  
  3. // Check what it looks like  
  4. echo 'Initial State:';  
  5. print_r($A);  
  6. echo "\n";  
  7. // Change the title using array syntax  
  8. $A['title'] = 'SPL _really_ rocks';  
  9. // Try setting a non existent property (ignored)  
  10. $A['not found'] = 1;  
  11. // Unset the author field  
  12. unset($A['author']);  
  13. // Check what it looks like again  
  14. echo 'Final State:';  
  15. print_r($A);  
  16. 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代码
  1. function offsetGet($key) {  
  2.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  3.      return strtolower($this->{$key});  
  4.    }  
  5.  }  

5. IteratorAggregate界面
但是,虽然$A可以像数组那样操作,却无法使用foreach遍历,除非部署了前面提到的Iterator界面。
另一个解决方法是,有时会需要将数据和遍历部分分开,这时就可以部署IteratorAggregate界面。它规定了一个getIterator()方法,返回一个使用Iterator界面的object。
还是以上一节的Article类为例:

PHP代码
  1. class Article implements ArrayAccess, IteratorAggregate {  
  2. /** 
  3.  * Defined by IteratorAggregate interface 
  4.  * Returns an iterator for for this object, for use with foreach 
  5.  * @return ArrayIterator 
  6.  */  
  7.  function getIterator() {  
  8.    return new ArrayIterator($this);  
  9.  }  



使用方法如下:

PHP代码
  1. $A = new Article('SPL Rocks','Joe Bloggs''PHP');  
  2. // Loop (getIterator will be called automatically)  
  3. echo 'Looping with foreach:';  
  4. foreach ( $A as $field => $value ) {  
  5.  echo "$field : $value";  
  6. }  
  7. echo '';  
  8. // Get the size of the iterator (see how many properties are left)  
  9. 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代码
  1. class PartyMemberIterator implements SeekableIterator  
  2. {  
  3.     public function __construct(PartyMember $member)  
  4.     {  
  5.         // Store $member locally for iteration  
  6.     }  
  7.     public function seek($index)  
  8.     {  
  9.         $this->rewind();  
  10.         $position = 0;  
  11.         while ($position < $index && $this->valid()) {  
  12.             $this->next();  
  13.             $position++;  
  14.         }  
  15.         if (!$this->valid()) {  
  16.             throw new OutOfBoundsException('Invalid position');  
  17.         }  
  18.     }  
  19.     // Implement current(), key(), next(), rewind()  
  20.     // and valid() to iterate over data in $member  
  21. }  

8. Countable界面
这个界面规定了一个count()方法,返回结果集的数量。
第三部分 SPL Classes
9. SPL的内置类
SPL除了定义一系列Interfaces以外,还提供一系列的内置类,它们对应不同的任务,大大简化了编程。
查看所有的内置类,可以使用下面的代码:

PHP代码
  1. // a simple foreach() to traverse the SPL class names  
  2. foreach(spl_classes() as $key=>$value)  
  3. {  
  4.     echo $key.' -> '.$value.'';  
  5. }  

10. DirectoryIterator类
这个类用来查看一个目录中的所有文件和子目录:
 

PHP代码
  1. try{  
  2.   /*** class create new DirectoryIterator Object ***/  
  3.     foreach ( new DirectoryIterator('./'as $Item )  
  4.         {  
  5.         echo $Item.'';  
  6.         }  
  7.     }  
  8. /*** if an exception is thrown, catch it here ***/  
  9. catch(Exception $e){  
  10.     echo 'No files Found!';  
  11. }  


查看文件的详细信息:
 

PHP代码
  1. foreach(new DirectoryIterator('./' ) as $file )  
  2.     {  
  3.     if$file->getFilename()  == 'foo.txt' )  
  4.         {  
  5.         echo ' getFilename() '; var_dump($file->getFilename()); echo ' ';  
  6.     echo ' getBasename() '; var_dump($file->getBasename()); echo ' ';  
  7.         echo ' isDot() '; var_dump($file->isDot()); echo ' ';  
  8.         echo ' __toString() '; var_dump($file->__toString()); echo ' ';  
  9.         echo ' getPath() '; var_dump($file->getPath()); echo ' ';  
  10.         echo ' getPathname() '; var_dump($file->getPathname()); echo ' ';  
  11.         echo ' getPerms() '; var_dump($file->getPerms()); echo ' ';  
  12.         echo ' getInode() '; var_dump($file->getInode()); echo ' ';  
  13.         echo ' getSize() '; var_dump($file->getSize()); echo ' ';  
  14.         echo ' getOwner() '; var_dump($file->getOwner()); echo ' ';  
  15.         echo ' $file->getGroup() '; var_dump($file->getGroup()); echo ' ';  
  16.         echo ' getATime() '; var_dump($file->getATime()); echo ' ';  
  17.         echo ' getMTime() '; var_dump($file->getMTime()); echo ' ';  
  18.         echo ' getCTime() '; var_dump($file->getCTime()); echo ' ';  
  19.         echo ' getType() '; var_dump($file->getType()); echo ' ';  
  20.         echo ' isWritable() '; var_dump($file->isWritable()); echo ' ';  
  21.         echo ' isReadable() '; var_dump($file->isReadable()); echo ' ';  
  22.         echo ' isExecutable( '; var_dump($file->isExecutable()); echo ' ';  
  23.         echo ' isFile() '; var_dump($file->isFile()); echo ' ';  
  24.         echo ' isDir() '; var_dump($file->isDir()); echo ' ';  
  25.         echo ' isLink() '; var_dump($file->isLink()); echo ' ';  
  26.         echo ' getFileInfo() '; var_dump($file->getFileInfo()); echo ' ';  
  27.         echo ' getPathInfo() '; var_dump($file->getPathInfo()); echo ' ';  
  28.         echo ' openFile() '; var_dump($file->openFile()); echo ' ';  
  29.         echo ' setFileClass() '; var_dump($file->setFileClass()); echo ' ';  
  30.         echo ' setInfoClass() '; var_dump($file->setInfoClass()); echo ' ';  
  31.         }  
  32. }  


除了foreach循环外,还可以使用while循环:

PHP代码
  1.     /*** create a new iterator object ***/  
  2.     $it = new DirectoryIterator('./');  
  3.     /*** loop directly over the object ***/  
  4.     while($it->valid())  
  5.     {  
  6.         echo $it->key().' -- '.$it->current().' ';  
  7.         /*** move to the next iteration ***/  
  8.         $it->next();  
  9.     }  

如果要过滤所有子目录,可以在valid()方法中过滤:

PHP代码
  1. /*** create a new iterator object ***/  
  2. $it = new DirectoryIterator('./');  
  3. /*** loop directly over the object ***/  
  4. while($it->valid())  
  5. {  
  6.     /*** check if value is a directory ***/  
  7.     if($it->isDir())  
  8.     {  
  9.        /*** echo the key and current value ***/  
  10.        echo $it->key().' -- '.$it->current().'';  
  11.     }  
  12.     /*** move to the next iteration ***/  
  13.     $it->next();  
  14.  }  

11. ArrayObject类
这个类可以将Array转化为object。
 

PHP代码
  1. /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. /*** create the array object ***/  
  4. $arrayObj = new ArrayObject($array);  
  5. /*** iterate over the array ***/  
  6. for($iterator = $arrayObj->getIterator();  
  7.    /*** check if valid ***/  
  8.    $iterator->valid();  
  9.    /*** move to the next array member ***/  
  10.    $iterator->next())  
  11.     {  
  12.     /*** output the key and current array value ***/  
  13.     echo $iterator->key() . ' => ' . $iterator->current() . '';  
  14.     }  


增加一个元素:
    $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代码
  1. /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. try {  
  4.     $object = new ArrayIterator($array);  
  5.     foreach($object as $key=>$value)  
  6.     {  
  7.         echo $key.' => '.$value.'';  
  8.     }  
  9. }  
  10. catch (Exception $e)  
  11. {  
  12.     echo $e->getMessage();  
  13. }  
  14.   
  15. //rayIterator类也支持offset类方法和count()方法:  
  16.   
  17.     /*** a simple array ***/  
  18. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  19. try {  
  20.     $object = new ArrayIterator($array);  
  21.     /*** check for the existence of the offset 2 ***/  
  22.     if($object->offSetExists(2))  
  23.     {  
  24.         /*** set the offset of 2 to a new value ***/  
  25.         $object->offSetSet(2, 'Goanna');  
  26.     }  
  27.    /*** unset the kiwi ***/  
  28.    foreach($object as $key=>$value)  
  29.    {  
  30.         /*** check the value of the key ***/  
  31.         if($object->offSetGet($key) === 'kiwi')  
  32.         {  
  33.             /*** unset the current key ***/  
  34.             $object->offSetUnset($key);  
  35.         }  
  36.         echo ''.$key.' - '.$value.''."\n";  
  37.     }  
  38. }  
  39. catch (Exception $e)  
  40. {  
  41.     echo $e->getMessage();  
  42. }  


    ?>
   

13. RecursiveArrayIterator类和RecursiveIteratorIterator类
ArrayIterator类和ArrayObject类,只支持遍历一维数组。如果要遍历多维数组,必须先用 RecursiveIteratorIterator生成一个Iterator,然后再对这个Iterator使用 RecursiveIteratorIterator。

PHP代码
  1. $array = array(  
  2.    array('name'=>'butch''sex'=>'m''breed'=>'boxer'),  
  3.    array('name'=>'fido''sex'=>'m''breed'=>'doberman'),  
  4.    array('name'=>'girly','sex'=>'f''breed'=>'poodle')  
  5. );  
  6. foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key=>$value)  
  7. {  
  8.     echo $key.' -- '.$value.'';  
  9. }  

14. FilterIterator类
FilterIterator类可以对元素进行过滤,只要在accept()方法中设置过滤条件就可以了。
示例如下:

PHP代码
  1.         /*** a simple array ***/  
  2.     $animals = array('koala''kangaroo''wombat''wallaby''emu''NZ'=>'kiwi''kookaburra''platypus');  
  3.     class CullingIterator extends FilterIterator{  
  4.     /*** The filteriterator takes  a iterator as param: ***/  
  5.     public function __construct( Iterator $it ){  
  6.       parent::__construct( $it );  
  7.     }  
  8.     /*** check if key is numeric ***/  
  9.     function accept(){  
  10.       return is_numeric($this->key());  
  11.     }  
  12.     }/*** end of class ***/  
  13.     $cull = new CullingIterator(new ArrayIterator($animals));  
  14.     foreach($cull as $key=>$value)  
  15.         {  
  16.         echo $key.' == '.$value.'';  
  17.         }  
  18.     ?>  
  19. //下面是另一个返回质数的例子:  
  20.      
  21.     class PrimeFilter extends FilterIterator{  
  22.     /*** The filteriterator takes  a iterator as param: ***/  
  23.     public function __construct(Iterator $it){  
  24.       parent::__construct($it);  
  25.     }  
  26.     /*** check if current value is prime ***/  
  27.     function accept(){  
  28.     if($this->current() % 2 != 1)  
  29.         {  
  30.         return false;  
  31.         }  
  32.     $d = 3;  
  33.     $x = sqrt($this->current());  
  34.     while ($this->current() % $d != 0 && $d < $x)  
  35.         {  
  36.         $d += 2;  
  37.         }  
  38.      return (($this->current() % $d == 0 && $this->current() != $d) * 1) == 0 ? true : false;  
  39.     }  
  40.     }/*** end of class ***/  
  41.     /*** an array of numbers ***/  
  42.     $numbers = range(212345,212456);  
  43.     /*** create a new FilterIterator object ***/  
  44.     $primes = new primeFilter(new ArrayIterator($numbers));  
  45.     foreach($primes as $value)  
  46.         {  
  47.         echo $value.' is prime.';  
  48.         }  

15. SimpleXMLIterator类
这个类用来遍历xml文件。
示例如下:
 原文的XML在就是变型的,或者说在解释的时候已经坏掉了,所以。我删除了,直接看方法吧:by 膘叔

PHP代码
  1. /*** a new simpleXML iterator object ***/  
  2. try    {  
  3.        /*** a new simple xml iterator ***/  
  4.        $it = new SimpleXMLIterator($xmlstring);  
  5.        /*** a new limitIterator object ***/  
  6.        foreach(new RecursiveIteratorIterator($it,1) as $name => $data)  
  7.           {  
  8.           echo $name.' -- '.$data.'';  
  9.           }  
  10.     }  
  11. catch(Exception $e)  
  12.     {  
  13.     echo $e->getMessage();  
  14.     }  

new RecursiveIteratorIterator($it,1)表示显示所有包括父元素在内的子元素。
显示某一个特定的元素值,可以这样写:

PHP代码
  1. try {  
  2. /*** a new simpleXML iterator object ***/  
  3. $sxi =  new SimpleXMLIterator($xmlstring); 
  4. foreach ( $sxi as $node )  
  5.     {  
  6.     foreach($node as $k=>$v)  
  7.         {  
  8.         echo $v->species.'';  
  9.         }  
  10.     }  
  11. }  
  12. catch(Exception $e)  
  13. {  
  14. echo $e->getMessage();  
  15. }  


相对应的while循环写法为:
 

PHP代码
  1. try {  
  2. $sxe = simplexml_load_string($xmlstring'SimpleXMLIterator');  
  3. for ($sxe->rewind(); $sxe->valid(); $sxe->next())  
  4.     {  
  5.     if($sxe->hasChildren())  
  6.         {  
  7.         foreach($sxe->getChildren() as $element=>$value)  
  8.           {  
  9.           echo $value->species.'';  
  10.           }  
  11.         }  
  12.      }  
  13.    }  
  14. catch(Exception $e)  
  15.    {  
  16.    echo $e->getMessage();  
  17.    }  


最方便的写法,还是使用xpath:
 

PHP代码
  1. try {  
  2.  /*** a new simpleXML iterator object ***/  
  3.  $sxi =  new SimpleXMLIterator($xmlstring);  
  4.  /*** set the xpath ***/  
  5.  $foo = $sxi->xpath('animal/category/species');  
  6.  /*** iterate over the xpath ***/  
  7.  foreach ($foo as $k=>$v)  
  8.      {  
  9.      echo $v.'';  
  10.      }  
  11.  }  
  12. ch(Exception $e)  
  13.  {  
  14.  echo $e->getMessage();  
  15.  }  


下面的例子,显示有namespace的情况:

PHP代码
  1. /*** a new simpleXML iterator object ***/  
  2. try {  
  3.     /*** a new simpleXML iterator object ***/  
  4.     $sxi =  new SimpleXMLIterator($xmlstring);  
  5.     $sxi-> registerXPathNamespace('spec''http://www.exampe.org/species-title');  
  6.     /*** set the xpath ***/  
  7.     $result = $sxi->xpath('//spec:name');  
  8.     /*** get all declared namespaces ***/  
  9.    foreach($sxi->getDocNamespaces('animal'as $ns)  
  10.         {  
  11.         echo $ns.'';  
  12.         }  
  13.     /*** iterate over the xpath ***/  
  14.     foreach ($result as $k=>$v)  
  15.         {  
  16.         echo $v.'';  
  17.         }  
  18.     }  
  19. catch(Exception $e)  
  20.     {  
  21.     echo $e->getMessage();  
  22.     }  


增加一个节点:

PHP代码
  1. try {  
  2.     /*** a new simpleXML iterator object ***/  
  3.     $sxi =  new SimpleXMLIterator($xmlstring);  
  4.     /*** add a child ***/  
  5.     $sxi->addChild('animal''Tiger');  
  6.     /*** a new simpleXML iterator object ***/  
  7.     $new = new SimpleXmlIterator($sxi->saveXML());  
  8.     /*** iterate over the new tree ***/  
  9.     foreach($new as $val)  
  10.         {  
  11.         echo $val.'';  
  12.         }  
  13.     }  
  14. catch(Exception $e)  
  15.     {  
  16.     echo $e->getMessage();  
  17.     }  

增加属性:

PHP代码
  1. try {  
  2.     /*** a new simpleXML iterator object ***/  
  3.     $sxi =  new SimpleXMLIterator($xmlstring);  
  4.     /*** add an attribute with a namespace ***/  
  5.     $sxi->addAttribute('id:att1''good things''urn::test-foo');  
  6.     /*** add an attribute without a  namespace ***/  
  7.     $sxi->addAttribute('att2''no-ns');  
  8.     echo htmlentities($sxi->saveXML());  
  9.     }  
  10. catch(Exception $e)  
  11.     {  
  12.     echo $e->getMessage();  
  13.     }  

16. CachingIterator类
这个类有一个hasNext()方法,用来判断是否还有下一个元素。
示例如下:
 

PHP代码
  1.    /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. try {  
  4.     /*** create a new object ***/  
  5.     $object = new CachingIterator(new ArrayIterator($array));  
  6.     foreach($object as $value)  
  7.         {  
  8.         echo $value;  
  9.         if($object->hasNext())  
  10.             {  
  11.             echo ',';  
  12.             }  
  13.         }  
  14.     }  
  15. catch (Exception $e)  
  16.     {  
  17.     echo $e->getMessage();  
  18.     }  

17. LimitIterator类
这个类用来限定返回结果集的数量和位置,必须提供offset和limit两个参数,与SQL命令中limit语句类似。
示例如下:

PHP代码
  1.     /*** the offset value ***/  
  2. $offset = 3;  
  3. /*** the limit of records to show ***/  
  4. $limit = 2;  
  5. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  6. $it = new LimitIterator(new ArrayIterator($array), $offset$limit);  
  7. foreach($it as $k=>$v)  
  8.     {  
  9.     echo $it->getPosition().'';  
  10.     }  

另一个例子是:
   

PHP代码
  1. /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. $it = new LimitIterator(new ArrayIterator($array));  
  4. try  
  5.     {  
  6.     $it->seek(5);  
  7.     echo $it->current();  
  8.     }  
  9. catch(OutOfBoundsException $e)  
  10.     {  
  11.     echo $e->getMessage() . "";  
  12.     }  


18. SplFileObject类
这个类用来对文本文件进行遍历。
示例如下:

PHP代码
  1. try{  
  2.     // iterate directly over the object  
  3.     foreachnew SplFileObject("/usr/local/apache/logs/access_log"as $line)  
  4.     // and echo each line of the file  
  5.     echo $line.'';  
  6. }  
  7. catch (Exception $e)  
  8.     {  
  9.     echo $e->getMessage();  
  10.     }  

返回文本文件的第三行,可以这样写:

PHP代码
  1. try{  
  2.     $file = new SplFileObject("/usr/local/apache/logs/access_log");  
  3.     $file->seek(3);  
  4.     echo $file->current();  
  5. }  
  6. catch (Exception $e)  
  7. {  
  8.     echo $e->getMessage();  
  9. }  


[参考文献]
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

 




本站采用创作共享版权协议, 要求署名、非商业和保持一致. 本站欢迎任何非商业应用的转载, 但须注明出自"易栈网-膘叔", 保留原始链接, 此外还必须标注原文标题和链接.

« 上一篇 | 下一篇 »

发表评论

评论内容 (必填):