当前位置:网站首页>[PHP SPL notes]
[PHP SPL notes]
2022-07-07 05:15:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack .
This few days , I'm learning PHP In language SPL.
This thing should belong to PHP Advanced content in , It looks complicated , But it's very useful , So I took long notes . Otherwise I can't remember , When I need to use it later , We still have to learn from scratch .
Because this is a note for your reference , It's not a tutorial , So it's simpler , Didn't explain much . But I want to , If you are a skilled PHP5 The programmer , It should be enough to understand the following materials , And you will find it very useful . Now beyond that , There is no in-depth online SPL Introduction to Chinese .
================
PHP SPL note
Catalog
The first part brief introduction
1. What is? SPL?
2. What is? Iterator?
The second part SPL Interfaces
3. Iterator Interface
4. ArrayAccess Interface
5. IteratorAggregate Interface
6. RecursiveIterator Interface
7. SeekableIterator Interface
8. Countable Interface
The third part SPL Classes
9. SPL Built in classes for
10. DirectoryIterator class
11. ArrayObject class
12. ArrayIterator class
13. RecursiveArrayIterator Classes and RecursiveIteratorIterator class
14. FilterIterator class
15. SimpleXMLIterator class
16. CachingIterator class
17. LimitIterator class
18. SplFileObject class
First part brief introduction
1. What is? SPL?
SPL yes Standard PHP Library(PHP Standard library ) Abbreviation .
According to the official definition , It is ”a collection of interfaces and classes that are meant to solve standard problems”. however , Currently in use ,SPL It is more seen as a way to make object( object ) imitation array( Array ) Acting interfaces and classes.
2. What is? Iterator?
SPL The core concept is Iterator. This refers to a Design Pattern, according to 《Design Patterns》 The definition of a Book ,Iterator The role of is ”provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.”
wikipedia In the said ,”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”.
In layman's terms ,Iterator Can make many different data structures , Can have a unified operation interface , For example, the result set of a database 、 Filesets in the same directory 、 Or a set of lines in the text .
If, under normal circumstances , Traverse a MySQL The result set , The program needs to be written like this :
// 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
}
Read the contents of a directory , It needs to be written like this :
// Fetch the "aggregate structure"
$dh = opendir("/home/harryf/files");
// Iterate over the structure
while ( $file = readdir($dh) ) {
// do stuff with the file here
}
Read the contents of a text file , It needs to be written like this :
// 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
}
The above three codes , Although the treatment is different resource( resources ), But the function is to traverse the result set (loop over contents), therefore Iterator The basic idea of , It is to unify these three different operations , Use the same command interface , Deal with different resources .
The second part SPL Interfaces
3. Iterator Interface
SPL Regulations , All deployed Iterator Interface class, Can be used in foreach Loop in .Iterator The interface contains 5 Methods that must be deployed :
* 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().
Here is a deployment Iterator Interface class Example :
/**
* 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;
}
}
How to use it is as follows :
// Create iterator object
$colors = new ArrayReloaded(array ("red","green","blue",));
// Iterate away!
foreach ( $colors as $color ) {
echo $color."<br>";
}
You can also be in foreach Use in loop key() Method :
// Display the keys as well
foreach ( $colors as $key => $color ) {
echo "$key: $color<br>";
}
except foreach Out of the loop , You can also use while loop ,
// Reset the iterator - foreach does this automatically
$colors->rewind();
// Loop while valid
while ( $colors->valid() ) {
echo $colors->key().": ".$colors->current()."
";
$colors->next();
}
According to the test ,while The cycle should be slightly faster than foreach loop , Because there is a lack of intermediate calls at runtime .
4. ArrayAccess Interface
Deploy ArrayAccess Interface , You can make object image array Do that .ArrayAccess The interface contains four methods that must be deployed :
* 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.
Here is a deployment ArrayAccess An example of the interface :
/**
* 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));
}
}
How to use it is as follows :
// 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>";
The operation results are as follows :
Initial State:
Article Object
(
[title] => SPL Rocks
[author] => Joe Bloggs
[category] => PHP
)
Final State:
Article Object
(
[title] => SPL _really_ rocks
[category] => PHP
)
You can see ,$A Although it is a object, But it can be like array Do that .
You can also read data , Add logic inside the program :
function offsetGet($key) {
if ( array_key_exists($key,get_object_vars($this)) ) {
return strtolower($this->{$key});
}
}
5. IteratorAggregate Interface
however , although $A You can operate like an array , But I can't use foreach Traverse , Unless you deploy the previously mentioned Iterator Interface .
Another solution is , Sometimes you need to separate the data from the traversal part , Then you can deploy IteratorAggregate Interface . It stipulates a getIterator() Method , Return to a use Iterator Interface object.
It's from the previous section Article Class, for example :
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);
}
How to use it is as follows :
$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";
The results are as follows :
Looping with foreach:
title : SPL Rocks
author : Joe Bloggs
category : PHP
Object has 3 elements
6. RecursiveIterator Interface
This interface is used to traverse multiple layers of data , It inherited Iterator Interface , Therefore, it also has standard current()、key()、next()、 rewind() and valid() Method . meanwhile , It also stipulates getChildren() and hasChildren() Method .The getChildren() method must return an object that implements RecursiveIterator.
7. SeekableIterator Interface
SeekableIterator So is the interface Iterator Extension of interface , except Iterator Of 5 There are other ways , It also stipulates that seek() Method , The parameter is the position of the element , Return the element . If the location does not exist , Throw out OutOfBoundsException.
The following is an example :
<?php
class 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 Interface
This interface specifies a count() Method , Returns the number of result sets .
The third part SPL Classes
9. SPL Built in classes for
SPL In addition to defining a series Interfaces outside , It also provides a series of built-in classes , They correspond to different tasks , Greatly simplified programming .
View all built-in classes , You can use the following code :
<?php
// a simple foreach() to traverse the SPL class names
foreach(spl_classes() as $key=>$value)
{
echo $key." -> ".$value."<br />";
}
?>
10. DirectoryIterator class
This class is used to view all files and subdirectories in a directory :
<?php
try{
/*** 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 />";
}
?>
View file details :
<table>
<?php
foreach(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>
except foreach Out of the loop , You can also use while loop :
<?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();
}
?>
If you want to filter all subdirectories , Can be in valid() Method :
<?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 class
This class can put Array Turn into 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 />";
}
?>
Add an element :
$arrayObj->append("dingo");
Sort the elements :
$arrayObj->natcasesort();
Show the number of elements :
echo $arrayObj->count();
Delete an element :
$arrayObj->offsetUnset(5);
Whether an element exists :
if ($arrayObj->offsetExists(3))
{
echo "Offset Exists<br />";
}
Change the element value at a certain position :
$arrayObj->offsetSet(5, "galah");
Display the element value of a certain position :
echo $arrayObj->offsetGet(4);
12. ArrayIterator class
This class is actually for ArrayObject Class , Provide traversal function for the latter .
Examples are as follows :
<?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 Class also supports offset Class methods and count() Method :
<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>"."
";
}
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>
</ul>
13. RecursiveArrayIterator Classes and RecursiveIteratorIterator class
ArrayIterator Classes and ArrayObject class , Only one-dimensional array traversal is supported . If you want to traverse a multidimensional array , Must use first RecursiveIteratorIterator Generate a Iterator, And then to this Iterator Use 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 class
FilterIterator Class can filter elements , As long as accept() Just set the filter condition in the method .
Examples are as follows :
<?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 />";
}
?>
Here is another example of returning prime numbers :
<?php
class 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 class
This class is used to traverse xml file .
Examples are as follows :
<?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) Indicates that all child elements including the parent element are displayed .
Display the value of a specific element , It can be written like this :
<?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();
}
?>
Corresponding while The circulation is :
<?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."<br />";
}
}
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
The most convenient way to write , Or use 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();
}
?>
The following example , Show that namespace The situation of :
<?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();
}
?>
Add a node :
<?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();
}
?>
Attribute added :
<?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 class
This class has a hasNext() Method , Used to determine whether there is another element .
Examples are as follows :
<?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 class
This class is used to limit the number and location of the returned result set , You must provide offset and limit Two parameters , And SQL In command limit Statements like .
Examples are as follows :
<?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 />";
}
?>
Another example is :
<?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 class
This class is used to traverse text files .
Examples are as follows :
<?php
try{
// iterate directly over the object
foreach( new SplFileObject("/usr/local/apache/logs/access_log") as $line)
// and echo each line of the file
echo $line."<br />";
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>
Return to the third line of the text file , It can be written like this :
<?php
try{
$file = new SplFileObject("/usr/local/apache/logs/access_log");
$file->seek(3);
echo $file->current();
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>
[ reference ]
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
( End )
边栏推荐
猜你喜欢
What changes will PMP certification bring?
Ansible报错:“msg“: “Invalid/incorrect password: Permission denied, please try again.“
Ansible中的inventory主机清单(预祝你我有数不尽的鲜花和浪漫)
The sooner you understand the four rules of life, the more blessed you will be
如何设计 API 接口,实现统一格式返回?
Why do many people misunderstand technical debt
Ansible reports an error: "MSG": "invalid/incorrect password: permission denied, please try again“
Function pointer and pointer function in C language
window定时计划任务
[opencv] image morphological operation opencv marks the positions of different connected domains
随机推荐
01 machine learning related regulations
Comparison between thread and runnable in creating threads
AOSP ~Binder 通信原理 (一) - 概要
National meteorological data / rainfall distribution data / solar radiation data /npp net primary productivity data / vegetation coverage data
ASP. Net MVC - resource cannot be found error - asp Net MVC – Resource Cannot be found error
Redis如何实现多可用区?
Leetcode longest public prefix
QT控件样式系列(一)之QSlider
The founder has a debt of 1billion. Let's start the class. Is it about to "end the class"?
Full link voltage test: the dispute between shadow database and shadow table
2. Overview of securities investment funds
STM32 encapsulates the one key configuration function of esp8266: realize the switching between AP mode and sta mode, and the creation of server and client
Function pointer and pointer function in C language
Clickhouse (03) how to install and deploy Clickhouse
LabVIEW在打开一个新的引用,提示内存已满
How to design API interface and realize unified format return?
Weebly mobile website editor mobile browsing New Era
vector和类拷贝构造函数
npm ERR! 400 Bad Request - PUT xxx - “devDependencies“ dep “xx“ is not a valid dependency name
ScheduledExecutorService定时器