찾다
백엔드 개발PHP 튜토리얼PHP 표준 라이브러리 SPL

PHP 표준 라이브러리 SPL

Nov 15, 2016 pm 03:55 PM
php

第一部 简介

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 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示例:

/**
* 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 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界面的实例:

/**
* 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&#39;s key e.g. $A[&#39;title&#39;] = &#39;foo&#39;;
 * @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&#39;s key e.g. echo $A[&#39;title&#39;];
 * @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&#39;s key e.g. unset($A[&#39;title&#39;]);
 * @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&#39;s key e.g. isset($A[&#39;title&#39;])
 * @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(&#39;SPL Rocks&#39;,&#39;Joe Bloggs&#39;, &#39;PHP&#39;);

// Check what it looks like
echo &#39;Initial State:<div>&#39;;
print_r($A);
echo &#39;</div>&#39;;

// Change the title using array syntax
$A[&#39;title&#39;] = &#39;SPL _really_ rocks&#39;;

// Try setting a non existent property (ignored)
$A[&#39;not found&#39;] = 1;

// Unset the author field
unset($A[&#39;author&#39;]);

// Check what it looks like again
echo &#39;Final State:<div>&#39;;
print_r($A);
echo &#39;</div>&#39;;

运行结果如下:

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(&#39;SPL Rocks&#39;,&#39;Joe Bloggs&#39;, &#39;PHP&#39;);

// Loop (getIterator will be called automatically)
echo &#39;Looping with foreach:<div>&#39;;
foreach ( $A as $field => $value ) {
 echo "$field : $value<br>";
}
echo &#39;</div>&#39;;

// 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 : 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)
    {
        // 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(&#39;Invalid position&#39;);
        }
    }

    // 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.&#39; -> &#39;.$value.&#39;<br />&#39;;
        }
?>

10. DirectoryIterator类

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

<?php

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

查看文件的详细信息:

<table>
<?php

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

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

<?php
/*** create a new iterator object ***/
$it = new DirectoryIterator(&#39;./&#39;);

/*** loop directly over the object ***/
while($it->valid())
    {
    echo $it->key().&#39; -- &#39;.$it->current().&#39;<br />&#39;;
    /*** move to the next iteration ***/
    $it->next();
    }
?>

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

<?php
/*** create a new iterator object ***/
$it = new DirectoryIterator(&#39;./&#39;);

/*** 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().&#39; -- &#39;.$it->current().&#39;<br />&#39;;
                }
        /*** move to the next iteration ***/
        $it->next();
        }
?>

11. ArrayObject类

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

<?php

/*** a simple array ***/
$array = array(&#39;koala&#39;, &#39;kangaroo&#39;, &#39;wombat&#39;, &#39;wallaby&#39;, &#39;emu&#39;, &#39;kiwi&#39;, &#39;kookaburra&#39;, &#39;platypus&#39;);

/*** 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() . &#39; => &#39; . $iterator->current() . &#39;<br />&#39;;
    }
?>

增加一个元素:

$arrayObj->append(&#39;dingo&#39;);

对元素排序:

$arrayObj->natcasesort();

显示元素的数量:

echo $arrayObj->count();

删除一个元素:

$arrayObj->offsetUnset(5);

某一个元素是否存在:

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

更改某个位置的元素值:

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

显示某个位置的元素值:

echo $arrayObj->offsetGet(4);

12. ArrayIterator类

这个类实际上是对ArrayObject类的补充,为后者提供遍历功能。

示例如下:

<?php
/*** a simple array ***/
$array = array(&#39;koala&#39;, &#39;kangaroo&#39;, &#39;wombat&#39;, &#39;wallaby&#39;, &#39;emu&#39;, &#39;kiwi&#39;, &#39;kookaburra&#39;, &#39;platypus&#39;);

try {
    $object = new ArrayIterator($array);
    foreach($object as $key=>$value)
        {
        echo $key.&#39; => &#39;.$value.&#39;<br />&#39;;
        }
    }
catch (Exception $e)
    {
    echo $e->getMessage();
    }
?>

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

<ul>
<?php
/*** a simple array ***/
$array = array(&#39;koala&#39;, &#39;kangaroo&#39;, &#39;wombat&#39;, &#39;wallaby&#39;, &#39;emu&#39;, &#39;kiwi&#39;, &#39;kookaburra&#39;, &#39;platypus&#39;);

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, &#39;Goanna&#39;);
    }
   /*** unset the kiwi ***/
   foreach($object as $key=>$value)
        {
        /*** check the value of the key ***/
        if($object->offSetGet($key) === &#39;kiwi&#39;)
            {
            /*** unset the current key ***/
            $object->offSetUnset($key);
            }
        echo &#39;<li>&#39;.$key.&#39; - &#39;.$value.&#39;</li>&#39;."\n";
        }
    }
catch (Exception $e)
    {
    echo $e->getMessage();
    }
?>
</ul>

13. RecursiveArrayIterator类和RecursiveIteratorIterator类

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

<?php
$array = array(
    array(&#39;name&#39;=>&#39;butch&#39;, &#39;sex&#39;=>&#39;m&#39;, &#39;breed&#39;=>&#39;boxer&#39;),
    array(&#39;name&#39;=>&#39;fido&#39;, &#39;sex&#39;=>&#39;m&#39;, &#39;breed&#39;=>&#39;doberman&#39;),
    array(&#39;name&#39;=>&#39;girly&#39;,&#39;sex&#39;=>&#39;f&#39;, &#39;breed&#39;=>&#39;poodle&#39;)
);

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key=>$value)
    {
    echo $key.&#39; -- &#39;.$value.&#39;<br />&#39;;
    }
?>

14. FilterIterator类

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

示例如下:

<?php
/*** a simple array ***/
$animals = array(&#39;koala&#39;, &#39;kangaroo&#39;, &#39;wombat&#39;, &#39;wallaby&#39;, &#39;emu&#39;, &#39;NZ&#39;=>&#39;kiwi&#39;, &#39;kookaburra&#39;, &#39;platypus&#39;);

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.&#39; == &#39;.$value.&#39;<br />&#39;;
    }
?>

下面是另一个返回质数的例子:

<?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.&#39; is prime.<br />&#39;;
    }
?>

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.&#39; -- &#39;.$data.&#39;<br />&#39;;
          }
    }
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.&#39;<br />&#39;;
            }
        }
    }
catch(Exception $e)
    {
    echo $e->getMessage();
    }
?>

相对应的while循环写法为:

<?php

try {
$sxe = simplexml_load_string($xmlstring, &#39;SimpleXMLIterator&#39;);

for ($sxe->rewind(); $sxe->valid(); $sxe->next())
    {
    if($sxe->hasChildren())
        {
        foreach($sxe->getChildren() as $element=>$value)
          {
          echo $value->species.&#39;<br />&#39;;
          }
        }
     }
   }
catch(Exception $e)
   {
   echo $e->getMessage();
   }
?>

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

<?php
try {
    /*** a new simpleXML iterator object ***/
    $sxi =  new SimpleXMLIterator($xmlstring);

    /*** set the xpath ***/
    $foo = $sxi->xpath(&#39;animal/category/species&#39;);

    /*** iterate over the xpath ***/
    foreach ($foo as $k=>$v)
        {
        echo $v.&#39;<br />&#39;;
        }
    }
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(&#39;spec&#39;, &#39;http://www.exampe.org/species-title&#39;);

    /*** set the xpath ***/
    $result = $sxi->xpath(&#39;//spec:name&#39;);

    /*** get all declared namespaces ***/
   foreach($sxi->getDocNamespaces(&#39;animal&#39;) as $ns)
        {
        echo $ns.&#39;<br />&#39;;
        }

    /*** iterate over the xpath ***/
    foreach ($result as $k=>$v)
        {
        echo $v.&#39;<br />&#39;;
        }
    }
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(&#39;animal&#39;, &#39;Tiger&#39;);

    /*** a new simpleXML iterator object ***/
    $new = new SimpleXmlIterator($sxi->saveXML());

    /*** iterate over the new tree ***/
    foreach($new as $val)
        {
        echo $val.&#39;<br />&#39;;
        }
    }
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(&#39;id:att1&#39;, &#39;good things&#39;, &#39;urn::test-foo&#39;);

    /*** add an attribute without a  namespace ***/
    $sxi->addAttribute(&#39;att2&#39;, &#39;no-ns&#39;);

    echo htmlentities($sxi->saveXML());
    }
catch(Exception $e)
    {
    echo $e->getMessage();
    }
?>

16. CachingIterator类

这个类有一个hasNext()方法,用来判断是否还有下一个元素。

示例如下:

<?php
/*** a simple array ***/
$array = array(&#39;koala&#39;, &#39;kangaroo&#39;, &#39;wombat&#39;, &#39;wallaby&#39;, &#39;emu&#39;, &#39;kiwi&#39;, &#39;kookaburra&#39;, &#39;platypus&#39;);

try {
    /*** create a new object ***/
    $object = new CachingIterator(new ArrayIterator($array));
    foreach($object as $value)
        {
        echo $value;
        if($object->hasNext())
            {
            echo &#39;,&#39;;
            }
        }
    }
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(&#39;koala&#39;, &#39;kangaroo&#39;, &#39;wombat&#39;, &#39;wallaby&#39;, &#39;emu&#39;, &#39;kiwi&#39;, &#39;kookaburra&#39;, &#39;platypus&#39;);

$it = new LimitIterator(new ArrayIterator($array), $offset, $limit);

foreach($it as $k=>$v)
    {
    echo $it->getPosition().&#39;<br />&#39;;
    }
?>

另一个例子是:

<?php

/*** a simple array ***/
$array = array(&#39;koala&#39;, &#39;kangaroo&#39;, &#39;wombat&#39;, &#39;wallaby&#39;, &#39;emu&#39;, &#39;kiwi&#39;, &#39;kookaburra&#39;, &#39;platypus&#39;);

$it = new LimitIterator(new ArrayIterator($array));

try
    {
    $it->seek(5);
    echo $it->current();
    }
catch(OutOfBoundsException $e)
    {
    echo $e->getMessage() . "<br />";
    }
?>

18. SplFileObject类

这个类用来对文本文件进行遍历。

示例如下:

<?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.&#39;<br />&#39;;
}
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();
    }
?>


성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
세션을 저장하기 위해 데이터베이스를 사용하면 어떤 장점이 있습니까?세션을 저장하기 위해 데이터베이스를 사용하면 어떤 장점이 있습니까?Apr 24, 2025 am 12:16 AM

데이터베이스 스토리지 세션 사용의 주요 장점에는 지속성, 확장 성 및 보안이 포함됩니다. 1. 지속성 : 서버가 다시 시작 되더라도 세션 데이터는 변경되지 않아도됩니다. 2. 확장 성 : 분산 시스템에 적용하여 세션 데이터가 여러 서버간에 동기화되도록합니다. 3. 보안 : 데이터베이스는 민감한 정보를 보호하기 위해 암호화 된 스토리지를 제공합니다.

PHP에서 사용자 정의 세션 처리를 어떻게 구현합니까?PHP에서 사용자 정의 세션 처리를 어떻게 구현합니까?Apr 24, 2025 am 12:16 AM

SessionHandlerInterface 인터페이스를 구현하여 PHP에서 사용자 정의 세션 처리 구현을 수행 할 수 있습니다. 특정 단계에는 다음이 포함됩니다. 1) CustomsessionHandler와 같은 SessionHandlerInterface를 구현하는 클래스 만들기; 2) 인터페이스의 방법 (예 : Open, Close, Read, Write, Despare, GC)의 수명주기 및 세션 데이터의 저장 방법을 정의하기 위해 방법을 다시 작성합니다. 3) PHP 스크립트에 사용자 정의 세션 프로세서를 등록하고 세션을 시작하십시오. 이를 통해 MySQL 및 Redis와 같은 미디어에 데이터를 저장하여 성능, 보안 및 확장 성을 향상시킬 수 있습니다.

세션 ID 란 무엇입니까?세션 ID 란 무엇입니까?Apr 24, 2025 am 12:13 AM

SessionId는 웹 애플리케이션에 사용되는 메커니즘으로 사용자 세션 상태를 추적합니다. 1. 사용자와 서버 간의 여러 상호 작용 중에 사용자의 신원 정보를 유지하는 데 사용되는 무작위로 생성 된 문자열입니다. 2. 서버는 쿠키 또는 URL 매개 변수를 통해 클라이언트로 생성하여 보낸다. 3. 생성은 일반적으로 임의의 알고리즘을 사용하여 독창성과 예측 불가능 성을 보장합니다. 4. 실제 개발에서 Redis와 같은 메모리 내 데이터베이스를 사용하여 세션 데이터를 저장하여 성능 및 보안을 향상시킬 수 있습니다.

무국적 환경 (예 : API)에서 세션을 어떻게 처리합니까?무국적 환경 (예 : API)에서 세션을 어떻게 처리합니까?Apr 24, 2025 am 12:12 AM

JWT 또는 쿠키를 사용하여 API와 같은 무국적 환경에서 세션을 관리 할 수 ​​있습니다. 1. JWT는 무국적자 및 확장 성에 적합하지만 빅 데이터와 관련하여 크기가 크다. 2. 쿠키는보다 전통적이고 구현하기 쉽지만 보안을 보장하기 위해주의해서 구성해야합니다.

세션과 관련된 크로스 사이트 스크립팅 (XSS) 공격으로부터 어떻게 보호 할 수 있습니까?세션과 관련된 크로스 사이트 스크립팅 (XSS) 공격으로부터 어떻게 보호 할 수 있습니까?Apr 23, 2025 am 12:16 AM

세션 관련 XSS 공격으로부터 응용 프로그램을 보호하려면 다음 조치가 필요합니다. 1. 세션 쿠키를 보호하기 위해 Httponly 및 Secure 플래그를 설정하십시오. 2. 모든 사용자 입력에 대한 내보내기 코드. 3. 스크립트 소스를 제한하기 위해 컨텐츠 보안 정책 (CSP)을 구현하십시오. 이러한 정책을 통해 세션 관련 XSS 공격을 효과적으로 보호 할 수 있으며 사용자 데이터가 보장 될 수 있습니다.

PHP 세션 성능을 어떻게 최적화 할 수 있습니까?PHP 세션 성능을 어떻게 최적화 할 수 있습니까?Apr 23, 2025 am 12:13 AM

PHP 세션 성능을 최적화하는 방법 : 1. 지연 세션 시작, 2. 데이터베이스를 사용하여 세션을 저장, 3. 세션 데이터 압축, 4. 세션 수명주기 관리 및 5. 세션 공유 구현. 이러한 전략은 높은 동시성 환경에서 응용의 효율성을 크게 향상시킬 수 있습니다.

SESSION.GC_MAXLIFETIME 구성 설정은 무엇입니까?SESSION.GC_MAXLIFETIME 구성 설정은 무엇입니까?Apr 23, 2025 am 12:10 AM

THESESSION.GC_MAXLIFETIMESETTINGINSTTINGTINGSTINGTERMINESTERMINESTERSTINGSESSIONDATA, SETINSECONDS.1) IT'SCONFIGUDEDINPHP.INIORVIAINI_SET ()

PHP에서 세션 이름을 어떻게 구성합니까?PHP에서 세션 이름을 어떻게 구성합니까?Apr 23, 2025 am 12:08 AM

PHP에서는 Session_Name () 함수를 사용하여 세션 이름을 구성 할 수 있습니다. 특정 단계는 다음과 같습니다. 1. Session_Name () 함수를 사용하여 Session_Name ( "my_session")과 같은 세션 이름을 설정하십시오. 2. 세션 이름을 설정 한 후 세션을 시작하여 세션을 시작하십시오. 세션 이름을 구성하면 여러 응용 프로그램 간의 세션 데이터 충돌을 피하고 보안을 향상시킬 수 있지만 세션 이름의 독창성, 보안, 길이 및 설정 타이밍에주의를 기울일 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.