日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

PHP SPL笔记

發布時間:2023/11/27 生活经验 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PHP SPL笔记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

PHP SPL筆記

作者: 阮一峰

日期: 2008年7月 8日

這幾天,我在學習PHP語言中的SPL。

這個東西應該屬于PHP中的高級內容,看上去很復雜,但是非常有用,所以我做了長篇筆記。不然記不住,以后要用的時候,還是要從頭學起。

由于這是供自己參考的筆記,不是教程,所以寫得比較簡單,沒有多解釋。但是我想,如果你是一個熟練的PHP5程序員,應該足以看懂下面的材料,而且會發現它很有用?,F在除此之外,網上根本沒有任何深入的SPL中文介紹。

================

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的結果集,程序需要這樣寫:

// Fetch the "aggregate structure"
$result = mysql_query("SELECT * FROM users");// Iterate over the structure
while ( $row = mysql_fetch_array($result) ) {// do stuff with the row here
}

讀出一個目錄中的內容,需要這樣寫:

// Fetch the "aggregate structure"
$dh = opendir('/home/harryf/files');// Iterate over the structure
while ( $file = readdir($dh) ) {// do stuff with the file here
}

讀出一個文本文件的內容,需要這樣寫:

// Fetch the "aggregate structure"
$fh = fopen("/home/hfuecks/files/results.txt", "r");// Iterate over the structure
while (!feof($fh)) {$line = fgets($fh);// do stuff with the line here}

上面三段代碼,雖然處理的是不同的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 solelyresponsible 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示例:

/**
* An iterator for native PHP arrays, re-inventing the wheel
*
* Notice the "implements Iterator" - important!
*/
class ArrayReloaded implements Iterator {/*** A native PHP array to iterate over*/private $array = array();/*** A switch to keep track of the end of the array*/private $valid = FALSE;/*** Constructor* @param array native PHP array to iterate over*/function __construct($array) {$this->array = $array;}/*** Return the array "pointer" to the first element* PHP's reset() returns false if the array has no elements*/function rewind(){$this->valid = (FALSE !== reset($this->array));}/*** Return the current array element*/function current(){return current($this->array);}/*** Return the key of the current array element*/function key(){return key($this->array);}/*** Move forward by one* PHP's next() returns false if there are no more elements*/function next(){$this->valid = (FALSE !== next($this->array));}/*** Is the current element valid?*/function valid(){return $this->valid;}
}

使用方法如下:

// Create iterator object
$colors = new ArrayReloaded(array ('red','green','blue',));// Iterate away!
foreach ( $colors as $color ) {echo $color."<br>";
}

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

// Display the keys as well
foreach ( $colors as $key => $color ) {echo "$key: $color<br>";
}

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

// Reset the iterator - foreach does this automatically
$colors->rewind();// Loop while valid
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 valuefor 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界面的實例:

/**
* A class that can be used like an array
*/
class Article implements ArrayAccess {public $title;public $author;public $category;  function __construct($title,$author,$category) {$this->title = $title;$this->author = $author;$this->category = $category;}/*** Defined by ArrayAccess interface* Set a value given it's key e.g. $A['title'] = 'foo';* @param mixed key (string or integer)* @param mixed value* @return void*/function offsetSet($key, $value) {if ( array_key_exists($key,get_object_vars($this)) ) {$this->{$key} = $value;}}/*** Defined by ArrayAccess interface* Return a value given it's key e.g. echo $A['title'];* @param mixed key (string or integer)* @return mixed value*/function offsetGet($key) {if ( array_key_exists($key,get_object_vars($this)) ) {return $this->{$key};}}/*** Defined by ArrayAccess interface* Unset a value by it's key e.g. unset($A['title']);* @param mixed key (string or integer)* @return void*/function offsetUnset($key) {if ( array_key_exists($key,get_object_vars($this)) ) {unset($this->{$key});}}/*** Defined by ArrayAccess interface* Check value exists, given it's key e.g. isset($A['title'])* @param mixed key (string or integer)* @return boolean*/function offsetExists($offset) {return array_key_exists($offset,get_object_vars($this));}}

使用方法如下:

// Create the object
$A = new Article('SPL Rocks','Joe Bloggs', 'PHP');// Check what it looks like
echo 'Initial State:<div>';
print_r($A);
echo '</div>';// Change the title using array syntax
$A['title'] = 'SPL _really_ rocks';// Try setting a non existent property (ignored)
$A['not found'] = 1;// Unset the author field
unset($A['author']);// Check what it looks like again
echo 'Final State:<div>';
print_r($A);
echo '</div>';

運行結果如下:

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那樣操作。

你還可以在讀取數據時,增加程序內部的邏輯:

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類為例:

class Article implements ArrayAccess, IteratorAggregate {/*** Defined by IteratorAggregate interface* Returns an iterator for for this object, for use with foreach* @return ArrayIterator*/function getIterator() {return new ArrayIterator($this);}

使用方法如下:

$A = new Article('SPL Rocks','Joe Bloggs', 'PHP');// Loop (getIterator will be called automatically)
echo 'Looping with foreach:<div>';
foreach ( $A as $field => $value ) {echo "$field : $value<br>";
}
echo '</div>';// Get the size of the iterator (see how many properties are left)
echo "Object has ".sizeof($A->getIterator())." elements";

顯示結果如下:

Looping with foreach:title : SPL Rocks
author : Joe Bloggs
category : PHPObject 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。

下面是一個是實例:

<?phpclass PartyMemberIterator implements SeekableIterator
{public function __construct(PartyMember $member){// Store $member locally for iteration}public function seek($index){$this->rewind();$position = 0;while ($position < $index && $this->valid()) {$this->next();$position++;}if (!$this->valid()) {throw new OutOfBoundsException('Invalid position');}}// Implement current(), key(), next(), rewind()// and valid() to iterate over data in $member
}?>

8. Countable界面

這個界面規定了一個count()方法,返回結果集的數量。

第三部分 SPL Classes

9. SPL的內置類

SPL除了定義一系列Interfaces以外,還提供一系列的內置類,它們對應不同的任務,大大簡化了編程。

查看所有的內置類,可以使用下面的代碼:

<?php
// a simple foreach() to traverse the SPL class names
foreach(spl_classes() as $key=>$value){echo $key.' -&gt; '.$value.'<br />';}
?>

10. DirectoryIterator類

這個類用來查看一個目錄中的所有文件和子目錄:

<?phptry{/*** class create new DirectoryIterator Object ***/foreach ( new DirectoryIterator('./') as $Item ){echo $Item.'<br />';}}
/*** if an exception is thrown, catch it here ***/
catch(Exception $e){echo 'No files Found!<br />';
}
?>

查看文件的詳細信息:

<table>
<?phpforeach(new DirectoryIterator('./' ) as $file ){if( $file->getFilename()  == 'foo.txt' ){echo '<tr><td>getFilename()</td><td> '; var_dump($file->getFilename()); echo '</td></tr>';echo '<tr><td>getBasename()</td><td> '; var_dump($file->getBasename()); echo '</td></tr>';echo '<tr><td>isDot()</td><td> '; var_dump($file->isDot()); echo '</td></tr>';echo '<tr><td>__toString()</td><td> '; var_dump($file->__toString()); echo '</td></tr>';echo '<tr><td>getPath()</td><td> '; var_dump($file->getPath()); echo '</td></tr>';echo '<tr><td>getPathname()</td><td> '; var_dump($file->getPathname()); echo '</td></tr>';echo '<tr><td>getPerms()</td><td> '; var_dump($file->getPerms()); echo '</td></tr>';echo '<tr><td>getInode()</td><td> '; var_dump($file->getInode()); echo '</td></tr>';echo '<tr><td>getSize()</td><td> '; var_dump($file->getSize()); echo '</td></tr>';echo '<tr><td>getOwner()</td><td> '; var_dump($file->getOwner()); echo '</td></tr>';echo '<tr><td>$file->getGroup()</td><td> '; var_dump($file->getGroup()); echo '</td></tr>';echo '<tr><td>getATime()</td><td> '; var_dump($file->getATime()); echo '</td></tr>';echo '<tr><td>getMTime()</td><td> '; var_dump($file->getMTime()); echo '</td></tr>';echo '<tr><td>getCTime()</td><td> '; var_dump($file->getCTime()); echo '</td></tr>';echo '<tr><td>getType()</td><td> '; var_dump($file->getType()); echo '</td></tr>';echo '<tr><td>isWritable()</td><td> '; var_dump($file->isWritable()); echo '</td></tr>';echo '<tr><td>isReadable()</td><td> '; var_dump($file->isReadable()); echo '</td></tr>';echo '<tr><td>isExecutable(</td><td> '; var_dump($file->isExecutable()); echo '</td></tr>';echo '<tr><td>isFile()</td><td> '; var_dump($file->isFile()); echo '</td></tr>';echo '<tr><td>isDir()</td><td> '; var_dump($file->isDir()); echo '</td></tr>';echo '<tr><td>isLink()</td><td> '; var_dump($file->isLink()); echo '</td></tr>';echo '<tr><td>getFileInfo()</td><td> '; var_dump($file->getFileInfo()); echo '</td></tr>';echo '<tr><td>getPathInfo()</td><td> '; var_dump($file->getPathInfo()); echo '</td></tr>';echo '<tr><td>openFile()</td><td> '; var_dump($file->openFile()); echo '</td></tr>';echo '<tr><td>setFileClass()</td><td> '; var_dump($file->setFileClass()); echo '</td></tr>';echo '<tr><td>setInfoClass()</td><td> '; var_dump($file->setInfoClass()); echo '</td></tr>';}
}
?>
</table>

除了foreach循環外,還可以使用while循環:

<?php
/*** create a new iterator object ***/
$it = new DirectoryIterator('./');/*** loop directly over the object ***/
while($it->valid()){echo $it->key().' -- '.$it->current().'<br />';/*** move to the next iteration ***/$it->next();}
?>

如果要過濾所有子目錄,可以在valid()方法中過濾:

<?php
/*** create a new iterator object ***/
$it = new DirectoryIterator('./');/*** loop directly over the object ***/
while($it->valid()){/*** check if value is a directory ***/if($it->isDir()){/*** echo the key and current value ***/echo $it->key().' -- '.$it->current().'<br />';}/*** move to the next iteration ***/$it->next();}
?>

11. ArrayObject類

這個類可以將Array轉化為object。

<?php/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');/*** create the array object ***/
$arrayObj = new ArrayObject($array);/*** iterate over the array ***/
for($iterator = $arrayObj->getIterator();/*** check if valid ***/$iterator->valid();/*** move to the next array member ***/$iterator->next()){/*** output the key and current array value ***/echo $iterator->key() . ' => ' . $iterator->current() . '<br />';}
?>

增加一個元素:

$arrayObj->append('dingo');

對元素排序:

$arrayObj->natcasesort();

顯示元素的數量:

echo $arrayObj->count();

刪除一個元素:

$arrayObj->offsetUnset(5);

某一個元素是否存在:

 if ($arrayObj->offsetExists(3)){echo 'Offset Exists<br />';}

更改某個位置的元素值:

 $arrayObj->offsetSet(5, "galah");

顯示某個位置的元素值:

echo $arrayObj->offsetGet(4);
12. ArrayIterator類

這個類實際上是對ArrayObject類的補充,為后者提供遍歷功能。

示例如下:

<?php
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');try {$object = new ArrayIterator($array);foreach($object as $key=>$value){echo $key.' => '.$value.'<br />';}}
catch (Exception $e){echo $e->getMessage();}
?>

ArrayIterator類也支持offset類方法和count()方法:

<ul>
<?php
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');try {$object = new ArrayIterator($array);/*** check for the existence of the offset 2 ***/if($object->offSetExists(2)){/*** set the offset of 2 to a new value ***/$object->offSetSet(2, 'Goanna');}/*** unset the kiwi ***/foreach($object as $key=>$value){/*** check the value of the key ***/if($object->offSetGet($key) === 'kiwi'){/*** unset the current key ***/$object->offSetUnset($key);}echo '<li>'.$key.' - '.$value.'</li>'."\n";}}
catch (Exception $e){echo $e->getMessage();}
?>
</ul>

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.'<br />';}
?>

14. FilterIterator類

FilterIterator類可以對元素進行過濾,只要在accept()方法中設置過濾條件就可以了。

示例如下:

<?php
/*** a simple array ***/
$animals = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'NZ'=>'kiwi', 'kookaburra', 'platypus');class CullingIterator extends FilterIterator{/*** The filteriterator takes  a iterator as param: ***/
public function __construct( Iterator $it ){parent::__construct( $it );
}/*** check if key is numeric ***/
function accept(){return is_numeric($this->key());
}}/*** end of class ***/
$cull = new CullingIterator(new ArrayIterator($animals));foreach($cull as $key=>$value){echo $key.' == '.$value.'<br />';}
?>

下面是另一個返回質數的例子:

<?phpclass PrimeFilter extends FilterIterator{/*** The filteriterator takes  a iterator as param: ***/
public function __construct(Iterator $it){parent::__construct($it);
}/*** check if current value is prime ***/
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;
}}/*** end of class ***//*** an array of numbers ***/
$numbers = range(212345,212456);/*** create a new FilterIterator object ***/
$primes = new primeFilter(new ArrayIterator($numbers));foreach($primes as $value){echo $value.' is prime.<br />';}
?>

15. SimpleXMLIterator類

這個類用來遍歷xml文件。

示例如下:

<?php/*** a simple xml tree ***/$xmlstring = <<<XML
<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>
<document><animal><category id="26"><species>Phascolarctidae</species><type>koala</type><name>Bruce</name></category></animal><animal><category id="27"><species>macropod</species><type>kangaroo</type><name>Bruce</name></category></animal><animal><category id="28"><species>diprotodon</species><type>wombat</type><name>Bruce</name></category></animal><animal><category id="31"><species>macropod</species><type>wallaby</type><name>Bruce</name></category></animal><animal><category id="21"><species>dromaius</species><type>emu</type><name>Bruce</name></category></animal><animal><category id="22"><species>Apteryx</species><type>kiwi</type><name>Troy</name></category></animal><animal><category id="23"><species>kingfisher</species><type>kookaburra</type><name>Bruce</name></category></animal><animal><category id="48"><species>monotremes</species><type>platypus</type><name>Bruce</name></category></animal><animal><category id="4"><species>arachnid</species><type>funnel web</type><name>Bruce</name><legs>8</legs></category></animal>
</document>
XML;/*** a new simpleXML iterator object ***/
try    {/*** a new simple xml iterator ***/$it = new SimpleXMLIterator($xmlstring);/*** a new limitIterator object ***/foreach(new RecursiveIteratorIterator($it,1) as $name => $data){echo $name.' -- '.$data.'<br />';}}
catch(Exception $e){echo $e->getMessage();}
?>

new RecursiveIteratorIterator($it,1)表示顯示所有包括父元素在內的子元素。

顯示某一個特定的元素值,可以這樣寫:

<?php
try {/*** a new simpleXML iterator object ***/$sxi =  new SimpleXMLIterator($xmlstring);foreach ( $sxi as $node ){foreach($node as $k=>$v){echo $v->species.'<br />';}}}
catch(Exception $e){echo $e->getMessage();}
?>

相對應的while循環寫法為:

<?phptry {
$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.'<br />';}}}}
catch(Exception $e){echo $e->getMessage();}
?>

最方便的寫法,還是使用xpath:

<?php
try {/*** a new simpleXML iterator object ***/$sxi =  new SimpleXMLIterator($xmlstring);/*** set the xpath ***/$foo = $sxi->xpath('animal/category/species');/*** iterate over the xpath ***/foreach ($foo as $k=>$v){echo $v.'<br />';}}
catch(Exception $e){echo $e->getMessage();}
?>

下面的例子,顯示有namespace的情況:

<?php/*** a simple xml tree ***/$xmlstring = <<<XML
<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>
<document xmlns:spec="http://example.org/animal-species"><animal><category id="26"><species>Phascolarctidae</species><spec:name>Speed Hump</spec:name><type>koala</type><name>Bruce</name></category></animal><animal><category id="27"><species>macropod</species><spec:name>Boonga</spec:name><type>kangaroo</type><name>Bruce</name></category></animal><animal><category id="28"><species>diprotodon</species><spec:name>pot holer</spec:name><type>wombat</type><name>Bruce</name></category></animal><animal><category id="31"><species>macropod</species><spec:name>Target</spec:name><type>wallaby</type><name>Bruce</name></category></animal><animal><category id="21"><species>dromaius</species><spec:name>Road Runner</spec:name><type>emu</type><name>Bruce</name></category></animal><animal><category id="22"><species>Apteryx</species><spec:name>Football</spec:name><type>kiwi</type><name>Troy</name></category></animal><animal><category id="23"><species>kingfisher</species><spec:name>snaker</spec:name><type>kookaburra</type><name>Bruce</name></category></animal><animal><category id="48"><species>monotremes</species><spec:name>Swamp Rat</spec:name><type>platypus</type><name>Bruce</name></category></animal><animal><category id="4"><species>arachnid</species><spec:name>Killer</spec:name><type>funnel web</type><name>Bruce</name><legs>8</legs></category></animal>
</document>
XML;/*** a new simpleXML iterator object ***/
try {/*** a new simpleXML iterator object ***/$sxi =  new SimpleXMLIterator($xmlstring);$sxi-> registerXPathNamespace('spec', 'http://www.exampe.org/species-title');/*** set the xpath ***/$result = $sxi->xpath('//spec:name');/*** get all declared namespaces ***/foreach($sxi->getDocNamespaces('animal') as $ns){echo $ns.'<br />';}/*** iterate over the xpath ***/foreach ($result as $k=>$v){echo $v.'<br />';}}
catch(Exception $e){echo $e->getMessage();}
?>

增加一個節點:

<?php $xmlstring = <<<XML
<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>
<document><animal>koala</animal><animal>kangaroo</animal><animal>wombat</animal><animal>wallaby</animal><animal>emu</animal><animal>kiwi</animal><animal>kookaburra</animal><animal>platypus</animal><animal>funnel web</animal>
</document>
XML;try {/*** a new simpleXML iterator object ***/$sxi =  new SimpleXMLIterator($xmlstring);/*** add a child ***/$sxi->addChild('animal', 'Tiger');/*** a new simpleXML iterator object ***/$new = new SimpleXmlIterator($sxi->saveXML());/*** iterate over the new tree ***/foreach($new as $val){echo $val.'<br />';}}
catch(Exception $e){echo $e->getMessage();}
?>

增加屬性:

<?php 
$xmlstring =<<<XML
<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>
<document><animal>koala</animal><animal>kangaroo</animal><animal>wombat</animal><animal>wallaby</animal><animal>emu</animal><animal>kiwi</animal><animal>kookaburra</animal><animal>platypus</animal><animal>funnel web</animal>
</document>
XML;try {/*** a new simpleXML iterator object ***/$sxi =  new SimpleXMLIterator($xmlstring);/*** add an attribute with a namespace ***/$sxi->addAttribute('id:att1', 'good things', 'urn::test-foo');/*** add an attribute without a  namespace ***/$sxi->addAttribute('att2', 'no-ns');echo htmlentities($sxi->saveXML());}
catch(Exception $e){echo $e->getMessage();}
?>

16. CachingIterator類

這個類有一個hasNext()方法,用來判斷是否還有下一個元素。

示例如下:

<?php
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');try {/*** create a new object ***/$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
/*** the offset value ***/
$offset = 3;/*** the limit of records to show ***/
$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().'<br />';}
?>

另一個例子是:

<?php/*** a simple array ***/
$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() . "<br />";}
?>

18. SplFileObject類

這個類用來對文本文件進行遍歷。

示例如下:

<?phptry{// iterate directly over the objectforeach( new SplFileObject(&quot;/usr/local/apache/logs/access_log&quot;) as $line)// and echo each line of the fileecho $line.'<br />';
}
catch (Exception $e){echo $e->getMessage();}
?>

返回文本文件的第三行,可以這樣寫:

<?phptry{$file = new SplFileObject("/usr/local/apache/logs/access_log");$file->seek(3);echo $file->current();}
catch (Exception $e){echo $e->getMessage();}
?>

總結

以上是生活随笔為你收集整理的PHP SPL笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 亚洲经典一区二区三区四区 | 可以免费看的黄色网址 | 女人扒开腿让男人捅爽 | 久久久免费看片 | 丰满少妇一区二区三区专区 | 最近免费中文字幕中文高清百度 | 日韩三级电影网址 | 男人手机天堂 | 国产113页 | 91宅男 | 色网站视频 | 欧美大喷水吹潮合集在线观看 | 国产凹凸一区二二区 | www.黄色大片 | 日韩欧美国产一区二区三区 | 可以在线观看av的网站 | 日本熟妇一区二区三区四区 | aaa在线视频 | 欧美综合一区二区 | 久久久久久久久久久久 | 国产区视频在线观看 | 日本性网站 | 欧美aa大片| 久久片 | 国产色无码精品视频 | 亚洲天堂中文 | 国精品人妻无码一区二区三区喝尿 | www操| 九九九国产视频 | 亚洲天堂中文字幕在线 | 欧美精品一区二区三区三州 | 图片区亚洲| 亚洲午夜色 | 九九久久免费视频 | 男生把女生困困的视频 | 日本aaa级片| 手机在线看片福利 | 国产视频二区三区 | 久久久久国产精品午夜一区 | 日韩视频播放 | 致命魔术电影高清在线观看 | 手机看片日韩 | 国产福利视频一区二区 | 日本成人久久 | 国产一级片自拍 | 老司机av影院 | 天堂中文字幕 | 美女黄视频大全 | 亚洲精品国产精品国自产观看浪潮 | 国产成人毛毛毛片 | 久月婷婷 | 亚州色图欧美色图| 国产chinesehd精品 | 亚洲精品久久久久久一区二区 | 亚洲免费一区二区 | 久久精品视频8 | 高清日韩av | 激情五月色婷婷 | 色女人av | 日韩精品一区二区在线 | 亚洲精品高潮 | 国产免费资源 | 久久成人人人人精品欧 | av毛片精品 | 欧美一级片在线看 | 午夜福利视频合集1000 | 国产精品jizz在线观看老狼 | 全黄性性激高免费视频 | 日韩在线| 国产超碰精品 | 成人性生交大片免费看96 | 天堂资源网 | 人人爽av | 亚洲熟女综合色一区二区三区 | 日韩乱码一区二区三区 | 女厕厕露p撒尿八个少妇 | 疯狂做受xxxx国产 | 午夜电影网一区 | 午夜精彩视频 | 最新中文字幕视频 | 日批小视频| 在线射| 久久久中文字幕 | 免费污污视频在线观看 | 嫩草影院在线观看视频 | 奇米激情 | 人人爽夜夜爽 | 久久久精品中文字幕 | 成人免费毛片足控 | 中文字幕理伦片免费看 | 色av免费| 欧洲美女毛片 | 欧美色图另类 | 蜜桃成人免费视频 | 国产第一草草影院 | 亚洲综合视频在线 | 丰满少妇在线观看资源站 | 日本一区二区在线免费 | 伊人影片 |