ReflectionClass 类

(PHP 5, PHP 7)

简介

ReflectionClass 类报告了一个类的有关信息。

类摘要

ReflectionClass implements Reflector {
/* 常量 */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* 属性 */
public $name ;
/* 方法 */
public __construct ( mixed $argument )
public static export ( mixed $argument , bool $return = false ) : string
public getConstant ( string $name ) : mixed
public getConstants ( ) : array
public getConstructor ( ) : ReflectionMethod
public getDefaultProperties ( ) : array
public getDocComment ( ) : string
public getEndLine ( ) : int
public getExtension ( ) : ReflectionExtension
public getExtensionName ( ) : string
public getFileName ( ) : string
public getInterfaceNames ( ) : array
public getInterfaces ( ) : array
public getMethod ( string $name ) : ReflectionMethod
public getMethods ( int $filter = ? ) : array
public getModifiers ( ) : int
public getName ( ) : string
public getNamespaceName ( ) : string
public getParentClass ( ) : ReflectionClass
public getProperties ( int $filter = ? ) : array
public getProperty ( string $name ) : ReflectionProperty
public getReflectionConstant ( string $name ) : ReflectionClassConstant|false
public getReflectionConstants ( int|null $filter = null ) : array
public getShortName ( ) : string
public getStartLine ( ) : int
public getStaticProperties ( ) : array
public getStaticPropertyValue ( string $name , mixed &$def_value = ? ) : mixed
public getTraitAliases ( ) : array
public getTraitNames ( ) : array
public getTraits ( ) : array
public hasConstant ( string $name ) : bool
public hasMethod ( string $name ) : bool
public hasProperty ( string $name ) : bool
public implementsInterface ( string $interface ) : bool
public inNamespace ( ) : bool
public isAbstract ( ) : bool
public isAnonymous ( ) : bool
public isCloneable ( ) : bool
public isFinal ( ) : bool
public isInstance ( object $object ) : bool
public isInstantiable ( ) : bool
public isInterface ( ) : bool
public isInternal ( ) : bool
public isIterable ( ) : bool
public isIterateable ( ) : bool
public isSubclassOf ( string $class ) : bool
public isTrait ( ) : bool
public isUserDefined ( ) : bool
public newInstance ( mixed $args , mixed $... = ? ) : object
public newInstanceArgs ( array $args = ? ) : object
public newInstanceWithoutConstructor ( ) : object
public setStaticPropertyValue ( string $name , string $value ) : void
public __toString ( ) : string
}

属性

name

类的名称。只读，并在尝试赋值的时候会抛出 ReflectionException。

预定义常量

ReflectionClass 修饰符

ReflectionClass::IS_IMPLICIT_ABSTRACT

指示了类是一个抽象类（abstract）， 因为它有抽象（abstract）方法。

ReflectionClass::IS_EXPLICIT_ABSTRACT

指示了类是一个抽象类（abstract）， 因为它已明确定义。

ReflectionClass::IS_FINAL

指示这是一个 final 类。

Table of Contents

  • ReflectionClass::__construct — 初始化 ReflectionClass 类
  • ReflectionClass::export — 导出一个类
  • ReflectionClass::getConstant — 获取定义过的一个常量
  • ReflectionClass::getConstants — 获取一组常量
  • ReflectionClass::getConstructor — 获取类的构造函数
  • ReflectionClass::getDefaultProperties — 获取默认属性
  • ReflectionClass::getDocComment — 获取文档注释
  • ReflectionClass::getEndLine — 获取最后一行的行数
  • ReflectionClass::getExtension — 根据已定义的类获取所在扩展的 ReflectionExtension 对象
  • ReflectionClass::getExtensionName — 获取定义的类所在的扩展的名称
  • ReflectionClass::getFileName — 获取定义类的文件名
  • ReflectionClass::getInterfaceNames — 获取接口（interface）名称
  • ReflectionClass::getInterfaces — 获取接口
  • ReflectionClass::getMethod — 获取一个类方法的 ReflectionMethod。
  • ReflectionClass::getMethods — 获取方法的数组
  • ReflectionClass::getModifiers — 获取类的修饰符
  • ReflectionClass::getName — 获取类名
  • ReflectionClass::getNamespaceName — 获取命名空间的名称
  • ReflectionClass::getParentClass — 获取父类
  • ReflectionClass::getProperties — 获取一组属性
  • ReflectionClass::getProperty — 获取类的一个属性的 ReflectionProperty
  • ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant
  • ReflectionClass::getReflectionConstants — Gets class constants
  • ReflectionClass::getShortName — 获取短名
  • ReflectionClass::getStartLine — 获取起始行号
  • ReflectionClass::getStaticProperties — 获取静态（static）属性
  • ReflectionClass::getStaticPropertyValue — 获取静态（static）属性的值
  • ReflectionClass::getTraitAliases — 返回 trait 别名的一个数组
  • ReflectionClass::getTraitNames — 返回这个类所使用 traits 的名称的数组
  • ReflectionClass::getTraits — 返回这个类所使用的 traits 数组
  • ReflectionClass::hasConstant — 检查常量是否已经定义
  • ReflectionClass::hasMethod — 检查方法是否已定义
  • ReflectionClass::hasProperty — 检查属性是否已定义
  • ReflectionClass::implementsInterface — 接口的实现
  • ReflectionClass::inNamespace — 检查是否位于命名空间中
  • ReflectionClass::isAbstract — 检查类是否是抽象类（abstract）
  • ReflectionClass::isAnonymous — 检查类是否是匿名类
  • ReflectionClass::isCloneable — 返回了一个类是否可复制
  • ReflectionClass::isFinal — 检查类是否声明为 final
  • ReflectionClass::isInstance — 检查类的实例
  • ReflectionClass::isInstantiable — 检查类是否可实例化
  • ReflectionClass::isInterface — 检查类是否是一个接口（interface）
  • ReflectionClass::isInternal — 检查类是否由扩展或核心在内部定义
  • ReflectionClass::isIterable — Check whether this class is iterable
  • ReflectionClass::isIterateable — 检查是否可迭代（iterateable）
  • ReflectionClass::isSubclassOf — 检查是否为一个子类
  • ReflectionClass::isTrait — 返回了是否为一个 trait
  • ReflectionClass::isUserDefined — 检查是否由用户定义的
  • ReflectionClass::newInstance — 从指定的参数创建一个新的类实例
  • ReflectionClass::newInstanceArgs — 从给出的参数创建一个新的类实例。
  • ReflectionClass::newInstanceWithoutConstructor — 创建一个新的类实例而不调用它的构造函数
  • ReflectionClass::setStaticPropertyValue — 设置静态属性的值
  • ReflectionClass::__toString — 返回 ReflectionClass 对象字符串的表示形式。

User Contributed Notes

featherbits 27-Jan-2021 04:10
In order to get class attributes look here (php8)
https://www.php.net/manual/en/language.attributes.reflection.php
YoungOfCthulhu 21-Sep-2015 02:20
It is also possible to do reflection from within the class and get the methods for instance.

<?php

class test
{
    private $test = "";

    public function setTest($test)
    {
        $this->test = $test;
        return $this;
    }

    public function getTest()
    {
        return $this->test;
    }

    public function run(){
        $class = new ReflectionClass('test');
        $methods = $class->getMethods();
        var_dump($methods);
    }
}

Called from another php file you get the proper result:
array(3) {
  [0]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(8) "setTest"
    ["class"]=>
    string(4) "test"
  }
  [1]=>
  &object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(8) "getTest"
    ["class"]=>
    string(4) "test"
  }
  [2]=>
  &object(ReflectionMethod)#5 (2) {
    ["name"]=>
    string(3) "run"
    ["class"]=>
    string(4) "test"
  }
}
Anonymous 17-May-2013 06:45
Reflecting an alias will give you a reflection of the resolved class.

<?php

class X {

}

class_alias('X','Y');
class_alias('Y','Z');
$z = new ReflectionClass('Z');
echo $z->getName(); // X

?>
Anonymous 11-Nov-2011 09:58
Unserialized reflection class cause error.

<?php
/**
 * abc
 */
class a{}

$ref = new ReflectionClass('a');
$ref = unserialize(serialize($ref));
var_dump($ref);
var_dump($ref->getDocComment());

// object(ReflectionClass)#2 (1) {
//   ["name"]=>
//   string(1) "a"
// }
// PHP Fatal error:  ReflectionClass::getDocComment(): Internal error: Failed to retrieve the reflection object
?>
danbettles at yahoo dot co dot uk 29-Mar-2009 02:48
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.

So instead of:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('Core\Singleton');
?>

You would type:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('App\Core\Singleton');
?>


初始化 ReflectionClass 类

  • ? ReflectionClass
  • ReflectionClass::export ?
  • PHP Manual
  • ReflectionClass
  • 初始化 ReflectionClass 类

ReflectionClass::__construct

(PHP 5, PHP 7)

ReflectionClass::__construct — 初始化 ReflectionClass 类

说明

public ReflectionClass::__construct ( mixed $argument )

初始化新的 ReflectionClass 对象。

参数

argument

既可以是包含类名的字符串（string）也可以是对象（object）。

返回值

返回初始化完成后的 ReflectionClass 实例。

错误／异常

如果要反射的 Class 不存在，抛出异常 ReflectionException。

范例

Example #1 ReflectionClass 的基本用法

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

以上例程的输出类似于：

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

参见

  • ReflectionObject::__construct() - Constructs a ReflectionObject
  • Constructors

User Contributed Notes

danbettles at yahoo dot co dot uk 22-May-2015 06:47
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.

So instead of:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('Core\Singleton');
?>

You would type:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('App\Core\Singleton');
?>
nulled 18-Dec-2013 03:42
if (is_file($classfile))
            require_once $classfile;

if (! class_exists($classname, false))
            exit('ERROR: ' . $classname . ' is not defined as a Class');

The above code is useful to tell if the class was defined.  You could also use another commentors method using Try Catch Exceptions.  But, if you do not use try blocks much, the above function based method works just fine.

From there, you can than call:

$class = new ReflectionClass($classname);

        if (! $class->isSubclassOf('PanelCommon'))
            exit("ERROR: {$classname} must extends PanelCommon");

        if (! $class->isUserDefined())
            exit("ERROR: {$classname} must be user defined and not internal to PHP");

        if (! $class->IsInstantiable())
            exit("ERROR: {$classname} must be IsInstantiable and not an Interface or Abstract class");

        if (! $class->hasMethod('home'))
            exit("ERROR: {$classname} lacks required method/function home()");

Forforth and so on.
me [at] klay [dot] me 28-Oct-2013 11:09
Example of usage:

    public static function getClassData($class)
    {
        // Trying to create a new object of ReflectionClass class
        $class = new ReflectionClass($class);

        $details = sprintf('%s - %s%s%s%s%s%s%s%s',
            $class->getName(),
            $class->isInternal()     ? 'internal class,' : 'user-defined class,',
            $class->isTrait()        ? '  is trait,'  : '',
            $class->isInterface()    ? '  is interface,'  : '',
            $class->isAbstract()     ? '  is abstract,'  : '',
            $class->isFinal()        ? '  is final,'  : '',
            $class->isCloneable()    ? '  is cloneable,'  : '',
            $class->isInstantiable() ? ' is instantiable,'  : '',
            $class->isIterateable()  ? ' is iterable  : ''
        );

        return '<pre class="debug">' . rtrim($details, ',') . '</pre>';
    }
gafisher at griasolutions dot com 30-Jan-2012 01:23
Running the following code on Windows Vista (I know, I know), PHP 5.3.9, the ReflectionClass constructor actually throws a ReflectionException when the desired class cannot be instantiated:

<?php
    try {
        $ReflectedClass = new ReflectionClass('NonExist');
    } catch (LogicException $Exception) {
        die('Not gonna make it in here...');
    } catch (ReflectionException $Exception) {
        die('Your class does not exist!');
    }
?>
cspray at gmail dot com 12-Jun-2011 07:14
Useful to know that if you pass a string into the construct and the class cannot be instantiated for some reason a SPL LogicException will be thrown.

This code was ran on a Mac OS X 10.6.7, AMP, PHP 5.3+

<?php

    //  index.php
    try {
        $ReflectedClass = new ReflectionClass('NonExist');
    } catch (LogicException $logicDuh) {
        print_r($logicDuh);
    }

?>

Will return a deeply nested array full of useful information about the error.
ivo at jansch dot nl 24-Jan-2010 04:16
It's very useful to know that you can also use the ReflectionClass to inspect interfaces, even thouth Interfaces are not classes. Example:

<?php

  interface Edible
  {
    public function eat();
  }

  $refl = new ReflectionClass("Edible");
  $methods = $refl->getMethods();
?>

[Edit by danbrown AT php DOT net - Contains a bugfix by (dbl AT bnet DOT com) on 18-AUG-2010 with the following message: "underline had to be removed for it to work ( new Reflection_Class -> new ReflectionClass )"]


导出一个类

  • ? ReflectionClass::__construct
  • ReflectionClass::getConstant ?
  • PHP Manual
  • ReflectionClass
  • 导出一个类

ReflectionClass::export

(PHP 5, PHP 7)

ReflectionClass::export — 导出一个类

说明

public static ReflectionClass::export ( mixed $argument , bool $return = false ) : string

导出一个反射后的类。

参数

argument

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

范例

Example #1 ReflectionClass::export() 的基本用法

<?php
class Apple {
    public $var1;
    public $var2 = 'Orange';

    public function type() {
        return 'Apple';
    }
}
ReflectionClass::export('Apple');
?>

以上例程的输出类似于：

Class [ <user> class Apple ] {
  @@ php shell code 1-8

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [2] {
    Property [ <default> public $var1 ]
    Property [ <default> public $var2 ]
  }

  - Methods [1] {
    Method [ <user> public method type ] {
      @@ php shell code 5 - 7
    }
  }
}

参见

  • ReflectionClass::getName() - 获取类名

User Contributed Notes

There are no user contributed notes for this page.


获取定义过的一个常量

  • ? ReflectionClass::export
  • ReflectionClass::getConstants ?
  • PHP Manual
  • ReflectionClass
  • 获取定义过的一个常量

ReflectionClass::getConstant

(PHP 5, PHP 7)

ReflectionClass::getConstant — 获取定义过的一个常量

说明

public ReflectionClass::getConstant ( string $name ) : mixed

获取定义过的一个常量。

Warning

本函数还未编写文档，仅有参数列表。

参数

name

常量的名称。

返回值

常量的值。

参见

  • ReflectionClass::getConstants() - 获取一组常量

User Contributed Notes

aurelien dot tisserand at wavesoftware dot ch 08-Nov-2013 03:27
If the $name constant doesn't exist in the targetted class the function returns bool(false), not empty nor null but false (you to test with "==="

$constFounded = false ;
$this->currentlangClass = new ReflectionClass($langFile);
$this->currentlangClass->getConstant($constant);
if($myConst !== false){
              $constFounded = true ;
}
Bhimsen 31-May-2012 05:46
The "getconstant" method can be used to get the value associated with a constant
of a particular class that you are examining.
The following code snippet shows this:

<?php
    class Test{
        const ONE = "Number one";
        const TWO = "Number two";
    }

    $obj = new ReflectionClass( "Test" );
    echo $obj->getconstant( "ONE" )."\n";
    echo $obj->getconstant( "TWO" )."\n";

?>

output:
Number one
Number two


获取一组常量

  • ? ReflectionClass::getConstant
  • ReflectionClass::getConstructor ?
  • PHP Manual
  • ReflectionClass
  • 获取一组常量

ReflectionClass::getConstants

(PHP 5, PHP 7)

ReflectionClass::getConstants — 获取一组常量

说明

public ReflectionClass::getConstants ( ) : array

获取某个类的全部已定义的常量，不管可见性如何定义。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

常量的数组，常量名是数组的键，常量的值是数组的值。

参见

  • ReflectionClass::getConstant() - 获取定义过的一个常量

User Contributed Notes

dmitrochenkooleg at gmail dot com 05-Apr-2019 10:12
Get the latest constants declared.

abstract class AbstractEnum
{
    /**
     * Возвращает все константы класса || Return all constants
     *
     * @return array
     */
    static function getConstants()
    {
        $rc = new \ReflectionClass(get_called_class());

        return $rc->getConstants();
    }

    /**
     * Возвращает массив констант определенные в вызываемом классе  || Return last constants
     *
     * @return array
     */
    static function lastConstants()
    {
        $parentConstants = static::getParentConstants();

        $allConstants = static::getConstants();

        return array_diff($allConstants, $parentConstants);
    }

    /**
     * Возвращает все константы родительских классов || Return parent constants
     *
     * @return array
     */
    static function getParentConstants()
    {
        $rc = new \ReflectionClass(get_parent_class(static::class));
        $consts = $rc->getConstants();

        return $consts;
    }
}

======
class Roles extends AbstractEnum
{
    const ROOT = 'root';
    const ADMIN = 'admin';
    const USER = 'user';
}

// Output:
All: root, admin, user
Last: root, admin, user

class NewRoles extends Roles
{
    const CLIENT = 'client';
    const MODERATOR = 'moderator';
    const SUPERMODERATOR = 'super'.self::USER;
}

// Output:
All: client, moderator, superuser, root, admin, user
Last: client, moderator, superuser

class AdditionalRoles extends Roles
{
    const VIEWER = 'viewer';
    const CHECKER = 'checker';
    const ROOT = 'rooter';
}

All: viewer, checker, rooter, client, moderator, superuser, admin, user
Last: viewer, checker, rooter
Panni 17-Nov-2018 09:21
If you want to define a static getConstants() function which works with inheritance you can do the following:

<?php

abstract class AbstractClass
{
    const TEST = "test";

    public static function getConstants()
    {
        // "static::class" here does the magic
        $reflectionClass = new ReflectionClass(static::class);
        return $reflectionClass->getConstants();
    }
}

class ChildClass extends AbstractClass
{
    const TYPE_A = 1;
    const TYPE_B = 'hello';
}

$example = new ChildClass();
var_dump($example->getConstants());

// Result:
array(3) {
  'TYPE_A' => int(1)
  'TYPE_B' => string(5) "hello"
  'TEST' => string(4) "test"
}

?>
Sandor Toth 21-Nov-2016 02:50
You can pass $this as class for the ReflectionClass. __CLASS__ won't help if you extend the original class, because it is a magic constant based on the file itself.

<?php

class Example {
  const TYPE_A = 1;
  const TYPE_B = 'hello';

  public function getConstants()
  {
    $reflectionClass = new ReflectionClass($this);
    return $reflectionClass->getConstants();
  }
}

$example = new Example();
var_dump($example->getConstants());

// Result:
array ( size = 2)
  'TYPE_A' => int 1
  'TYPE_B' => (string) 'hello'
davide dot renzi at gmail dot com 16-Jul-2014 11:21
If you want to return the constants defined inside a class then you can also define an internal method as follows:

<?php
class myClass {
    const NONE = 0;
    const REQUEST = 100;
    const AUTH = 101;

    // others...

    static function getConstants() {
        $oClass = new ReflectionClass(__CLASS__);
        return $oClass->getConstants();
    }
}
?>
shgninc at gmail dot com 20-Nov-2013 10:00
I use a functions to do somthing base on the class constant name as below. This example maybe helpful for everybody.
<?php
public function renderData($question_type = NULL, $data = array()) {
        $types = array();
        $qt = new ReflectionClass(questionType);
        $types = $qt->getConstants();
        if ($type = array_search($question_type, $types)){
                //.....Do somthing
}
}
?>
djhob1972 at yahoo dot com dot au 16-Dec-2009 05:42
I was trying to determine how to get a var_dump of constants that are within an interface.  Thats right, not using any classes but the interface itself.

Along my travels I found it quite interesting that the ReflectionClass along with a direct call to the interface will also dump its constants.  Perfect!!!!

This was using PHP 5.3.1 and my example as below:-

1st File:

constants.php

<?php
<?php>

interface MyConstants
{
    // --------------------------
    // Programmatic Level
    // --------------------------
    const DEBUG_MODE_ACTIVE       = FALSE;
    const PHP_VERSION_REQUIREMENT = "5.1.2";
}
?>

=======
Second file:
=======

test.php

<?php>
include_once ("constants.php");

$oClass = new ReflectionClass ('MyConstants');
$array = $oClass->getConstants ();
var_dump ($array);
unset ($oClass);
?>

what you would get from the command line:-

?:\???\htdocs\????>php test.php
array(2) {
  ["DEBUG_MODE_ACTIVE"]=> bool(false)
  ["PHP_VERSION_REQUIREMENT"]=> string(5) "5.1.2"

But as you can see this can work quite well to your advantage in many ways so I truely hope this helps someone else with a similar headache in the future to come!

Enjoy!


获取类的构造函数

  • ? ReflectionClass::getConstants
  • ReflectionClass::getDefaultProperties ?
  • PHP Manual
  • ReflectionClass
  • 获取类的构造函数

ReflectionClass::getConstructor

(PHP 5, PHP 7)

ReflectionClass::getConstructor — 获取类的构造函数

说明

public ReflectionClass::getConstructor ( ) : ReflectionMethod

获取已反射的类的构造函数。

参数

此函数没有参数。

返回值

一个 ReflectionMethod 对象，反射了类的构造函数，或者当类不存在构造函数时返回 null。

范例

Example #1 ReflectionClass::getConstructor() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$constructor = $class->getConstructor();
var_dump($constructor);
?>

以上例程会输出：

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(15) "ReflectionClass"
}

参见

  • ReflectionClass::getName() - 获取类名

User Contributed Notes

martin dot melka at gmail dot com 01-Jul-2019 09:03
This method will return the parent's constructor, if the current class does not override it.

NULL will only be returned when the class has no constructor AND none of its parents have a constructor either.
jochem at drecomm dot nl 13-May-2011 08:13
Old constructors also count as contructor:

<?php

class SomeClass {

    function SomeClass($some_arg) {
    }

}

$refl = new ReflectionClass('SomeClass');

var_dump($refl->isInstantiable()); // bool(true)

echo $refl->getConstructor();

/* OUTPUT:
Method [ <user, ctor> public method SomeClass ] {
  @@ /var/www/vhosts/api.example.com/httpdocs/testRefl.php 5 - 6

  - Parameters [1] {
    Parameter #0 [ <required> $some_arg ]
  }
}
*/

?>

Some more behavior:

<?php

class SomeClass {

   function funcA($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('SomeClass');

var_dump($refl->isInstantiable()); // bool(true)

var_dump($refl->getConstructor()); // NULL

/* --------------- */

class AnotherClass {

   private function __construct() {
   }

   function funcB($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('AnotherClass');

var_dump($refl->isInstantiable()); // bool(false)

echo $refl->getConstructor();
/*
Method [ <user, ctor> private method __construct ] {
  @@ /testRefl.php 22 - 23
}
*/

?>

Tested on PHP 5.2.4
Rob McVey 16-Jul-2010 07:47
Just posting some example code for anyone wanting to mess around with this stuff:

<?php

class Say
{
    private $what_to_say;
    public function __construct($no_default, $word = "Hello World", $options = array('a', 'b'))
    {
        $this->what_to_say = $word;
    }

    public function speak()
    {
        echo $this->what_to_say;
    }
}

$class = new ReflectionClass('Say');

$constructor = $class->getConstructor();

echo $constructor;

/*     OUTPUTS:

Method [ <user, ctor> public method __construct ] {
  @@ /reflect.php 6 - 9

  - Parameters [3] {
    Parameter #0 [ <required> $no_default ]
    Parameter #1 [ <optional> $word = 'Hello World' ]
    Parameter #2 [ <optional> $options = Array ]
  }
}

*/

$parameters = $constructor->getParameters();

var_export($parameters);

/*    OUTPUT:

array (
  0 =>
  ReflectionParameter::__set_state(array(
     'name' => 'no_default',
  )),
  1 =>
  ReflectionParameter::__set_state(array(
     'name' => 'word',
  )),
  2 =>
  ReflectionParameter::__set_state(array(
     'name' => 'options',
  )),
)

*/

$nl = "\n";
echo "$nl\tParameters$nl";
foreach($parameters as $param)
{
    echo "****** $" . $param->name . " ******$nl";
    echo "Nullable:\t\t" . $param->allowsNull() . $nl
         ."Default Value:\t\t";
    echo ($param->isDefaultValueAvailable()) ? $param->getDefaultValue() : "None";
    echo $nl ."Is Array:\t\t";
    echo ($param->isArray()) ? "Yes" : "No";
    echo $nl . "Optional:\t\t";
    echo ($param->isOptional()) ? "Yes" : "No";
    echo $nl;
}

/*    OUTPUT:

    Parameters
****** $no_default ******
Nullable:        1
Default Value:    None
Is Array:        No
Optional:        No
****** $word ******
Nullable:        1
Default Value:    Hello World
Is Array:        No
Optional:        Yes
****** $options ******
Nullable:        1
Default Value:    Array
Is Array:        No
Optional:        Yes

*/

?>

To clarify the possibly confusing behavior of ReflectionParemeter::isArray(), it will return true if the parameter has type hinting:

<?php
...
public function __construct($no_default, $word = "Hello World", array $options = array('a', 'b'))
...
?>

Calling isArray() will now return true for the $options parameter


获取默认属性

  • ? ReflectionClass::getConstructor
  • ReflectionClass::getDocComment ?
  • PHP Manual
  • ReflectionClass
  • 获取默认属性

ReflectionClass::getDefaultProperties

(PHP 5, PHP 7)

ReflectionClass::getDefaultProperties — 获取默认属性

说明

public ReflectionClass::getDefaultProperties ( ) : array

获取类的默认属性（包括了继承的属性）。

Note:

This method only works for static properties when used on internal classes. The default value of a static class property can not be tracked when using this method on user defined classes.

参数

此函数没有参数。

返回值

默认属性的数组，其键是属性的名称，其值是属性的默认值或者在属性没有默认值时是 null。 这个函数不区分静态和非静态属性，也不考虑可见性修饰符。

范例

Example #1 ReflectionClass::getDefaultProperties() 例子

<?php
class Bar {
    protected $inheritedProperty = 'inheritedDefault';
}

class Foo extends Bar {
    public $property = 'propertyDefault';
    private $privateProperty = 'privatePropertyDefault';
    public static $staticProperty = 'staticProperty';
    public $defaultlessProperty;
}

$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

以上例程会输出：

array(5) {
   ["staticProperty"]=>
   string(14) "staticProperty"
   ["property"]=>
   string(15) "propertyDefault"
   ["privateProperty"]=>
   string(22) "privatePropertyDefault"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "inheritedDefault"
}

参见

  • ReflectionClass::getProperties() - 获取一组属性
  • ReflectionClass::getStaticProperties() - 获取静态（static）属性
  • ReflectionClass::getProperty() - 获取类的一个属性的 ReflectionProperty

User Contributed Notes

articice at ua dot fm 17-Mar-2016 12:15
runaurufu is not quite right, get_class_vars() does not return protected params, while this one does.

Thus it's extremely useful when having an abstract parent class and protected properties overriding in children.
For example, I use a class factory and one of the children has some static test methods that still need to output a paramether name, like $this->name, etc. With this example code, one can use static::getNotStaticProperty('name'), but not get_class_vars('name').

Try it:

trait static_reflector {
    /*
     * a purely static function that returns default properties of the non-static instance of the same class
     */
    static protected function getNonStaticProperty($key) {
        $me = get_class();
        $reflectionClass = new \ReflectionClass($me);
        $properties_list = $reflectionClass->getDefaultProperties();
        if (isset($properties_list[$key]))
            return $var_name = $properties_list[$key];
        else throw new RuntimeException("BUG: Unable to reflect non-static property '{$key}' from default properties of class {$me}");
    }
}

class a {

    use \static_reflector;

    protected $key_a = 'test ok';

    public static function test() {
        echo static::getNonStaticProperty('key_a')."\n";

        try {
            print static::getNonStaticProperty('key_b');
            echo "FAIL No exception thrown";
        } catch (RuntimeException $e) {
            echo "OK ".$e->getMessage();
        }

    }
}

echo get_class_vars('a')['key_a'];
a::test();

this will return:
Notice: Undefined index: key_a in ...
test ok
OK BUG: Unable to reflect non-static property 'key_b' from default properties of class a

ps: Yes, this is copied from a unit test.
runaurufu AT gmail.com 04-Aug-2011 01:02
Worth noting that it will not return private parameters of parent class...
so it works exactly as get_class_vars or get_object_vars
captainjester at hotmail dot com 20-Jan-2010 03:20
This will return all properties in a class and any parent classes.  The array will have keys set to the property names and empty values.


获取文档注释

  • ? ReflectionClass::getDefaultProperties
  • ReflectionClass::getEndLine ?
  • PHP Manual
  • ReflectionClass
  • 获取文档注释

ReflectionClass::getDocComment

(PHP 5, PHP 7)

ReflectionClass::getDocComment — 获取文档注释

说明

public ReflectionClass::getDocComment ( ) : string

从一个类中获取文档注释。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

如果存在则返回文档注释，否则返回 false。

范例

Example #1 ReflectionClass::getDocComment() 例子

<?php
/**
* A test class
*
* @param  foo bar
* @return baz
*/
class TestClass { }

$rc = new ReflectionClass('TestClass');
var_dump($rc->getDocComment())
?>

以上例程会输出：

string(55) "/**
* A test class
*
* @param  foo bar
* @return baz
*/"

参见

  • ReflectionClass::getName() - 获取类名

User Contributed Notes

bohwaz 15-Feb-2019 10:41
Please note that doc comments are handled differently than regular comments by PHP and the OpCache.

Doc comments are actually kept by the OpCache and accessible by this reflection API, unless disabled by the "opcache.save_comments" INI directive, see http://php.net/manual/en/opcache.configuration.php#ini.opcache.save-comments
i at hyurl dot com 23-Jul-2017 04:35
Not only this method can find a document by a given method name of a class, like this
 <?php
class Foo{
    /**
     * something describes this method
     */
    function bar(){
        /** code here... */
    }
}
$ref = new ReflectionClass('Foo');
print_r($ref->getMethod('bar')->getDocComment()); //will print out the method document as expected.
?>
But, also, if there is no method document in the defination, and the class extends from some other class, the program will automatically
try to find document from the parent class., like this:
<?php
class Foo2 extends Foo{}

$ref = new ReflectionClass('Foo');
print_r($ref->getMethod('bar')->getDocComment()); //will print out the method document as expected.
?>
geoffreybans at gmail dot com 07-Jan-2016 02:15
This code can help you get the contents of a docBlock in array format beginning with the @symbol and ignoring the (*) asterists.

class Home {

    /**
     *This method loads the homepage
     *@param int $id The user id
     *@throws \Exception If the user id doesn't exist
     *@return void
     */
    public function index( $id)
    {

         #...your code here

      }

}

$object = new Home();

//get the comment string
$comment_string= (new ReflectionClass($object))->getMethod('index')->getdoccomment();

//define the regular expression pattern to use for string matching
$pattern = "#(@[a-zA-Z]+\s*[a-zA-Z0-9, ()_].*)#";

//perform the regular expression on the string provided
preg_match_all($pattern, $comment_string, $matches, PREG_PATTERN_ORDER);

echo "<pre>"; print_r($matches);

//this outputs
Array
(
    [0] => Array
        (
            [0] => @param int $id The user id
            [1] => @throws \Exception If the user id doesn't exist
            [2] => @return void
        )

    [1] => Array
        (
            [0] => @param int $id The user id
            [1] => @throws \Exception If the user id doesn't exist
            [2] => @return void
        )

)

//you can then be able to access the particular string values by index
gabe at fijiwebdesign dot com 23-Aug-2014 11:46
You can also get the docblock definitions for the defined methods of a class as such:

<?php
/**
 * This is an Example class
 */
class Example
{
    /**
     * This is an example function
     */
    public function fn()
    {
        // void
    }
}

$reflector = new ReflectionClass('Example');

// to get the Class DocBlock
echo $reflector->getDocComment()

// to get the Method DocBlock
$reflector->getMethod('fn')->getDocComment();

?>
sun 28-Jun-2014 02:11
Note that \ReflectionClass::getDocComment() ignores all other PHP code and all white-space between the last encountered T_DOC_COMMENT and the class/element definition.

The only exceptions appear to be T_NAMESPACE declarations and T_FUNCTION definitions.

<?php
/**
 * Before namespace.
 */
namespace Foo;

 /**
 * After namespace.
   */

// ^^ contains excessive leading + trailing white-space.
use Bar\Baz;
const FOO = 'BAR';
$ns = 'bar';
# function foo() {}
$a = 2 + 1;
#/** what? */
// ^^ A single-line T_DOC_COMMENT is invisible when commented out.
count(array());

class Foo {
}

$reflector = new \ReflectionClass('Foo\Foo');
var_dump($reflector->getDocComment());
?>
yields, despite all the garbage in between:

string(28) "/**
 * After namespace.
   */"

To sum up:

1. If there are multiple doc comments, the last encountered applies.

2. Removing the "After namespace." docblock yields FALSE.
   (The namespace delimits the scope.)

3. Uncommenting the function definition yields FALSE.
   (The doc comment applies to the function instead.)

4. Despite being an own language construct, the "const" constant declaration does not delimit the scope.

5. Any leading and trailing white-space before and after the T_DOC_COMMENT ("/**...*/") is ignored, but the entire string content within (including all white-space) is consumed literally/verbatim.

[PHP 5.4.29]
uramihsayibok, gmail, com 15-Sep-2010 09:50
According to what I can find in the PHP (5.3.2) source code, getDocComment will return the doc comment as the parser found it.
The doc comment (T_DOC_COMMENT) must begin with a /** - that's two asterisks, not one. The comment continues until the first */. A normal multi-line comment /*...*/ (T_COMMENT) does not count as a doc comment.

The doc comment itself includes those five characters, so <?php substr($doccomment, 3, -2) ?> will get you what's inside. A call to trim() after is recommended.
joe dot scylla at gmail dot com 14-Oct-2009 08:23
If you're using a bytecode cache like eAccelerator this method will return FALSE even if there is a properly formatted Docblock. It looks like the information required by this method gets stripped out by the bytecode cache.


获取最后一行的行数

  • ? ReflectionClass::getDocComment
  • ReflectionClass::getExtension ?
  • PHP Manual
  • ReflectionClass
  • 获取最后一行的行数

ReflectionClass::getEndLine

(PHP 5, PHP 7)

ReflectionClass::getEndLine — 获取最后一行的行数

说明

public ReflectionClass::getEndLine ( ) : int

从用户定义的类获取其最后一行的行数。

参数

此函数没有参数。

返回值

返回用户定义的类最后一行的行数，如果未知则返回 false。

范例

Example #1 ReflectionClass::getEndLine() 例子

<?php
// Test Class
class TestClass { }

$rc = new ReflectionClass('TestClass');

echo $rc->getEndLine();
?>

以上例程会输出：

3

参见

  • ReflectionClass::getStartLine() - 获取起始行号

User Contributed Notes

There are no user contributed notes for this page.


根据已定义的类获取所在扩展的 ReflectionExtension 对象

  • ? ReflectionClass::getEndLine
  • ReflectionClass::getExtensionName ?
  • PHP Manual
  • ReflectionClass
  • 根据已定义的类获取所在扩展的 ReflectionExtension 对象

ReflectionClass::getExtension

(PHP 5, PHP 7)

ReflectionClass::getExtension — 根据已定义的类获取所在扩展的 ReflectionExtension 对象

说明

public ReflectionClass::getExtension ( ) : ReflectionExtension

获取已定义类的扩展的 ReflectionExtension 对象。

参数

此函数没有参数。

返回值

类所处的扩展的 ReflectionExtension 对象的表示，如果是用户定义的类则返回 null。

范例

Example #1 ReflectionClass::getExtension() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtension();
var_dump($extension);
?>

以上例程会输出：

object(ReflectionExtension)#2 (1) {
  ["name"]=>
  string(10) "Reflection"
}

参见

  • ReflectionClass::getExtensionName() - 获取定义的类所在的扩展的名称

User Contributed Notes

There are no user contributed notes for this page.


获取定义的类所在的扩展的名称

  • ? ReflectionClass::getExtension
  • ReflectionClass::getFileName ?
  • PHP Manual
  • ReflectionClass
  • 获取定义的类所在的扩展的名称

ReflectionClass::getExtensionName

(PHP 5, PHP 7)

ReflectionClass::getExtensionName — 获取定义的类所在的扩展的名称

说明

public ReflectionClass::getExtensionName ( ) : string

获取定义的类所在的扩展的名称。

参数

此函数没有参数。

返回值

获取定义的类所在的扩展的名称，如果是用户定义的类，则返回 false。

范例

Example #1 ReflectionClass::getExtensionName() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtensionName();
var_dump($extension);
?>

以上例程会输出：

string(10) "Reflection"

参见

  • ReflectionClass::getExtension() - 根据已定义的类获取所在扩展的 ReflectionExtension 对象

User Contributed Notes

There are no user contributed notes for this page.


获取定义类的文件名

  • ? ReflectionClass::getExtensionName
  • ReflectionClass::getInterfaceNames ?
  • PHP Manual
  • ReflectionClass
  • 获取定义类的文件名

ReflectionClass::getFileName

(PHP 5, PHP 7)

ReflectionClass::getFileName — 获取定义类的文件名

说明

public ReflectionClass::getFileName ( ) : string

获取类被定义的文件的文件名。

参数

此函数没有参数。

返回值

返回类所定义的文件名。如果这个类是在 PHP 核心或 PHP 扩展中定义的，则返回 false。

参见

  • ReflectionClass::getExtensionName() - 获取定义的类所在的扩展的名称

User Contributed Notes

robot at znframework dot com 25-Nov-2017 06:47
<?php

$a = new \ReflectionClass('ZN\Database\InternalDB');

var_dump($a->getFileName());

// Output:  C:\xampp7\htdocs\develop\Internal\Database\DB\InternalDB.php


获取接口（interface）名称

  • ? ReflectionClass::getFileName
  • ReflectionClass::getInterfaces ?
  • PHP Manual
  • ReflectionClass
  • 获取接口（interface）名称

ReflectionClass::getInterfaceNames

(PHP 5 >= 5.2.0, PHP 7)

ReflectionClass::getInterfaceNames — 获取接口（interface）名称

说明

public ReflectionClass::getInterfaceNames ( ) : array

获取接口（interface）名称。

参数

此函数没有参数。

返回值

一个数值数组，接口（interface）的名称是数组的值。

范例

Example #1 ReflectionClass::getInterfaceNames() 例子

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaceNames());
?>

以上例程的输出类似于：

Array
(
    [0] => Foo
    [1] => Bar
)

参见

  • ReflectionClass::getInterfaces() - 获取接口

User Contributed Notes

pvdhurk 23-Jul-2020 12:43
For the record, it will return the full name (not the short name) for each Interface

Example with namespace would've helped.
pinpin 27-Mar-2011 04:11
It seems the interface names are actually listed in a defined order:
- "extends" takes precedence over "implements" (i.e. first will be interfaces from (implemented in) the parent class (if any), then interfaces implemented in the class itself)
- when multiple interfaces are implemented at one time/level, it can be:
+ from an "implements" : they're listed in the defined order
+ from an "extends" (a class extends another class which implements multiple interfaces; or an interface extends multiple interfaces) : they're listed in REVERSE order

<?php
interface Foo {}
interface Bar {}
interface Other {}
interface Foobar extends Foo, Bar {}
interface Barfoo extends Bar, Foo {}

class Test1 implements Foo, Bar {}
class Test2 implements Bar, Foo {}

class Test3 extends Test1 {}
class Test4 extends Test2 {}

class Test5 extends Test1 implements Other {}

class Test6 implements Foobar, Other {}
class TestO implements Other {}
class Test7 extends TestO implements Barfoo {}

$r=new ReflectionClass('Test1');
print_r($r->getInterfaceNames()); // Foo, Bar

$r=new ReflectionClass('Test2');
print_r($r->getInterfaceNames()); // Bar, Foo

$r=new ReflectionClass('Test3');
print_r($r->getInterfaceNames()); // Bar, Foo

$r=new ReflectionClass('Test4');
print_r($r->getInterfaceNames()); // Foo, Bar

$r=new ReflectionClass('Test5');
print_r($r->getInterfaceNames()); // Bar, Foo, Other

$r=new ReflectionClass('Test6');
print_r($r->getInterfaceNames()); // Foobar, Bar, Foo, Other

$r=new ReflectionClass('Test7');
print_r($r->getInterfaceNames()); // Other, Barfoo, Foo, Bar
?>


获取接口

  • ? ReflectionClass::getInterfaceNames
  • ReflectionClass::getMethod ?
  • PHP Manual
  • ReflectionClass
  • 获取接口

ReflectionClass::getInterfaces

(PHP 5, PHP 7)

ReflectionClass::getInterfaces — 获取接口

说明

public ReflectionClass::getInterfaces ( ) : array

获取接口。

参数

此函数没有参数。

返回值

接口的关联数组，数组键是接口（interface）的名称，数组的值是 ReflectionClass 对象。

范例

Example #1 ReflectionClass::getInterfaces() 例子

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaces());
?>

以上例程的输出类似于：

Array
(
    [Foo] => ReflectionClass Object
        (
            [name] => Foo
        )

    [Bar] => ReflectionClass Object
        (
            [name] => Bar
        )

)

参见

  • ReflectionClass::getInterfaceNames() - 获取接口（interface）名称

User Contributed Notes

There are no user contributed notes for this page.


获取一个类方法的 ReflectionMethod。

  • ? ReflectionClass::getInterfaces
  • ReflectionClass::getMethods ?
  • PHP Manual
  • ReflectionClass
  • 获取一个类方法的 ReflectionMethod。

ReflectionClass::getMethod

(PHP 5, PHP 7)

ReflectionClass::getMethod — 获取一个类方法的 ReflectionMethod。

说明

public ReflectionClass::getMethod ( string $name ) : ReflectionMethod

获取一个类方法的 ReflectionMethod。

参数

name

要反射的方法名称。

返回值

一个 ReflectionMethod。

错误／异常

如果方法不存在则会抛出 ReflectionException 异常。

范例

Example #1 ReflectionClass::getMethod() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>

以上例程会输出：

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(9) "getMethod"
  ["class"]=>
  string(15) "ReflectionClass"
}

参见

  • ReflectionClass::getMethods() - 获取方法的数组

User Contributed Notes

Jarrod Nettles 22-Dec-2010 12:58
If you ever need to get the type hint of a parameter in a method use this.

<?php

//Target our class
$reflector = new ReflectionClass('MyClass');

//Get the parameters of a method
$parameters = $reflector->getMethod('FireCannon')->getParameters();

//Loop through each parameter and get the type
foreach($parameters as $param)
{
     //Before you call getClass() that class must be defined!
     echo $param->getClass()->name;
}

?>


获取方法的数组

  • ? ReflectionClass::getMethod
  • ReflectionClass::getModifiers ?
  • PHP Manual
  • ReflectionClass
  • 获取方法的数组

ReflectionClass::getMethods

(PHP 5, PHP 7)

ReflectionClass::getMethods — 获取方法的数组

说明

public ReflectionClass::getMethods ( int $filter = ? ) : array

获取类的方法的一个数组。

参数

filter

过滤结果为仅包含某些属性的方法。默认不过滤。

ReflectionMethod::IS_STATIC、
ReflectionMethod::IS_PUBLIC、
ReflectionMethod::IS_PROTECTED、
ReflectionMethod::IS_PRIVATE、
ReflectionMethod::IS_ABSTRACT、
ReflectionMethod::IS_FINAL 的按位或（OR），就会返回任意满足条件的属性。

Note: 请注意：其他位操作，例如 ~ 无法按预期运行。这个例子也就是说，无法获取所有的非静态方法。

返回值

包含每个方法 ReflectionMethod 对象的数组。

范例

Example #1 ReflectionClass::getMethods() 的基本用法

<?php
class Apple {
    public function firstMethod() { }
    final protected function secondMethod() { }
    private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods();
var_dump($methods);
?>

以上例程会输出：

array(3) {
  [0]=>
  &object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(11) "firstMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [2]=>
  &object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

Example #2 从 ReflectionClass::getMethods() 中过滤结果

<?php
class Apple {
    public function firstMethod() { }
    final protected function secondMethod() { }
    private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_FINAL);
var_dump($methods);
?>

以上例程会输出：

array(2) {
  [0]=>
  &object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

参见

  • ReflectionClass::getMethod() - 获取一个类方法的 ReflectionMethod。
  • get_class_methods() - 返回由类的方法名组成的数组

User Contributed Notes

tom at r dot je 11-Jun-2014 05:40
ReflectionClass::getMethods() sorts the methods by class (lowest in the inheritance tree first) then by the order they are defined in the class definition:

<?php
class A {
    public function method1() {

    }

    public function method2() {

    }
}

class B extends A {

    public function method3() {

    }

    public function method4() {

    }
}

$class = new ReflectionClass('B');
print_r($class->getMethods());
?>

This will output:

Array
(
    [0] => ReflectionMethod Object
        (
            [name] => method3
            [class] => B
        )

    [1] => ReflectionMethod Object
        (
            [name] => method4
            [class] => B
        )

    [2] => ReflectionMethod Object
        (
            [name] => method1
            [class] => A
        )

    [3] => ReflectionMethod Object
        (
            [name] => method2
            [class] => A
        )

)
x_atrix at yahoo dot com 10-Jul-2013 05:00
Note, for ReflectionClass::getMethods() not all methods in a final class are final, just the ones that have explicit modifier.
If you want to use an and operator for the filter, here is a simple implementation
<?php
final class Apple {
    public function publicMethod() { }
    public final function publicFinalMethod() { }
    protected final function protectedFinalMethod() { }
    private static function privateStaticMethod() { }
}

class MyReflection extends ReflectionClass {
    public function __construct($argument) {
        parent::__construct($argument);
    }

    /**
     * (non-PHPdoc)
     * @see ReflectionClass::getMethods()
     */
    public function getMethods($filter = null, $useAndOperator = true) {
        if ($useAndOperator !== true) {
            return parent::getMethods($filter);
        }

        $methods = parent::getMethods($filter);
        $results = array();

        foreach ($methods as $method) {
            if (($method->getModifiers() & $filter) === $filter) {
                $results[] = $method;
            }
        }

        return $results;
    }
}

$class = new MyReflection('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_FINAL | ReflectionMethod::IS_PUBLIC);
var_dump($methods);

$methods = $class->getMethods(ReflectionMethod::IS_FINAL | ReflectionMethod::IS_PUBLIC, false);
var_dump($methods);
?>

Result:
array(1) {
  [0]=>
  object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(17) "publicFinalMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

array(3) {
  [0]=>
  &object(ReflectionMethod)#5 (2) {
    ["name"]=>
    string(12) "publicMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(17) "publicFinalMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [2]=>
  &object(ReflectionMethod)#6 (2) {
    ["name"]=>
    string(20) "protectedFinalMethod"
    ["class"]=>
    string(5) "Apple"
  }
}
deminy at deminy dot net 22-Jun-2011 09:24
Method ReflectionClass::getMethods doesn't work constantly across different versions of PHP. For following code piece

<?php
class Dummy implements Iterator
{
    public function current () {}
    public function next () {}
    public function key () {}
    public function valid () {}
    public function rewind () {}
}

$reflection = new ReflectionClass('Dummy');
$aMethods = $reflection->getMethods();
echo '# of methods: ', count($aMethods), "\n";
?>

, it outputs "# of methods: 10" on PHP 5.2.14 and PHP 5.2.17, including all methods defined in the class itself and in the interface no matter if a method has been implemented or overridden; however, it returns "# of methods: 5" on PHP 5.3.5. Based on some other tests did by my colleagues, I assume it also returns "# of methods: 5" on PHP 5.2.10 and PHP 5.3.6.


获取类的修饰符

  • ? ReflectionClass::getMethods
  • ReflectionClass::getName ?
  • PHP Manual
  • ReflectionClass
  • 获取类的修饰符

ReflectionClass::getModifiers

(PHP 5, PHP 7)

ReflectionClass::getModifiers — 获取类的修饰符

说明

public ReflectionClass::getModifiers ( ) : int

返回这个类访问修饰符的位字段。

参数

此函数没有参数。

返回值

返回 修饰符常量 的位掩码。

参见

  • ReflectionClass::getProperties() - 获取一组属性
  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

Nicola Pietroluongo 26-Feb-2015 01:17
It's the amount of memory allocation in bit.
By default many systems allocate 1048576 bit (1 Megabit).

/* Example 1 */

class Test {}
$classTest = new Test();
$reflectionClass = new \ReflectionClass('Test');
$classModifiers = $reflectionClass->getModifiers();
var_export($classModifiers);

//output
1048576

/* Example 2 */

class Test {}
//the constructor is missing
$reflectionClass = new \ReflectionClass('Test');
$classModifiers = $reflectionClass->getModifiers();
var_export($classModifiers);

//output
0


获取类名

  • ? ReflectionClass::getModifiers
  • ReflectionClass::getNamespaceName ?
  • PHP Manual
  • ReflectionClass
  • 获取类名

ReflectionClass::getName

(PHP 5, PHP 7)

ReflectionClass::getName — 获取类名

说明

public ReflectionClass::getName ( ) : string

获取类的名称。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The class name.

范例

Example #1 ReflectionClass::getName() 例子

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

以上例程会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getNamespaceName() - 获取命名空间的名称

User Contributed Notes

There are no user contributed notes for this page.


获取命名空间的名称

  • ? ReflectionClass::getName
  • ReflectionClass::getParentClass ?
  • PHP Manual
  • ReflectionClass
  • 获取命名空间的名称

ReflectionClass::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::getNamespaceName — 获取命名空间的名称

说明

public ReflectionClass::getNamespaceName ( ) : string

获取命名空间（namespace）的名称。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

命名空间的名称。

范例

Example #1 ReflectionClass::getNamespaceName() 例子

<?php
namespace A\B;

class Foo { }

$class = new \ReflectionClass('stdClass');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());

$class = new \ReflectionClass('A\\B\\Foo');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());
?>

以上例程会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getParentClass() - 获取父类
  • namespaces

User Contributed Notes

francois 14-Aug-2011 04:08
If the object does not belong to a namespace, an empty string is returned


获取父类

  • ? ReflectionClass::getNamespaceName
  • ReflectionClass::getProperties ?
  • PHP Manual
  • ReflectionClass
  • 获取父类

ReflectionClass::getParentClass

(PHP 5, PHP 7)

ReflectionClass::getParentClass — 获取父类

说明

public ReflectionClass::getParentClass ( ) : ReflectionClass

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

一个 ReflectionClass。

参见

  • ReflectionClass::__construct() - 初始化 ReflectionClass 类

User Contributed Notes

isaac dot z dot foster at gmail dot com 15-Jun-2013 09:02
Quick correction, the code for getting all parent classes below has a "typo", you need to reset the $class variable to the parent class instance, otherwise it just endlessly loops:

        $class = new ReflectionClass('classname');

        $parents = array();

        while ($parent = $class->getParentClass()) {
            $parents[] = $parent->getName();
            $class = $parent;
        }

        echo "Parents: " . implode(", ", $parents);
havelangep at hotmail dot com 16-Dec-2010 01:26
Here is a "replacement" for is_a that will additionally look both into the extended classes and in the implemented interfaces

<?php
/**
     * Check if a class extends or implements a specific class/interface
     * @param string $search The class or interface name to look for
     * @param string $className The class name of the object to compare to
     * @return bool
     */
    function IsExtendsOrImplements( $search, $className ) {
        $class = new ReflectionClass( $className );
        if( false === $class ) {
            return false;
        }
        do {
            $name = $class->getName();
            if( $search == $name ) {
                return true;
            }
            $interfaces = $class->getInterfaceNames();
            if( is_array( $interfaces ) && in_array( $search, $interfaces )) {
                return true;
            }
            $class = $class->getParentClass();
        } while( false !== $class );
        return false;
    }
?>
jochem at drecomm dot nl 18-Nov-2010 04:34
When you want to find all parents (parent, parent of parent, parent of parent's parent and so on) try:

<?php
$class = new ReflectionClass('whatever');

$parents = array();

while ($parent = $class->getParentClass()) {
    $parents[] = $parent->getName();
}

echo "Parents: " . implode(", ", $parents);
?>

ReflectionClass::getParentClass() can return a ReflectionClass object of the parent class or false if no parent.

(PHP Version 5.1.6)


获取一组属性

  • ? ReflectionClass::getParentClass
  • ReflectionClass::getProperty ?
  • PHP Manual
  • ReflectionClass
  • 获取一组属性

ReflectionClass::getProperties

(PHP 5, PHP 7)

ReflectionClass::getProperties — 获取一组属性

说明

public ReflectionClass::getProperties ( int $filter = ? ) : array

获取反射过的属性。

参数

filter

可选的过滤器，过滤为所需类型的属性。它使用 ReflectionProperty 常量 来配置，默认获取所有类型的属性。

返回值

ReflectionProperty 对象的数组。

范例

Example #1 ReflectionClass::getProperties() 过滤例子

这个例子延时了可选 filter 参数的用法，例子里实际上忽略了私有属性。

<?php
class Foo {
    public    $foo  = 1;
    protected $bar  = 2;
    private   $baz  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
    print $prop->getName() . "\n";
}

var_dump($props);

?>

以上例程的输出类似于：

foo
bar
array(2) {
  [0]=>
  object(ReflectionProperty)#3 (2) {
    ["name"]=>
    string(3) "foo"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionProperty)#4 (2) {
    ["name"]=>
    string(3) "bar"
    ["class"]=>
    string(3) "Foo"
  }
}

参见

  • ReflectionClass::getProperty() - 获取类的一个属性的 ReflectionProperty
  • ReflectionProperty
  • ReflectionProperty 修饰符常量

User Contributed Notes

kelunik at php dot net 21-Jan-2018 10:58
Note that inherited properties are returned, but no private properties of parent classes. Depending on the use case, you need to check that, too.

do {
    foreach ($reflectionClass->getProperties() as $property) {
        /* ... */
    }
} while ($reflectionClass = $reflectionClass->getParentClass());
postmaster at greg0ire dot fr 08-Jul-2014 09:23
The code in the first example actually does get inherited properties with at least php 5.5.9 . I don't know if / when this behavior changed.

Here is the output:
    array(2) {
     [0] =>
     class ReflectionProperty#2 (2) {
       public $name =>
       string(2) "a2"
       public $class =>
       string(2) "AA"
     }
     [1] =>
     class ReflectionProperty#3 (2) {
       public $name =>
       string(2) "a1"
       public $class =>
       string(1) "A"
     }
    }
Yzmir Ramirez 16-Oct-2010 08:53
Looks like you can access public, protected, private variables by casting the object to an array (useful for Unit Testing).  However casting to an array still won't allow you access to protected and private static variables.

In PHP 5.3.0+ use ReflectionProperty::setAccessable(true);

<?php

echo "PHP Version: ".phpversion()."\n";

class Foo {
    public    $foo  = 'public';
    protected $bar  = 'protected';
    private   $baz  = 'private';

    public static    $sfoo  = 'public static';
    protected static $sbar  = 'protected static';
    private static   $sbaz  = 'private static';

    const COO = 'const';

}

$obj = new Foo;

$arr = (array)$obj;

print_r($arr);

echo "Accessing Public Static: ".Foo::$sfoo."\n";
// echo Foo::$sbar."\n"; // Fatal error: Cannot access protected property Foo::$sbar
// echo Foo::$sbaz."\n"; // Fatal error: Cannot access private property Foo::$sbaz
echo "Accessing Constant: ".Foo::COO."\n";
?>

PHP Version: 5.2.12
Array
(
    [foo] => public
    [*bar] => protected
    [Foobaz] => private
)
Accessing Public Static: public static
Accessing Constant: const

PHP Version: 5.1.6
Array
(
    [foo] => public
    [*bar] => protected
    [Foobaz] => private
)
Accessing Public Static: public static
Accessing Constant: const
mcurtis 28-Jan-2009 02:41
It should be noted that the 'filter' parameter in the getProperties(filter) method is expected to be of type long.  Not sure why, but it doesn't function as a way of passing in a string to fetch a subset of properties by string match.
muratyaman at gmail dot com 22-Jan-2009 07:47
Some may find this useful.

<?php
/**
 * Recursive function to get an associative array of class properties by property name => ReflectionProperty() object
 * including inherited ones from extended classes
 * @param string $className Class name
 * @param string $types Any combination of <b>public, private, protected, static</b>
 * @return array
 */
function getClassProperties($className, $types='public'){
    $ref = new ReflectionClass($className);
    $props = $ref->getProperties();
    $props_arr = array();
    foreach($props as $prop){
        $f = $prop->getName();

        if($prop->isPublic() and (stripos($types, 'public') === FALSE)) continue;
        if($prop->isPrivate() and (stripos($types, 'private') === FALSE)) continue;
        if($prop->isProtected() and (stripos($types, 'protected') === FALSE)) continue;
        if($prop->isStatic() and (stripos($types, 'static') === FALSE)) continue;

        $props_arr[$f] = $prop;
    }
    if($parentClass = $ref->getParentClass()){
        $parent_props_arr = getClassProperties($parentClass->getName());//RECURSION
        if(count($parent_props_arr) > 0)
            $props_arr = array_merge($parent_props_arr, $props_arr);
    }
    return $props_arr;
}

//USAGE

class A{
  public $a1;

    function abc(){
        //do something
    }
}

class AA extends A{
    public $a2;

    function edf(){
        //do something
    }
}

class AAA extends AA{
  //may not have extra properties, but may have extra methods
    function ghi(){
        //ok
    }
}

//$ref = new ReflectionClass('AAA'); $props = $ref->getProperties();//This will get no properties!
$props_arr = getClassProperties('AAA', 'public');//Use this
var_dump($props_arr);
/*
OUTPUT on PHP5.2.6:
array
  'a1' =>
    object(ReflectionProperty)[4]
      public 'name' => string 'a1' (length=2)
      public 'class' => string 'AAA' (length=3)
  'a2' =>
    object(ReflectionProperty)[3]
      public 'name' => string 'a2' (length=2)
      public 'class' => string 'AAA' (length=3)

*/

?>
david dot thalmann at gmail dot com 05-Jan-2009 08:19
With PHP 5.3 protected or private properties are easy to access with setAccessible(). However, it's sometimes needed (e.g. Unit Tests) and here is a workaround for getValue():

<?php

$class = new ReflectionClass('SomeClass');
$props = $class->getProperties();
// $propsStatic = $class->getStaticProperties();

$myPrivatePropertyValue = $props['aPrivateProperty'];

?>

Note that it wont work if you access the property directly with getProperty().


获取类的一个属性的 ReflectionProperty

  • ? ReflectionClass::getProperties
  • ReflectionClass::getReflectionConstant ?
  • PHP Manual
  • ReflectionClass
  • 获取类的一个属性的 ReflectionProperty

ReflectionClass::getProperty

(PHP 5, PHP 7)

ReflectionClass::getProperty — 获取类的一个属性的 ReflectionProperty

说明

public ReflectionClass::getProperty ( string $name ) : ReflectionProperty

获取类的一个属性的 ReflectionProperty。

参数

name

属性名。

返回值

一个 ReflectionProperty。

范例

Example #1 ReflectionClass::getProperty() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$property = $class->getProperty('name');
var_dump($property);
?>

以上例程会输出：

object(ReflectionProperty)#2 (2) {
  ["name"]=>
  string(4) "name"
  ["class"]=>
  string(15) "ReflectionClass"
}

参见

  • ReflectionClass::getProperties() - 获取一组属性

User Contributed Notes

dohpaz42 16-Jun-2015 04:16
Accessing private properties is possible, but care must be taken if that private property was defined lower into the inheritance chain. For example, if class A extends class B, and class B defines a private property called 'foo', getProperty will throw a ReflectionException.

Instead, you can loop over getParentClass until it returns false to look for the private property, at which point you can access and/or modify its value as needed.
eric at naeseth dot com 02-Aug-2011 03:38
If the class doesn't have a property with the given name, a ReflectionException will be raised.


Gets a ReflectionClassConstant for a class's constant

  • ? ReflectionClass::getProperty
  • ReflectionClass::getReflectionConstants ?
  • PHP Manual
  • ReflectionClass
  • Gets a ReflectionClassConstant for a class's constant

ReflectionClass::getReflectionConstant

(PHP 7 >= 7.1.0)

ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant

说明

public ReflectionClass::getReflectionConstant ( string $name ) : ReflectionClassConstant|false

Gets a ReflectionClassConstant for a class's property.

参数

name

The class constant name.

返回值

A ReflectionClassConstant, 或者在失败时返回 false.

参见

  • ReflectionClass::getReflectionConstants() - Gets class constants
  • ReflectionClassConstant

User Contributed Notes

There are no user contributed notes for this page.


Gets class constants

  • ? ReflectionClass::getReflectionConstant
  • ReflectionClass::getShortName ?
  • PHP Manual
  • ReflectionClass
  • Gets class constants

ReflectionClass::getReflectionConstants

(PHP 7 >= 7.1.0)

ReflectionClass::getReflectionConstants — Gets class constants

说明

public ReflectionClass::getReflectionConstants ( int|null $filter = null ) : array

Retrieves reflected constants.

参数

filter

The optional filter, for filtering desired constant visibilities. It's configured using the ReflectionClassConstant constants, and defaults to all constant visibilities.

返回值

An array of ReflectionClassConstant objects.

更新日志

版本 | 说明
8.0.0 | filter has been added.

范例

Example #1 Basic ReflectionClass::getReflectionConstants() example

<?php
class Foo {
    public    const FOO  = 1;
    protected const BAR  = 2;
    private   const BAZ  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$consts  = $reflect->getReflectionConstants();

foreach ($consts as $const) {
    print $const->getName() . "\n";
}

var_dump($consts);

?>

以上例程的输出类似于：

FOO
BAR
BAZ
array(3) {
  [0]=>
  object(ReflectionClassConstant)#3 (2) {
    ["name"]=>
    string(3) "FOO"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionClassConstant)#4 (2) {
    ["name"]=>
    string(3) "BAR"
    ["class"]=>
    string(3) "Foo"
  }
  [2]=>
  object(ReflectionClassConstant)#5 (2) {
    ["name"]=>
    string(3) "BAZ"
    ["class"]=>
    string(3) "Foo"
  }
}

参见

  • ReflectionClass::getReflectionConstant() - Gets a ReflectionClassConstant for a class's constant
  • ReflectionClassConstant

User Contributed Notes

There are no user contributed notes for this page.


获取短名

  • ? ReflectionClass::getReflectionConstants
  • ReflectionClass::getStartLine ?
  • PHP Manual
  • ReflectionClass
  • 获取短名

ReflectionClass::getShortName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::getShortName — 获取短名

说明

public ReflectionClass::getShortName ( ) : string

获取类的短名，就是不含命名空间（namespace）的那一部分。

参数

此函数没有参数。

返回值

类的短名。

范例

Example #1 ReflectionClass::getShortName() 例子

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

以上例程会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getName() - 获取类名

User Contributed Notes

There are no user contributed notes for this page.


获取起始行号

  • ? ReflectionClass::getShortName
  • ReflectionClass::getStaticProperties ?
  • PHP Manual
  • ReflectionClass
  • 获取起始行号

ReflectionClass::getStartLine

(PHP 5, PHP 7)

ReflectionClass::getStartLine — 获取起始行号

说明

public ReflectionClass::getStartLine ( ) : int

获取起始的行号。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

起始的行号，类型是 integer 的。

参见

  • ReflectionClass::getEndLine() - 获取最后一行的行数

User Contributed Notes

There are no user contributed notes for this page.


获取静态（static）属性

  • ? ReflectionClass::getStartLine
  • ReflectionClass::getStaticPropertyValue ?
  • PHP Manual
  • ReflectionClass
  • 获取静态（static）属性

ReflectionClass::getStaticProperties

(PHP 5, PHP 7)

ReflectionClass::getStaticProperties — 获取静态（static）属性

说明

public ReflectionClass::getStaticProperties ( ) : array

获取静态（static）属性。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

静态（static）的属性，类型是 array。

参见

  • ReflectionClass::getStaticPropertyValue() - 获取静态（static）属性的值
  • ReflectionClass::setStaticPropertyValue() - 设置静态属性的值

User Contributed Notes

joao dot felipe dot c dot b at gmail dot com 24-Mar-2016 01:06
getStaticProperties return a set of the property itself. It's diferente from getProperties(ReflectionProperty::IS_STATIC) because it return a set of ReflectionProperty class.
jlennox @ google mail 08-May-2010 10:03
I had the need to recursive merge the results from a subclass with all of it's parents, and this was the resulting code:

<?php
function GetStaticPropertiesRecursive($class) {
    $currentClass = $class;
    $joinedProperties = array();
    do {
        $reflection = new ReflectionClass($class);
        $staticProperties = $reflection->getStaticProperties();
        foreach ($staticProperties as $name => $value) {
            if (is_array($value)) {
                if (isset($joinedProperties[$name]))
                    $joinedProperties[$name] = array_merge($value, $joinedProperties[$name]);
                else
                    $joinedProperties[$name] = $value;
            } else {
                if (isset($joinedProperties[$name]))
                    $joinedProperties[$name][] = $value;
                else
                    $joinedProperties[$name] = array($value);
            }
        }
    } while ($class = get_parent_class($class));
    return $joinedProperties;
}

Using this function:
class base {
    public static $Test = array("foo1", "foo2");
}
class sub extends base {
    public static $Test = "sub";
}

print_r(GetStaticPropertiesRecursive("sub"));
?>

That outputs:
Array
(
    [Test] => Array
        (
            [0] => foo1
            [1] => foo2
            [2] => sub
        )

)

The merge follows the rules of array_merge on duplicate keys.


获取静态（static）属性的值

  • ? ReflectionClass::getStaticProperties
  • ReflectionClass::getTraitAliases ?
  • PHP Manual
  • ReflectionClass
  • 获取静态（static）属性的值

ReflectionClass::getStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::getStaticPropertyValue — 获取静态（static）属性的值

说明

public ReflectionClass::getStaticPropertyValue ( string $name , mixed &$def_value = ? ) : mixed

获取这个类里静态（static）属性的值。

参数

name

静态属性的名称，来返回它的值。

def_value

假如类没有定义 name 的 static 属性，将返回一个默认值。 如果属性不存在，并且省略了此参数，将会抛出 ReflectionException 。

返回值

静态属性的值。

范例

Example #1 ReflectionClass::getStaticPropertyValue() 的基本用法

<?php
class Apple {
    public static $color = 'Red';
}

$class = new ReflectionClass('Apple');
var_dump($class->getStaticPropertyValue('color'));
?>

以上例程会输出：

string(3) "Red"

参见

  • ReflectionClass::getStaticProperties() - 获取静态（static）属性
  • ReflectionClass::setStaticPropertyValue() - 设置静态属性的值

User Contributed Notes

Antares 16-Aug-2011 07:11
It seems this method has a security level different from the getStaticProperties method.

If you make two classes A and B looking like

<?php
class A{
        protected static $static_var='foo';

        public function getStatic(){
           $class=new ReflectionClass($this);
           return $class->getStaticPropertyValue('static_var');
        }

        public function getStatic2(){
            $class=new ReflectionClass($this);
            $staticProps=$class->getStaticProperties();
            return $staticProps['static_var'];
        }

        public function __construct(){
              echo $this->getStatic2();
              echo $this->getStatic();
        }
}

class B extends A{
        protected static $static_var='foo2';

}
?>

Then the output will be an exception for the getStatic() call, when the getStatic2() will correctly return 'foo2';
Mauro Gabriel Titimoli 21-Jan-2010 12:05
If you want to change a static property of a variable class...

PHP 5.2
<?php
$reflection = new ReflectionClass($className);
$staticPropertyReference = & $reflection->getStaticPropertyValue($staticPropertyName);

$staticPropertyReference = 'new value';
?>

PHP 5.3
<?php
$className::$$classProperty
?>


返回 trait 别名的一个数组

  • ? ReflectionClass::getStaticPropertyValue
  • ReflectionClass::getTraitNames ?
  • PHP Manual
  • ReflectionClass
  • 返回 trait 别名的一个数组

ReflectionClass::getTraitAliases

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraitAliases — 返回 trait 别名的一个数组

说明

public ReflectionClass::getTraitAliases ( ) : array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回了一个数组，新的方法名位于键中，原始名称（格式是 "TraitName::original"）位于数组的值中。 出现一个错误的情况下返回 null。

User Contributed Notes

dhairya dot coder at gmail dot com 10-Feb-2016 11:43
trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

class Apple{

    use A {
        A::bigTalk as talk;
    }
}

$obj=new ReflectionClass('Apple');
echo "<pre>";
var_dump($obj->getTraitAliases());
echo "</pre>";


返回这个类所使用 traits 的名称的数组

  • ? ReflectionClass::getTraitAliases
  • ReflectionClass::getTraits ?
  • PHP Manual
  • ReflectionClass
  • 返回这个类所使用 traits 的名称的数组

ReflectionClass::getTraitNames

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraitNames — 返回这个类所使用 traits 的名称的数组

说明

public ReflectionClass::getTraitNames ( ) : array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回的数组的值包含了 trait 的名称。 出现错误的情况下返回 null。

User Contributed Notes

emulienfou at gmail dot com 30-Nov-2013 03:55
This remote return only the trait names from the current class.

If your class extends another class using your trait, you can't get the names. However, you can do something like :

<?php
$traitsNames = [];
$recursiveClasses = function ($class) use(&$recursiveClasses, &$traitsNames) {
    if ($class->getParentClass() != false) {
        $recursiveClasses($class->getParentClass());
    }
    else {
        $traitsNames = array_merge($traitsNames, $class->getTraitNames());
    }
};
$recursiveClasses($controllerClass);


返回这个类所使用的 traits 数组

  • ? ReflectionClass::getTraitNames
  • ReflectionClass::hasConstant ?
  • PHP Manual
  • ReflectionClass
  • 返回这个类所使用的 traits 数组

ReflectionClass::getTraits

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraits — 返回这个类所使用的 traits 数组

说明

public ReflectionClass::getTraits ( ) : array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回了一个数组，键是 trait 的名称，值是 trait 实例的 ReflectionClass。 出现错误的情况下返回 null。

User Contributed Notes

Anonymous 15-Jan-2015 04:03
Note that getTraits will NOT return any traits inherited from a parent.

This is currently viewed as the desired behavior.  See https://bugs.php.net/bug.php?id=61554


检查常量是否已经定义

  • ? ReflectionClass::getTraits
  • ReflectionClass::hasMethod ?
  • PHP Manual
  • ReflectionClass
  • 检查常量是否已经定义

ReflectionClass::hasConstant

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasConstant — 检查常量是否已经定义

说明

public ReflectionClass::hasConstant ( string $name ) : bool

检查类中是否已经定义了指定的常量。

参数

name

要被检查的常量名称。

返回值

如果已定义返回 true，否则返回 false。

范例

Example #1 ReflectionClass::hasConstant() 例子

<?php
class Foo {
    const c1 = 1;
}

$class = new ReflectionClass("Foo");

var_dump($class->hasConstant("c1"));
var_dump($class->hasConstant("c2"));
?>

以上例程的输出类似于：

bool(true)
bool(false)

参见

  • ReflectionClass::hasMethod() - 检查方法是否已定义
  • ReflectionClass::hasProperty() - 检查属性是否已定义

User Contributed Notes

There are no user contributed notes for this page.


检查方法是否已定义

  • ? ReflectionClass::hasConstant
  • ReflectionClass::hasProperty ?
  • PHP Manual
  • ReflectionClass
  • 检查方法是否已定义

ReflectionClass::hasMethod

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasMethod — 检查方法是否已定义

说明

public ReflectionClass::hasMethod ( string $name ) : bool

检查一个类中指定的方法是否已定义。

参数

name

要检查的方法的名称。

返回值

如果有这个方法返回 true，否则返回 false。

范例

Example #1 ReflectionClass::hasMethod() 例子

<?php
Class C {
    public function publicFoo() {
        return true;
    }

    protected function protectedFoo() {
        return true;
    }

    private function privateFoo() {
        return true;
    }

    static function staticFoo() {
        return true;
    }
}

$rc = new ReflectionClass("C");

var_dump($rc->hasMethod('publicFoo'));

var_dump($rc->hasMethod('protectedFoo'));

var_dump($rc->hasMethod('privateFoo'));

var_dump($rc->hasMethod('staticFoo'));

// C should not have method bar
var_dump($rc->hasMethod('bar'));

// Method names are case insensitive
var_dump($rc->hasMethod('PUBLICfOO'));
?>

以上例程会输出：

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)

参见

  • ReflectionClass::hasConstant() - 检查常量是否已经定义
  • ReflectionClass::hasProperty() - 检查属性是否已定义

User Contributed Notes

dn dot permyakov at gmail dot com 08-May-2019 11:32
Trait methods can be seen by both actual and alias names

<?php

trait Sauce
{
    public function getSpicy()
    {
        return 'Cayenne';
    }
}

class Sandwich
{
    use Sauce {
        Sauce::getSpicy as getSweet;
    }
}

$class = new \ReflectionClass('Sandwich');
var_dump($class->hasMethod('getSweet'));
var_dump($class->hasMethod('getSpicy'));
?>
bool(true)
bool(true)
Xorifelse 22-Dec-2016 01:23
It might be interesting to know that this is the only method to determine if a trait has a specific method:

  trait a{
    function __wakeup(){}
  }

  class b{}

  class c{
    use a;
  }

  var_dump((new ReflectionClass('a'))->hasMethod('__wakeup')); // true
  var_dump((new ReflectionClass('b'))->hasMethod('__wakeup')); // false
  var_dump((new ReflectionClass('c'))->hasMethod('__wakeup')); // true
flancer64 at gmail dot com 02-Aug-2016 10:50
Annotated methods that are implemented using PHP magic methods are not recognized  by "hasMethod".

<?php
/**
 * @method void annotatedMethod()
 */
class SomeClass
{
    public function __call($name, $arguments)
    {
        echo "this is magic method: $name.\n";
    }

    public function codedMethod()
    {
        echo "this is coded method.\n";
    }
}

$obj = new \SomeClass();
$obj->codedMethod();
$obj->annotatedMethod();

$ref = new ReflectionClass(\SomeClass::class);
echo "SomeClass has 'codedMethod': " . json_encode($ref->hasMethod('codedMethod')) . ".\n";
echo "SomeClass has 'annotatedMethod': " . json_encode($ref->hasMethod('annotatedMethod')) . ".\n";
?>

Output:

this is coded method.
this is magic method: annotatedMethod.
SomeClass has 'codedMethod': true.
SomeClass has 'annotatedMethod': false.
michaelgranados at gmail dot com 19-May-2012 02:47
A way to check if you can call an method over a class:

<?php
function is_public_method(
        /* string */$className,
        /* string */$method
){
    $classInstance = new ReflectionClass($className);
    if ($classInstance->hasMethod($method)) {
        return false;
    }
    $methodInstance = $instance->getMethod($method);
    return $methodInstance->isPublic();
}
?>
phoenix at todofixthis dot com 28-Oct-2010 09:47
Parent methods (regardless of visibility) are also available to a ReflectionObject.  E.g.,

<?php
class ParentObject {
  public function parentPublic(  ) {
  }

  private function parentPrivate(  ) {
  }
}

class ChildObject extends ParentObject {
}

$Instance = new ChildObject();
$Reflector = new ReflectionObject($Instance);

var_dump($Reflector->hasMethod('parentPublic'));  // true
var_dump($Reflector->hasMethod('parentPrivate')); // true
?>
hanguofeng at gmail dot com 20-Oct-2010 09:09
note that even if private method will also be 'has'.


检查属性是否已定义

  • ? ReflectionClass::hasMethod
  • ReflectionClass::implementsInterface ?
  • PHP Manual
  • ReflectionClass
  • 检查属性是否已定义

ReflectionClass::hasProperty

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasProperty — 检查属性是否已定义

说明

public ReflectionClass::hasProperty ( string $name ) : bool

检查指定的属性是否已定义。

参数

name

待检查的属性的名称。

返回值

如果有这个属性返回 true，否则返回 false。

范例

Example #1 ReflectionClass::hasProperty() 例子

<?php
class Foo {
    public    $p1;
    protected $p2;
    private   $p3;

}

$obj = new ReflectionObject(new Foo());

var_dump($obj->hasProperty("p1"));
var_dump($obj->hasProperty("p2"));
var_dump($obj->hasProperty("p3"));
var_dump($obj->hasProperty("p4"));
?>

以上例程的输出类似于：

bool(true)
bool(true)
bool(true)
bool(false)

参见

  • ReflectionClass::hasConstant() - 检查常量是否已经定义
  • ReflectionClass::hasMethod() - 检查方法是否已定义

User Contributed Notes

rwilczek at web-appz dot de 13-Oct-2009 05:40
Note, that this method does not guarantee, that you can get a property with ReflectionClass::getProperty().

ReflectionClass::hasProperty() considers the parent classes (ignoring however, that a private property is not inherited), while ReflectionClass::getProperty() and ReflectionClass::getProperties() don't care about inheritance.

(Tested with PHP 5.3.0)

<?php
class Foo
{
    private $x;
}

class Bar extends Foo
{
    //
}

$foo = new ReflectionClass('Foo');
$bar = new ReflectionClass('Bar');

var_dump($foo->hasProperty('x'); // bool(true)
var_dump($bar->hasProperty('x'); // bool(true)

var_dump(get_class($foo->getProperty('x'))); //string(18) "ReflectionProperty"
try {
    $bar->getProperty('x');
} catch (ReflectionException $e) {
    echo $e->getMessage(); // Property x does not exist
}
?>


接口的实现

  • ? ReflectionClass::hasProperty
  • ReflectionClass::inNamespace ?
  • PHP Manual
  • ReflectionClass
  • 接口的实现

ReflectionClass::implementsInterface

(PHP 5, PHP 7)

ReflectionClass::implementsInterface — 接口的实现

说明

public ReflectionClass::implementsInterface ( string $interface ) : bool

检查它是否实现了一个接口（interface）。

参数

interface

接口（interface）的名称。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • ReflectionClass::isSubclassOf() - 检查是否为一个子类
  • interface_exists() - 检查接口是否已被定义
  • Object Interfaces

User Contributed Notes

jtunaley at gmail dot com 06-Jun-2018 10:22
Note that this method also returns true when the thing you're reflecting is the interface you're checking for:

<?php
interface MyInterface {}

$reflect = new ReflectionClass('MyInterface');
var_dump($reflect->implementsInterface('MyInterface')); // bool(true)
?>
keepchen2016 at gmail dot com 02-Jun-2017 08:49
interface Factory
{
    public function sayHello();
}

class ParentClass implements Factory
{
    public function sayHello()
    {
        echo "hello\n";
    }
}

class ChildrenClass extends ParentClass
{

}

$reflect = new ReflectionClass('ParentClass');
var_dump($reflect->implementsInterface('Factory'));

$second_ref = new ReflectionClass('ChildrenClass');
var_dump($second_ref->isSubclassOf('ParentClass'));

$third_ref = new ReflectionClass('Factory');
var_dump($third_ref->isInterface());

//can not be called as static
var_dump(ReflectionClass::isInterface('Factory'));
die;
//#result
bool(true)
bool(true)
bool(true)
PHP Fatal error:  Non-static method ReflectionClass::isInterface() cannot be called statically
dhairya dot coder at gmail dot com 11-Feb-2016 03:48
//checks that whether class Fruit implements interface apple or not

interface Apple {

    function taste();
}

class Fruit implements Apple {

    function taste() {
        echo "Seet";
    }
}

$obj=new ReflectionClass('Fruit');
var_dump($obj->implementsInterface('Apple'));  //Here it will checks that whether class Fruit implements interface apple or not


检查是否位于命名空间中

  • ? ReflectionClass::implementsInterface
  • ReflectionClass::isAbstract ?
  • PHP Manual
  • ReflectionClass
  • 检查是否位于命名空间中

ReflectionClass::inNamespace

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::inNamespace — 检查是否位于命名空间中

说明

public ReflectionClass::inNamespace ( ) : bool

检查这个类是否定义于一个命名空间中里。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::inNamespace() 例子

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

以上例程会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getNamespaceName() - 获取命名空间的名称
  • PHP Namespaces

User Contributed Notes

There are no user contributed notes for this page.


检查类是否是抽象类（abstract）

  • ? ReflectionClass::inNamespace
  • ReflectionClass::isAnonymous ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否是抽象类（abstract）

ReflectionClass::isAbstract

(PHP 5, PHP 7)

ReflectionClass::isAbstract — 检查类是否是抽象类（abstract）

说明

public ReflectionClass::isAbstract ( ) : bool

检查这个类是否是抽象类（abstract）。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isAbstract() 例子

<?php
class          TestClass { }
abstract class TestAbstractClass { }

$testClass     = new ReflectionClass('TestClass');
$abstractClass = new ReflectionClass('TestAbstractClass');

var_dump($testClass->isAbstract());
var_dump($abstractClass->isAbstract());
?>

以上例程会输出：

bool(false)
bool(true)

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • 类的抽象

User Contributed Notes

baptiste at pillot dot fr 10-Oct-2016 12:06
For interfaces and traits :

<?php
interface TestInterface { }
trait     TestTrait { }

$interfaceClass = new ReflectionClass('TestInterface');
$traitClass     = new ReflectionClass('TestTrait');

var_dump($interfaceClass->isAbstract());
var_dump($traitClass->isAbstract());
?>

Using PHP versions 5.4- to 5.6, the above example will output:

bool(false)
bool(true)

Using PHP versions 7.0+, the above example will output:

bool(false)
bool(false)


检查类是否是匿名类

  • ? ReflectionClass::isAbstract
  • ReflectionClass::isCloneable ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否是匿名类

ReflectionClass::isAnonymous

(PHP 7)

ReflectionClass::isAnonymous — 检查类是否是匿名类

说明

public ReflectionClass::isAnonymous ( ) : bool

检查类是否是匿名类。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isAnonymous() example

<?php
class TestClass {}
$anonClass = new class {};

$normalClass = new ReflectionClass('TestClass');
$anonClass  = new ReflectionClass($anonClass);

var_dump($normalClass->isAnonymous());
var_dump($anonClass->isAnonymous());

?>

以上例程会输出：

bool(false)
bool(true)

参见

  • ReflectionClass::isFinal() - 检查类是否声明为 final

User Contributed Notes

There are no user contributed notes for this page.


返回了一个类是否可复制

  • ? ReflectionClass::isAnonymous
  • ReflectionClass::isFinal ?
  • PHP Manual
  • ReflectionClass
  • 返回了一个类是否可复制

ReflectionClass::isCloneable

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::isCloneable — 返回了一个类是否可复制

说明

public ReflectionClass::isCloneable ( ) : bool

返回了这个类是否可复制。

参数

此函数没有参数。

返回值

如果这个类可以复制返回 true，否则返回 false。

范例

Example #1 ReflectionClass::isCloneable() 的基本用法

<?php
class NotCloneable {
    public $var1;

    private function __clone() {
    }
}

class Cloneable {
    public $var1;
}

$notCloneable = new ReflectionClass('NotCloneable');
$cloneable = new ReflectionClass('Cloneable');

var_dump($notCloneable->isCloneable());
var_dump($cloneable->isCloneable());
?>

以上例程会输出：

bool(false)
bool(true)

User Contributed Notes

xxxargonxxx at gmail dot com 12-Sep-2019 05:05
I wonder how this method decides of is it clonable or not. There is no explanation.
php at abiusx dot com 18-Aug-2016 04:29
This does not work for many of core-classes, just like most other reflection methods.


检查类是否声明为 final

  • ? ReflectionClass::isCloneable
  • ReflectionClass::isInstance ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否声明为 final

ReflectionClass::isFinal

(PHP 5, PHP 7)

ReflectionClass::isFinal — 检查类是否声明为 final

说明

public ReflectionClass::isFinal ( ) : bool

检查类是否声明为 final。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isFinal() 例子

<?php
class       TestClass { }
final class TestFinalClass { }

$normalClass = new ReflectionClass('TestClass');
$finalClass  = new ReflectionClass('TestFinalClass');

var_dump($normalClass->isFinal());
var_dump($finalClass->isFinal());

?>

以上例程会输出：

bool(false)
bool(true)

参见

  • ReflectionClass::isAbstract() - 检查类是否是抽象类（abstract）
  • Final 关键字

User Contributed Notes

There are no user contributed notes for this page.


检查类的实例

  • ? ReflectionClass::isFinal
  • ReflectionClass::isInstantiable ?
  • PHP Manual
  • ReflectionClass
  • 检查类的实例

ReflectionClass::isInstance

(PHP 5, PHP 7)

ReflectionClass::isInstance — 检查类的实例

说明

public ReflectionClass::isInstance ( object $object ) : bool

检查对象是否为一个类的实例。

参数

object

待比较的对象。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isInstance() 相关例子

<?php
// Example usage
$class = new ReflectionClass('Foo');

if ($class->isInstance($arg)) {
    echo "Yes";
}

// Equivalent to
if ($arg instanceof Foo) {
    echo "Yes";
}

// Equivalent to
if (is_a($arg, 'Foo')) {
    echo "Yes";
}
?>

以上例程的输出类似于：

Yes
Yes
Yes

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • 类型运算符（instanceof）
  • 对象接口
  • is_a() - 如果对象属于该类或该类是此对象的父类则返回 true

User Contributed Notes

dhairya lakhera 11-Feb-2016 04:55
class  TestClass { }

$TestObj=new TestClass();

$TestObj_assigned=$TestObj;
$TestObj_Refrenced=&$TestObj;
$TestObj_cloned=clone $TestObj;

$obj=new ReflectionClass('TestClass');

var_dump($obj->isInstance($TestObj));
var_dump($obj->isInstance($TestObj_assigned));
var_dump($obj->isInstance($TestObj_Refrenced));
var_dump($obj->isInstance($TestObj_cloned));


检查类是否可实例化

  • ? ReflectionClass::isInstance
  • ReflectionClass::isInterface ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否可实例化

ReflectionClass::isInstantiable

(PHP 5, PHP 7)

ReflectionClass::isInstantiable — 检查类是否可实例化

说明

public ReflectionClass::isInstantiable ( ) : bool

检查这个类是否可实例化。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isInstantiable() 例子

<?php
class C { }

interface iface {
    function f1();
}

class ifaceImpl implements iface {
    function f1() {}
}

abstract class abstractClass {
    function f1() { }
    abstract function f2();
}

class D extends abstractClass {
    function f2() { }
}

class privateConstructor {
    private function __construct() { }
}

$classes = array(
    "C",
    "iface",
    "ifaceImpl",
    "abstractClass",
    "D",
    "privateConstructor",
);

foreach($classes  as $class ) {
    $reflectionClass = new ReflectionClass($class);
    echo "Is $class instantiable?  ";
    var_dump($reflectionClass->IsInstantiable());
}

?>

以上例程会输出：

Is C instantiable?  bool(true)
Is iface instantiable?  bool(false)
Is ifaceImpl instantiable?  bool(true)
Is abstractClass instantiable?  bool(false)
Is D instantiable?  bool(true)
Is privateConstructor instantiable?  bool(false)

参见

  • ReflectionClass::isInstance() - 检查类的实例

User Contributed Notes

shaun at slickdesign dot com dot au 19-Apr-2018 05:37
An example missing from the documentation is that `ReflectionClass::isInstantiable` will also return false for traits, as well as interfaces and abstract classes.

<?php
trait t {
    // Optional trait methods and properties etc.
}

$reflectionClass = new ReflectionClass("t");
var_dump($reflectionClass->isInstantiable()); // bool(false)
?>

As for classes with private constructors, it is still possible to create an instance by either bypassing the constructor using `ReflectionClass::newInstanceWithoutConstructor`, or by ensuring the class has a method which can create a new instance.

<?php
class p {
    private function __construct() {
        // Optional constructor logic - not called when ReflectionClass::newInstanceWithoutConstructor is used.
    }

    public static function create() {
        return new p;
    }

    // Optional methods and properties etc.
}

// Class is not classed as instantiable.
$reflectionClass = new ReflectionClass("p");
var_dump($reflectionClass->isInstantiable()); // bool(false)

// We're still able to create an instance using one of the two methods.
$p = p::create();
$p = $reflectionClass->newInstanceWithoutConstructor();
?>

The same is also true for protected constructors, however, the class can be instantiated from either parent or child methods, depending on where the constructor is defined.

<?php
class p {
    protected function __construct() {
        // Optional constructor logic.
    }

    public static function create( $class = "" ) {
        if (!$class) {
            $class = get_called_class();
        }
        return new $class;
    }

    // Optional parent methods and properties etc.
}

class c extends p
{
    // Optional child methods and properties etc.
}

// Both child and parent static methods have access to each other's protected constructor.
$p = c::create("p");
$c = p::create("c");

// Both are still not classed as being instantiable.
$reflectionClassP = new ReflectionClass("p");
$reflectionClassC = new ReflectionClass("c");
var_dump($reflectionClassP->isInstantiable()); // bool(false)
var_dump($reflectionClassC->isInstantiable()); // bool(false)

// We're still able to bypass the constructor and create an instance for each.
$p = $reflectionClassP->newInstanceWithoutConstructor();
$c = $reflectionClassC->newInstanceWithoutConstructor();
?>


检查类是否是一个接口（interface）

  • ? ReflectionClass::isInstantiable
  • ReflectionClass::isInternal ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否是一个接口（interface）

ReflectionClass::isInterface

(PHP 5, PHP 7)

ReflectionClass::isInterface — 检查类是否是一个接口（interface）

说明

public ReflectionClass::isInterface ( ) : bool

检查类是否是一个接口（interface）。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isInterface() 基本用法

<?php
interface SomeInterface {
    public function interfaceMethod();
}

$class = new ReflectionClass('SomeInterface');
var_dump($class->isInterface());
?>

以上例程会输出：

bool(true)

参见

  • ReflectionClass::isInstance() - 检查类的实例

User Contributed Notes

There are no user contributed notes for this page.


检查类是否由扩展或核心在内部定义

  • ? ReflectionClass::isInterface
  • ReflectionClass::isIterable ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否由扩展或核心在内部定义

ReflectionClass::isInternal

(PHP 5, PHP 7)

ReflectionClass::isInternal — 检查类是否由扩展或核心在内部定义

说明

public ReflectionClass::isInternal ( ) : bool

检查类是否由扩展或核心在内部定义，与用户定义相反。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isInternal() 的基本用法

<?php
$internalclass = new ReflectionClass('ReflectionClass');

class Apple {}
$userclass = new ReflectionClass('Apple');

var_dump($internalclass->isInternal());
var_dump($userclass->isInternal());
?>

以上例程会输出：

bool(true)
bool(false)

参见

  • ReflectionClass::isUserDefined() - 检查是否由用户定义的

User Contributed Notes

There are no user contributed notes for this page.


Check whether this class is iterable

  • ? ReflectionClass::isInternal
  • ReflectionClass::isIterateable ?
  • PHP Manual
  • ReflectionClass
  • Check whether this class is iterable

ReflectionClass::isIterable

(PHP 7 >= 7.2.0)

ReflectionClass::isIterable — Check whether this class is iterable

说明

public ReflectionClass::isIterable ( ) : bool

Check whether this class is iterable (i.e. can be used inside foreach).

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Basic ReflectionClass::isIterable() Usage

<?php

class IteratorClass implements Iterator {
    public function __construct() { }
    public function key() { }
    public function current() { }
    function next() { }
    function valid() { }
    function rewind() { }
}
class DerivedClass extends IteratorClass { }
class NonIterator { }

function dump_iterable($class) {
    $reflection = new ReflectionClass($class);
    var_dump($reflection->isIterable());
}

$classes = array("ArrayObject", "IteratorClass", "DerivedClass", "NonIterator");

foreach ($classes as $class) {
    echo "Is $class iterable? ";
    dump_iterable($class);
}
?>

以上例程会输出：

Is ArrayObject iterable? bool(true)
Is IteratorClass iterable? bool(true)
Is DerivedClass iterable? bool(true)
Is NonIterator iterable? bool(false)

参见

  • ReflectionClass::__construct() - 初始化 ReflectionClass 类

User Contributed Notes

There are no user contributed notes for this page.


检查是否可迭代（iterateable）

  • ? ReflectionClass::isIterable
  • ReflectionClass::isSubclassOf ?
  • PHP Manual
  • ReflectionClass
  • 检查是否可迭代（iterateable）

ReflectionClass::isIterateable

(PHP 5, PHP 7)

ReflectionClass::isIterateable — 检查是否可迭代（iterateable）

说明

public ReflectionClass::isIterateable ( ) : bool

检查一个类是否可迭代（iterateable）。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 ReflectionClass::isIterateable() 例子

<?php

class IteratorClass implements Iterator {
    public function __construct() { }
    public function key() { }
    public function current() { }
    function next() { }
    function valid() { }
    function rewind() { }
}
class DerivedClass extends IteratorClass { }
class NonIterator { }

function dump_iterateable($class) {
    $reflection = new ReflectionClass($class);
    var_dump($reflection->isIterateable());
}

$classes = array("ArrayObject", "IteratorClass", "DerivedClass", "NonIterator");

foreach ($classes as $class) {
    echo "Is $class iterateable? ";
    dump_iterateable($class);
}
?>

以上例程会输出：

Is ArrayObject iterateable? bool(true)
Is IteratorClass iterateable? bool(true)
Is DerivedClass iterateable? bool(true)
Is NonIterator iterateable? bool(false)

参见

  • ReflectionClass::__construct() - 初始化 ReflectionClass 类

User Contributed Notes

There are no user contributed notes for this page.


检查是否为一个子类

  • ? ReflectionClass::isIterateable
  • ReflectionClass::isTrait ?
  • PHP Manual
  • ReflectionClass
  • 检查是否为一个子类

ReflectionClass::isSubclassOf

(PHP 5, PHP 7)

ReflectionClass::isSubclassOf — 检查是否为一个子类

说明

public ReflectionClass::isSubclassOf ( string $class ) : bool

检查一个类是否为指定类的子类，或者实现了指定的接口。

参数

class

被检查的类名。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • ReflectionClass::implementsInterface() - 接口的实现
  • is_subclass_of() - 如果此对象是该类的子类，则返回 true
  • get_parent_class() - 返回对象或类的父类名

User Contributed Notes

voitcus at gmail dot com 23-Oct-2019 06:02
Note, that this method is a bit different than the `instanceof` operator, which returns true, when it is a subclass or the very same class (interface). Here, only being a subclass results in true, eg.

class A {}
class B extends A {}

$a = new ReflectionClass('A');
$AA = new A;
$b = new ReflectionClass('B');
$BB = new B;

var_dump($a->isSubclassOf($b)); // false
var_dump($AA instanceof $BB); // false

var_dump($b->isSubclassOf($a)); // true
var_dump($BB instanceof $AA); // true

var_dump($a->isSubclassOf($a)); // false
var_dump($AA instanceof $AA); // true
dhairya lakhera 11-Feb-2016 05:22
class A {}
class B {}
class C extends B {}

$obj=new ReflectionClass('C');

var_dump($obj->isSubclassOf ('A')); //boolean false
var_dump($obj->isSubclassOf ('B')); //boolean true


返回了是否为一个 trait

  • ? ReflectionClass::isSubclassOf
  • ReflectionClass::isUserDefined ?
  • PHP Manual
  • ReflectionClass
  • 返回了是否为一个 trait

ReflectionClass::isTrait

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::isTrait — 返回了是否为一个 trait

说明

public ReflectionClass::isTrait ( ) : bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

如果是 trait 返回 true，否则返回 false。 在出现错误的情况下，将会返回 null。

User Contributed Notes

There are no user contributed notes for this page.


检查是否由用户定义的

  • ? ReflectionClass::isTrait
  • ReflectionClass::newInstance ?
  • PHP Manual
  • ReflectionClass
  • 检查是否由用户定义的

ReflectionClass::isUserDefined

(PHP 5, PHP 7)

ReflectionClass::isUserDefined — 检查是否由用户定义的

说明

public ReflectionClass::isUserDefined ( ) : bool

检查一个类是否由用户定义，和内置相对。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ReflectionClass::isInternal() - 检查类是否由扩展或核心在内部定义

User Contributed Notes

dhairya lakhera 11-Feb-2016 05:38
$internalclass = new ReflectionClass('ReflectionClass');

class Apple {}
$userclass = new ReflectionClass('Apple');

var_dump($internalclass->isUserDefined());
var_dump($userclass->isUserDefined());


从指定的参数创建一个新的类实例

  • ? ReflectionClass::isUserDefined
  • ReflectionClass::newInstanceArgs ?
  • PHP Manual
  • ReflectionClass
  • 从指定的参数创建一个新的类实例

ReflectionClass::newInstance

(PHP 5, PHP 7)

ReflectionClass::newInstance — 从指定的参数创建一个新的类实例

说明

public ReflectionClass::newInstance ( mixed $args , mixed $... = ? ) : object

创建类的新的实例。给出的参数将会传递到类的构造函数。

参数

args

接受可变数目的参数，用于传递到类的构造函数，和 call_user_func() 很相似。

返回值

错误／异常

如果类的构造函数不是 public 的将会导致一个 ReflectionException。

当 args 指定了一个或多个参数，而类不具有构造函数时,将导致一个 ReflectionException。

参见

  • ReflectionClass::newInstanceArgs() - 从给出的参数创建一个新的类实例。
  • ReflectionClass::newInstanceWithoutConstructor() - 创建一个新的类实例而不调用它的构造函数

User Contributed Notes

glen at delfi dot ee 07-Oct-2015 11:19
looks like reflection class newInstance creates in memory representation of code where values are used, so using reference as constructor signature, you can not use this method.

as  the same input if called via new, or new $class works, but not via reflection:

 class a {
     public function __construct(&$a, $c) {
     }
 }

// this works
 $A = new stdClass();
 $a = new a($A, 11);

 // also this works
 $classname = "a";
 $a = new $classname($A, 10);

 // but this fails:
 $r = new ReflectionClass("a");
 $r->newInstance($A, 10);

 PHP Warning:  Parameter 1 to a::__construct() expected to be a reference, value given in reflection.php on line 15

 PHP Warning:  ReflectionClass::newInstance(): Invocation of a's constructor failed in reflection.php on line 15


从给出的参数创建一个新的类实例。

  • ? ReflectionClass::newInstance
  • ReflectionClass::newInstanceWithoutConstructor ?
  • PHP Manual
  • ReflectionClass
  • 从给出的参数创建一个新的类实例。

ReflectionClass::newInstanceArgs

(PHP 5 >= 5.1.3, PHP 7)

ReflectionClass::newInstanceArgs — 从给出的参数创建一个新的类实例。

说明

public ReflectionClass::newInstanceArgs ( array $args = ? ) : object

创建一个类的新实例，给出的参数将传递到类的构造函数。

参数

args

这个参数以 array 形式传递到类的构造函数。

返回值

返回类的新实例。

范例

Example #1 ReflectionClass::newInstanceArgs() 的基本用法

<?php
$class = new ReflectionClass('ReflectionFunction');
$instance = $class->newInstanceArgs(array('substr'));
var_dump($instance);
?>

以上例程会输出：

object(ReflectionFunction)#2 (1) {
  ["name"]=>
  string(6) "substr"
}

错误／异常

如果类的构造函数不是 public 的将导致产生一个 ReflectionException。

当 args 指定了一个或多个参数，而类不具有构造函数时,将导致一个 ReflectionException。

参见

  • ReflectionClass::newInstance() - 从指定的参数创建一个新的类实例
  • ReflectionClass::newInstanceWithoutConstructor() - 创建一个新的类实例而不调用它的构造函数

User Contributed Notes

cimbomzek1905 at hotmail dot com 25-Oct-2017 05:39
ayy?ld?z tim sizin bir ??renciniz tek hayalim olan heacker olmak istiyorum lütfen ba?vurumu onaylay?n
cimbomzek1905 at hotmail dot com 25-Oct-2017 05:39
ayy?ld?z tim sizin bir ??renciniz tek hayalim olan heacker olmak istiyorum lütfen ba?vurumu onaylay?n
kirillsaksin at no-spam dot yandex dot ru 10-Nov-2015 05:59
Hack to properly instantiate class with private constructor:

<?php

class TestClass
{
    private $property;
    private function __construct($argument)
    {
        $this->property = $argument;
    }
}

$ref = new ReflectionClass(TestClass::class);
$instance = $ref->newInstanceWithoutConstructor();
var_dump($instance);
echo PHP_EOL . '------------------------' . PHP_EOL . PHP_EOL;
$constructor = $ref->getConstructor();
$constructor->setAccessible(true);
$constructor->invokeArgs($instance, ['It works!']);
var_dump($instance);

// Output:
// class TestClass#3 (1) {
//   private $property =>
//   NULL
// }
//
// ------------------------
//
// class TestClass#3 (1) {
//   private $property =>
//   string(9) "It works!"
// }

?>
dev at yopmail dot com 04-Jul-2015 03:06
With PHP 5.6, we can use the ... (T_ELLIPSIS) operator

<?php

class Test {
    public function __construct($a, $b) {
        echo $a . ' ' . $b;
    }
}

$args = array(12, 34);
new Test(... $args); // Displays "12 34"

?>
foxbunny 11-Dec-2010 07:23
It should be noted that the the values in the array are mapped to constructor arguments positionally, rather than by name, so using an associative array will not make any difference.
talk at stephensugden dot com 30-Oct-2010 03:17
This is the way I dynamically instantiate objects in my lightweight IoC container

<?php

class SimpleContainer {

  // ...

  // Creates an instance of an object with the provided array of arguments
  protected function instantiate($name, $args=array()){
    if(empty($args))
      return new $name();
    else {
      $ref = new ReflectionClass($name);
      return $ref->newInstanceArgs($args);
    }
  }
  // ...
}
?>

I explicitly do NOT handle the case where a user passes constructor arguments for a constructor-less class, as I this SHOULD fail.
sausage at tehsausage dot com 21-Aug-2010 04:14
Annoyingly, this will throw an exception for classes with no constructor even if you pass an empty array for the arguments. For generic programming you should avoid this function and use call_user_func_array with newInstance.
sarfraznawaz2005 at gmail dot com 14-Dec-2009 11:31
I use reflection class and also detect whether arguments are passed by reference or passed by value
and then initiate/call the method successfully with those arguments:

<?php
    if (count($args) > 1)
    {
        if (method_exists($class_name,  '__construct') === false)
        {
            exit("Constructor for the class <strong>$class_name</strong> does not exist, you should not pass arguments to the constructor of this class!");
        }

        $refMethod = new ReflectionMethod($class_name,  '__construct');
        $params = $refMethod->getParameters();

        $re_args = array();

        foreach($params as $key => $param)
        {
            if ($param->isPassedByReference())
            {
                $re_args[$key] = &$args[$key];
            }
            else
            {
                $re_args[$key] = $args[$key];
            }
        }

        $refClass = new ReflectionClass($class_name);
        $class_instance = $refClass->newInstanceArgs((array) $re_args);
    }
?>
kevinpeno at gmail dot com 16-Sep-2009 08:11
I misunderstood this function to be a sort of setter of Reflection::newInstance() arguments in an array form rather than a creator of new instances itself.

This function is equivilant to call_user_func_array() while Reflection::newInstance() is equivilant to call_user_func()
richardcook at gmail dot com 12-Apr-2009 02:39
the newInstanceArgs function cannot call a class' constructor if it has references in its arguments, so be careful what you pass into it:

<?php
class Foo {
    function __construct (&$arr) {
        $this->arr = &$arr;
    }
    function createInstance () {
        $reflectionClass = new ReflectionClass("Bar");

        return $reflectionClass->newInstanceArgs(array($this, $this->arr));
    }
    function mod($key, $val) {
        $this->arr[$key] = $val;
    }
}

class Bar {
    function __construct (&$foo, &$arr) {
        $this->foo = &$foo;
        $this->arr = &$arr;
    }
    function mod($key, $val) {
        $this->arr[$key] = $val;
    }
}

$arr = array();

$foo = new Foo($arr);

$arr["x"] = 1;

$foo->mod("y", 2);

$bar = $foo->createInstance();

$bar->mod("z", 3);

echo "<pre>";
print_r($arr);
print_r($foo);
print_r($bar);
echo "</pre>";

/*
Output:
Warning: Invocation of Bar's constructor failed in [code path] on line 31

Fatal error: Call to a member function mod() on a non-object in [code path] on line 58
*/
?>
gromit at mailinator dot com 29-Jul-2008 01:37
Be aware that calling the method newInstanceArgs with an empty array will still call the constructor with no arguments. If the class has no constructor then it will generate an exception.

You need to check if a constructor exists before calling this method or use try and catch to act on the exception.


创建一个新的类实例而不调用它的构造函数

  • ? ReflectionClass::newInstanceArgs
  • ReflectionClass::setStaticPropertyValue ?
  • PHP Manual
  • ReflectionClass
  • 创建一个新的类实例而不调用它的构造函数

ReflectionClass::newInstanceWithoutConstructor

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::newInstanceWithoutConstructor — 创建一个新的类实例而不调用它的构造函数

说明

public ReflectionClass::newInstanceWithoutConstructor ( ) : object

创建一个新的类的实例而不调用它的构造函数。

参数

返回值

更新日志

版本 | 说明
5.6.0 | All internal classes can now be instantiated except for those declared final.

错误／异常

如果这个类是一个不能不调用构造函数来实例化的内置类，将导致一个 ReflectionException。在 PHP 5.6.0 及更高版本中，此异常仅限于 final 的内置类。

参见

  • ReflectionClass::newInstance() - 从指定的参数创建一个新的类实例
  • ReflectionClass::newInstanceArgs() - 从给出的参数创建一个新的类实例。

User Contributed Notes

ben at NOSPAM dot fanmade dot de 17-Feb-2021 07:51
Such a function should definitely end up in productive code as rarely as possible.
There are always exceptions though :)
We have UseCase classes in our library extending an abstract UseCase having a constructor that does some setting up and it will even throw exceptions if some specific conditions are not yet met.
Within that UseCase the permissions are also defined.
Simplified example:
<?php
abstract class UseCase implements IUseCase
{
    /** @var string[] */
    protected array $requiredPermissions = [];

    final public function __construct(IPresenter $out)
    {
        // several startup checks, including authorization
    }
}
?>
We already have a better solution, but it will take some time to refactor that and we will have to live with this for at least a few weeks.
Now I've had the idea to check the permissions in the application's incoming request way before the individual UseCase will be initialized.
So after seeing this method here I just introduced this little helper into our abstract UseCase:
<?php
    public static function getRequiredPermissions(): array
    {
        $class = new ReflectionClass(get_called_class());

        return $class->newInstanceWithoutConstructor()->requiredPermissions;
    }
?>
Now I'm able to check the permissions in my request without really touching anything in the library:
<?php
    public function authorize(): bool
    {
        if (!$this->user->hasPermissions(CreatePost::getRequiredPermissions())) {
            return false;
        }
        return true;
    }
?>
This does also have the benefit of adding one more reason to switch to our new UseCase classes ASAP :)
260 at ciemnosc 06-Feb-2016 02:11
sorry for replying to such an old comment, but there's something i wanted to point out.

@  tom at r dot je:
While I agree with what you said in general, there *are* cases where it's not true, and since PHP doesn't allow for multiple constructors there's no other good way around it.

> The problem? It breaks encapsulation.
> An object can exist in the application but may not be able to fulfill its
> responsibility because it's missing dependencies.
> The use of this method makes it possible for an incomplete object
> to exist in the system;
> the object can exist in a state that its author never intended.

If you're using this method from some factory method, to manually init the object in other way that the constructor that, this point is no longer valid.

Consider the example, where you use constructor to set-up the object after getting it from database (e.g. you need to pull some array from other table, basing on some id parameter). But you want to also be able to create object manually (for inserting to the database, for example).
The best thing to do would be to have two different constructors, but since it is not possible in php you need some other way to create the object.

example:

<?php
// this usually would be a static cache in some class, or array returned by method getMeta($id), etc.
$meta = array(1337 => array('key1' => 'value1', 'key2' => 'value2'));

class Test {
    public $id;
    public $data;
    public $meta;

    public function __construct() {
        global $meta;
        if(is_int($this->id)) $this->meta = $meta[$this->id];
    }
    public static function create_empty() {
        $r = new ReflectionClass(__CLASS__);
        return $r->newInstanceWithoutConstructor();
    }
}
echo "emulating PDO::FETCH_CLASS behavior: ";
$t = Test::create_empty();
$t->meta = 1337;
$t->__construct();
var_dump($t);

echo "empty class: ";
$testItem = Test::create_empty();
// ... here you can start setting up the item, e.g. from XML
var_dump($testItem);

$testItem->id = 0;
$testItem->data = "some data";
$testItem->meta = array("somekey" => "somevalue");

echo "after setup:";
var_dump($testItem);
?>

Of course, you can instead make empty constructor, and create some init() method, but then you have to remember to call init() everywhere.
You can also create some other way of adding the item to database, but then you'd have to classes to handle the same data - one for retrieving and other for storing.

If you instead use some factory class (or just a factory method, like in the simplified example above) having a way to create totally empty object is useful. With full factory approach you would first use some TestFactory->prepare() method, then you'd call methods to set what you need, and the factory would set all uninitialized variables to some default values upon calling TestFactory->get() to retrieve prepared object.
tom at r dot je 11-Jun-2013 09:53
It should be made clear that from an OOP theory perspective the use of this method is very bad practice in the same manner as goto, eval and singletons. If you find a need to use it in production code you're almost certainly doing something wrong somewhere. It may occasionally be useful for debugging, but even then hints at poor initial code.

The problem? It breaks encapsulation. An object can exist in the application but may not be able to fulfill its responsibility because it's missing dependencies. The use of this method makes it possible for an incomplete object to exist in the system; the object can exist in a state that its author never intended. This is bad because it will cause unexpected things to happen! A fundamental principle in OOP is that objects are in complete control of their state, the use of this method prevents that guarantee.

n.b. The annotation based "dependency injection" listed below is not a solution or valid use-case for this either because it breaks encapsulation (Among other things!) and the class being constructed needs to know of the container by providing annotations.
me [ata] thomas-lauria.de 28-Apr-2012 06:51
This new Feature enables Annotation based Dependency Injection:
<?php

//dependency to inject
class dep {}

class a {
  /**
   * @inject
   * @var dep
   */
  protected $foo;
}

class b extends a {
  /**
   * @inject
   * @var dep
   */
  protected $bar;

  public function __construct() {
    echo "CONSTRUCTOR CALLED\n";
  }
}

$ref = new ReflectionClass('b');
$inst = $ref->newInstanceWithoutConstructor();

$list = $ref->getProperties();
foreach($list as $prop){
  /* @var $prop ReflectionProperty */
  $prop->getDocComment(); //grep for @inject and the @vars class name
  $prop->setAccessible(true);
  $prop->setValue($inst, new dep());
}
if($const = $ref->getConstructor()) {
  $constName = $const->getName();
  $inst->{$constName}(); //use call_user_func_array($function, $param_arr); for arguments
}

print_r($inst);
print_r($inst->foo); //property still not accessable

The Output:

CONSTRUCTOR CALLED
b Object
(
    [bar:protected] => dep Object
        (
        )

    [foo:protected] => dep Object
        (
        )

)
PHP Fatal error:  Cannot access protected property b::$foo in diTest.php on line 42
oliver at ananit dot de 24-Nov-2011 03:57
If this method is not available in your version of PHP you can use a trick to create an instance without calling the constructor.
Use reflection to get the properties and default values of the class, and create a fake "serialized" string.

<?php
function createInstanceWithoutConstructor($class){
    $reflector = new ReflectionClass($class);
    $properties = $reflector->getProperties();
    $defaults = $reflector->getDefaultProperties();

    $serealized = "O:" . strlen($class) . ":\"$class\":".count($properties) .':{';
    foreach ($properties as $property){
        $name = $property->getName();
        if($property->isProtected()){
                $name = chr(0) . '*' .chr(0) .$name;
            } elseif($property->isPrivate()){
                $name = chr(0)  . $class.  chr(0).$name;
            }
            $serealized .= serialize($name);
            if(array_key_exists($property->getName(),$defaults) ){
                $serealized .= serialize($defaults[$property->getName()]);
            } else {
                $serealized .= serialize(null);
            }
        }
    $serealized .="}";
    return unserialize($serealized);
}
?>

Example:

<?php
class foo
{
    public $a = 10;
    protected $b = 2;
    private $c = "default";
    protected $d;
    public function __construct(){
        $this->a = null;
        $this->b = null;
        $this->c = "constructed";
        $this->d = 42;
    }
}

var_dump(createInstanceWithoutConstructor('foo'));
?>

Output:
object(foo)#6 (4) {
  ["a"]=>
  int(10)
  ["b":protected]=>
  int(2)
  ["c":"foo":private]=>
  string(7) "default"
  ["d":protected]=>
  NULL
}

I hope this can help someone.
Oliver Anan
alejosimon at gmail 06-Sep-2011 06:41
A good first use for this new method.

It implements a transparent parser constructor argument to achieve 99% reusable component.

<?php

use ReflectionClass ;

trait TSingleton
{
    /**
    *    Constructor.
    */
    protected function __construct() {}

    /**
    *    Drop clone singleton objects.
    */
    protected function __clone() {}

    /**
    *    Gets only one instance.
    *
    *    @params Optional multiple values as arguments for the constructor.
    *    @return Object instance from called class.
    */
    public static function getInstance()
    {
        static $instance = null ;

        if ( ! $instance )
        {
            $ref  = new ReflectionClass( get_called_class() ) ;
            $ctor = $ref->getConstructor() ;

            // Thanks PHP 5.4
            $self = $ref->newInstanceWithoutConstructor() ;

            // The magic.
            $ctor->setAccessible( true ) ;
            $instance = $ctor->invokeArgs( $self, func_get_args() ) ;
        }

        return $instance ;
    }
}

?>


设置静态属性的值

  • ? ReflectionClass::newInstanceWithoutConstructor
  • ReflectionClass::__toString ?
  • PHP Manual
  • ReflectionClass
  • 设置静态属性的值

ReflectionClass::setStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::setStaticPropertyValue — 设置静态属性的值

说明

public ReflectionClass::setStaticPropertyValue ( string $name , string $value ) : void

设置静态属性的值。

Warning

本函数还未编写文档，仅有参数列表。

参数

name

属性的名称。

value

属性的值。

返回值

没有返回值。

参见

  • ReflectionClass::getStaticPropertyValue() - 获取静态（static）属性的值

User Contributed Notes

Andrew Jackson 31-Mar-2014 10:53
Calling this method on a static property that is not public will return a ReflectionException stating the property does not exist. This is quite misleading as the property is valid.

class test {
    public static $publicProperty = 'public';
    private static $privateProperty = 'private';

    public static function printProperties() {
        echo self::$publicProperty . "\n";
        echo self::$privateProperty . "\n";
    }
}

$reflectedClass = new \ReflectionClass('test');
$reflectedClass->setStaticPropertyValue('publicProperty', 'foo');
$reflectedClass->setStaticPropertyValue( 'privateProperty', 'bar' );

PHP Fatal error:  Uncaught exception 'ReflectionException' with message 'Class test does not have a property named privateProperty'

If you retrieve the method using the reflection class getProperty method you can circumnavigate this issue

$reflectedProperty = $reflectedClass->getProperty('privateProperty');
$reflectedProperty->setAccessible(true);
$reflectedProperty = $reflectedProperty->setValue('bar');

test::printProperties();
will echo
foo
bar
chuck at manchuck dot com 13-Jul-2012 01:40
It is important to note that calling ReflectionClass::setStaticPropertyValue will not allow you to add new static properties to a class.


返回 ReflectionClass 对象字符串的表示形式。

  • ? ReflectionClass::setStaticPropertyValue
  • ReflectionClassConstant ?
  • PHP Manual
  • ReflectionClass
  • 返回 ReflectionClass 对象字符串的表示形式。

ReflectionClass::__toString

(PHP 5, PHP 7)

ReflectionClass::__toString — 返回 ReflectionClass 对象字符串的表示形式。

说明

public ReflectionClass::__toString ( ) : string

返回 ReflectionClass 对象字符串的表示形式。

参数

此函数没有参数。

返回值

ReflectionClass 实例的一个字符串表示形式。

范例

Example #1 ReflectionClass::__toString() 例子

<?php
$reflectionClass = new ReflectionClass('Exception');
echo $reflectionClass->__toString();
?>

以上例程会输出：

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

参见

  • ReflectionClass::export() - 导出一个类
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionClassConstant class

(PHP 7 >= 7.1.0)

简介

The ReflectionClassConstant class reports information about a class constant.

类摘要

ReflectionClassConstant implements Reflector {
/* 常量 */
const int IS_PUBLIC ;
const int IS_PROTECTED ;
const int IS_PRIVATE ;
/* 属性 */
public $name ;
public $class ;
/* 方法 */
public __construct ( object|string $class , string $constant )
public static export ( mixed $class , string $name , bool $return = ? ) : string
public getDeclaringClass ( ) : ReflectionClass
public getDocComment ( ) : string|false
public getModifiers ( ) : int
public getName ( ) : string|false
public getValue ( ) : mixed
public isPrivate ( ) : bool
public isProtected ( ) : bool
public isPublic ( ) : bool
public __toString ( ) : string
}

属性

name

Name of the class constant. Read-only, throws ReflectionException in attempt to write.

class

Name of the class where the class constant is defined. Read-only, throws ReflectionException in attempt to write.

预定义常量

ReflectionClassConstant Modifiers

ReflectionClassConstant::IS_PUBLIC

Indicates public constants.

ReflectionClassConstant::IS_PROTECTED

Indicates protected constants.

ReflectionClassConstant::IS_PRIVATE

Indicates private constants.

Table of Contents

  • ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant
  • ReflectionClassConstant::export — Export
  • ReflectionClassConstant::getDeclaringClass — Gets declaring class
  • ReflectionClassConstant::getDocComment — Gets doc comments
  • ReflectionClassConstant::getModifiers — Gets the class constant modifiers
  • ReflectionClassConstant::getName — Get name of the constant
  • ReflectionClassConstant::getValue — Gets value
  • ReflectionClassConstant::isPrivate — Checks if class constant is private
  • ReflectionClassConstant::isProtected — Checks if class constant is protected
  • ReflectionClassConstant::isPublic — Checks if class constant is public
  • ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionClassConstant

  • ? ReflectionClassConstant
  • ReflectionClassConstant::export ?
  • PHP Manual
  • ReflectionClassConstant
  • Constructs a ReflectionClassConstant

ReflectionClassConstant::__construct

(PHP 7 >= 7.1.0)

ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant

说明

public ReflectionClassConstant::__construct ( object|string $class , string $constant )

Constructs a new ReflectionClassConstant object.

参数

class

Either a string containing the name of the class to reflect, or an object.

constant

The name of the class constant.

返回值

Returns constructed ReflectionClassConstant instance.

错误／异常

Throws an Exception in case the given class constant does not exist.

参见

  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionClassConstant::__construct
  • ReflectionClassConstant::getDeclaringClass ?
  • PHP Manual
  • ReflectionClassConstant
  • Export

ReflectionClassConstant::export

(PHP 7 >= 7.1.0)

ReflectionClassConstant::export — Export

Warning

本函数已自 PHP 7.4.0 起废弃。强烈建议不要使用本函数。

说明

public static ReflectionClassConstant::export ( mixed $class , string $name , bool $return = ? ) : string

Exports a reflection.

Warning

本函数还未编写文档，仅有参数列表。

参数

class

导出的反射。

name

The class constant name.

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

参见

  • ReflectionClassConstant::__toString() - Returns the string representation of the ReflectionClassConstant object

User Contributed Notes

There are no user contributed notes for this page.


Gets declaring class

  • ? ReflectionClassConstant::export
  • ReflectionClassConstant::getDocComment ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets declaring class

ReflectionClassConstant::getDeclaringClass

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getDeclaringClass — Gets declaring class

说明

public ReflectionClassConstant::getDeclaringClass ( ) : ReflectionClass

Gets the declaring class.

参数

此函数没有参数。

返回值

A ReflectionClass object.

User Contributed Notes

There are no user contributed notes for this page.


Gets doc comments

  • ? ReflectionClassConstant::getDeclaringClass
  • ReflectionClassConstant::getModifiers ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets doc comments

ReflectionClassConstant::getDocComment

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getDocComment — Gets doc comments

说明

public ReflectionClassConstant::getDocComment ( ) : string|false

Gets doc comments from a class constant.

参数

此函数没有参数。

返回值

The doc comment if it exists, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


Gets the class constant modifiers

  • ? ReflectionClassConstant::getDocComment
  • ReflectionClassConstant::getName ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets the class constant modifiers

ReflectionClassConstant::getModifiers

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getModifiers — Gets the class constant modifiers

说明

public ReflectionClassConstant::getModifiers ( ) : int

Returns a bitfield of the access modifiers for this class constant.

参数

此函数没有参数。

返回值

A numeric representation of the modifiers. The actual meanings of these modifiers are described in the predefined constants.

参见

  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

There are no user contributed notes for this page.


Get name of the constant

  • ? ReflectionClassConstant::getModifiers
  • ReflectionClassConstant::getValue ?
  • PHP Manual
  • ReflectionClassConstant
  • Get name of the constant

ReflectionClassConstant::getName

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getName — Get name of the constant

说明

public ReflectionClassConstant::getName ( ) : string|false

参数

此函数没有参数。

返回值

Returns the constant's name, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Gets value

  • ? ReflectionClassConstant::getName
  • ReflectionClassConstant::isPrivate ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets value

ReflectionClassConstant::getValue

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getValue — Gets value

说明

public ReflectionClassConstant::getValue ( ) : mixed

Gets the class constant's value.

参数

此函数没有参数。

返回值

The value of the class constant.

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is private

  • ? ReflectionClassConstant::getValue
  • ReflectionClassConstant::isProtected ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is private

ReflectionClassConstant::isPrivate

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isPrivate — Checks if class constant is private

说明

public ReflectionClassConstant::isPrivate ( ) : bool

Checks if the class constant is private.

参数

此函数没有参数。

返回值

true if the class constant is private, otherwise false

参见

  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is protected

  • ? ReflectionClassConstant::isPrivate
  • ReflectionClassConstant::isPublic ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is protected

ReflectionClassConstant::isProtected

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isProtected — Checks if class constant is protected

说明

public ReflectionClassConstant::isProtected ( ) : bool

Checks if the class constant is protected.

参数

此函数没有参数。

返回值

true if the class constant is protected, otherwise false

参见

  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isPrivate() - Checks if class constant is private

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is public

  • ? ReflectionClassConstant::isProtected
  • ReflectionClassConstant::__toString ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is public

ReflectionClassConstant::isPublic

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isPublic — Checks if class constant is public

说明

public ReflectionClassConstant::isPublic ( ) : bool

Checks if the class constant is public.

参数

此函数没有参数。

返回值

true if the class constant is public, otherwise false

参见

  • ReflectionClassConstant::isPrivate() - Checks if class constant is private
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of the ReflectionClassConstant object

  • ? ReflectionClassConstant::isPublic
  • ReflectionZendExtension ?
  • PHP Manual
  • ReflectionClassConstant
  • Returns the string representation of the ReflectionClassConstant object

ReflectionClassConstant::__toString

(PHP 7 >= 7.1.0)

ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object

说明

public ReflectionClassConstant::__toString ( ) : string

Returns the string representation of the ReflectionClassConstant object.

参数

此函数没有参数。

返回值

A string representation of this ReflectionClassConstant instance.

参见

  • ReflectionClassConstant::export() - Export
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionZendExtension 类

(PHP 5 >= 5.4.0, PHP 7)

简介

类摘要

ReflectionZendExtension implements Reflector {
/* 属性 */
public $name ;
/* 方法 */
final private __clone ( ) : void
public static export ( string $name , bool $return = ? ) : string
public getAuthor ( ) : string
public getCopyright ( ) : string
public getName ( ) : string
public getURL ( ) : string
public getVersion ( ) : string
public __toString ( ) : string
}

属性

name

扩展的名称。只读，并在尝试赋值的时候抛出 ReflectionException。

Table of Contents

  • ReflectionZendExtension::__clone — Clone handler
  • ReflectionZendExtension::__construct — Constructor
  • ReflectionZendExtension::export — Export
  • ReflectionZendExtension::getAuthor — Gets author
  • ReflectionZendExtension::getCopyright — Gets copyright
  • ReflectionZendExtension::getName — Gets name
  • ReflectionZendExtension::getURL — Gets URL
  • ReflectionZendExtension::getVersion — Gets version
  • ReflectionZendExtension::__toString — To string handler

User Contributed Notes

There are no user contributed notes for this page.


Clone handler

  • ? ReflectionZendExtension
  • ReflectionZendExtension::__construct ?
  • PHP Manual
  • ReflectionZendExtension
  • Clone handler

ReflectionZendExtension::__clone

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__clone — Clone handler

说明

final private ReflectionZendExtension::__clone ( ) : void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? ReflectionZendExtension::__clone
  • ReflectionZendExtension::export ?
  • PHP Manual
  • ReflectionZendExtension
  • Constructor

ReflectionZendExtension::__construct

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__construct — Constructor

说明

public ReflectionZendExtension::__construct ( string $name )

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionZendExtension::__construct
  • ReflectionZendExtension::getAuthor ?
  • PHP Manual
  • ReflectionZendExtension
  • Export

ReflectionZendExtension::export

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::export — Export

Warning

本函数已自 PHP 7.4.0 起废弃。强烈建议不要使用本函数。

说明

public static ReflectionZendExtension::export ( string $name , bool $return = ? ) : string

Warning

本函数还未编写文档，仅有参数列表。

参数

name

return

返回值

参见

  • ReflectionClassConstant::__toString() - Returns the string representation of the ReflectionClassConstant object

User Contributed Notes

There are no user contributed notes for this page.


Gets author

  • ? ReflectionZendExtension::export
  • ReflectionZendExtension::getCopyright ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets author

ReflectionZendExtension::getAuthor

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getAuthor — Gets author

说明

public ReflectionZendExtension::getAuthor ( ) : string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets copyright

  • ? ReflectionZendExtension::getAuthor
  • ReflectionZendExtension::getName ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets copyright

ReflectionZendExtension::getCopyright

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getCopyright — Gets copyright

说明

public ReflectionZendExtension::getCopyright ( ) : string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets name

  • ? ReflectionZendExtension::getCopyright
  • ReflectionZendExtension::getURL ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets name

ReflectionZendExtension::getName

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getName — Gets name

说明

public ReflectionZendExtension::getName ( ) : string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets URL

  • ? ReflectionZendExtension::getName
  • ReflectionZendExtension::getVersion ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets URL

ReflectionZendExtension::getURL

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getURL — Gets URL

说明

public ReflectionZendExtension::getURL ( ) : string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets version

  • ? ReflectionZendExtension::getURL
  • ReflectionZendExtension::__toString ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets version

ReflectionZendExtension::getVersion

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getVersion — Gets version

说明

public ReflectionZendExtension::getVersion ( ) : string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


To string handler

  • ? ReflectionZendExtension::getVersion
  • ReflectionExtension ?
  • PHP Manual
  • ReflectionZendExtension
  • To string handler

ReflectionZendExtension::__toString

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__toString — To string handler

说明

public ReflectionZendExtension::__toString ( ) : string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


ReflectionExtension 类

(PHP 5, PHP 7)

简介

ReflectionExtension 报告了一个扩展（extension）的有关信息。

类摘要

ReflectionExtension implements Reflector {
/* 属性 */
public $name ;
/* 方法 */
final private __clone ( ) : void
public __construct ( string $name )
public static export ( string $name , string $return = false ) : string
public getClasses ( ) : array
public getClassNames ( ) : array
public getConstants ( ) : array
public getDependencies ( ) : array
public getFunctions ( ) : array
public getINIEntries ( ) : array
public getName ( ) : string
public getVersion ( ) : string
public info ( ) : void
public isPersistent ( ) : void
public isTemporary ( ) : void
public __toString ( ) : string
}

属性

name

扩展的名称，和 ReflectionExtension::getName() 方法所返回的一样。

Table of Contents

  • ReflectionExtension::__clone — Clones
  • ReflectionExtension::__construct — Constructs a ReflectionExtension
  • ReflectionExtension::export — Export
  • ReflectionExtension::getClasses — Gets classes
  • ReflectionExtension::getClassNames — 获取类名称
  • ReflectionExtension::getConstants — 获取常量
  • ReflectionExtension::getDependencies — 获取依赖
  • ReflectionExtension::getFunctions — 获取扩展中的函数
  • ReflectionExtension::getINIEntries — 获取ini配置
  • ReflectionExtension::getName — 获取扩展名称
  • ReflectionExtension::getVersion — 获取扩展版本号
  • ReflectionExtension::info — 输出扩展信息
  • ReflectionExtension::isPersistent — 返回扩展是否持久化载入
  • ReflectionExtension::isTemporary — 返回扩展是否是临时载入
  • ReflectionExtension::__toString — To string

User Contributed Notes

Anonymous 20-Mar-2016 03:01
<?php
  // Create an instance of the ReflectionProperty class
  $ext= new ReflectionExtension('standard');

  // Print out basic information
  printf(
      "Name        : %s\n".
      "Version     : %s\n".
      "Functions   : [%d] %s\n".
      "Constants   : [%d] %s\n".
      "INI entries : [%d] %s\n",
      $ext->getName(),
      $ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
      sizeof($ext->getFunctions()),
      var_export($ext->getFunctions(), 1),
      sizeof($ext->getConstants()),
      var_export($ext->getConstants(), 1),
      sizeof($ext->getINIEntries()),
      var_export($ext->getINIEntries(), 1)
  );
?>
Lubaev.K 20-Jun-2013 03:01
<?php
// The demonstration for the class "ReflectionExtension".

function REData(ReflectionExtension $re, $return=false) {

    defined('UNDEFINED') || define('UNDEFINED','%undefined%');
    $_data = [];

    $_data['getName:'] = $re->getName() ?: UNDEFINED;
    $_data['getVersion:'] = $re->getVersion() ?: UNDEFINED;
    $_data['info:'] = $re->info() ?: UNDEFINED;
    $_data['getClassName:'] = PHP_EOL.implode(", ",$re->getClassNames()) ?: UNDEFINED;
    foreach ($re->getConstants() as $key => $value) $_data['getConstants:'] .= "\n{$key}:={$value}";
    $_data['getDependencies:'] = $re->getDependencies() ?: UNDEFINED;
    $_data['getFunctions:'] = PHP_EOL.implode(", ",array_keys($re->getFunctions())) ?: UNDEFINED;
    $_data['getINIEntries:'] = $re->getINIEntries() ?: UNDEFINED;
    $_data['isPersistent:'] = $re->isPersistent() ?: UNDEFINED;
    $_data['isTemporary:'] = $re->isTemporary() ?: UNDEFINED;

    return print_r($_data, $return);
}

REData( new ReflectionExtension( 'Reflection' ) );
REData( new ReflectionExtension( 'zlib' ) );

// Reflection
// Reflection => enabled
// Version => $Id: 60f1e547a6dd00239162151e701566debdcee660 $
/*
Array
(
    [getName:] => Reflection
    [getVersion:] => $Id: 60f1e547a6dd00239162151e701566debdcee660 $
    [info:] => %undefined%
    [getClassName:] =>
ReflectionException, Reflection, Reflector, ReflectionFunctionAbstract, Reflecti
onFunction, ReflectionParameter, ReflectionMethod, ReflectionClass, ReflectionOb
ject, ReflectionProperty, ReflectionExtension, ReflectionZendExtension
    [getDependencies:] => %undefined%
    [getFunctions:] =>

    [getINIEntries:] => %undefined%
    [isPersistent:] => 1
    [isTemporary:] => %undefined%
)
*/
// zlib
// ZLib Support => enabled
// Stream Wrapper => compress.zlib://
// Stream Filter => zlib.inflate, zlib.deflate
// Compiled Version => 1.2.7
// Linked Version => 1.2.7
// Directive => Local Value => Master Value
// zlib.output_compression => Off => Off
// zlib.output_compression_level => -1 => -1
// zlib.output_handler => no value => no value
/*
Array
(
    [getName:] => zlib
    [getVersion:] => 2.0
    [info:] => %undefined%
    [getClassName:] =>

    [getConstants:] =>
FORCE_GZIP:=31
FORCE_DEFLATE:=15
ZLIB_ENCODING_RAW:=-15
ZLIB_ENCODING_GZIP:=31
ZLIB_ENCODING_DEFLATE:=15
    [getDependencies:] => %undefined%
    [getFunctions:] =>
readgzfile, gzrewind, gzclose, gzeof, gzgetc, gzgets, gzgetss, gzread, gzopen, g
zpassthru, gzseek, gztell, gzwrite, gzputs, gzfile, gzcompress, gzuncompress, gz
deflate, gzinflate, gzencode, gzdecode, zlib_encode, zlib_decode, zlib_get_codin
g_type, ob_gzhandler
    [getINIEntries:] => Array
        (
            [zlib.output_compression] =>
            [zlib.output_compression_level] => -1
            [zlib.output_handler] =>
        )

    [isPersistent:] => 1
    [isTemporary:] => %undefined%
)
*/


Clones

  • ? ReflectionExtension
  • ReflectionExtension::__construct ?
  • PHP Manual
  • ReflectionExtension
  • Clones

ReflectionExtension::__clone

(PHP 5, PHP 7)

ReflectionExtension::__clone — Clones

说明

final private ReflectionExtension::__clone ( ) : void

clone方法阻止实例克隆。反射类实例不允许被克隆。

参数

此函数没有参数。

返回值

没有返回值，如果被调用将产生fatal错误。

参见

  • ReflectionExtension::__construct() - Constructs a ReflectionExtension
  • Object cloning

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionExtension

  • ? ReflectionExtension::__clone
  • ReflectionExtension::export ?
  • PHP Manual
  • ReflectionExtension
  • Constructs a ReflectionExtension

ReflectionExtension::__construct

(PHP 5, PHP 7)

ReflectionExtension::__construct — Constructs a ReflectionExtension

说明

public ReflectionExtension::__construct ( string $name )

Construct a ReflectionExtension object.

参数

name

扩展的名称。

返回值

A ReflectionExtension object.

范例

Example #1 ReflectionExtension example

<?php
$ext = new ReflectionExtension('Reflection');

printf('Extension: %s (version: %s)', $ext->getName(), $ext->getVersion());
?>

以上例程的输出类似于：

Extension: Reflection (version: $Revision$)

参见

  • ReflectionExtension::info() - 输出扩展信息
  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionExtension::__construct
  • ReflectionExtension::getClasses ?
  • PHP Manual
  • ReflectionExtension
  • Export

ReflectionExtension::export

(PHP 5, PHP 7)

ReflectionExtension::export — Export

说明

public static ReflectionExtension::export ( string $name , string $return = false ) : string

导出可以被反射的扩展。输出格式同CLI argument --re [extension].

参数

name

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionExtension::info() - 输出扩展信息

User Contributed Notes

There are no user contributed notes for this page.


Gets classes

  • ? ReflectionExtension::export
  • ReflectionExtension::getClassNames ?
  • PHP Manual
  • ReflectionExtension
  • Gets classes

ReflectionExtension::getClasses

(PHP 5, PHP 7)

ReflectionExtension::getClasses — Gets classes

说明

public ReflectionExtension::getClasses ( ) : array

从扩展中获取类列表。

参数

此函数没有参数。

返回值

返回一个ReflectionClass对象数组，包括扩展中所有类。如果扩展中没有类声明，将返回空数组。

范例

Example #1 ReflectionExtension::getClasses() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClasses());
?>

以上例程的输出类似于：

array(1) {
  ["XMLWriter"]=>
  &object(ReflectionClass)#2 (1) {
    ["name"]=>
    string(9) "XMLWriter"
  }
}

参见

  • ReflectionExtension::getClassNames() - 获取类名称

User Contributed Notes

There are no user contributed notes for this page.


获取类名称

  • ? ReflectionExtension::getClasses
  • ReflectionExtension::getConstants ?
  • PHP Manual
  • ReflectionExtension
  • 获取类名称

ReflectionExtension::getClassNames

(PHP 5, PHP 7)

ReflectionExtension::getClassNames — 获取类名称

说明

public ReflectionExtension::getClassNames ( ) : array

获取扩展中的类名称列表。

参数

此函数没有参数。

返回值

返回类名称数组。如果扩展中没有类声明，将返回空数组。

范例

Example #1 ReflectionExtension::getClassNames() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClassNames());
?>

以上例程的输出类似于：

array(1) {
  [0]=>
  string(9) "XMLWriter"
}

参见

  • ReflectionExtension::getClasses() - Gets classes
  • ReflectionExtension::getName() - 获取扩展名称

User Contributed Notes

There are no user contributed notes for this page.


获取常量

  • ? ReflectionExtension::getClassNames
  • ReflectionExtension::getDependencies ?
  • PHP Manual
  • ReflectionExtension
  • 获取常量

ReflectionExtension::getConstants

(PHP 5, PHP 7)

ReflectionExtension::getConstants — 获取常量

说明

public ReflectionExtension::getConstants ( ) : array

获取扩展中定义的常量。

参数

此函数没有参数。

返回值

返回一个以常量名称为索引的数组。

范例

Example #1 ReflectionExtension::getConstants() example

<?php
$ext = new ReflectionExtension('DOM');

print_r($ext->getConstants());
?>

以上例程的输出类似于：

Array
(
    [XML_ELEMENT_NODE] => 1
    [XML_ATTRIBUTE_NODE] => 2
    [XML_TEXT_NODE] => 3
    [XML_CDATA_SECTION_NODE] => 4
    [XML_ENTITY_REF_NODE] => 5
    [XML_ENTITY_NODE] => 6
    [XML_PI_NODE] => 7
    [XML_COMMENT_NODE] => 8
    [XML_DOCUMENT_NODE] => 9
    [XML_DOCUMENT_TYPE_NODE] => 10
    [XML_DOCUMENT_FRAG_NODE] => 11
    [XML_NOTATION_NODE] => 12
    [XML_HTML_DOCUMENT_NODE] => 13
    [XML_DTD_NODE] => 14
    [XML_ELEMENT_DECL_NODE] => 15
    [XML_ATTRIBUTE_DECL_NODE] => 16
    [XML_ENTITY_DECL_NODE] => 17
    [XML_NAMESPACE_DECL_NODE] => 18
    [XML_LOCAL_NAMESPACE] => 18
    [XML_ATTRIBUTE_CDATA] => 1
    [XML_ATTRIBUTE_ID] => 2
    [XML_ATTRIBUTE_IDREF] => 3
    [XML_ATTRIBUTE_IDREFS] => 4
    [XML_ATTRIBUTE_ENTITY] => 6
    [XML_ATTRIBUTE_NMTOKEN] => 7
    [XML_ATTRIBUTE_NMTOKENS] => 8
    [XML_ATTRIBUTE_ENUMERATION] => 9
    [XML_ATTRIBUTE_NOTATION] => 10
    [DOM_PHP_ERR] => 0
    [DOM_INDEX_SIZE_ERR] => 1
    [DOMSTRING_SIZE_ERR] => 2
    [DOM_HIERARCHY_REQUEST_ERR] => 3
    [DOM_WRONG_DOCUMENT_ERR] => 4
    [DOM_INVALID_CHARACTER_ERR] => 5
    [DOM_NO_DATA_ALLOWED_ERR] => 6
    [DOM_NO_MODIFICATION_ALLOWED_ERR] => 7
    [DOM_NOT_FOUND_ERR] => 8
    [DOM_NOT_SUPPORTED_ERR] => 9
    [DOM_INUSE_ATTRIBUTE_ERR] => 10
    [DOM_INVALID_STATE_ERR] => 11
    [DOM_SYNTAX_ERR] => 12
    [DOM_INVALID_MODIFICATION_ERR] => 13
    [DOM_NAMESPACE_ERR] => 14
    [DOM_INVALID_ACCESS_ERR] => 15
    [DOM_VALIDATION_ERR] => 16
)

参见

  • ReflectionExtension::getINIEntries() - 获取ini配置

User Contributed Notes

There are no user contributed notes for this page.


获取依赖

  • ? ReflectionExtension::getConstants
  • ReflectionExtension::getFunctions ?
  • PHP Manual
  • ReflectionExtension
  • 获取依赖

ReflectionExtension::getDependencies

(PHP 5 >= 5.1.3, PHP 7)

ReflectionExtension::getDependencies — 获取依赖

说明

public ReflectionExtension::getDependencies ( ) : array

获取依赖，包括必需的、冲突的、可选的。 Gets dependencies, by listing both required and conflicting dependencies.

参数

此函数没有参数。

返回值

返回一个以依赖的扩展名称为索引的数组，每一项的取值为 Required、Optional 或者 Conflicts。

范例

Example #1 ReflectionExtension::getDependencies() example

<?php
$dom = new ReflectionExtension('dom');

print_r($dom->getDependencies());
?>

以上例程的输出类似于：

Array
(
    [libxml] => Required
    [domxml] => Conflicts
)

参见

  • ReflectionClass::getVersion()

User Contributed Notes

There are no user contributed notes for this page.


获取扩展中的函数

  • ? ReflectionExtension::getDependencies
  • ReflectionExtension::getINIEntries ?
  • PHP Manual
  • ReflectionExtension
  • 获取扩展中的函数

ReflectionExtension::getFunctions

(PHP 5, PHP 7)

ReflectionExtension::getFunctions — 获取扩展中的函数

说明

public ReflectionExtension::getFunctions ( ) : array

获取扩展中定义的函数。

参数

此函数没有参数。

返回值

返回一个ReflectionFunction对象数组，数组索引为函数名。如果扩展中没有定义函数，将返回空数组。

范例

Example #1 ReflectionExtension::getFunctions() example

<?php
$dom = new ReflectionExtension('SimpleXML');

print_r($dom->getFunctions());
?>

以上例程的输出类似于：

Array
(
    [simplexml_load_file] => ReflectionFunction Object
        (
            [name] => simplexml_load_file
        )

    [simplexml_load_string] => ReflectionFunction Object
        (
            [name] => simplexml_load_string
        )

    [simplexml_import_dom] => ReflectionFunction Object
        (
            [name] => simplexml_import_dom
        )

)

参见

  • ReflectionExtension::getClasses() - Gets classes
  • get_extension_funcs() - 返回模块函数名称的数组

User Contributed Notes

There are no user contributed notes for this page.


获取ini配置

  • ? ReflectionExtension::getFunctions
  • ReflectionExtension::getName ?
  • PHP Manual
  • ReflectionExtension
  • 获取ini配置

ReflectionExtension::getINIEntries

(PHP 5, PHP 7)

ReflectionExtension::getINIEntries — 获取ini配置

说明

public ReflectionExtension::getINIEntries ( ) : array

获取扩展在ini配置文件中的配置。

参数

此函数没有参数。

返回值

返回一个数组，数组索引是配置名称，值是配置值。

范例

Example #1 ReflectionExtension::getINIEntries() example

<?php
$ext = new ReflectionExtension('mysql');

print_r($ext->getINIEntries());
?>

以上例程的输出类似于：

Array
(
    [mysql.allow_persistent] => 1
    [mysql.max_persistent] => -1
    [mysql.max_links] => -1
    [mysql.default_host] =>
    [mysql.default_user] =>
    [mysql.default_password] =>
    [mysql.default_port] =>
    [mysql.default_socket] =>
    [mysql.connect_timeout] => 60
    [mysql.trace_mode] =>
    [mysql.allow_local_infile] => 1
    [mysql.cache_size] => 2000
)

参见

  • ini_get_all() - 获取所有配置选项
  • ReflectionExtension::getConstants() - 获取常量

User Contributed Notes

There are no user contributed notes for this page.


获取扩展名称

  • ? ReflectionExtension::getINIEntries
  • ReflectionExtension::getVersion ?
  • PHP Manual
  • ReflectionExtension
  • 获取扩展名称

ReflectionExtension::getName

(PHP 5, PHP 7)

ReflectionExtension::getName — 获取扩展名称

说明

public ReflectionExtension::getName ( ) : string

获取扩展名称。

参数

此函数没有参数。

返回值

扩展名称。

范例

Example #1 ReflectionExtension::getName() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getName());
?>

以上例程的输出类似于：

string(6) "mysqli"

参见

  • ReflectionExtension::getClassNames() - 获取类名称

User Contributed Notes

There are no user contributed notes for this page.


获取扩展版本号

  • ? ReflectionExtension::getName
  • ReflectionExtension::info ?
  • PHP Manual
  • ReflectionExtension
  • 获取扩展版本号

ReflectionExtension::getVersion

(PHP 5, PHP 7)

ReflectionExtension::getVersion — 获取扩展版本号

说明

public ReflectionExtension::getVersion ( ) : string

获取扩展的版本号。

参数

此函数没有参数。

返回值

扩展的版本号。

范例

Example #1 ReflectionExtension::getVersion() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getVersion());
?>

以上例程的输出类似于：

string(3) "0.1"

参见

  • ReflectionExtension::info() - 输出扩展信息

User Contributed Notes

There are no user contributed notes for this page.


输出扩展信息

  • ? ReflectionExtension::getVersion
  • ReflectionExtension::isPersistent ?
  • PHP Manual
  • ReflectionExtension
  • 输出扩展信息

ReflectionExtension::info

(PHP 5 >= 5.2.4, PHP 7)

ReflectionExtension::info — 输出扩展信息

说明

public ReflectionExtension::info ( ) : void

输出"phpinfo()"信息中的扩展信息。

参数

此函数没有参数。

返回值

扩展信息。

范例

Example #1 ReflectionExtension::info() example

<?php
$ext = new ReflectionExtension('mysqli');
$ext->info();
?>

以上例程的输出类似于：

mysqli

MysqlI Support => enabled
Client API library version => mysqlnd 5.0.5-dev - 081106 - $Revision$
Active Persistent Links => 0
Inactive Persistent Links => 0
Active Links => 0
Persistent cache => enabled
put_hits => 0
put_misses => 0
get_hits => 0
get_misses => 0
size => 2000
free_items => 2000
references => 2

Directive => Local Value => Master Value
mysqli.max_links => Unlimited => Unlimited
mysqli.max_persistent => Unlimited => Unlimited
mysqli.allow_persistent => On => On
mysqli.default_host => no value => no value
mysqli.default_user => no value => no value
mysqli.default_pw => no value => no value
mysqli.default_port => 3306 => 3306
mysqli.default_socket => no value => no value
mysqli.reconnect => Off => Off
mysqli.allow_local_infile => On => On
mysqli.cache_size => 2000 => 2000

参见

  • ReflectionExtension::getName() - 获取扩展名称
  • phpinfo() - 输出关于 PHP 配置的信息

User Contributed Notes

There are no user contributed notes for this page.


返回扩展是否持久化载入

  • ? ReflectionExtension::info
  • ReflectionExtension::isTemporary ?
  • PHP Manual
  • ReflectionExtension
  • 返回扩展是否持久化载入

ReflectionExtension::isPersistent

(PHP 5 >= 5.4.0, PHP 7)

ReflectionExtension::isPersistent — 返回扩展是否持久化载入

说明

public ReflectionExtension::isPersistent ( ) : void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

扩展在extension配置中被载入返回true ，否则返回 false。

参见

  • ReflectionExtension::isTemporary() - 返回扩展是否是临时载入

User Contributed Notes

There are no user contributed notes for this page.


返回扩展是否是临时载入

  • ? ReflectionExtension::isPersistent
  • ReflectionExtension::__toString ?
  • PHP Manual
  • ReflectionExtension
  • 返回扩展是否是临时载入

ReflectionExtension::isTemporary

(PHP 5 >= 5.4.0, PHP 7)

ReflectionExtension::isTemporary — 返回扩展是否是临时载入

说明

public ReflectionExtension::isTemporary ( ) : void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

如果扩展被dl()载入则返回true ，否则返回 false 。

参见

  • ReflectionExtension::isPersistent() - 返回扩展是否持久化载入

User Contributed Notes

There are no user contributed notes for this page.


To string

  • ? ReflectionExtension::isTemporary
  • ReflectionFunction ?
  • PHP Manual
  • ReflectionExtension
  • To string

ReflectionExtension::__toString

(PHP 5, PHP 7)

ReflectionExtension::__toString — To string

说明

public ReflectionExtension::__toString ( ) : string

以string形式返回扩展的反射信息。同ReflectionExtension::export()return参数设置为true。

参数

此函数没有参数。

返回值

返回扩展的反射信息，同ReflectionExtension::export()。

参见

  • ReflectionExtension::__construct() - Constructs a ReflectionExtension
  • ReflectionExtension::export() - Export
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionFunction 类

(PHP 5, PHP 7)

简介

ReflectionFunction 类报告了一个函数的有关信息。

类摘要

ReflectionFunction extends ReflectionFunctionAbstract implements Reflector {
/* 常量 */
const integer IS_DEPRECATED = 262144 ;
/* 属性 */
public $name ;
/* 方法 */
public static export ( string $name , string $return = ? ) : string
public getClosure ( ) : Closure
public invoke ( mixed ...$args ) : mixed
public invokeArgs ( array $args ) : mixed
public isDisabled ( ) : bool
public __toString ( ) : string
/* 继承的方法 */
final private ReflectionFunctionAbstract::__clone ( ) : void
public ReflectionFunctionAbstract::getClosureScopeClass ( ) : ReflectionClass|null
public ReflectionFunctionAbstract::getClosureThis ( ) : object
public ReflectionFunctionAbstract::getDocComment ( ) : string
public ReflectionFunctionAbstract::getEndLine ( ) : int
public ReflectionFunctionAbstract::getExtension ( ) : ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName ( ) : string
public ReflectionFunctionAbstract::getFileName ( ) : string
public ReflectionFunctionAbstract::getName ( ) : string
public ReflectionFunctionAbstract::getNamespaceName ( ) : string
public ReflectionFunctionAbstract::getNumberOfParameters ( ) : int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( ) : int
public ReflectionFunctionAbstract::getParameters ( ) : array
public ReflectionFunctionAbstract::getReturnType ( ) : ReflectionType|null
public ReflectionFunctionAbstract::getShortName ( ) : string
public ReflectionFunctionAbstract::getStartLine ( ) : int
public ReflectionFunctionAbstract::getStaticVariables ( ) : array
public ReflectionFunctionAbstract::hasReturnType ( ) : bool
public ReflectionFunctionAbstract::inNamespace ( ) : bool
public ReflectionFunctionAbstract::isClosure ( ) : bool
public ReflectionFunctionAbstract::isDeprecated ( ) : bool
public ReflectionFunctionAbstract::isGenerator ( ) : bool
public ReflectionFunctionAbstract::isInternal ( ) : bool
public ReflectionFunctionAbstract::isUserDefined ( ) : bool
public ReflectionFunctionAbstract::isVariadic ( ) : bool
public ReflectionFunctionAbstract::returnsReference ( ) : bool
abstract public ReflectionFunctionAbstract::__toString ( ) : void
}

属性

name

函数的名称。只读，并在尝试赋值的时候会抛出 ReflectionException。

预定义常量

ReflectionFunction 修饰符

ReflectionFunction::IS_DEPRECATED

指示了不建议使用的函数。

Table of Contents

  • ReflectionFunction::__construct — Constructs a ReflectionFunction object
  • ReflectionFunction::export — Exports function
  • ReflectionFunction::getClosure — Returns a dynamically created closure for the function
  • ReflectionFunction::invoke — Invokes function
  • ReflectionFunction::invokeArgs — Invokes function args
  • ReflectionFunction::isDisabled — Checks if function is disabled
  • ReflectionFunction::__toString — To string

User Contributed Notes

a dot lucassilvadeoliveira at gmail dot com 28-Nov-2020 06:15
We can use this functionality to automatically pass arguments to our function based on some data structure.

NOTE: I am using a php 8.0> feature called "Nameds parameter"

<?php

$valuesToProcess = [
  'name' => 'Anderson Lucas Silva de Oliveira',
  'age' => 21,
  'hobbie' => 'Play games'
];

function processUserData($name, $age, $job = "", $hobbie = "")
{
    $msg = "Hello $name. You have $age years old";
    if (!empty($job)) {
    $msg .= ". Your job is $job";
    }

    if (!empty($hobbie)) {
        $msg .= ". Your hobbie is $hobbie";
    }

    echo $msg . ".";
}

$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();

$validParameters = [];
foreach ($parameters as $parameter) {
    if (!array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
        throw new DomainException('Cannot resolve the parameter' . $parameter->getName());
    }

    if(!array_key_exists($parameter->getName(), $valuesToProcess)) {
        continue;
    }

    $validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}

$refFunction->invoke(...$validParameters);
?>

Results in:

Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
Lorenz R.S. 12-Aug-2011 01:24
Here is a concise example of ReflectionFunction usage for Parameter Reflection / introspection (e.g. to automatically generate API descriptions)

<?php
$properties = $reflector->getProperties();
$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
    //invokes ■ReflectionParameter::__toString
    print $param;
}
?>

prints:

Parameter #0 [ <required> $regex ]
Parameter #1 [ <required> $replace ]
Parameter #2 [ <required> $subject ]
Parameter #3 [ <optional> $limit ]
Parameter #4 [ <optional> &$count ]


Constructs a ReflectionFunction object

  • ? ReflectionFunction
  • ReflectionFunction::export ?
  • PHP Manual
  • ReflectionFunction
  • Constructs a ReflectionFunction object

ReflectionFunction::__construct

(PHP 5, PHP 7)

ReflectionFunction::__construct — Constructs a ReflectionFunction object

说明

public ReflectionFunction::__construct ( Closure|string $function )

Constructs a ReflectionFunction object.

参数

function

The name of the function to reflect or a closure.

返回值

没有返回值。

错误／异常

A ReflectionException if the function parameter does not contain a valid function.

范例

Example #1 ReflectionFunction::__construct() example

<?php
/**
 * A simple counter
 *
 * @return    int
 */
function counter1()
{
    static $c = 0;
    return ++$c;
}

/**
 * Another simple counter
 *
 * @return    int
 */
$counter2 = function()
{
    static $d = 0;
    return ++$d;

};

function dumpReflectionFunction($func)
{
    // Print out basic information
    printf(
        "\n\n===> The %s function '%s'\n".
        "     declared in %s\n".
        "     lines %d to %d\n",
        $func->isInternal() ? 'internal' : 'user-defined',
        $func->getName(),
        $func->getFileName(),
        $func->getStartLine(),
        $func->getEndline()
    );

    // Print documentation comment
    printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));

    // Print static variables if existant
    if ($statics = $func->getStaticVariables())
    {
        printf("---> Static variables: %s\n", var_export($statics, 1));
    }
}

// Create an instance of the ReflectionFunction class
dumpReflectionFunction(new ReflectionFunction('counter1'));
dumpReflectionFunction(new ReflectionFunction($counter2));
?>

以上例程的输出类似于：

===> The user-defined function 'counter1'
     declared in Z:\reflectcounter.php
     lines 7 to 11
---> Documentation:
 '/**
 * A simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'c' => 0,
)

===> The user-defined function '{closure}'
     declared in Z:\reflectcounter.php
     lines 18 to 23
---> Documentation:
 '/**
 * Another simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'd' => 0,
)

参见

  • ReflectionMethod::__construct() - ReflectionMethod 的构造函数
  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Exports function

  • ? ReflectionFunction::__construct
  • ReflectionFunction::getClosure ?
  • PHP Manual
  • ReflectionFunction
  • Exports function

ReflectionFunction::export

(PHP 5, PHP 7)

ReflectionFunction::export — Exports function

Warning

本函数已自 PHP 7.4.0 起废弃。强烈建议不要使用本函数。

说明

public static ReflectionFunction::export ( string $name , string $return = ? ) : string

Exports a Reflected function.

参数

name

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionFunction::invoke() - Invokes function
  • ReflectionFunction::__toString() - To string

User Contributed Notes

hytest at gmail dot com 22-Nov-2011 08:04
Example:

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo ReflectionFunction::export('title',true);

?>

Output:

Function [ <user> function title ] {
  @@ /path/to/file.php 2 - 5

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}


Returns a dynamically created closure for the function

  • ? ReflectionFunction::export
  • ReflectionFunction::invoke ?
  • PHP Manual
  • ReflectionFunction
  • Returns a dynamically created closure for the function

ReflectionFunction::getClosure

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunction::getClosure — Returns a dynamically created closure for the function

说明

public ReflectionFunction::getClosure ( ) : Closure

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns Closure. Returns null in case of an error.

User Contributed Notes

php dot net-bug at spamhereplease dot com 23-Nov-2013 05:34
If you have a callback that is going to be invoked often, you can use this method (and the related method for ReflectProperty) to get a closure that will execute at near native speed.

Some benchmark comparisons with php 5.4.22 on ubuntu:

[function call]      [time]     [%slower]
function():          0.09527      0%
Reflection::Closure: 0.09729      2%
$string():           0.102641     8%
Reflection:          0.197122   107%
call_user_func:      0.214045   125%

[method call]        [time]  [% slower] [%vs func]
->method():          0.103611    0%       9%
Reflection::Closure: 0.1043      1%       9%
$string():           0.109885    6%      15%
Reflection:          0.20451    97%     115%
call_user_func:      0.219205  112%     130%


Invokes function

  • ? ReflectionFunction::getClosure
  • ReflectionFunction::invokeArgs ?
  • PHP Manual
  • ReflectionFunction
  • Invokes function

ReflectionFunction::invoke

(PHP 5, PHP 7)

ReflectionFunction::invoke — Invokes function

说明

public ReflectionFunction::invoke ( mixed ...$args ) : mixed

Invokes a reflected function.

参数

args

The passed in argument list. It accepts a variable number of arguments which are passed to the function much like call_user_func() is.

返回值

Returns the result of the invoked function call.

范例

Example #1 ReflectionFunction::invoke() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invoke('Dr', 'Phil');
?>

以上例程会输出：

Dr. Phil

注释

Note:

如果函数有参数需为引用，那么它们必须以引用方式传入。

参见

  • ReflectionFunction::export() - Exports function
  • __invoke()
  • call_user_func() - 把第一个参数作为回调函数调用

User Contributed Notes

spark at limao dot com dot br 10-Jun-2011 10:55
I know Reflections classes have a lot of power, but sometimes all we need is to store a annonymus function or even create a simple callback somewhere.

so here it is, the Callback class:
<?php
    class Callback{
        private $name = false;

        public function Callback($obj,$call=false){
            $name = array($obj);
            if($call) $name[] = $call;

            $this->name = $name;
        }
        public function invoke($params=array()){
            return call_user_func_array($this->name,$params);
        }
    }
?>

Usage:
<?php
    function sayName(){
        return "goku";
    }

    $myVar = new Callback("sayName");

    echo "Hi, I am ".$myVar->invoke()."!";

    //also works with methods: new Callback($obj,"method");
?>


Invokes function args

  • ? ReflectionFunction::invoke
  • ReflectionFunction::isDisabled ?
  • PHP Manual
  • ReflectionFunction
  • Invokes function args

ReflectionFunction::invokeArgs

(PHP 5 >= 5.1.2, PHP 7)

ReflectionFunction::invokeArgs — Invokes function args

说明

public ReflectionFunction::invokeArgs ( array $args ) : mixed

Invokes the function and pass its arguments as array.

参数

args

The passed arguments to the function as an array, much like call_user_func_array() works.

返回值

Returns the result of the invoked function

范例

Example #1 ReflectionFunction::invokeArgs() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invokeArgs(array('Dr', 'Phil'));
?>

以上例程会输出：

Dr. Phil

Example #2 ReflectionFunction::invokeArgs() with references example

<?php
function get_false_conditions(array $conditions, array &$false_conditions)
{
    foreach ($conditions as $condition) {
        if (!$condition) {
            $false_conditions[] = $condition;
        }
    }
}

$function_ref     = new ReflectionFunction('get_false_conditions');

$conditions       = array(true, false, -1, 0, 1);
$false_conditions = array();

$function_ref->invokeArgs(array($conditions, &$false_conditions));

var_dump($false_conditions);
?>

以上例程会输出：

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

注释

Note:

如果函数有参数需为引用，那么它们必须以引用方式传入。

参见

  • ReflectionFunction::invoke() - Invokes function
  • ReflectionFunctionAbstract::getNumberOfParameters() - 获取参数数目
  • __invoke()
  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数

User Contributed Notes

theyourcomputer at gmail dot com 05-Dec-2017 01:40
In the case of call_user_func_array(), if you were to pass around an anonymous function and reference $this within the anonymous function, $this will faithfully refer to the class in the context in which the function was defined. Using ReflectionFunction::invokeArgs() does not seem to retain its original context--yeah, even if you bind the anonymous function before invoking. I recommend call_user_func_array() where context is a concern.
Andrea Giammarchi 16-Feb-2008 06:41
I encountered a weird problem with ReflectionFunction, described in ticket 44139 of PHP Bugs.

If for some reason you need to call with invoke, or invokeArgs, a function like array_unshift (that accepts internally the array by reference) you could use this code to avoid the generated warning or fatal error.

<?php
function unshift(){
    $ref        = new ReflectionFunction('array_unshift');
    $arguments    = func_get_args();
    return        $ref->invokeArgs(array_merge(array(&$this->arr), $arguments));
}
?>

I don't know about performances (you can create an array manually too, starting from array(&$this->something) and adding arguments). However, it seems to work correctly without problems, at least until the send by reference will be usable with one single value ...


Checks if function is disabled

  • ? ReflectionFunction::invokeArgs
  • ReflectionFunction::__toString ?
  • PHP Manual
  • ReflectionFunction
  • Checks if function is disabled

ReflectionFunction::isDisabled

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunction::isDisabled — Checks if function is disabled

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

public ReflectionFunction::isDisabled ( ) : bool

Checks if the function is disabled, via the disable_functions directive.

参数

此函数没有参数。

返回值

true if it's disable, otherwise false

参见

  • ReflectionFunctionAbstract::isUserDefined() - 检查是否是用户定义
  • disable_functions directive

User Contributed Notes

There are no user contributed notes for this page.


To string

  • ? ReflectionFunction::isDisabled
  • ReflectionFunctionAbstract ?
  • PHP Manual
  • ReflectionFunction
  • To string

ReflectionFunction::__toString

(PHP 5, PHP 7)

ReflectionFunction::__toString — To string

说明

public ReflectionFunction::__toString ( ) : string

To string.

参数

此函数没有参数。

返回值

Returns ReflectionFunction::export()-like output for the function.

范例

Example #1 ReflectionFunction::__toString() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo new ReflectionFunction('title');
?>

以上例程的输出类似于：

Function [ <user> function title ] {
  @@ Command line code 1 - 1

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}

参见

  • ReflectionFunction::export() - Exports function
  • ReflectionClass::clone()
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionFunctionAbstract 类

(PHP 5 >= 5.2.0, PHP 7)

简介

ReflectionFunction 的父类，详情请阅读它的描述。

类摘要

ReflectionFunctionAbstract implements Reflector {
/* 属性 */
public $name ;
/* 方法 */
final private __clone ( ) : void
public getClosureScopeClass ( ) : ReflectionClass|null
public getClosureThis ( ) : object
public getDocComment ( ) : string
public getEndLine ( ) : int
public getExtension ( ) : ReflectionExtension
public getExtensionName ( ) : string
public getFileName ( ) : string
public getName ( ) : string
public getNamespaceName ( ) : string
public getNumberOfParameters ( ) : int
public getNumberOfRequiredParameters ( ) : int
public getParameters ( ) : array
public getReturnType ( ) : ReflectionType|null
public getShortName ( ) : string
public getStartLine ( ) : int
public getStaticVariables ( ) : array
public hasReturnType ( ) : bool
public inNamespace ( ) : bool
public isClosure ( ) : bool
public isDeprecated ( ) : bool
public isGenerator ( ) : bool
public isInternal ( ) : bool
public isUserDefined ( ) : bool
public isVariadic ( ) : bool
public returnsReference ( ) : bool
abstract public __toString ( ) : void
}

属性

name

函数的名称。只读，尝试赋值的时候将会抛出 ReflectionException。

Table of Contents

  • ReflectionFunctionAbstract::__clone — 复制函数
  • ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure
  • ReflectionFunctionAbstract::getClosureThis — 返回本身的匿名函数
  • ReflectionFunctionAbstract::getDocComment — 获取注释内容
  • ReflectionFunctionAbstract::getEndLine — 获取结束行号
  • ReflectionFunctionAbstract::getExtension — 获取扩展信息
  • ReflectionFunctionAbstract::getExtensionName — 获取扩展名称
  • ReflectionFunctionAbstract::getFileName — 获取文件名称
  • ReflectionFunctionAbstract::getName — 获取函数名称
  • ReflectionFunctionAbstract::getNamespaceName — 获取命名空间
  • ReflectionFunctionAbstract::getNumberOfParameters — 获取参数数目
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters — 获取必须输入参数个数
  • ReflectionFunctionAbstract::getParameters — 获取参数
  • ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function
  • ReflectionFunctionAbstract::getShortName — 获取函数短名称
  • ReflectionFunctionAbstract::getStartLine — 获取开始行号
  • ReflectionFunctionAbstract::getStaticVariables — 获取静态变量
  • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
  • ReflectionFunctionAbstract::inNamespace — 检查是否处于命名空间
  • ReflectionFunctionAbstract::isClosure — 检查是否是匿名函数
  • ReflectionFunctionAbstract::isDeprecated — 检查是否已经弃用
  • ReflectionFunctionAbstract::isGenerator — 判断函数是否是一个生成器函数
  • ReflectionFunctionAbstract::isInternal — 判断函数是否是内置函数
  • ReflectionFunctionAbstract::isUserDefined — 检查是否是用户定义
  • ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic
  • ReflectionFunctionAbstract::returnsReference — 检查是否返回参考信息
  • ReflectionFunctionAbstract::__toString — 字符串化

User Contributed Notes

There are no user contributed notes for this page.


复制函数

  • ? ReflectionFunctionAbstract
  • ReflectionFunctionAbstract::getClosureScopeClass ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 复制函数

ReflectionFunctionAbstract::__clone

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::__clone — 复制函数

说明

final private ReflectionFunctionAbstract::__clone ( ) : void

复制函数

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • Object cloning

User Contributed Notes

There are no user contributed notes for this page.


Returns the scope associated to the closure

  • ? ReflectionFunctionAbstract::__clone
  • ReflectionFunctionAbstract::getClosureThis ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns the scope associated to the closure

ReflectionFunctionAbstract::getClosureScopeClass

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure

说明

public ReflectionFunctionAbstract::getClosureScopeClass ( ) : ReflectionClass|null

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the class on success or null on failure.

User Contributed Notes

There are no user contributed notes for this page.


返回本身的匿名函数

  • ? ReflectionFunctionAbstract::getClosureScopeClass
  • ReflectionFunctionAbstract::getDocComment ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 返回本身的匿名函数

ReflectionFunctionAbstract::getClosureThis

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunctionAbstract::getClosureThis — 返回本身的匿名函数

说明

public ReflectionFunctionAbstract::getClosureThis ( ) : object

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回 $this 指向，产生错误返回 null

User Contributed Notes

There are no user contributed notes for this page.


获取注释内容

  • ? ReflectionFunctionAbstract::getClosureThis
  • ReflectionFunctionAbstract::getEndLine ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取注释内容

ReflectionFunctionAbstract::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionFunctionAbstract::getDocComment — 获取注释内容

说明

public ReflectionFunctionAbstract::getDocComment ( ) : string

获取函数的注释文本

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

如果存在注释文本返回其内容，否则返回 false

参见

  • ReflectionFunctionAbstract::getStartLine() - 获取开始行号

User Contributed Notes

jens dot kohl+php at gmail dot com 26-Mar-2012 11:19
Beware when you try to use the getDocComment() methods with eAccelerator turned on. eAccelerator ?optimizes? your code in a way that it removes any comments from your source. So at runtime you're not able to get any comments and therefor getDocComments return false.
bruno at vault7 dot com 12-Nov-2009 11:09
In order to retrieve a comment with this method, the comment must be imediately before the class, function or method, start with /** and end with */


获取结束行号

  • ? ReflectionFunctionAbstract::getDocComment
  • ReflectionFunctionAbstract::getExtension ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取结束行号

ReflectionFunctionAbstract::getEndLine

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getEndLine — 获取结束行号

说明

public ReflectionFunctionAbstract::getEndLine ( ) : int

获取结束行号

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

获取用户定义函数的结束行号，如果未知返回 false

参见

  • ReflectionFunctionAbstract::getStartLine() - 获取开始行号

User Contributed Notes

There are no user contributed notes for this page.


获取扩展信息

  • ? ReflectionFunctionAbstract::getEndLine
  • ReflectionFunctionAbstract::getExtensionName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取扩展信息

ReflectionFunctionAbstract::getExtension

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getExtension — 获取扩展信息

说明

public ReflectionFunctionAbstract::getExtension ( ) : ReflectionExtension

获取函数的扩展信息

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回 ReflectionExtension 对象，包含扩展信息

参见

  • ReflectionFunctionAbstract::getExtensionName() - 获取扩展名称

User Contributed Notes

There are no user contributed notes for this page.


获取扩展名称

  • ? ReflectionFunctionAbstract::getExtension
  • ReflectionFunctionAbstract::getFileName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取扩展名称

ReflectionFunctionAbstract::getExtensionName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getExtensionName — 获取扩展名称

说明

public ReflectionFunctionAbstract::getExtensionName ( ) : string

获取扩展名称

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回扩展名称

参见

  • ReflectionFunctionAbstract::getExtension() - 获取扩展信息

User Contributed Notes

There are no user contributed notes for this page.


获取文件名称

  • ? ReflectionFunctionAbstract::getExtensionName
  • ReflectionFunctionAbstract::getName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取文件名称

ReflectionFunctionAbstract::getFileName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getFileName — 获取文件名称

说明

public ReflectionFunctionAbstract::getFileName ( ) : string

获取函数定义的文件名称

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The file name.

参见

  • ReflectionFunctionAbstract::getNamespaceName() - 获取命名空间

User Contributed Notes

stein at visibone dot com 04-Jul-2013 10:53
Returns FALSE for an internal function (when isInternal() returns TRUE, e.g. for 'strlen').


获取函数名称

  • ? ReflectionFunctionAbstract::getFileName
  • ReflectionFunctionAbstract::getNamespaceName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取函数名称

ReflectionFunctionAbstract::getName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getName — 获取函数名称

说明

public ReflectionFunctionAbstract::getName ( ) : string

获取函数名称

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回函数名称

参见

  • ReflectionFunctionAbstract::getExtensionName() - 获取扩展名称
  • ReflectionFunctionAbstract::isUserDefined() - 检查是否是用户定义

User Contributed Notes

PR 14-Feb-2021 01:28
If you call getName() on an anonymous function you'll get "{closure}".


获取命名空间

  • ? ReflectionFunctionAbstract::getName
  • ReflectionFunctionAbstract::getNumberOfParameters ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取命名空间

ReflectionFunctionAbstract::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNamespaceName — 获取命名空间

说明

public ReflectionFunctionAbstract::getNamespaceName ( ) : string

获取类定义所属的命名空间

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回命名空间

参见

  • ReflectionFunctionAbstract::getFileName() - 获取文件名称
  • namespaces

User Contributed Notes

There are no user contributed notes for this page.


获取参数数目

  • ? ReflectionFunctionAbstract::getNamespaceName
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取参数数目

ReflectionFunctionAbstract::getNumberOfParameters

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNumberOfParameters — 获取参数数目

说明

public ReflectionFunctionAbstract::getNumberOfParameters ( ) : int

获取函数定义的参数数目，包括可选参数

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参数的个数

参见

  • ReflectionFunctionAbstract::getNumberOfRequiredParameters() - 获取必须输入参数个数
  • func_num_args() - Returns the number of arguments passed to the function

User Contributed Notes

8ctopus 23-Nov-2020 08:26
$reflection = new ReflectionFunction('implode');
echo $reflection->getNumberOfParameters();
Robert Pitt ( LitePHP ) 11-Apr-2010 03:42
Working on a new MVC Application Framework i use this method to check how many arguments are required before calling the sub method!

Example

<?php
        $this->method_args_count = $this->CReflection
            ->getMethod($Route->getMethod())
            ->getNumberOfParameters();
        //Maybe be 5 but if uri is /controller/method/single_param/ we only of 1
        $this->params = $Route->getParams(); //0 in some cases

        if($this->method_args_count > count($this->params))
        {
            $this->difference = ($this->method_args_count - count($this->params));
            for($i=0;$i<=$this->difference;$i++)
            {
                $this->params[] = false;
            }
        }

        //Call the method with correct amount of params
        // but as false for params that have not been passed!
        call_user_func_array(array(new $this->obj,$Route->getMethod()),$this->params);
?>


获取必须输入参数个数

  • ? ReflectionFunctionAbstract::getNumberOfParameters
  • ReflectionFunctionAbstract::getParameters ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取必须输入参数个数

ReflectionFunctionAbstract::getNumberOfRequiredParameters

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNumberOfRequiredParameters — 获取必须输入参数个数

说明

public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( ) : int

获取函数定义中，必须输入的参数个数

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

必须输入的参数个数

参见

  • ReflectionFunctionAbstract::getNumberOfParameters() - 获取参数数目

User Contributed Notes

cesar at magic3w dot com 07-Jul-2015 12:45
It's interesting to note that this function will treat optional parameters that come before a required parameter as required too. This is good since it allows you to verify that the function will be receiving enough parameters for the it to work, regardless where they are located.

<?php

class MyTest() {
    public function test($a = null, $b) {}
    public function test2($a = null, $b, $c = null) {}
}

//Create the reflection
$r  = new \ReflectionMethod('MyTest', 'test');
$r2 = new \ReflectionMethod('MyTest', 'test2');

//Verify the numbers
echo 'Test: ' . $r->getNumberOfRequiredParameters()); //Output: 2
echo 'Test2: ' . $r->getNumberOfRequiredParameters()); //Output: 2

?>
sebastian at sebastian-eiweleit dot de 02-Sep-2013 03:03
<?php
namespace ExampleWorld;
// The Class
class helloWorld {
    /* Method with two required arguments */

    public function requiredTwoArguments ( $var1, $var2 ) {
        // Some code ...
    }

    /* Method with two arguments, but just one is required */
    public function requiredOneArgument ( $var1, $var2 = false ) {
        // Some code ...
    }
}

$r = new \ReflectionMethod ( 'ExampleWorld\helloWorld', 'requiredTwoArguments' );
echo $r->getNumberOfRequiredParameters ();

$r = new \ReflectionMethod ( 'ExampleWorld\helloWorld', 'requiredOneArgument' );
echo $r->getNumberOfRequiredParameters ();

// Output: 2 1


获取参数

  • ? ReflectionFunctionAbstract::getNumberOfRequiredParameters
  • ReflectionFunctionAbstract::getReturnType ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取参数

ReflectionFunctionAbstract::getParameters

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getParameters — 获取参数

说明

public ReflectionFunctionAbstract::getParameters ( ) : array

通过 ReflectionParameter 数组返回参数列表

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

一组 ReflectionParameter 对象表示每一参数

参见

  • ReflectionFunctionAbstract::getNumberOfParameters() - 获取参数数目
  • func_get_args() - 返回一个包含函数参数列表的数组

User Contributed Notes

a dot lucassilvadeoliveira at gmail dot com 28-Nov-2020 06:08
We can use this functionality to automatically pass arguments to our function based on some data structure.

NOTE: I am using a php 8.0> feature called "Nameds parameter".

<?php

$valuesToProcess = [
  'name' => 'Anderson Lucas Silva de Oliveira',
  'age' => 21,
  'hobbie' => 'Play games'
];

function processUserData($name, $age, $job = "", $hobbie = "")
{
    $msg = "Hello $name. You have $age years old";
    if (!empty($job)) {
    $msg .= ". Your job is $job";
    }

    if (!empty($hobbie)) {
        $msg .= ". Your hobbie is $hobbie";
    }

    echo $msg . ".";
}

$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();

$validParameters = [];
foreach ($parameters as $parameter) {
    if (!array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
        throw new DomainException('Cannot resolve the parameter' . $parameter->getName());
    }

    if(!array_key_exists($parameter->getName(), $valuesToProcess)) {
        continue;
    }

    $validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}

$refFunction->invoke(...$validParameters);
?>

Results in:

Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
dabidi at slupca dot pl 27-Oct-2015 01:33
This is part of my private framework that uses reflection.
This function get arguments list from theme method and puts corresponding vars from $_REQUEST ($_GET, $_POST, and $_COOKIE)

<?php
public static function fire_theme_method($class, $method)
{
        $fire_args=array();

        $reflection = new ReflectionMethod($class, $method);

    foreach($reflection->getParameters() AS $arg)
    {
        if($_REQUEST[$arg->name])
        $fire_args[$arg->name]=$_REQUEST[$arg->name];
        else
        $fire_args[$arg->name]=null;
    }

    return call_user_func_array(array($class, $method), $fire_args);
}
?>
For example, if my theme method needs only id, and we get this url:
http://example.com/my_class/my_method/?id=12&some_unwanted_var=123
will be ignored some_unwanted_var

Of course behind this i have .htaccess, autoloader and controller


Gets the specified return type of a function

  • ? ReflectionFunctionAbstract::getParameters
  • ReflectionFunctionAbstract::getShortName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets the specified return type of a function

ReflectionFunctionAbstract::getReturnType

(PHP 7)

ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function

说明

public ReflectionFunctionAbstract::getReturnType ( ) : ReflectionType|null

Gets the specified return type of a reflected function.

参数

此函数没有参数。

返回值

Returns a ReflectionType object if a return type is specified, null otherwise.

范例

Example #1 ReflectionFunctionAbstract::getReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
echo $reflection1->getReturnType();

以上例程会输出：

int

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->getReturnType());

以上例程会输出：

null

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

参见

  • ReflectionFunctionAbstract::hasReturnType() - Checks if the function has a specified return type
  • ReflectionType::__toString() - To string

User Contributed Notes

There are no user contributed notes for this page.


获取函数短名称

  • ? ReflectionFunctionAbstract::getReturnType
  • ReflectionFunctionAbstract::getStartLine ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取函数短名称

ReflectionFunctionAbstract::getShortName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getShortName — 获取函数短名称

说明

public ReflectionFunctionAbstract::getShortName ( ) : string

获取函数的段名称 (没有命名空间定义)

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

函数短名称

参见

  • ReflectionFunctionAbstract::getNamespaceName() - 获取命名空间
  • namespaces

User Contributed Notes

There are no user contributed notes for this page.


获取开始行号

  • ? ReflectionFunctionAbstract::getShortName
  • ReflectionFunctionAbstract::getStaticVariables ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取开始行号

ReflectionFunctionAbstract::getStartLine

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getStartLine — 获取开始行号

说明

public ReflectionFunctionAbstract::getStartLine ( ) : int

获取函数定义的开始行号

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

开始行号

参见

  • ReflectionFunctionAbstract::getEndLine() - 获取结束行号

User Contributed Notes

There are no user contributed notes for this page.


获取静态变量

  • ? ReflectionFunctionAbstract::getStartLine
  • ReflectionFunctionAbstract::hasReturnType ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取静态变量

ReflectionFunctionAbstract::getStaticVariables

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getStaticVariables — 获取静态变量

说明

public ReflectionFunctionAbstract::getStaticVariables ( ) : array

获取静态变量

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回一个静态变量的 array

参见

  • ReflectionFunctionAbstract::getParameters() - 获取参数

User Contributed Notes

Martiros Aghajanyan 11-Oct-2014 01:27
<?php

function test()
{
    static $a = 0, $b = 15;
    $a++;
    $b++;
    return $a;
}

$rf = new ReflectionFunction('test');

// result - Array ( [a] => 0 [b] => 15 )
print_r( $rf->getStaticVariables() );

//call test function and print again static variables
test();

// result - Array ( [a] => 1 [b] => 16 )
print_r( $rf->getStaticVariables() );

?>


Checks if the function has a specified return type

  • ? ReflectionFunctionAbstract::getStaticVariables
  • ReflectionFunctionAbstract::inNamespace ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if the function has a specified return type

ReflectionFunctionAbstract::hasReturnType

(PHP 7)

ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type

说明

public ReflectionFunctionAbstract::hasReturnType ( ) : bool

Checks whether the reflected function has a return type specified.

参数

此函数没有参数。

返回值

Returns true if the function is a specified return type, otherwise false.

范例

Example #1 ReflectionFunctionAbstract::hasReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
var_dump($reflection1->hasReturnType());

以上例程会输出：

bool(true)

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->hasReturnType());

以上例程会输出：

bool(false)

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

参见

  • ReflectionFunctionAbstract::getReturnType() - Gets the specified return type of a function

User Contributed Notes

There are no user contributed notes for this page.


检查是否处于命名空间

  • ? ReflectionFunctionAbstract::hasReturnType
  • ReflectionFunctionAbstract::isClosure ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否处于命名空间

ReflectionFunctionAbstract::inNamespace

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::inNamespace — 检查是否处于命名空间

说明

public ReflectionFunctionAbstract::inNamespace ( ) : bool

检查函数是否在命名空间内定义

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

在命名空间内返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::getNamespaceName() - 获取命名空间
  • namespaces

User Contributed Notes

There are no user contributed notes for this page.


检查是否是匿名函数

  • ? ReflectionFunctionAbstract::inNamespace
  • ReflectionFunctionAbstract::isDeprecated ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否是匿名函数

ReflectionFunctionAbstract::isClosure

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::isClosure — 检查是否是匿名函数

说明

public ReflectionFunctionAbstract::isClosure ( ) : bool

检查是否是匿名函数

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

匿名函数返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::()

User Contributed Notes

There are no user contributed notes for this page.


检查是否已经弃用

  • ? ReflectionFunctionAbstract::isClosure
  • ReflectionFunctionAbstract::isGenerator ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否已经弃用

ReflectionFunctionAbstract::isDeprecated

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isDeprecated — 检查是否已经弃用

说明

public ReflectionFunctionAbstract::isDeprecated ( ) : bool

检查函数是否已经被弃用

参数

此函数没有参数。

返回值

弃用返回 true，否则返回 false

范例

Example #1 ReflectionFunctionAbstract::isDeprecated() example

<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>

以上例程会输出：

bool(true)

参见

  • ReflectionFunctionAbstract::getDocComment() - 获取注释内容

User Contributed Notes

There are no user contributed notes for this page.


判断函数是否是一个生成器函数

  • ? ReflectionFunctionAbstract::isDeprecated
  • ReflectionFunctionAbstract::isInternal ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 判断函数是否是一个生成器函数

ReflectionFunctionAbstract::isGenerator

(PHP 5 >= 5.5.0, PHP 7)

ReflectionFunctionAbstract::isGenerator — 判断函数是否是一个生成器函数

说明

public ReflectionFunctionAbstract::isGenerator ( ) : bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

生成器函数返回 true，否则返回 false on failure.

User Contributed Notes

There are no user contributed notes for this page.


判断函数是否是内置函数

  • ? ReflectionFunctionAbstract::isGenerator
  • ReflectionFunctionAbstract::isUserDefined ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 判断函数是否是内置函数

ReflectionFunctionAbstract::isInternal

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isInternal — 判断函数是否是内置函数

说明

public ReflectionFunctionAbstract::isInternal ( ) : bool

判断函数是否是内置函数，与用户自定义函数相反

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

内置函数返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::isUserDefined() - 检查是否是用户定义

User Contributed Notes

There are no user contributed notes for this page.


检查是否是用户定义

  • ? ReflectionFunctionAbstract::isInternal
  • ReflectionFunctionAbstract::isVariadic ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否是用户定义

ReflectionFunctionAbstract::isUserDefined

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isUserDefined — 检查是否是用户定义

说明

public ReflectionFunctionAbstract::isUserDefined ( ) : bool

检查函数是否是用户自定义，也就是说不是 PHP 自己内置函数

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

用户自定义函数返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::isInternal() - 判断函数是否是内置函数

User Contributed Notes

There are no user contributed notes for this page.


Checks if the function is variadic

  • ? ReflectionFunctionAbstract::isUserDefined
  • ReflectionFunctionAbstract::returnsReference ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if the function is variadic

ReflectionFunctionAbstract::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic

说明

public ReflectionFunctionAbstract::isVariadic ( ) : bool

Checks if the function is variadic.

参数

此函数没有参数。

返回值

Returns true if the function is variadic, otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


检查是否返回参考信息

  • ? ReflectionFunctionAbstract::isVariadic
  • ReflectionFunctionAbstract::__toString ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否返回参考信息

ReflectionFunctionAbstract::returnsReference

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::returnsReference — 检查是否返回参考信息

说明

public ReflectionFunctionAbstract::returnsReference ( ) : bool

检查是否返回参考信息

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回参考信息返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::isClosure() - 检查是否是匿名函数

User Contributed Notes

There are no user contributed notes for this page.


字符串化

  • ? ReflectionFunctionAbstract::returnsReference
  • ReflectionMethod ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 字符串化

ReflectionFunctionAbstract::__toString

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::__toString — 字符串化

说明

abstract public ReflectionFunctionAbstract::__toString ( ) : void

To string.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The string.

参见

  • ReflectionClass::clone()
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionMethod 类

(PHP 5, PHP 7)

简介

ReflectionMethod 类报告了一个方法的有关信息。

类摘要

ReflectionMethod extends ReflectionFunctionAbstract implements Reflector {
/* 常量 */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
const integer IS_ABSTRACT = 2 ;
const integer IS_FINAL = 4 ;
/* 属性 */
public $name ;
public $class ;
/* 方法 */
public __construct ( mixed $class , string $name )
public static export ( string $class , string $name , bool $return = false ) : string
public getClosure ( object $object ) : Closure
public getDeclaringClass ( ) : ReflectionClass
public getModifiers ( ) : int
public getPrototype ( ) : ReflectionMethod
public invoke ( object $object , mixed $parameter = ? , mixed $... = ? ) : mixed
public invokeArgs ( object $object , array $args ) : mixed
public isAbstract ( ) : bool
public isConstructor ( ) : bool
public isDestructor ( ) : bool
public isFinal ( ) : bool
public isPrivate ( ) : bool
public isProtected ( ) : bool
public isPublic ( ) : bool
public isStatic ( ) : bool
public setAccessible ( bool $accessible ) : void
public __toString ( ) : string
/* 继承的方法 */
final private ReflectionFunctionAbstract::__clone ( ) : void
public ReflectionFunctionAbstract::getClosureScopeClass ( ) : ReflectionClass|null
public ReflectionFunctionAbstract::getClosureThis ( ) : object
public ReflectionFunctionAbstract::getDocComment ( ) : string
public ReflectionFunctionAbstract::getEndLine ( ) : int
public ReflectionFunctionAbstract::getExtension ( ) : ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName ( ) : string
public ReflectionFunctionAbstract::getFileName ( ) : string
public ReflectionFunctionAbstract::getName ( ) : string
public ReflectionFunctionAbstract::getNamespaceName ( ) : string
public ReflectionFunctionAbstract::getNumberOfParameters ( ) : int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( ) : int
public ReflectionFunctionAbstract::getParameters ( ) : array
public ReflectionFunctionAbstract::getReturnType ( ) : ReflectionType|null
public ReflectionFunctionAbstract::getShortName ( ) : string
public ReflectionFunctionAbstract::getStartLine ( ) : int
public ReflectionFunctionAbstract::getStaticVariables ( ) : array
public ReflectionFunctionAbstract::hasReturnType ( ) : bool
public ReflectionFunctionAbstract::inNamespace ( ) : bool
public ReflectionFunctionAbstract::isClosure ( ) : bool
public ReflectionFunctionAbstract::isDeprecated ( ) : bool
public ReflectionFunctionAbstract::isGenerator ( ) : bool
public ReflectionFunctionAbstract::isInternal ( ) : bool
public ReflectionFunctionAbstract::isUserDefined ( ) : bool
public ReflectionFunctionAbstract::isVariadic ( ) : bool
public ReflectionFunctionAbstract::returnsReference ( ) : bool
abstract public ReflectionFunctionAbstract::__toString ( ) : void
}

属性

name

Method name

class

Class name

预定义常量

ReflectionMethod 修饰符

ReflectionMethod::IS_STATIC

指示一个方法是静态（static）的。

ReflectionMethod::IS_PUBLIC

指示一个方法是 public 的。

ReflectionMethod::IS_PROTECTED

指示一个方法是 protected 的。

ReflectionMethod::IS_PRIVATE

指示一个方法是 private 的。

ReflectionMethod::IS_ABSTRACT

指示一个方法是 abstract 的。

ReflectionMethod::IS_FINAL

指示一个方法是 final 的。

Table of Contents

  • ReflectionMethod::__construct — ReflectionMethod 的构造函数
  • ReflectionMethod::export — 输出一个回调方法
  • ReflectionMethod::getClosure — 返回一个动态建立的方法调用接口，译者注：可以使用这个返回值直接调用非公开方法。
  • ReflectionMethod::getDeclaringClass — 获取被反射的方法所在类的反射实例
  • ReflectionMethod::getModifiers — 获取方法的修饰符
  • ReflectionMethod::getPrototype — 返回方法原型 (如果存在)
  • ReflectionMethod::invoke — Invoke
  • ReflectionMethod::invokeArgs — 带参数执行
  • ReflectionMethod::isAbstract — 判断方法是否是抽象方法
  • ReflectionMethod::isConstructor — 判断方法是否是构造方法
  • ReflectionMethod::isDestructor — 判断方法是否是析构方法
  • ReflectionMethod::isFinal — 判断方法是否定义 final
  • ReflectionMethod::isPrivate — 判断方法是否是私有方法
  • ReflectionMethod::isProtected — 判断方法是否是保护方法 (protected)
  • ReflectionMethod::isPublic — 判断方法是否是公开方法
  • ReflectionMethod::isStatic — 判断方法是否是静态方法
  • ReflectionMethod::setAccessible — 设置方法是否访问
  • ReflectionMethod::__toString — 返回反射方法对象的字符串表达

User Contributed Notes

Anonymous 02-Nov-2020 10:15
We can make a "Automatic dependenci injector" in classes when her constructors depends other classes (with type hint).

<?php

class Dependence1 {
    function foo() {
        echo "foo";
    }
}

class Dependence2 {
    function foo2() {
        echo "foo2";
    }
}

final class myClass
{
    private $dep1;
    private $dep2;

    public function __construct(
        Dependence1 $dependence1,
        Dependence2 $dependence2
    )
    {
        $this->dep1 = $dependence1;
        $this->dep2 = $dependence2;
    }

}

// Automatic dependence injection (CLASSES)

$constructor = new ReflectionMethod(myClass::class, '__construct');
$parameters = $constructor->getParameters();

$dependences = [];
foreach ($parameters as $parameter) {
    $dependenceClass = (string) $parameter->getType();
    $dependences[] = new $dependenceClass();
}

$instance = new myClass(...$dependences);
var_dump($instance);

?>

Results in:

object(myClass)#6 (2) {
  ["dep1":"myClass":private]=>
  object(Dependence1)#4 (0) {
  }
  ["dep2":"myClass":private]=>
  object(Dependence2)#5 (0) {
  }
}
webseiten dot designer at googlemail dot com 02-Apr-2011 11:53
Note that the public member $class contains the name of the class in which the method has been defined:

<?php
class A {public function __construct() {}}
class B extends A {}

$method = new ReflectionMethod('B', '__construct');
echo $method->class; // prints 'A'
?>
no dot prob at gmx dot net 02-Jun-2006 01:09
I have written a function which returns the value of a given DocComment tag.

Full example:

<?php

header('Content-Type: text/plain');

class Example
{
    /**
     * This is my DocComment!
     *
     * @DocTag: prints Hello World!
     */
    public function myMethod()
    {
        echo 'Hello World!';
    }
}

function getDocComment($str, $tag = '')
{
    if (empty($tag))
    {
        return $str;
    }

    $matches = array();
    preg_match("/".$tag.":(.*)(\\r\\n|\\r|\\n)/U", $str, $matches);

    if (isset($matches[1]))
    {
        return trim($matches[1]);
    }

    return '';
}

$method = new ReflectionMethod('Example', 'myMethod');

// will return Hello World!
echo getDocComment($method->getDocComment(), '@DocTag');

?>

Maybe you can add this functionality to the getDocComment methods of the reflection classes.


ReflectionMethod 的构造函数

  • ? ReflectionMethod
  • ReflectionMethod::export ?
  • PHP Manual
  • ReflectionMethod
  • ReflectionMethod 的构造函数

ReflectionMethod::__construct

(PHP 5, PHP 7)

ReflectionMethod::__construct — ReflectionMethod 的构造函数

说明

public ReflectionMethod::__construct ( mixed $class , string $name )
public ReflectionMethod::__construct ( string $class_method )

构造一个新的 ReflectionMethod

参数

class

包含方法的类名称或者这个类的一个实例

name

方法的名称

class_method

类名称和方法名称，之间使用 :: 分隔

返回值

没有返回值。

错误／异常

如果指定的方法不存在，那么抛出一个 ReflectionException

范例

Example #1 ReflectionMethod::__construct() example

<?php
class Counter
{
    private static $c = 0;

    /**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function increment()
    {
        return ++self::$c;
    }
}

// Create an instance of the ReflectionMethod class
$method = new ReflectionMethod('Counter', 'increment');

// Print out basic information
printf(
    "===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d[%s]\n",
        $method->isInternal() ? 'internal' : 'user-defined',
        $method->isAbstract() ? ' abstract' : '',
        $method->isFinal() ? ' final' : '',
        $method->isPublic() ? ' public' : '',
        $method->isPrivate() ? ' private' : '',
        $method->isProtected() ? ' protected' : '',
        $method->isStatic() ? ' static' : '',
        $method->getName(),
        $method->isConstructor() ? 'the constructor' : 'a regular method',
        $method->getFileName(),
        $method->getStartLine(),
        $method->getEndline(),
        $method->getModifiers(),
        implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// 打印注释文档
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));

// 打印存在的静态变量
if ($statics= $method->getStaticVariables()) {
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// 执行方法
printf("---> Invocation results in: ");
var_dump($method->invoke(NULL));
?>

以上例程的输出类似于：

===> The user-defined final public static method 'increment' (which is a regular method)
     declared in /Users/philip/cvs/phpdoc/test.php
     lines 14 to 17
     having the modifiers 261[final public static]
---> Documentation:
 '/**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */'
---> Invocation results in: int(1)

参见

  • ReflectionMethod::export() - 输出一个回调方法
  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


输出一个回调方法

  • ? ReflectionMethod::__construct
  • ReflectionMethod::getClosure ?
  • PHP Manual
  • ReflectionMethod
  • 输出一个回调方法

ReflectionMethod::export

(PHP 5, PHP 7)

ReflectionMethod::export — 输出一个回调方法

说明

public static ReflectionMethod::export ( string $class , string $name , bool $return = false ) : string

Exports a ReflectionMethod.

Warning

本函数还未编写文档，仅有参数列表。

参数

class

类名称

name

方法名称

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionMethod::__construct() - ReflectionMethod 的构造函数
  • ReflectionMethod::__toString() - 返回反射方法对象的字符串表达

User Contributed Notes

There are no user contributed notes for this page.


返回一个动态建立的方法调用接口，译者注：可以使用这个返回值直接调用非公开方法。

  • ? ReflectionMethod::export
  • ReflectionMethod::getDeclaringClass ?
  • PHP Manual
  • ReflectionMethod
  • 返回一个动态建立的方法调用接口，译者注：可以使用这个返回值直接调用非公开方法。

ReflectionMethod::getClosure

(PHP 5 >= 5.4.0, PHP 7)

ReflectionMethod::getClosure — 返回一个动态建立的方法调用接口，译者注：可以使用这个返回值直接调用非公开方法。

说明

public ReflectionMethod::getClosure ( object $object ) : Closure

Warning

本函数还未编写文档，仅有参数列表。

参数

object

不可以使用静态方法，需要其他类型的方法

返回值

返回 Closure 如果产生任何错误返回 null

User Contributed Notes

okto 14-Aug-2016 10:45
Use method from another class context.

<?php

class A {
    private $var = 'class A';

    public function getVar() {
        return $this->var;
    }

    public function getCl() {
        return function () {
            $this->getVar();
        };
    }
}

class B {
    private $var = 'class B';
}

$a = new A();
$b = new B();

print $a->getVar() . PHP_EOL;

$reflection = new ReflectionClass(get_class($a));
$closure    = $reflection->getMethod('getVar')->getClosure($a);
$get_var_b  = $closure->bindTo($b, $b);

print $get_var_b() . PHP_EOL;

// Output:
// class A
// class B
Denis Doronin 18-Jan-2013 08:05
You can call private methods with getClosure():

<?php

function call_private_method($object, $method, $args = array()) {
    $reflection = new ReflectionClass(get_class($object));
    $closure = $reflection->getMethod($method)->getClosure($object);
    return call_user_func_array($closure, $args);
}

class Example {

    private $x = 1, $y = 10;

    private function sum() {
        print $this->x + $this->y;
    }

}

call_private_method(new Example(), 'sum');

?>

Output is 11.


获取被反射的方法所在类的反射实例

  • ? ReflectionMethod::getClosure
  • ReflectionMethod::getModifiers ?
  • PHP Manual
  • ReflectionMethod
  • 获取被反射的方法所在类的反射实例

ReflectionMethod::getDeclaringClass

(PHP 5, PHP 7)

ReflectionMethod::getDeclaringClass — 获取被反射的方法所在类的反射实例

说明

public ReflectionMethod::getDeclaringClass ( ) : ReflectionClass

获取被反射的方法所在的类的反射实例。

参数

此函数没有参数。

返回值

返回一个类的 ReflectionClass 反射对象，被反射的方法是这个类的一部分。

范例

Example #1 ReflectionMethod::getDeclaringClass() example

<?php
class HelloWorld {

    protected function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
var_dump($reflectionMethod->getDeclaringClass());
?>

以上例程会输出：

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(10) "HelloWorld"
}

参见

  • ReflectionMethod::isAbstract() - 判断方法是否是抽象方法

User Contributed Notes

There are no user contributed notes for this page.


获取方法的修饰符

  • ? ReflectionMethod::getDeclaringClass
  • ReflectionMethod::getPrototype ?
  • PHP Manual
  • ReflectionMethod
  • 获取方法的修饰符

ReflectionMethod::getModifiers

(PHP 5, PHP 7)

ReflectionMethod::getModifiers — 获取方法的修饰符

说明

public ReflectionMethod::getModifiers ( ) : int

返回一个方法的修饰符，返回值是一个位标

参数

此函数没有参数。

返回值

使用一个数字表示方法修饰符，具体数字的含义可以参考 predefined constants 中的说明。

范例

Example #1 ReflectionMethod::getModifiers() example

<?php
class Testing
{
    final public static function foo()
    {
        return;
    }
    public function bar()
    {
        return;
    }
}

$foo = new ReflectionMethod('Testing', 'foo');

echo "Modifiers for method foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Testing', 'bar');

echo "Modifiers for method bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));
?>

以上例程的输出类似于：

Modifiers for method foo():
261
final public static
Modifiers for method bar():
65792
public

参见

  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

There are no user contributed notes for this page.


返回方法原型 (如果存在)

  • ? ReflectionMethod::getModifiers
  • ReflectionMethod::invoke ?
  • PHP Manual
  • ReflectionMethod
  • 返回方法原型 (如果存在)

ReflectionMethod::getPrototype

(PHP 5 >= 5.1.2, PHP 7)

ReflectionMethod::getPrototype — 返回方法原型 (如果存在)

说明

public ReflectionMethod::getPrototype ( ) : ReflectionMethod

返回方法原型

参数

此函数没有参数。

返回值

方法原型的一个 ReflectionMethod 实例

错误／异常

如果方法没有原型，产生一个 ReflectionException

范例

Example #1 ReflectionMethod::getPrototype() example

<?php
class Hello {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}
class HelloWorld extends Hello {

    public function sayHelloTo($name) {
        return 'Hello world: ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
var_dump($reflectionMethod->getPrototype());
?>

以上例程会输出：

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(10) "sayHelloTo"
  ["class"]=>
  string(5) "Hello"
}

参见

  • ReflectionMethod::getModifiers() - 获取方法的修饰符

User Contributed Notes

There are no user contributed notes for this page.


Invoke

  • ? ReflectionMethod::getPrototype
  • ReflectionMethod::invokeArgs ?
  • PHP Manual
  • ReflectionMethod
  • Invoke

ReflectionMethod::invoke

(PHP 5, PHP 7)

ReflectionMethod::invoke — Invoke

说明

public ReflectionMethod::invoke ( object $object , mixed $parameter = ? , mixed $... = ? ) : mixed

执行一个反射的方法。

参数

object

如果执行的方法是静态类，那么这个参数传送 null。

parameter

0，或者传送给方法的参数列表。可以通过这个参数，给方法传送大量的参数。

返回值

返回方法的返回值

错误／异常

如果 object 并没有包含一个可以使用的类实例，那么将产生 一个 ReflectionException。

如果方法调用失败，也会产生一个 ReflectionException。

范例

Example #1 ReflectionMethod::invoke() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invoke(new HelloWorld(), 'Mike');
?>

以上例程会输出：

Hello Mike

注释

Note:

如果函数有参数需为引用，那么它们必须以引用方式传入。

参见

  • ReflectionMethod::invokeArgs() - 带参数执行
  • __invoke()
  • call_user_func() - 把第一个参数作为回调函数调用

User Contributed Notes

dimitriy at remerov dot ru 06-Jun-2012 01:19
This method can be used to call a overwritten public method of a parent class on an child instance
The following code will output "A":

<?php

class A
{
    public function foo()
    {
        return __CLASS__;
    }
}

class B extends A
{
    public function foo()
    {
        return __CLASS__;
    }
}

$b = new B();

$reflection = new ReflectionObject($b);

$parentReflection = $reflection->getParentClass();

$parentFooReflection = $parentReflection->getMethod('foo');

$data = $parentFooReflection->invoke($b);

echo $data;

?>
templargrey at wp dot pl 21-Jul-2011 01:12
Seems that Reflection doesn`t resolve late static bindings - var_dump will show "string 'a' (length=1)".

<?php
class ParentClass { protected static $a = 'a'; static public function init() { return static::$a; } }
class ChildClass extends ParentClass { protected static $a = 'b'; }

$r = new ReflectionClass('ChildClass');
var_dump($r->getMethod('init')->invoke(null));
?>
rojaro at gmail dot com 10-Feb-2011 01:56
Note: If you want to invoke protected or private methods, you'll first have to make them accessible using the setAccessible() method (see http://php.net/reflectionmethod.setaccessible ).


带参数执行

  • ? ReflectionMethod::invoke
  • ReflectionMethod::isAbstract ?
  • PHP Manual
  • ReflectionMethod
  • 带参数执行

ReflectionMethod::invokeArgs

(PHP 5 >= 5.1.2, PHP 7)

ReflectionMethod::invokeArgs — 带参数执行

说明

public ReflectionMethod::invokeArgs ( object $object , array $args ) : mixed

使用数组给方法传送参数，并执行他。

参数

object

调用方法的对象，如果是静态对象，设置为 null

args

使用 array 传送的方法参数。

返回值

返回方法返回值

错误／异常

如果 object 指定的实例无法执行方法，那么产生 ReflectionException 异常。

如果方法调用失败，产生 ReflectionException

范例

Example #1 ReflectionMethod::invokeArgs() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invokeArgs(new HelloWorld(), array('Mike'));
?>

以上例程会输出：

Hello Mike

注释

Note:

如果函数有参数需为引用，那么它们必须以引用方式传入。

参见

  • ReflectionMethod::invoke() - Invoke
  • __invoke()
  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数

User Contributed Notes

CodeCoutureXX at gmail dot com 03-Sep-2015 09:12
If you need to call ReflectionMethod::invokeArgs() on a static function you can pass NULL in for the $object parameter.

Example:

<?php
     class myClass {
          public static myStaticFunc($a, $b) {
               return $a + $b;
          }
     }

     $ref = new ReflectionMethod('myClass', 'myStaticFunc');
     echo $ref->invokeArgs(NULL, [12, 7]);
?>

produces the following output:

19
cweiske at cweiske dot de 25-Mar-2011 07:34
Passing arguments by reference works:
<?php $rm->invokeArgs($object, array(&$foo, $bar)); ?>
agent_harris at secure-mail dot biz 13-Feb-2011 07:12
There is a simple workaround for the reference passing problem:
Since the reflection api has to handle all parameters in a generic way it has no chance to guess if you wish to pass data per value or reference.

But it seems that you can also decide to pass a reference from where you call the function or method (not just only by the ampersand prefix in its declaration).

So just do the following; which worked for me:

<?php
//...
$method->invoke($object, $inputValue, &$outputValue);
?>

Since this will only be necessary with arrays and primitive data types it should be acceptable in most cases to know in advance if you need to pass per reference. But it is probably although necessary to keep the ampersand always in the declaration (because of the at least two layers between the actual function and your invoke call).

If this is the expected behavior it will maybe make sense to mention it in the documentation for invoke and invokeArgs.
serg dot smertin at gmail dot com 21-Sep-2010 06:51
We can do black magic, which is useful in templating block calls:

<?php
     $object->__named('methodNameHere', array('arg3' => 'three', 'arg1' => 'one'));

     ...

      /**
       * Pass method arguments by name
       *
       * @param string $method
       * @param array $args
       * @return mixed
       */
      public function __named($method, array $args = array())
      {
        $reflection = new ReflectionMethod($this, $method);

        $pass = array();
        foreach($reflection->getParameters() as $param)
        {
          /* @var $param ReflectionParameter */
          if(isset($args[$param->getName()]))
          {
            $pass[] = $args[$param->getName()];
          }
          else
          {
            $pass[] = $param->getDefaultValue();
          }
        }

        return $reflection->invokeArgs($this, $pass);
      }
?>


判断方法是否是抽象方法

  • ? ReflectionMethod::invokeArgs
  • ReflectionMethod::isConstructor ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是抽象方法

ReflectionMethod::isAbstract

(PHP 5, PHP 7)

ReflectionMethod::isAbstract — 判断方法是否是抽象方法

说明

public ReflectionMethod::isAbstract ( ) : bool

判断方法是否是抽象方法

参数

此函数没有参数。

返回值

如果是抽象方法返回 true，否则返回 false

参见

  • ReflectionMethod::getDeclaringClass() - 获取被反射的方法所在类的反射实例

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是构造方法

  • ? ReflectionMethod::isAbstract
  • ReflectionMethod::isDestructor ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是构造方法

ReflectionMethod::isConstructor

(PHP 5, PHP 7)

ReflectionMethod::isConstructor — 判断方法是否是构造方法

说明

public ReflectionMethod::isConstructor ( ) : bool

判断方法是否是构造方法

参数

此函数没有参数。

返回值

如果是构造方法返回 true，否则返回 false

参见

  • ReflectionMethod::__construct() - ReflectionMethod 的构造函数
  • ReflectionMethod::isAbstract() - 判断方法是否是抽象方法
  • ReflectionMethod::isDestructor() - 判断方法是否是析构方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是析构方法

  • ? ReflectionMethod::isConstructor
  • ReflectionMethod::isFinal ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是析构方法

ReflectionMethod::isDestructor

(PHP 5, PHP 7)

ReflectionMethod::isDestructor — 判断方法是否是析构方法

说明

public ReflectionMethod::isDestructor ( ) : bool

判断方法是否是析构方法

参数

此函数没有参数。

返回值

如果是析构方法返回 true，否则返回 false

参见

  • ReflectionMethod::isConstructor() - 判断方法是否是构造方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否定义 final

  • ? ReflectionMethod::isDestructor
  • ReflectionMethod::isPrivate ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否定义 final

ReflectionMethod::isFinal

(PHP 5, PHP 7)

ReflectionMethod::isFinal — 判断方法是否定义 final

说明

public ReflectionMethod::isFinal ( ) : bool

判断方法是否定义 final

参数

此函数没有参数。

返回值

如果是 final 返回 true，否则返回 false

参见

  • ReflectionMethod::isStatic() - 判断方法是否是静态方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是私有方法

  • ? ReflectionMethod::isFinal
  • ReflectionMethod::isProtected ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是私有方法

ReflectionMethod::isPrivate

(PHP 5, PHP 7)

ReflectionMethod::isPrivate — 判断方法是否是私有方法

说明

public ReflectionMethod::isPrivate ( ) : bool

判断方法是否是私有方法

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

私有方法返回 true，否则返回 false

参见

  • ReflectionMethod::isPublic() - 判断方法是否是公开方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是保护方法 (protected)

  • ? ReflectionMethod::isPrivate
  • ReflectionMethod::isPublic ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是保护方法 (protected)

ReflectionMethod::isProtected

(PHP 5, PHP 7)

ReflectionMethod::isProtected — 判断方法是否是保护方法 (protected)

说明

public ReflectionMethod::isProtected ( ) : bool

判断方法是否是保护方法

参数

此函数没有参数。

返回值

保护方法返回 true，否则返回 false

参见

  • ReflectionMethod::isPrivate() - 判断方法是否是私有方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是公开方法

  • ? ReflectionMethod::isProtected
  • ReflectionMethod::isStatic ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是公开方法

ReflectionMethod::isPublic

(PHP 5, PHP 7)

ReflectionMethod::isPublic — 判断方法是否是公开方法

说明

public ReflectionMethod::isPublic ( ) : bool

判断方法是否是公开方法

参数

此函数没有参数。

返回值

公开方法返回 true，否则返回 false

参见

  • ReflectionMethod::isPrivate() - 判断方法是否是私有方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是静态方法

  • ? ReflectionMethod::isPublic
  • ReflectionMethod::setAccessible ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是静态方法

ReflectionMethod::isStatic

(PHP 5, PHP 7)

ReflectionMethod::isStatic — 判断方法是否是静态方法

说明

public ReflectionMethod::isStatic ( ) : bool

判断方法是否是静态方法

参数

此函数没有参数。

返回值

静态方法返回 true，否则返回 false

参见

  • ReflectionMethod::isFinal() - 判断方法是否定义 final

User Contributed Notes

There are no user contributed notes for this page.


设置方法是否访问

  • ? ReflectionMethod::isStatic
  • ReflectionMethod::__toString ?
  • PHP Manual
  • ReflectionMethod
  • 设置方法是否访问

ReflectionMethod::setAccessible

(PHP 5 >= 5.3.2, PHP 7)

ReflectionMethod::setAccessible — 设置方法是否访问

说明

public ReflectionMethod::setAccessible ( bool $accessible ) : void

设置方法是否可以访问，例如通过设置可以访问能够执行私有方法和保护方法

参数

accessible

可以访问设置 true，否则设置 false

返回值

没有返回值。

参见

  • ReflectionMethod::isPrivate() - 判断方法是否是私有方法
  • ReflectionMethod::isProtected() - 判断方法是否是保护方法 (protected)

User Contributed Notes

dave1010 at gmail dot com 11-May-2011 03:21
This is handy for accessing private methods but remember that things are normally private for a reason! Unit Testing is one (debatable) use case for this.

Example:
<?php
class Foo {
  private function myPrivateMethod() {
    return 7;
  }
}

$method = new ReflectionMethod('Foo', 'myPrivateMethod');
$method->setAccessible(true);

echo $method->invoke(new Foo);
// echos "7"
?>

This works nicely with PHPUnit: http://php.net/manual/en/reflectionmethod.setaccessible.php


返回反射方法对象的字符串表达

  • ? ReflectionMethod::setAccessible
  • ReflectionObject ?
  • PHP Manual
  • ReflectionMethod
  • 返回反射方法对象的字符串表达

ReflectionMethod::__toString

(PHP 5, PHP 7)

ReflectionMethod::__toString — 返回反射方法对象的字符串表达

说明

public ReflectionMethod::__toString ( ) : string

返回反射方法对象的字符串表达

参数

此函数没有参数。

返回值

ReflectionMethod 实例的字符串表达，也就是字符串

范例

Example #1 ReflectionMethod::__toString() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
echo $reflectionMethod;
?>

以上例程会输出：

Method [ <user> public method sayHelloTo ] {
  @@ /var/www/examples/reflection.php 16 - 18

  - Parameters [1] {
    Parameter #0 [ <required> $name ]
  }
}

参见

  • ReflectionMethod::export() - 输出一个回调方法
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionObject 类

(PHP 5, PHP 7)

简介

ReflectionObject 类报告了一个对象（object）的相关信息。

类摘要

ReflectionObject extends ReflectionClass implements Reflector {
/* 常量 */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* 属性 */
public $name ;
/* 方法 */
public static export ( string $argument , bool $return = ? ) : string
/* 继承的方法 */
public ReflectionClass::__construct ( mixed $argument )
public static ReflectionClass::export ( mixed $argument , bool $return = false ) : string
public ReflectionClass::getConstant ( string $name ) : mixed
public ReflectionClass::getConstants ( ) : array
public ReflectionClass::getConstructor ( ) : ReflectionMethod
public ReflectionClass::getDefaultProperties ( ) : array
public ReflectionClass::getDocComment ( ) : string
public ReflectionClass::getEndLine ( ) : int
public ReflectionClass::getExtension ( ) : ReflectionExtension
public ReflectionClass::getExtensionName ( ) : string
public ReflectionClass::getFileName ( ) : string
public ReflectionClass::getInterfaceNames ( ) : array
public ReflectionClass::getInterfaces ( ) : array
public ReflectionClass::getMethod ( string $name ) : ReflectionMethod
public ReflectionClass::getMethods ( int $filter = ? ) : array
public ReflectionClass::getModifiers ( ) : int
public ReflectionClass::getName ( ) : string
public ReflectionClass::getNamespaceName ( ) : string
public ReflectionClass::getParentClass ( ) : ReflectionClass
public ReflectionClass::getProperties ( int $filter = ? ) : array
public ReflectionClass::getProperty ( string $name ) : ReflectionProperty
public ReflectionClass::getReflectionConstant ( string $name ) : ReflectionClassConstant|false
public ReflectionClass::getReflectionConstants ( int|null $filter = null ) : array
public ReflectionClass::getShortName ( ) : string
public ReflectionClass::getStartLine ( ) : int
public ReflectionClass::getStaticProperties ( ) : array
public ReflectionClass::getStaticPropertyValue ( string $name , mixed &$def_value = ? ) : mixed
public ReflectionClass::getTraitAliases ( ) : array
public ReflectionClass::getTraitNames ( ) : array
public ReflectionClass::getTraits ( ) : array
public ReflectionClass::hasConstant ( string $name ) : bool
public ReflectionClass::hasMethod ( string $name ) : bool
public ReflectionClass::hasProperty ( string $name ) : bool
public ReflectionClass::implementsInterface ( string $interface ) : bool
public ReflectionClass::inNamespace ( ) : bool
public ReflectionClass::isAbstract ( ) : bool
public ReflectionClass::isAnonymous ( ) : bool
public ReflectionClass::isCloneable ( ) : bool
public ReflectionClass::isFinal ( ) : bool
public ReflectionClass::isInstance ( object $object ) : bool
public ReflectionClass::isInstantiable ( ) : bool
public ReflectionClass::isInterface ( ) : bool
public ReflectionClass::isInternal ( ) : bool
public ReflectionClass::isIterable ( ) : bool
public ReflectionClass::isIterateable ( ) : bool
public ReflectionClass::isSubclassOf ( string $class ) : bool
public ReflectionClass::isTrait ( ) : bool
public ReflectionClass::isUserDefined ( ) : bool
public ReflectionClass::newInstance ( mixed $args , mixed $... = ? ) : object
public ReflectionClass::newInstanceArgs ( array $args = ? ) : object
public ReflectionClass::newInstanceWithoutConstructor ( ) : object
public ReflectionClass::setStaticPropertyValue ( string $name , string $value ) : void
public ReflectionClass::__toString ( ) : string
}

属性

name

对象的类名。只读，在尝试赋值的时候会抛出 ReflectionException。

Table of Contents

  • ReflectionObject::__construct — Constructs a ReflectionObject
  • ReflectionObject::export — Export

User Contributed Notes

ccb_bc at hotmail dot com 21-May-2019 03:39
<?php
    class FullReflectionObject {

        /**
        * @var obj => $ReflectionObject = propriedade que representa o objeto $ReflectionObject
        * @var obj => $ReflectionProperty = propriedade que representa o objeto $ReflectionProperty
        * @var obj => $ReflectionMethod = propriedade que representa o objeto $ReflectionMethod
        * @var obj => $ReflectionParameter = propriedade que representa o objeto $ReflectionParameter
        * @var bol => $reflect_object = true se o método object() for invocado
        * @var bol => $reflect_property = true se o método property() for invocado
        * @var bol => $reflect_method = true se o método method() for invocado
        * @var bol => $reflect_parameter = true se o método parameter() for invocado
        */

        private $ReflectionObject;
        private $ReflectionProperty;
        private $ReflectionMethod;
        private $ReflectionParameter;
        private $reflect_object    = false;
        private $reflect_property  = false;
        private $reflect_method    = false;
        private $reflect_parameter = false;

        /**
        * @param obj => $object = objeto a ser refletido
        */
        public function object(object $object) : object {
            $this->reflect_object = true;
            $this->ReflectionObject = new \ReflectionObject($object);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual a properiedade ser refletida pertence
        * @param str => $property = nome da properiedade a ser refletida
        */
        public function property(string $class_name, string $property) : object {
            $this->reflect_property = true;
            $this->ReflectionProperty = new \ReflectionProperty($class_name, $property);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual o método ser refletido pertence
        * @param str => $method = nome do método a ser refletido
        */
        public function method(string $class_name, string $method) : object {
            $this->reflect_method = true;
            $this->ReflectionMethod = new \ReflectionMethod($class_name, $method);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual o parametro a ser refletido pertence
        * @param str => $method = nome do método o qual o parametro a ser refletido pertence
        * @param str => $parameter = nome do parametro a ser refletido
        */
        public function parameter(string $class_name, string $method, string $parameter) : object {
            $this->reflect_parameter = true;
            $this->ReflectionParameter = new \ReflectionParameter(array($class_name, $method), $parameter);
            return $this;
        }

        public function __call($methodName, $args){
            if($this->reflect_object){
                return call_user_func_array(array($this->ReflectionObject, $methodName), $args);
            }
            if($this->reflect_property){
                return call_user_func_array(array($this->ReflectionProperty, $methodName), $args);
            }
            if($this->reflect_method){
                return call_user_func_array(array($this->ReflectionMethod, $methodName), $args);
            }
            if($this->reflect_parameter){
                return call_user_func_array(array($this->ReflectionParameter, $methodName), $args);
            }
        }
    }

    // Digamos que você tenha no seu projeto a classe Client do pacote Guzzle
    $FullReflectionObject = new FullReflectionObject;
    var_dump($FullReflectionObject->object(new GuzzleHttp\Client)->getMethods());
    var_dump($FullReflectionObject->property('GuzzleHttp\Client', 'config')->isPrivate());
    var_dump($FullReflectionObject->method('GuzzleHttp\Client', 'buildUri')->isPrivate());
    var_dump($FullReflectionObject->parameter('GuzzleHttp\Client', 'send', 'options')->getDefaultValue());
kuldipem at gmail dot com 17-Jun-2015 06:01
class a {
    const abc = 1;
    public function __get($key){
        $r = new ReflectionObject($this);
        if($r->hasConstant($key)){ return $r->getConstant($key); }
    }
}
class b {
    public function getA(){
        return new a();
    }
}
$b = new b();
var_dump($b->getA()::abc);
var_dump($b->getA()::def);
marcel dot nolte at noltecomputer dot de 02-Sep-2009 02:42
To simply enlist all methods and properties of an object simply write:

<?php ReflectionObject::export($yourObject); ?>

,which will cause an var_export-like output.


Constructs a ReflectionObject

  • ? ReflectionObject
  • ReflectionObject::export ?
  • PHP Manual
  • ReflectionObject
  • Constructs a ReflectionObject

ReflectionObject::__construct

(PHP 5, PHP 7)

ReflectionObject::__construct — Constructs a ReflectionObject

说明

public ReflectionObject::__construct ( object $object )

Constructs a ReflectionObject.

Warning

本函数还未编写文档，仅有参数列表。

参数

object

An object instance.

返回值

没有返回值。

参见

  • ReflectionObject::export() - Export
  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionObject::__construct
  • ReflectionParameter ?
  • PHP Manual
  • ReflectionObject
  • Export

ReflectionObject::export

(PHP 5, PHP 7)

ReflectionObject::export — Export

说明

public static ReflectionObject::export ( string $argument , bool $return = ? ) : string

Exports a reflection.

Warning

本函数还未编写文档，仅有参数列表。

参数

argument

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionObject::__construct() - Constructs a ReflectionObject

User Contributed Notes

There are no user contributed notes for this page.


ReflectionParameter 类

(PHP 5, PHP 7)

简介

ReflectionParameter 取回了函数或方法参数的相关信息。

要自行检查函数的参数，首先创建一个 ReflectionFunction 或 ReflectionMethod 的实例，然后使用它们的 ReflectionFunctionAbstract::getParameters() 方法来获取参数的数组。

类摘要

ReflectionParameter implements Reflector {
/* 属性 */
public $name ;
/* 方法 */
public allowsNull ( ) : bool
public canBePassedByValue ( ) : bool
final private __clone ( ) : void
public static export ( string $function , string $parameter , bool $return = ? ) : string
public getClass ( ) : ReflectionClass
public getDeclaringClass ( ) : ReflectionClass|null
public getDeclaringFunction ( ) : ReflectionFunctionAbstract
public getDefaultValue ( ) : mixed
public getDefaultValueConstantName ( ) : string|null
public getName ( ) : string
public getPosition ( ) : int
public getType ( ) : ReflectionType|null
public hasType ( ) : bool
public isArray ( ) : bool
public isCallable ( ) : bool
public isDefaultValueAvailable ( ) : bool
public isDefaultValueConstant ( ) : bool
public isOptional ( ) : bool
public isPassedByReference ( ) : bool
public isVariadic ( ) : bool
public __toString ( ) : string
}

属性

name

参数的名称。只读，在尝试赋值的时候会抛出 ReflectionException。

Table of Contents

  • ReflectionParameter::allowsNull — Checks if null is allowed
  • ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value
  • ReflectionParameter::__clone — Clone
  • ReflectionParameter::__construct — Construct
  • ReflectionParameter::export — Exports
  • ReflectionParameter::getClass — 获得类型提示类。
  • ReflectionParameter::getDeclaringClass — Gets declaring class
  • ReflectionParameter::getDeclaringFunction — Gets declaring function
  • ReflectionParameter::getDefaultValue — Gets default parameter value
  • ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::getName — Gets parameter name
  • ReflectionParameter::getPosition — Gets parameter position
  • ReflectionParameter::getType — Gets a parameter's type
  • ReflectionParameter::hasType — Checks if parameter has a type
  • ReflectionParameter::isArray — Checks if parameter expects an array
  • ReflectionParameter::isCallable — Returns whether parameter MUST be callable
  • ReflectionParameter::isDefaultValueAvailable — 检查是否有默认值。
  • ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant
  • ReflectionParameter::isOptional — Checks if optional
  • ReflectionParameter::isPassedByReference — Checks if passed by reference
  • ReflectionParameter::isVariadic — Checks if the parameter is variadic
  • ReflectionParameter::__toString — To string

User Contributed Notes

fgm at riff dot org 11-May-2008 12:44
The note about the signature of the ReflectionParameter constructor is actually incomplete, at least in 5.2.5: it is possible to use an integer for the second parameter, and the constructor will use it to return the n-th parameter.

This allows you to obtain proper ReflectionParameter objects even when documenting code from extensions which (strangely enough) define several parameters with the same name. The string-based constructor always returns the first parameter with the matching name, whereas the integer-based constructor correctly returns the n-th parameter.

So, in short, this works:
<?php
// supposing the extension defined something like:
// Some_Class::someMethod($a, $x, $y, $x, $y)
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 4);
// returns the last parameter, whereas
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 'y');
// always returns the first $y at position 2
?>
killgecNOFSPAM at gmail dot com 25-Jul-2007 05:53
Signature of constructor of ReflectionParameter correctly is:

public function __construct(array/string $function, string $name);

where $function is either a name of a global function, or a class/method name pair.
massimo at mmware dot it 18-Jul-2007 08:58
I found these limitations using class ReflectionParameter from ReflectionFunction with INTERNAL FUNCTIONS (eg print_r, str_replace, ... ) :

1. parameter names don't match with manual: (try example 19.35 with arg "call_user_func" )
2. some functions (eg PCRE function, preg_match etc) have EMPTY parameter names
3. calling getDefaultValue on Parameters will result in Exception "Cannot determine default value for internal functions"


Checks if null is allowed

  • ? ReflectionParameter
  • ReflectionParameter::canBePassedByValue ?
  • PHP Manual
  • ReflectionParameter
  • Checks if null is allowed

ReflectionParameter::allowsNull

(PHP 5, PHP 7)

ReflectionParameter::allowsNull — Checks if null is allowed

说明

public ReflectionParameter::allowsNull ( ) : bool

Checks whether the parameter allows null.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if null is allowed, otherwise false

参见

  • ReflectionParameter::isOptional() - Checks if optional

User Contributed Notes

Geoffrey LAURENT 05-May-2013 03:53
The allowsNull method look if arguments have a type.
If a type is defined, null is allowed only if default value is null.

 <?php
function myfunction ( $param ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : true

<?php
function myfunction ( stdClass $param ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : false

<?php
function myfunction ( stdClass $param = null ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";
?>

Result : true


Returns whether this parameter can be passed by value

  • ? ReflectionParameter::allowsNull
  • ReflectionParameter::__clone ?
  • PHP Manual
  • ReflectionParameter
  • Returns whether this parameter can be passed by value

ReflectionParameter::canBePassedByValue

(PHP 5 >= 5.4.0, PHP 7)

ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value

说明

public ReflectionParameter::canBePassedByValue ( ) : bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns true if the parameter can be passed by value, false otherwise. Returns null in case of an error.

User Contributed Notes

There are no user contributed notes for this page.


Clone

  • ? ReflectionParameter::canBePassedByValue
  • ReflectionParameter::__construct ?
  • PHP Manual
  • ReflectionParameter
  • Clone

ReflectionParameter::__clone

(PHP 5, PHP 7)

ReflectionParameter::__clone — Clone

说明

final private ReflectionParameter::__clone ( ) : void

Clones.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • ReflectionParameter::toString()
  • Object cloning

User Contributed Notes

There are no user contributed notes for this page.


Construct

  • ? ReflectionParameter::__clone
  • ReflectionParameter::export ?
  • PHP Manual
  • ReflectionParameter
  • Construct

ReflectionParameter::__construct

(PHP 5, PHP 7)

ReflectionParameter::__construct — Construct

说明

public ReflectionParameter::__construct ( string|array|object $function , int|string $param )

Constructs a ReflectionParameter instance.

参数

function

The function to reflect parameters from.

param

Either an int specifying the position of the parameter (starting with zero), or the parameter name as string.

返回值

没有返回值。

范例

Example #1 Using the ReflectionParameter class

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

$reflect = new ReflectionFunction('foo');

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Class: %s\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n".
        "}\n",
        $i, // $param->getPosition() can be used from PHP 5.2.3
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'yes' : 'no'
    );
}
?>

以上例程的输出类似于：

Function [ <user> function foo ] {
  @@ /Users/philip/cvs/phpdoc/a 2 - 2

  - Parameters [3] {
    Parameter #0 [ <required> $a ]
    Parameter #1 [ <required> $b ]
    Parameter #2 [ <required> $c ]
  }
}
-- Parameter #0: a {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #1: b {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #2: c {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}

参见

  • ReflectionFunctionAbstract::getParameters() - 获取参数
  • ReflectionFunction::__construct() - Constructs a ReflectionFunction object
  • ReflectionMethod::__construct() - ReflectionMethod 的构造函数
  • Constructors

User Contributed Notes

tracid2008 t gmail o com 06-Dec-2011 03:31
You also can use a class instead of a function name. Just use an array like that
<?php
$reflect = new ReflectionParameter(array('className', 'methodName'), 'property');
?>


Exports

  • ? ReflectionParameter::__construct
  • ReflectionParameter::getClass ?
  • PHP Manual
  • ReflectionParameter
  • Exports

ReflectionParameter::export

(PHP 5, PHP 7)

ReflectionParameter::export — Exports

Warning

本函数已自 PHP 7.4.0 起废弃。强烈建议不要使用本函数。

说明

public static ReflectionParameter::export ( string $function , string $parameter , bool $return = ? ) : string

Exports.

Warning

本函数还未编写文档，仅有参数列表。

参数

function

The function name.

parameter

The parameter name.

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

The exported reflection.

参见

  • ReflectionParameter::__toString() - To string

User Contributed Notes

There are no user contributed notes for this page.


获得类型提示类。

  • ? ReflectionParameter::export
  • ReflectionParameter::getDeclaringClass ?
  • PHP Manual
  • ReflectionParameter
  • 获得类型提示类。

ReflectionParameter::getClass

(PHP 5, PHP 7)

ReflectionParameter::getClass — 获得类型提示类。

说明

public ReflectionParameter::getClass ( ) : ReflectionClass

获取参数的类型提示类，类型为ReflectionClass对象。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

一个 ReflectionClass 对象。

范例

Example #1 使用 ReflectionParameter 类

<?php
function foo(Exception $a) { }

$functionReflection = new ReflectionFunction('foo');
$parameters = $functionReflection->getParameters();
$aParameter = $parameters[0];

echo $aParameter->getClass()->name;
?>

以上例程会输出：

Exception

参见

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

User Contributed Notes

tarik at bitstore dot ru 22-Feb-2021 07:08
You may use this one function instead depricated

    /**
     * Get parameter class
     * @param \ReflectionParameter $parameter
     * @return \ReflectionClass|null
     */
    private function getClass(\ReflectionParameter $parameter):?\ReflectionClass
    {
        $type = $parameter->getType();
        if (!$type || $type->isBuiltin())
            return NULL;

// This line triggers autoloader!
        if(!class_exists($type->getName()))
            return NULL;

        return  new \ReflectionClass($type->getName());
    }
Dylan 12-Feb-2021 11:47
For php version >=8
ReflectionParamter::getType() is the recommended way to replace the deprecated methods:

- getClass()
e.g: $name = $param->getType() && !$param->getType()->isBuiltin()
       ? new ReflectionClass($param->getType()->getName())
       : null;

- isArray()
e.g: $isArray = $param->getType() && $param->getType()->getName() === 'array';

- isCallable()
e.g: $isCallable = $param->getType() && $param->getType()->getName() === 'callable';

This method is available in PHP 7.0 and later.
richard dot t dot rohrig at gmail dot com 01-Jun-2020 09:33
Example of how to use getClass() in conjunction with getConstructor() to build the dependencies of a class.

private function buildDependencies(ReflectionClass $reflection)
    {
        $constructor = $reflection->getConstructor();

        if (!$constructor) {
            return [];
        }

        $params = $constructor->getParameters();

        return array_map(function ($param) {

            $className = $param->getClass();

            if (!$className) {
                throw new Exception();
            }

            $className = $param->getClass()->getName();

            return $this->make($className);
        }, $params);
    }
tom at r dot je 11-May-2012 09:15
ReflectionParameter::getClass() will cause a fatal error (and trigger __autoload) if the class required by the parameter is not defined.

Sometimes it's useful to only know the class name without needing the class to be loaded.

Here's a simple function that will retrieve only the class name without requiring the class to exist:

<?php
function getClassName(ReflectionParameter $param) {
    preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
    return isset($matches[1]) ? $matches[1] : null;
}
?>
infernaz at gmail dot com 31-Jan-2011 12:09
The method returns ReflectionClass object of parameter type class or NULL if none.

<?php

class A {
    function b(B $c, array $d, $e) {
    }
}
class B {
}

$refl = new ReflectionClass('A');
$par = $refl->getMethod('b')->getParameters();

var_dump($par[0]->getClass()->getName());  // outputs B
var_dump($par[1]->getClass());  // note that array type outputs NULL
var_dump($par[2]->getClass());  // outputs NULL

?>


Gets declaring class

  • ? ReflectionParameter::getClass
  • ReflectionParameter::getDeclaringFunction ?
  • PHP Manual
  • ReflectionParameter
  • Gets declaring class

ReflectionParameter::getDeclaringClass

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getDeclaringClass — Gets declaring class

说明

public ReflectionParameter::getDeclaringClass ( ) : ReflectionClass|null

Gets the declaring class.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A ReflectionClass object or null if called on function.

范例

Example #1 Getting the class that declared the method

<?php
class Foo
{
    public function bar(\DateTime $datetime)
    {
    }
}

class Baz extends Foo
{
}

$param = new \ReflectionParameter(['Baz', 'bar'], 0);

var_dump($param->getDeclaringClass());

以上例程会输出：

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(3) "Foo"
}

参见

  • ReflectionParameter::getClass() - 获得类型提示类。

User Contributed Notes

There are no user contributed notes for this page.


Gets declaring function

  • ? ReflectionParameter::getDeclaringClass
  • ReflectionParameter::getDefaultValue ?
  • PHP Manual
  • ReflectionParameter
  • Gets declaring function

ReflectionParameter::getDeclaringFunction

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getDeclaringFunction — Gets declaring function

说明

public ReflectionParameter::getDeclaringFunction ( ) : ReflectionFunctionAbstract

Gets the declaring function.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A ReflectionFunction object.

参见

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

User Contributed Notes

There are no user contributed notes for this page.


Gets default parameter value

  • ? ReflectionParameter::getDeclaringFunction
  • ReflectionParameter::getDefaultValueConstantName ?
  • PHP Manual
  • ReflectionParameter
  • Gets default parameter value

ReflectionParameter::getDefaultValue

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::getDefaultValue — Gets default parameter value

说明

public ReflectionParameter::getDefaultValue ( ) : mixed

Gets the default value of the parameter for any user-defined or internal function or method. If the parameter is not optional a ReflectionException will be thrown.

参数

此函数没有参数。

返回值

The parameters default value.

更新日志

版本 | 说明
8.0.0 | This method now allows getting the default value of parameters of built-in functions and built-in class methods. Previously, a ReflectionException was thrown.

范例

Example #1 Getting default values of function parameters

<?php
function foo($test, $bar = 'baz')
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValue() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

以上例程会输出：

Name: test

Name: bar
Default value: baz

参见

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isDefaultValueAvailable() - 检查是否有默认值。
  • ReflectionParameter::getDefaultValueConstantName() - Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::isPassedByReference() - Checks if passed by reference

User Contributed Notes

gmail@asmqb7 16-May-2016 12:57
[Editor's note: fixed on user's request]

Getting `Uncaught ReflectionException: Internal error: Failed to retrieve the default value`?

You have to wrap this inside ->isDefaultValueAvailable().


Returns the default value's constant name if default value is constant or null

  • ? ReflectionParameter::getDefaultValue
  • ReflectionParameter::getName ?
  • PHP Manual
  • ReflectionParameter
  • Returns the default value's constant name if default value is constant or null

ReflectionParameter::getDefaultValueConstantName

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null

说明

public ReflectionParameter::getDefaultValueConstantName ( ) : string|null

Returns the default value's constant name of the parameter of any user-defined or internal function or method, if default value is constant or null. If the parameter is not optional a ReflectionException will be thrown.

参数

此函数没有参数。

返回值

Returns string on success or null on failure.

更新日志

版本 | 说明
8.0.0 | This method now allows getting the default values' constant names of built-in functions and built-in class methods. Previously, a ReflectionException was thrown.

范例

Example #1 Getting default values' constant names of function parameters

<?php
function foo($test, $bar = PHP_INT_MIN)
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValueConstantName() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

以上例程会输出：

Name: test

Name: bar
Default value: PHP_INT_MIN

参见

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isDefaultValueConstant() - Returns whether the default value of this parameter is a constant
  • ReflectionParameter::getDefaultValue() - Gets default parameter value

User Contributed Notes

There are no user contributed notes for this page.


Gets parameter name

  • ? ReflectionParameter::getDefaultValueConstantName
  • ReflectionParameter::getPosition ?
  • PHP Manual
  • ReflectionParameter
  • Gets parameter name

ReflectionParameter::getName

(PHP 5, PHP 7)

ReflectionParameter::getName — Gets parameter name

说明

public ReflectionParameter::getName ( ) : string

Gets the name of the parameter.

参数

此函数没有参数。

返回值

The name of the reflected parameter.

参见

  • ReflectionParameter::getValue()

User Contributed Notes

mike 25-May-2015 07:26
FYI, it returns the parameter name without the dollars($) sign at the start.


Gets parameter position

  • ? ReflectionParameter::getName
  • ReflectionParameter::getType ?
  • PHP Manual
  • ReflectionParameter
  • Gets parameter position

ReflectionParameter::getPosition

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getPosition — Gets parameter position

说明

public ReflectionParameter::getPosition ( ) : int

Gets the position of the parameter.

参数

此函数没有参数。

返回值

The position of the parameter, left to right, starting at position #0.

参见

  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

micah at raincross-tech dot com 05-Dec-2010 07:26
Note that the ReflectionFunctionAbstract::getParameters() method will return the parameters in the correct order.


Gets a parameter's type

  • ? ReflectionParameter::getPosition
  • ReflectionParameter::hasType ?
  • PHP Manual
  • ReflectionParameter
  • Gets a parameter's type

ReflectionParameter::getType

(PHP 7)

ReflectionParameter::getType — Gets a parameter's type

说明

public ReflectionParameter::getType ( ) : ReflectionType|null

Gets the associated type of a parameter.

参数

此函数没有参数。

返回值

Returns a ReflectionType object if a parameter type is specified, null otherwise.

范例

Example #1 ReflectionParameter::getType() Usage as of PHP 7.1.0

As of PHP 7.1.0, ReflectionType::__toString() is deprecated, and ReflectionParameter::getType() may return an instance of ReflectionNamedType. To get the name of the parameter type, ReflectionNamedType() is available in this case.

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

assert($reflectionType1 instanceof ReflectionNamedType);
echo $reflectionType1->getName(), PHP_EOL;
var_dump($reflectionType2);
?>

以上例程会输出：

int
NULL

Example #2 ReflectionParameter::getType() Usage before PHP 7.1.0

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

echo $reflectionType1, PHP_EOL;
var_dump($reflectionType2);
?>

以上例程在 PHP 7.0 中的输出：

int
NULL

参见

  • ReflectionParameter::hasType() - Checks if parameter has a type
  • ReflectionType::__toString() - To string

User Contributed Notes

Will Beaumont 05-Sep-2020 04:26
As of 7.1, if a parameter type is found then this method returns an instance of ReflectionNamedType (https://www.php.net/manual/en/class.reflectionnamedtype.php), a subclass of ReflectionType.


Checks if parameter has a type

  • ? ReflectionParameter::getType
  • ReflectionParameter::isArray ?
  • PHP Manual
  • ReflectionParameter
  • Checks if parameter has a type

ReflectionParameter::hasType

(PHP 7)

ReflectionParameter::hasType — Checks if parameter has a type

说明

public ReflectionParameter::hasType ( ) : bool

Checks if the parameter has a type associated with it.

参数

此函数没有参数。

返回值

true if a type is specified, false otherwise.

范例

Example #1 ReflectionParameter::hasType() example

<?php
function someFunction(string $param, $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->hasType());
var_dump($reflectionParams[1]->hasType());

以上例程的输出类似于：

bool(true)
bool(false)

参见

  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

There are no user contributed notes for this page.


Checks if parameter expects an array

  • ? ReflectionParameter::hasType
  • ReflectionParameter::isCallable ?
  • PHP Manual
  • ReflectionParameter
  • Checks if parameter expects an array

ReflectionParameter::isArray

(PHP 5 >= 5.1.2, PHP 7)

ReflectionParameter::isArray — Checks if parameter expects an array

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

public ReflectionParameter::isArray ( ) : bool

Checks if the parameter expects an array.

参数

此函数没有参数。

返回值

true if an array is expected, false otherwise.

参见

  • ReflectionParameter::isOptional() - Checks if optional

User Contributed Notes

denis at example dot com 19-Feb-2020 08:45
Hi, this is simple example of how to use it.

class Test
{
    public function testArray(array $a)
    {
        // do something...

        return $a;
    }

    public function testString(string $a)
    {
        // do something...

        return $a;
    }
}

$reflection = new ReflectionClass('Test');

foreach($reflection->getMethods() as $methods){
    foreach($methods->getParameters() as $param){
        var_dump($param->isArray());
    }
}

//bool(true)
//bool(false)


Returns whether parameter MUST be callable

  • ? ReflectionParameter::isArray
  • ReflectionParameter::isDefaultValueAvailable ?
  • PHP Manual
  • ReflectionParameter
  • Returns whether parameter MUST be callable

ReflectionParameter::isCallable

(PHP 5 >= 5.4.0, PHP 7)

ReflectionParameter::isCallable — Returns whether parameter MUST be callable

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

public ReflectionParameter::isCallable ( ) : bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns true if the parameter is callable, false if it is not or null on failure.

User Contributed Notes

me at abiusx dot com 15-Jan-2016 05:18
Apparently this does not return true for callback arguments to many of the internal functions, such as array_map and array_walk.


检查是否有默认值。

  • ? ReflectionParameter::isCallable
  • ReflectionParameter::isDefaultValueConstant ?
  • PHP Manual
  • ReflectionParameter
  • 检查是否有默认值。

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isDefaultValueAvailable — 检查是否有默认值。

说明

public ReflectionParameter::isDefaultValueAvailable ( ) : bool

检查参数是否有默认值。

参数

此函数没有参数。

返回值

如果有默认值返回，true if a default value is available, 否则返回 false

参见

  • ReflectionParameter::getDefaultValue() - Gets default parameter value
  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the default value of this parameter is a constant

  • ? ReflectionParameter::isDefaultValueAvailable
  • ReflectionParameter::isOptional ?
  • PHP Manual
  • ReflectionParameter
  • Returns whether the default value of this parameter is a constant

ReflectionParameter::isDefaultValueConstant

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant

说明

public ReflectionParameter::isDefaultValueConstant ( ) : bool

Returns whether the default value of this parameter is a constant.

参数

此函数没有参数。

返回值

Returns true if the default value is constant, and false otherwise.

参见

  • ReflectionParameter::getDefaultValueConstantName() - Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::isDefaultValueAvailable() - 检查是否有默认值。

User Contributed Notes

kristianoye at gmail dot com 25-May-2015 09:39
This method returns true only if the parameter's default value is set to a named constant.  e.g.

class Foo {
   const OPTION_MULTIGET = 1;

   //Method 1
   public function setGetOptions($opts=0);

   //Method 2
   public function setMultiGetOptions($opts=Foo::OPTION_MULTIGET);
}

Method 1's first ReflectionParameter will return isDefaultValueConstant() = false (0 is a "constant"/static value but not a named constant) and Method 2's will return isDefaultValueConsntant() = true.


Checks if optional

  • ? ReflectionParameter::isDefaultValueConstant
  • ReflectionParameter::isPassedByReference ?
  • PHP Manual
  • ReflectionParameter
  • Checks if optional

ReflectionParameter::isOptional

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isOptional — Checks if optional

说明

public ReflectionParameter::isOptional ( ) : bool

Checks if the parameter is optional.

参数

此函数没有参数。

返回值

true if the parameter is optional, otherwise false

参见

  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

There are no user contributed notes for this page.


Checks if passed by reference

  • ? ReflectionParameter::isOptional
  • ReflectionParameter::isVariadic ?
  • PHP Manual
  • ReflectionParameter
  • Checks if passed by reference

ReflectionParameter::isPassedByReference

(PHP 5, PHP 7)

ReflectionParameter::isPassedByReference — Checks if passed by reference

说明

public ReflectionParameter::isPassedByReference ( ) : bool

Checks if the parameter is passed in by reference.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the parameter is passed in by reference, otherwise false

参见

  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

There are no user contributed notes for this page.


Checks if the parameter is variadic

  • ? ReflectionParameter::isPassedByReference
  • ReflectionParameter::__toString ?
  • PHP Manual
  • ReflectionParameter
  • Checks if the parameter is variadic

ReflectionParameter::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionParameter::isVariadic — Checks if the parameter is variadic

说明

public ReflectionParameter::isVariadic ( ) : bool

Checks if the parameter was declared as a variadic parameter.

参数

此函数没有参数。

返回值

Returns true if the parameter is variadic, otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


To string

  • ? ReflectionParameter::isVariadic
  • ReflectionProperty ?
  • PHP Manual
  • ReflectionParameter
  • To string

ReflectionParameter::__toString

(PHP 5, PHP 7)

ReflectionParameter::__toString — To string

说明

public ReflectionParameter::__toString ( ) : string

To string.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • ReflectionParameter::export() - Exports
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionProperty 类

(PHP 5, PHP 7)

简介

ReflectionProperty 类报告了类的属性的相关信息。

类摘要

ReflectionProperty implements Reflector {
/* 常量 */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
/* 属性 */
public $name ;
public $class ;
/* 方法 */
final private __clone ( ) : void
public static export ( mixed $class , string $name , bool $return = ? ) : string
public getDeclaringClass ( ) : ReflectionClass
public getDefaultValue ( ) : mixed
public getDocComment ( ) : string|false
public getModifiers ( ) : int
public getName ( ) : string
public getType ( ) : ReflectionType|null
public getValue ( object|null $object = null ) : mixed
public hasDefaultValue ( ) : bool
public hasType ( ) : bool
public isDefault ( ) : bool
public isInitialized ( object|null $object = null ) : bool
public isPrivate ( ) : bool
public isProtected ( ) : bool
public isPublic ( ) : bool
public isStatic ( ) : bool
public setAccessible ( bool $accessible ) : void
public setValue ( object $object , mixed $value ) : void
public __toString ( ) : string
}

属性

name

属性的名称。只读，在尝试赋值的时候抛出 ReflectionException。

class

定义的属性所在的类。只读，在尝试赋值的时候抛出 ReflectionException。

预定义常量

ReflectionProperty 修饰符

ReflectionProperty::IS_STATIC

指示了 static 的属性。

ReflectionProperty::IS_PUBLIC

指示了 public 的属性。

ReflectionProperty::IS_PROTECTED

指示了 protected 的属性。

ReflectionProperty::IS_PRIVATE

指示了 private 的属性。

Table of Contents

  • ReflectionProperty::__clone — Clone
  • ReflectionProperty::__construct — Construct a ReflectionProperty object
  • ReflectionProperty::export — Export
  • ReflectionProperty::getDeclaringClass — Gets declaring class
  • ReflectionProperty::getDefaultValue — Returns the default value declared for a property
  • ReflectionProperty::getDocComment — Gets the property doc comment
  • ReflectionProperty::getModifiers — Gets the property modifiers
  • ReflectionProperty::getName — Gets property name
  • ReflectionProperty::getType — Gets a property's type
  • ReflectionProperty::getValue — Gets value
  • ReflectionProperty::hasDefaultValue — Checks if property has a default value declared
  • ReflectionProperty::hasType — Checks if property has a type
  • ReflectionProperty::isDefault — Checks if property is a default property
  • ReflectionProperty::isInitialized — Checks whether a property is initialized
  • ReflectionProperty::isPrivate — Checks if property is private
  • ReflectionProperty::isProtected — Checks if property is protected
  • ReflectionProperty::isPublic — Checks if property is public
  • ReflectionProperty::isStatic — Checks if property is static
  • ReflectionProperty::setAccessible — Set property accessibility
  • ReflectionProperty::setValue — Set property value
  • ReflectionProperty::__toString — To string

User Contributed Notes

Nanhe Kumar 06-Jan-2014 12:36
<?php
//serialize static properties (class variable)

class Student {

    private $members = array();
    protected $name;
    public static $noOfStudent;

    public function __construct($name = 'Nanhe Kumar') {
        $this->name = $name;
        Student::$noOfStudent++;
    }

    public function __sleep() {
        $vars = get_class_vars(get_class($this));
        foreach ($vars as $key => $val) {
            if (!empty($val))
                $this->members[$key] = $val;
        }
        return array_keys(get_object_vars($this));
    }

    public function __wakeup() {
        foreach ($this->members as $key => $val) {
            $prop = new ReflectionProperty(get_class($this), $key);
            $prop->setValue(get_class($this), $val);
        }
        $this->members = array();
    }

    public function getTotalStudent() {
        return self::$noOfStudent;
    }

}

$so1 = new Student();
$so2 = new Student();
$serialized = serialize($so1);
print_r($serialized); //O:7:"Student":2:{s:16:"Studentmembers";a:1:{s:11:"noOfStudent";i:2;}s:7:"*name";s:11:"Nanhe Kumar";}
$unserialized = unserialize($serialized);
print_r($unserialized); //Student Object ( [members:Student:private] => Array ( ) [name:protected] => Nanhe Kumar )
echo Student::$noOfStudent; //2
?>
rasmus at mindplay dot dk 30-Jul-2010 05:06
I think a more accurate explanation is this:

The Reflection classes are designed to reflect upon the source code of an application, not on any runtime information.

I think you misunderstand the ReflectionProperty constructor in your example above. The fact that it accepts an object as argument is just a convenience feature - you are actually inspecting the class of that object, not the object itself, so it's basically equivalent to:

<?php

// works fine
$Reflection = new ReflectionProperty(get_class($a), 'a');

// throws exception
$Reflection = new ReflectionProperty(get_class($a), 'foo');

?>

Getting the class of the object you're passing in is implied, since inspecting a defined property is the purpose of this class.

In your example, $a->foo is a dynamic member - it is not defined as a member of class, so there is no defining class reference, line number, default value, etc. - which means, there is nothing to reflect upon.

Clearly this very useful library could use some real documentation...


Clone

  • ? ReflectionProperty
  • ReflectionProperty::__construct ?
  • PHP Manual
  • ReflectionProperty
  • Clone

ReflectionProperty::__clone

(PHP 5, PHP 7)

ReflectionProperty::__clone — Clone

说明

final private ReflectionProperty::__clone ( ) : void

Clones.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • ReflectionProperty::export() - Export
  • Object cloning

User Contributed Notes

There are no user contributed notes for this page.


Construct a ReflectionProperty object

  • ? ReflectionProperty::__clone
  • ReflectionProperty::export ?
  • PHP Manual
  • ReflectionProperty
  • Construct a ReflectionProperty object

ReflectionProperty::__construct

(PHP 5, PHP 7)

ReflectionProperty::__construct — Construct a ReflectionProperty object

说明

public ReflectionProperty::__construct ( object|string $class , string $property )

Warning

本函数还未编写文档，仅有参数列表。

参数

class

Either a string containing the name of the class to reflect, or an object.

property

The name of the property being reflected.

返回值

没有返回值。

错误／异常

Trying to get or set private or protected class property's values will result in an exception being thrown.

范例

Example #1 ReflectionProperty::__construct() example

<?php
class Str
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('Str', 'length');

// Print out basic information
printf(
    "===> The%s%s%s%s property '%s' (which was %s)\n" .
    "     having the modifiers %s\n",
        $prop->isPublic() ? ' public' : '',
        $prop->isPrivate() ? ' private' : '',
        $prop->isProtected() ? ' protected' : '',
        $prop->isStatic() ? ' static' : '',
        $prop->getName(),
        $prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of Str
$obj= new Str();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

以上例程的输出类似于：

===> The public property 'length' (which was declared at compile-time)
     having the modifiers array (
  0 => 'public',
)
---> Value is: int(5)
---> Setting value to 10, new value is: int(10)
object(Str)#2 (1) {
  ["length"]=>
  int(10)
}

Example #2 Getting value from private and protected properties using ReflectionProperty class

<?php

class Foo {
    public $x = 1;
    protected $y = 2;
    private $z = 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

?>

以上例程的输出类似于：

int(2)
int(3)

参见

  • ReflectionProperty::getName() - Gets property name
  • Constructors

User Contributed Notes

geoffsmiths at hotmail dot com 05-Jul-2017 12:20
At example #2: the comment // int(2) is stated while the value for the private property is actually 3. (private $z = 3;)

var_dump($prop->getValue($obj)); // This should be int(3)


Export

  • ? ReflectionProperty::__construct
  • ReflectionProperty::getDeclaringClass ?
  • PHP Manual
  • ReflectionProperty
  • Export

ReflectionProperty::export

(PHP 5, PHP 7)

ReflectionProperty::export — Export

说明

public static ReflectionProperty::export ( mixed $class , string $name , bool $return = ? ) : string

Exports a reflection.

Warning

本函数还未编写文档，仅有参数列表。

参数

argument

导出的反射。

name

The property name.

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

参见

  • ReflectionProperty::__toString() - To string

User Contributed Notes

antonfedonyuk at gmail dot com 03-Sep-2020 03:16
Note: export() method is deprecated in PHP 7.4, use __toString() instead - this method return same result.


Gets declaring class

  • ? ReflectionProperty::export
  • ReflectionProperty::getDefaultValue ?
  • PHP Manual
  • ReflectionProperty
  • Gets declaring class

ReflectionProperty::getDeclaringClass

(PHP 5, PHP 7)

ReflectionProperty::getDeclaringClass — Gets declaring class

说明

public ReflectionProperty::getDeclaringClass ( ) : ReflectionClass

Gets the declaring class.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A ReflectionClass object.

参见

  • ReflectionProperty::getName() - Gets property name

User Contributed Notes

metamarkers at gmail dot com 17-May-2013 06:30
If you're reflecting an object and get the declaring class of a property that's set but wasn't declared in any class, it returns the class of the instance.

<?php

class X {

}

$x = new X();
$x->foo = 'bar';
$reflection = new ReflectionObject($x);
echo $reflection->getProperty('foo')->getDeclaringClass()->getName(); // X

?>


Returns the default value declared for a property

  • ? ReflectionProperty::getDeclaringClass
  • ReflectionProperty::getDocComment ?
  • PHP Manual
  • ReflectionProperty
  • Returns the default value declared for a property

ReflectionProperty::getDefaultValue

(PHP 8)

ReflectionProperty::getDefaultValue — Returns the default value declared for a property

说明

public ReflectionProperty::getDefaultValue ( ) : mixed

Gets the implicit or explicitly declared default value for a property.

参数

此函数没有参数。

返回值

The default value if the property has any default value (including null). If there is no default value, then null is returned. It is not possible to differentiate between a null default value and an unitialized typed property. Use ReflectionClass::hasDefaultValue() to detect the difference.

范例

Example #1 ReflectionClass::getDefaultValue() example

<?php
class Foo {
    public $bar = 1;
    public ?int $baz;
    public int $boing = 0;
}

$ro = new ReflectionClass(Foo::class);
var_dump($ro->getProperty('bar')->getDefaultValue());
var_dump($ro->getProperty('baz')->getDefaultValue());
var_dump($ro->getProperty('boing')->getDefaultValue());
?>

以上例程会输出：

int(1)
NULL
int(0)

参见

  • ReflectionProperty::hasDefaultValue() - Checks if property has a default value declared

User Contributed Notes

There are no user contributed notes for this page.


Gets the property doc comment

  • ? ReflectionProperty::getDefaultValue
  • ReflectionProperty::getModifiers ?
  • PHP Manual
  • ReflectionProperty
  • Gets the property doc comment

ReflectionProperty::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionProperty::getDocComment — Gets the property doc comment

说明

public ReflectionProperty::getDocComment ( ) : string|false

Gets the doc comment for a property.

参数

此函数没有参数。

返回值

The doc comment if it exists, otherwise false.

范例

Example #1 ReflectionProperty::getDocComment() example

<?php
class Str
{
    /**
     * @var int  The length of the string
     */
    public $length = 5;
}

$prop = new ReflectionProperty('Str', 'length');

var_dump($prop->getDocComment());

?>

以上例程的输出类似于：

string(53) "/**
     * @var int  The length of the string
     */"

Example #2 Multiple property declarations

If multiple property declarations are preceeded by a single doc comment, the doc comment refers to the first property only.

<?php
class Foo
{
    /** @var string */
    public $a, $b;
}
$class = new \ReflectionClass('Foo');
foreach ($class->getProperties() as $property) {
    echo $property->getName() . ': ' . var_export($property->getDocComment(), true) . PHP_EOL;
}
?>

以上例程会输出：

a: '/** @var string */'
b: false

参见

  • ReflectionProperty::getModifiers() - Gets the property modifiers
  • ReflectionProperty::getName() - Gets property name
  • ReflectionProperty::getValue() - Gets value

User Contributed Notes

There are no user contributed notes for this page.


Gets the property modifiers

  • ? ReflectionProperty::getDocComment
  • ReflectionProperty::getName ?
  • PHP Manual
  • ReflectionProperty
  • Gets the property modifiers

ReflectionProperty::getModifiers

(PHP 5, PHP 7)

ReflectionProperty::getModifiers — Gets the property modifiers

说明

public ReflectionProperty::getModifiers ( ) : int

Gets the modifiers.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A numeric representation of the modifiers.

参见

  • ReflectionProperty::isPrivate() - Checks if property is private
  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

There are no user contributed notes for this page.


Gets property name

  • ? ReflectionProperty::getModifiers
  • ReflectionProperty::getType ?
  • PHP Manual
  • ReflectionProperty
  • Gets property name

ReflectionProperty::getName

(PHP 5, PHP 7)

ReflectionProperty::getName — Gets property name

说明

public ReflectionProperty::getName ( ) : string

Gets the properties name.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The name of the reflected property.

参见

  • ReflectionProperty::getValue() - Gets value

User Contributed Notes

There are no user contributed notes for this page.


Gets a property's type

  • ? ReflectionProperty::getName
  • ReflectionProperty::getValue ?
  • PHP Manual
  • ReflectionProperty
  • Gets a property's type

ReflectionProperty::getType

(PHP 7 >= 7.4.0)

ReflectionProperty::getType — Gets a property's type

说明

public ReflectionProperty::getType ( ) : ReflectionType|null

Gets the associated type of a property.

参数

此函数没有参数。

返回值

Returns a ReflectionType if the property has a type, and null otherwise.

范例

Example #1 ReflectionProperty::getType() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
echo $rp->getType()->getName();
?>

以上例程会输出：

string

参见

  • ReflectionProperty::hasType() - Checks if property has a type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized

User Contributed Notes

andr3medeiros at gmail dot com 06-Aug-2020 10:31
<?php

namespace App\Traits;

use ReflectionClass;
use Illuminate\Support\Str;
use InvalidArgumentException;

trait FieldTypeTrait {

  protected function getType(String $field, ReflectionClass $reflectedClass = null)
  {
    if(is_null($reflectedClass)) {
      $reflectedClass = new ReflectionClass($this);
    }

    if ($reflectedClass->hasProperty($field)) {
      return $this->getFieldType($field, $reflectedClass);
    }

    return null;
  }

  protected function enumValue(String $field) {
    if($this->isEnum($field)) {
      throw new InvalidArgumentException("'$field' is not an enum");
    }

    $type = $this->getType($field);
    $enumClass = $type->name;

    return new $enumClass($this->{$field});
  }

  protected function isEnum(String $field)
  {
    $type = $this->getType($field);

    if(!is_object($type)) {
      return false;
    }

    $className = $type->name;

    $reflectedClass = new ReflectionClass($className);
    $reflectedParent = $reflectedClass->getParentClass();

    return $reflectedParent->getName() == 'MyCLabs\Enum\Enum';
  }

  private function getUseStatements(): array
  {
    $reflectedThis = new ReflectionClass($this);
    $contents = file_get_contents($reflectedThis->getFileName());

    $matches = [];

    preg_match_all("/use ([\w\\\\]+)( as \w+)*/", $contents, $matches);

    $results = [];
    foreach ($matches[1] as $index => $value) {
      $results[] = [
        'namespace' => $value,
        'alias' => isset($matches[2][$index]) ? str_replace(' as ', '', $matches[2][$index]) : null
      ];
    }

    return $results;
  }

  private function getFieldType(String $field, ReflectionClass $reflectedClass)
  {
    $docComment = $reflectedClass->getProperty($field)->getDocComment();
    $type = $this->getFieldTypeByFieldDocComment($docComment);

    if (!is_object($type)) {
      $fromClass = $this->getTypeByClassDocComment($field, $reflectedClass->getDocComment());

      if(is_object($fromClass)) {
          return $fromClass;
      }
    }

    return $type;
  }

  private function getFieldTypeByFieldDocComment(String $docComment)
  {
    $matches = [];

    if (preg_match("/\@var (\w+)(\[\])*/", $docComment, $matches) === 1) {

      if (count($matches) > 0) {
        $type = $matches[1];
        $isArray = isset($matches[2]);
        $fullyQualifiedName = $this->getFullyQualifiedName($type);

        if (class_exists($fullyQualifiedName)) {
          return (object) [
            'name' => $fullyQualifiedName,
            'array' => $isArray
          ];
        }
      }

      return $type;
    }
  }

  private function getTypeByClassDocComment(String $field, String $docComment)
  {
    $matches = [];

    if (preg_match_all("/\@property (\w+) (\\$\w+)/", $docComment, $matches) > 0) {
      $type = null;
      $isArray = false;

      foreach ($matches[2] as $index => $value) {
        if($value == $field) {
          $type = $matches[1][$index];
          $isArray = Str::endsWith($type, '[]');
          $type = str_replace('[]', '', $type);
        }
      }

      if ($type) {
        $fullyQualifiedName = $this->getFullyQualifiedName($type);

        if (class_exists($fullyQualifiedName)) {
          return (object) [
            'name' => $fullyQualifiedName,
            'array' => $isArray
          ];
        }
      }

      return $type;
    }
  }

  private function getFullyQualifiedName($className)
  {
    $useStatements = collect($this->getUseStatements());
    $aliasedStatement = $useStatements->where('alias', $className);

    if ($aliasedStatement) {
      return $aliasedStatement['namespace'];
    }

    $statement = $useStatements->first(function ($statement) use ($className) {
      return Str::endsWith($statement['namespace'], $className);
    });

    if ($statement) {
      return $statement['namespace'];
    }

    return null;
  }
}
email at dronov dot vg 03-Jun-2020 02:46
class User
{
    /**
     * @var string
     */
    public $name;
}

function getTypeNameFromAnnotation(string $className, string $propertyName): ?string
{
    $rp = new \ReflectionProperty($className, $propertyName);
    if (preg_match('/@var\s+([^\s]+)/', $rp->getDocComment(), $matches)) {
        return $matches[1];
    }

    return null;
}

echo getTypeNameFromAnnotation('User', 'name');

// string


Gets value

  • ? ReflectionProperty::getType
  • ReflectionProperty::hasDefaultValue ?
  • PHP Manual
  • ReflectionProperty
  • Gets value

ReflectionProperty::getValue

(PHP 5, PHP 7)

ReflectionProperty::getValue — Gets value

说明

public ReflectionProperty::getValue ( object|null $object = null ) : mixed

Gets the property's value.

参数

object

If the property is non-static an object must be provided to fetch the property from. If you want to fetch the default property without providing an object use ReflectionClass::getDefaultProperties() instead.

返回值

The current value of the property.

错误／异常

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

更新日志

版本 | 说明
8.0.0 | object is nullable now.

范例

Example #1 ReflectionProperty::getValue() example

<?php
class Foo {
    public static $staticProperty = 'foobar';

    public $property = 'barfoo';
    protected $privateProperty = 'foofoo';
}

$reflectionClass = new ReflectionClass('Foo');

var_dump($reflectionClass->getProperty('staticProperty')->getValue());
var_dump($reflectionClass->getProperty('property')->getValue(new Foo));

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
var_dump($reflectionProperty->getValue(new Foo));
?>

以上例程会输出：

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

参见

  • ReflectionProperty::setValue() - Set property value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::getDefaultProperties() - 获取默认属性
  • ReflectionClass::getStaticPropertyValue() - 获取静态（static）属性的值

User Contributed Notes

sergiy dot sokolenko at gmail dot com 28-Jun-2010 03:48
To allow protected and private properties to be accessed, you should use
ReflectionProperty::setAccessible(bool $accessible):

<?php
/** Class Foo with protected and private members */
class Foo {
    protected $bar = 'barrr!';
    private $baz = 'bazzz!';
}

$reflFoo = new ReflectionClass('Foo');
$reflBar = $reflFoo->getProperty('bar');
$reflBaz = $reflFoo->getProperty('baz');

// Set private and protected members accessible for getValue/setValue
$reflBar->setAccessible(true);
$reflBaz->setAccessible(true);

$foo = new Foo();
echo $reflBar->getValue($foo); // will output "barrr!"
echo $reflBaz->getValue($foo); // will output "bazzz!"

// You can also setValue
$reflBar->setValue($foo, "new value");
echo $reflBar->getValue($foo); // will output "new value"
?>


Checks if property has a default value declared

  • ? ReflectionProperty::getValue
  • ReflectionProperty::hasType ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property has a default value declared

ReflectionProperty::hasDefaultValue

(PHP 8)

ReflectionProperty::hasDefaultValue — Checks if property has a default value declared

说明

public ReflectionProperty::hasDefaultValue ( ) : bool

Checks whether the property was declared with a default value, including an implicit null default value. Only returns false for typed properties without default value (or dynamic properties).

参数

此函数没有参数。

返回值

If the property has any default value (including null) true is returned; if the property is typed without a default value declared or is a dynamic property, false is returned.

范例

Example #1 ReflectionClass::hasDefaultValue() example

<?php
class Foo {
    public $bar;
    public ?int $baz;
    public ?int $foo = null;
    public int $boing;

    public function __construct()
    {
        $this->ping = '';
    }
}

$ro = new ReflectionObject(new Foo());
var_dump($ro->getProperty('bar')->hasDefaultValue());
var_dump($ro->getProperty('baz')->hasDefaultValue());
var_dump($ro->getProperty('foo')->hasDefaultValue());
var_dump($ro->getProperty('boing')->hasDefaultValue());
var_dump($ro->getProperty('ping')->hasDefaultValue()); // Dynamic property
var_dump($ro->getProperty('pong')->hasDefaultValue()); // Not defined property
?>

以上例程会输出：

bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Fatal error: Uncaught ReflectionException: Property Foo::$pong does not exist in example.php

参见

  • ReflectionProperty::getDefaultValue() - Returns the default value declared for a property

User Contributed Notes

There are no user contributed notes for this page.


Checks if property has a type

  • ? ReflectionProperty::hasDefaultValue
  • ReflectionProperty::isDefault ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property has a type

ReflectionProperty::hasType

(PHP 7 >= 7.4.0)

ReflectionProperty::hasType — Checks if property has a type

说明

public ReflectionProperty::hasType ( ) : bool

Checks if the property has a type associated with it.

参数

此函数没有参数。

返回值

true if a type is specified, false otherwise.

范例

Example #1 ReflectionProperty::hasType() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
var_dump($rp->hasType());
?>

以上例程会输出：

bool(true)

参见

  • ReflectionProperty::getType() - Gets a property's type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is a default property

  • ? ReflectionProperty::hasType
  • ReflectionProperty::isInitialized ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is a default property

ReflectionProperty::isDefault

(PHP 5, PHP 7)

ReflectionProperty::isDefault — Checks if property is a default property

说明

public ReflectionProperty::isDefault ( ) : bool

Checks whether the property was declared at compile-time, or whether the property was dynamically declared at run-time.

参数

此函数没有参数。

返回值

true if the property was declared at compile-time, or false if it was created at run-time.

范例

Example #1 ReflectionClass::isDefault() example

<?php
class Foo {
    public $bar;
}

$o = new Foo();
$o->bar = 42;
$o->baz = 42;

$ro = new ReflectionObject($o);
var_dump($ro->getProperty('bar')->isDefault());
var_dump($ro->getProperty('baz')->isDefault());
?>

以上例程会输出：

bool(true)
bool(false)

参见

  • ReflectionProperty::getValue() - Gets value

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a property is initialized

  • ? ReflectionProperty::isDefault
  • ReflectionProperty::isPrivate ?
  • PHP Manual
  • ReflectionProperty
  • Checks whether a property is initialized

ReflectionProperty::isInitialized

(PHP 7 >= 7.4.0)

ReflectionProperty::isInitialized — Checks whether a property is initialized

说明

public ReflectionProperty::isInitialized ( object|null $object = null ) : bool

Checks whether a property is initialized.

参数

object

If the property is non-static an object must be provided to fetch the property from.

返回值

Returns false for typed properties prior to initialization, and for properties that have been explicitly unset(). For all other properties true will be returned.

错误／异常

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

更新日志

版本 | 说明
8.0.0 | object is nullable now.

范例

Example #1 ReflectionProperty::isInitialized() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
$user = new User;
var_dump($rp->isInitialized($user));
$user->name = 'Nikita';
var_dump($rp->isInitialized($user));
?>

以上例程会输出：

bool(false)
bool(true)

参见

  • ReflectionProperty::hasType() - Checks if property has a type

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is private

  • ? ReflectionProperty::isInitialized
  • ReflectionProperty::isProtected ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is private

ReflectionProperty::isPrivate

(PHP 5, PHP 7)

ReflectionProperty::isPrivate — Checks if property is private

说明

public ReflectionProperty::isPrivate ( ) : bool

Checks whether the property is private.

参数

此函数没有参数。

返回值

true if the property is private, false otherwise.

参见

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isStatic() - Checks if property is static

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is protected

  • ? ReflectionProperty::isPrivate
  • ReflectionProperty::isPublic ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is protected

ReflectionProperty::isProtected

(PHP 5, PHP 7)

ReflectionProperty::isProtected — Checks if property is protected

说明

public ReflectionProperty::isProtected ( ) : bool

Checks whether the property is protected.

参数

此函数没有参数。

返回值

true if the property is protected, false otherwise.

参见

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isStatic() - Checks if property is static

User Contributed Notes

Ievgen Iefimenko the_boss at bk dot ru 09-Jun-2012 09:44
<?php

/**
* Return 1 if property is public,
* else return void
*/

class Classname{
    private $variable;
}

$obj = new Classname;
$rp = new ReflectionProperty($obj,'variable');
echo $rp->isPrivate();
?>


Checks if property is public

  • ? ReflectionProperty::isProtected
  • ReflectionProperty::isStatic ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is public

ReflectionProperty::isPublic

(PHP 5, PHP 7)

ReflectionProperty::isPublic — Checks if property is public

说明

public ReflectionProperty::isPublic ( ) : bool

Checks whether the property is public.

参数

此函数没有参数。

返回值

true if the property is public, false otherwise.

参见

  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isStatic() - Checks if property is static

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is static

  • ? ReflectionProperty::isPublic
  • ReflectionProperty::setAccessible ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is static

ReflectionProperty::isStatic

(PHP 5, PHP 7)

ReflectionProperty::isStatic — Checks if property is static

说明

public ReflectionProperty::isStatic ( ) : bool

Checks whether the property is static.

参数

此函数没有参数。

返回值

true if the property is static, false otherwise.

参见

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private

User Contributed Notes

There are no user contributed notes for this page.


Set property accessibility

  • ? ReflectionProperty::isStatic
  • ReflectionProperty::setValue ?
  • PHP Manual
  • ReflectionProperty
  • Set property accessibility

ReflectionProperty::setAccessible

(PHP 5 >= 5.3.0, PHP 7)

ReflectionProperty::setAccessible — Set property accessibility

说明

public ReflectionProperty::setAccessible ( bool $accessible ) : void

Enables access to a protected or private property via the ReflectionProperty::getValue() and ReflectionProperty::setValue() methods.

参数

accessible

true to allow accessibility, or false.

返回值

没有返回值。

范例

Example #1 Simple Class definition

<?php
class MyClass
{
    private $foo = 'bar';
}

$property = new ReflectionProperty("MyClass", "foo");
$property->setAccessible(true);

$obj = new MyClass();
echo $property->getValue($obj);
echo $obj->foo;
?>

以上例程的输出类似于：

bar
Fatal error: Uncaught Error: Cannot access private property MyClass::$foo in /in/WJqTv:12

参见

  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isProtected() - Checks if property is protected

User Contributed Notes

matthieu at mnapoli dot fr 19-Oct-2012 08:50
Note that the property will only become accessible using the ReflectionProperty class. The property is still private or protected in the class instances.

<?php
class MyClass {
     private $myProperty = true;
}

$class = new ReflectionClass("MyClass");
$property = $class->getProperty("myProperty");
$property->setAccessible(true);

$obj = new MyClass();
echo $property->getValue($obj); // Works
echo $obj->myProperty; // Doesn't work (error)
?>
Yzmir Ramirez 15-Oct-2010 05:31
Have you tried:

<?php

echo "PHP Version: ".phpversion()."\n";

class Foo
{
    private   $bar  = "private";
    protected $bar2 = "protected";
    public    $bar3 = "public";
}

$obj = new Foo;

$arr = (array)$obj;

print_r($arr);
?>

Output:

PHP Version: 5.2.12
Array
(
    [Foobar] => private
    [*bar2] => protected
    [bar3] => public
)

PHP Version: 5.1.6
Array
(
    [Foobar] => private
    [*bar2] => protected
    [bar3] => public
)
Rob McVey 11-Jun-2010 10:11
If you are using < PHP 5.3 and need to get the private attributes and values, you can use this method:

This is what you are doing:

<?php
$obj_with_privates = new MyObject();
$class     = get_class($obj_with_privates);
$vars     = get_object_vars($obj_with_privates);
//will not show private attributes
print_r($vars);

$reflection = new ReflectionClass( $class );
$attributes = $reflection->getProperties();
//still no private access!
print_r($attributes);
?>

This is what you should do:

<?php
$obj_with_privates = new MyObject();

$class         = get_class( $obj_with_privates );
$reflection = new ReflectionClass( $class );
$abstract    = $reflection->getMethods( ReflectionMethod::IS_ABSTRACT );
$priv_attr  = $reflection->getProperties( ReflectionProperty::IS_PRIVATE );
$privates   = array();
$parent     = get_parent_class( $class );
$child         = $class;
$constructor = $reflection->getConstructor();

//If the class has abstract methods you need to implement them
$abstr_methods = "";
if(sizeof($abstr_methods))
{
    foreach($abstract as $method)
    {
        $mname = $method->name;
        $abstr_methods .= "public function $mname(){return false;}";
    }
}

//Convert private attributes to public attributes
if(sizeof($priv_attr))
{
    $parseable = unserialize(str_replace("\0$class\0", "\0*\0", serialize($obj)));
    foreach($priv_attr as $attribute)
    {
        $aname = $attribute->name;
        $privates[$aname] = $parseable->$aname;
    }
}

$temp_child_class = "temp" . str_replace("_", "", "$class");

//You can gain access to protected attributes by extending the target class
$class_def = "
class $temp_child_class extends $class{
    $constructor
    public function reflect_getmyvars(){
        return get_object_vars(\$this);
    }
    $abstr_methods
}
";

//place class definition in memory
eval($class_def);

//generate object from dynamic class
$tcobj =@ new $temp_child_class;
//call the method we added to the object (to access protected vars)
$vars = $tcobj->reflect_getmyvars();

$attribs = array_merge($vars, $privates);

//will now show private attributes
print_r($attribs);
?>


Set property value

  • ? ReflectionProperty::setAccessible
  • ReflectionProperty::__toString ?
  • PHP Manual
  • ReflectionProperty
  • Set property value

ReflectionProperty::setValue

(PHP 5, PHP 7)

ReflectionProperty::setValue — Set property value

说明

public ReflectionProperty::setValue ( object $object , mixed $value ) : void
public ReflectionProperty::setValue ( mixed $value ) : void

Sets (changes) the property's value.

参数

object

If the property is non-static an object must be provided to change the property on. If the property is static this parameter is left out and only value needs to be provided.

value

The new value.

返回值

没有返回值。

错误／异常

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

范例

Example #1 ReflectionProperty::setValue() example

<?php
class Foo {
    public static $staticProperty;

    public $property;
    protected $privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

$reflectionClass->getProperty('staticProperty')->setValue('foo');
var_dump(Foo::$staticProperty);

$foo = new Foo;

$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

以上例程会输出：

string(3) "foo"
string(3) "bar"
string(6) "foobar"

参见

  • ReflectionProperty::getValue() - Gets value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::setStaticPropertyValue() - 设置静态属性的值

User Contributed Notes

me at ircmaxell dot om 22-Jun-2011 09:27
You can use ReflectionProperty::setValue to set the value on static properties as well as regular instance properties.  Simply pass null in place of the instance:

<?php
class Foo {
    protected static $bar = null;
    public static function sayBar() {
        echo self::$bar;
    }
}

$r = new ReflectionProperty('Foo', 'bar');
$r->setAccessible(true);
$r->setValue(null, 'foo');

Foo::sayBar(); // "foo"
?>


To string

  • ? ReflectionProperty::setValue
  • ReflectionType ?
  • PHP Manual
  • ReflectionProperty
  • To string

ReflectionProperty::__toString

(PHP 5, PHP 7)

ReflectionProperty::__toString — To string

说明

public ReflectionProperty::__toString ( ) : string

To string.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionType class

(PHP 7)

简介

ReflectionType 类用于获取函数、类方法的参数或者返回值的类型。

类摘要

ReflectionType {
/* 方法 */
public allowsNull ( ) : bool
public __toString ( ) : string
}

Table of Contents

  • ReflectionType::allowsNull — Checks if null is allowed
  • ReflectionType::__toString — To string

User Contributed Notes

Ondej Mirtes 27-Sep-2020 06:53
Method ReflectionType::getName() does not exist. This may have been virtually true in the past but not anymore. It exists on ReflectionNamedType which used to be the only child class of ReflectionType. So you could have kind of relied on that.

But in PHP 8 there's also ReflectionUnionType which doesn't have the getName() method. So in order to support PHP 8, you need to support both ReflectionNamedType and ReflectionUnionType.
benjamin dot morel at gmail dot com 18-Sep-2020 09:03
Known subclasses:

- ReflectionNamedType
- ReflectionUnionType
roland at mxchange dot org 11-Mar-2020 09:13
I guess it is <?php ReflectionNamedType::getName(); ?> ?
1franck 28-Jan-2020 08:59
For those who stumble on notice about ReflectionType::__toString() beeing deprecated, use method ReflectionType::getName() instead which is not yet documented.


Checks if null is allowed

  • ? ReflectionType
  • ReflectionType::__toString ?
  • PHP Manual
  • ReflectionType
  • Checks if null is allowed

ReflectionType::allowsNull

(PHP 7)

ReflectionType::allowsNull — Checks if null is allowed

说明

public ReflectionType::allowsNull ( ) : bool

Checks whether the parameter allows null.

参数

此函数没有参数。

返回值

true if null is allowed, otherwise false

范例

Example #1 ReflectionType::allowsNull() example

<?php
function someFunction(string $param, StdClass $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->allowsNull());
var_dump($reflectionParams[1]->getType()->allowsNull());

以上例程会输出：

bool(false)
bool(true)

参见

  • ReflectionNamedType::isBuiltin()
  • ReflectionType::__toString() - To string
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

There are no user contributed notes for this page.


To string

  • ? ReflectionType::allowsNull
  • ReflectionGenerator ?
  • PHP Manual
  • ReflectionType
  • To string

ReflectionType::__toString

(PHP 7)

ReflectionType::__toString — To string

Warning

本函数已自 PHP 7.1.0 起废弃。强烈建议不要使用本函数。

说明

public ReflectionType::__toString ( ) : string

Gets the parameter type name.

参数

此函数没有参数。

返回值

Returns the type of the parameter.

范例

Example #1 ReflectionType::__toString() example

<?php
function someFunction(string $param) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

echo $reflectionParam->getType();

以上例程的输出类似于：

string

更新日志

版本 | 说明
7.1.0 | ReflectionType::__toString() has been deprecated.

参见

  • ReflectionNamedType::getName()
  • ReflectionNamedType::isBuiltin()
  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionUnionType::getTypes()
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

Anonymous 26-Jul-2020 04:32
Regarding this method's deprecation:

ReflectionType::__toString() was first deprecated in PHP 7.1.0 alpha1.
The deprecation notice was removed in PHP 7.1.0 RC3, before being reinstated in PHP 7.4.0 alpha1.

Starting with PHP 7.1.0 beta 3, ReflectionParameter::getType() & ReflectionFunctionAbstract::getReturnType() return instances of ReflectionNamedType instead of ReflectionType.
The ReflectionNamedType class inherits from ReflectionType but provides an additional getName() method which can be used to retrieve the type hint.

Lastly, PHP 8.0.0 alpha1 introduced the concept of union types (see https://wiki.php.net/rfc/union_types_v2). As a result, ReflectionParameter::getType() & ReflectionFunctionAbstract::getReturnType() will now return either instances of ReflectionNamedType or ReflectionUnionType depending on the type hint, both of which are descendants of ReflectionType.


生成器反射类

(PHP 7)

简介

ReflectionGenerator类用于获取生成器的信息。

类摘要

ReflectionGenerator {
/* 方法 */
public getExecutingFile ( ) : string
public getExecutingGenerator ( ) : Generator
public getExecutingLine ( ) : int
public getFunction ( ) : ReflectionFunctionAbstract
public getThis ( ) : object|null
public getTrace ( int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT ) : array
}

Table of Contents

  • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
  • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
  • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
  • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
  • ReflectionGenerator::getFunction — Gets the function name of the generator
  • ReflectionGenerator::getThis — Gets the $this value of the generator
  • ReflectionGenerator::getTrace — Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionGenerator object

  • ? ReflectionGenerator
  • ReflectionGenerator::getExecutingFile ?
  • PHP Manual
  • ReflectionGenerator
  • Constructs a ReflectionGenerator object

ReflectionGenerator::__construct

(PHP 7)

ReflectionGenerator::__construct — Constructs a ReflectionGenerator object

说明

public ReflectionGenerator::__construct ( Generator $generator )

Constructs a ReflectionGenerator object.

参数

generator

A generator object.

返回值

没有返回值。

范例

Example #1 ReflectionGenerator::__construct() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

echo <<< output
{$reflectionGen->getFunction()->name}
Line: {$reflectionGen->getExecutingLine()}
File: {$reflectionGen->getExecutingFile()}
output;

以上例程的输出类似于：

gen
Line: 5
File: /path/to/file/example.php

参见

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the file name of the currently executing generator

  • ? ReflectionGenerator::__construct
  • ReflectionGenerator::getExecutingGenerator ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the file name of the currently executing generator

ReflectionGenerator::getExecutingFile

(PHP 7)

ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator

说明

public ReflectionGenerator::getExecutingFile ( ) : string

Get the full path and file name of the currently executing generator.

参数

此函数没有参数。

返回值

Returns the full path and file name of the currently executing generator.

范例

Example #1 ReflectionGenerator::getExecutingFile() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "File: {$reflectionGen->getExecutingFile()}";

以上例程的输出类似于：

File: /path/to/file/example.php

参见

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object

User Contributed Notes

There are no user contributed notes for this page.


Gets the executing Generator object

  • ? ReflectionGenerator::getExecutingFile
  • ReflectionGenerator::getExecutingLine ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the executing Generator object

ReflectionGenerator::getExecutingGenerator

(PHP 7)

ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object

说明

public ReflectionGenerator::getExecutingGenerator ( ) : Generator

Get the executing Generator object

参数

此函数没有参数。

返回值

Returns the currently executing Generator object.

范例

Example #1 ReflectionGenerator::getExecutingGenerator() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

$gen2 = $reflectionGen->getExecutingGenerator();

var_dump($gen2 === $gen);
var_dump($gen2->current());

以上例程的输出类似于：

bool(true)
int(1);

参见

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the currently executing line of the generator

  • ? ReflectionGenerator::getExecutingGenerator
  • ReflectionGenerator::getFunction ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the currently executing line of the generator

ReflectionGenerator::getExecutingLine

(PHP 7)

ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator

说明

public ReflectionGenerator::getExecutingLine ( ) : int

Get the currently executing line number of the generator.

参数

此函数没有参数。

返回值

Returns the line number of the currently executing statement in the generator.

范例

Example #1 ReflectionGenerator::getExecutingLine() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "Line: {$reflectionGen->getExecutingLine()}";

以上例程的输出类似于：

Line: 7

参见

  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the function name of the generator

  • ? ReflectionGenerator::getExecutingLine
  • ReflectionGenerator::getThis ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the function name of the generator

ReflectionGenerator::getFunction

(PHP 7)

ReflectionGenerator::getFunction — Gets the function name of the generator

说明

public ReflectionGenerator::getFunction ( ) : ReflectionFunctionAbstract

Enables the function name of the generator to be obtained by returning a class derived from ReflectionFunctionAbstract.

参数

此函数没有参数。

返回值

Returns a ReflectionFunctionAbstract class. This will be ReflectionFunction for functions, or ReflectionMethod for methods.

范例

Example #1 ReflectionGenerator::getFunction() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getFunction());

以上例程的输出类似于：

object(ReflectionFunction)#3 (1) {
  ["name"]=>
  string(3) "gen"
}

参见

  • ReflectionGenerator::getThis() - Gets the $this value of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the $this value of the generator

  • ? ReflectionGenerator::getFunction
  • ReflectionGenerator::getTrace ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the $this value of the generator

ReflectionGenerator::getThis

(PHP 7)

ReflectionGenerator::getThis — Gets the $this value of the generator

说明

public ReflectionGenerator::getThis ( ) : object|null

Get the $this value that the generator has access to.

参数

此函数没有参数。

返回值

Returns the $this value, or null if the generator was not created in a class context.

范例

Example #1 ReflectionGenerator::getThis() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getThis());

以上例程的输出类似于：

object(GenExample)#3 (0) {
}

参见

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the trace of the executing generator

  • ? ReflectionGenerator::getThis
  • Reflector ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the trace of the executing generator

ReflectionGenerator::getTrace

(PHP 7)

ReflectionGenerator::getTrace — Gets the trace of the executing generator

说明

public ReflectionGenerator::getTrace ( int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT ) : array

Get the trace of the currently executing generator.

参数

options

The value of options can be any of the following flags.

Available options
Option | Description
DEBUG_BACKTRACE_PROVIDE_OBJECT | Default.
DEBUG_BACKTRACE_IGNORE_ARGS | Don't include the argument information for functions in the stack trace.

返回值

Returns the trace of the currently executing generator.

范例

Example #1 ReflectionGenerator::getTrace() example

<?php
function foo() {
    yield 1;
}

function bar()
{
    yield from foo();
}

function baz()
{
    yield from bar();
}

$gen = baz();
$gen->valid(); // start the generator

var_dump((new ReflectionGenerator($gen))->getTrace());

以上例程的输出类似于：

array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(8)
    ["function"]=>
    string(3) "foo"
    ["args"]=>
    array(0) {
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(3) "bar"
    ["args"]=>
    array(0) {
    }
  }
}

参见

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getThis() - Gets the $this value of the generator

User Contributed Notes

There are no user contributed notes for this page.


Reflector 接口

(PHP 5, PHP 7)

简介

Reflector 是一个接口，被所有可导出的反射类所实现（implement）。

类摘要

Reflector {
/* 方法 */
public static export ( ) : string
public __toString ( ) : string
}

Table of Contents

  • Reflector::export — Exports
  • Reflector::__toString — 转化成字符串

User Contributed Notes

There are no user contributed notes for this page.


Exports

  • ? Reflector
  • Reflector::__toString ?
  • PHP Manual
  • Reflector
  • Exports

Reflector::export

(PHP 5, PHP 7)

Reflector::export — Exports

说明

public static Reflector::export ( ) : string

输出。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • Reflection::__toString()

User Contributed Notes

There are no user contributed notes for this page.


转化成字符串

  • ? Reflector::export
  • ReflectionException ?
  • PHP Manual
  • Reflector
  • 转化成字符串

Reflector::__toString

(PHP 5, PHP 7)

Reflector::__toString — 转化成字符串

说明

public Reflector::__toString ( ) : string

转化成字符串。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • ReflectionProperty::export() - Export
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionException 类

(PHP 5, PHP 7)

简介

ReflectionException 类。

类摘要

ReflectionException extends Exception {
/* 属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

temirkhan.nasukhov 18-Apr-2019 11:50
Note that this exception is unchecked even if it is not based on RuntimeException.  Such error must lead to direct fixes in code and not in catch-handle of situation.

Also keep in mind that IDE (mine is Phpstorm 2018.3.4) inspections will highlight it for that reason so do not create phpdoc with throws for any Runtime exceptions.

<?php

/**
 * This way is wrong
 *
 * @throws \ReflectionException
 */
function createReflection()
{
    return new \ReflectionClass('invalid argument');
}

/**
 * This way is fine(I don't mean the code of course)
 */
function createReflection()
{
    return new \ReflectionClass('invalid argument');
}


Variable handling

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Variable handling 函数
    • boolval — 获取变量的布尔值
    • debug_zval_dump — Dumps a string representation of an internal zend value to output
    • doubleval — floatval 的别名
    • empty — 检查一个变量是否为空
    • floatval — 获取变量的浮点值
    • get_defined_vars — 返回由所有已定义变量所组成的数组
    • get_resource_id — Returns an integer identifier for the given resource
    • get_resource_type — 返回资源（resource）类型
    • gettype — 获取变量的类型
    • intval — 获取变量的整数值
    • is_array — 检测变量是否是数组
    • is_bool — 检测变量是否是布尔值
    • is_callable — 检测参数是否为合法的可调用结构
    • is_countable — Verify that the contents of a variable is a countable value
    • is_double — is_float 的别名
    • is_float — 检测变量是否是浮点型
    • is_int — 检测变量是否是整数
    • is_integer — is_int 的别名
    • is_iterable — Verify that the contents of a variable is an iterable value
    • is_long — is_int 的别名
    • is_null — 检测变量是否为 null
    • is_numeric — 检测变量是否为数字或数字字符串
    • is_object — 检测变量是否是一个对象
    • is_real — is_float 的别名
    • is_resource — 检测变量是否为资源类型
    • is_scalar — 检测变量是否是一个标量
    • is_string — 检测变量是否是字符串
    • isset — 检测变量是否已设置并且非 null
    • print_r — 以易于理解的格式打印变量。
    • serialize — 产生一个可存储的值的表示
    • settype — 设置变量的类型
    • strval — 获取变量的字符串值
    • unserialize — 从已存储的表示中创建 PHP 的值
    • unset — 释放给定的变量
    • var_dump — 打印变量的相关信息
    • var_export — 输出或返回一个变量的字符串表示

User Contributed Notes

There are no user contributed notes for this page.


简介

For information on how variables behave, see the Variables entry in the Language Reference section of the manual.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

变量配置选项
名字 | 默认 | 可修改范围 | 更新日志
unserialize_callback_func | NULL | PHP_INI_ALL | 自 PHP 4.2.0 起可用。
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

unserialize_callback_func string

如果解串行器发现有未定义类要被实例化，将会调用 unserialize() 回调函数（用该未定义类名作为参数）。如果指定函数不存在，或者此函数没有包含／实现该未定义类，则显示警告。所以仅在确实需要实现这样的回调函数时才设置该选项。

参见 unserialize() 和 Autoloading Objects.

User Contributed Notes

There are no user contributed notes for this page.


Variable handling 函数

Table of Contents

  • boolval — 获取变量的布尔值
  • debug_zval_dump — Dumps a string representation of an internal zend value to output
  • doubleval — floatval 的别名
  • empty — 检查一个变量是否为空
  • floatval — 获取变量的浮点值
  • get_defined_vars — 返回由所有已定义变量所组成的数组
  • get_resource_id — Returns an integer identifier for the given resource
  • get_resource_type — 返回资源（resource）类型
  • gettype — 获取变量的类型
  • intval — 获取变量的整数值
  • is_array — 检测变量是否是数组
  • is_bool — 检测变量是否是布尔值
  • is_callable — 检测参数是否为合法的可调用结构
  • is_countable — Verify that the contents of a variable is a countable value
  • is_double — is_float 的别名
  • is_float — 检测变量是否是浮点型
  • is_int — 检测变量是否是整数
  • is_integer — is_int 的别名
  • is_iterable — Verify that the contents of a variable is an iterable value
  • is_long — is_int 的别名
  • is_null — 检测变量是否为 null
  • is_numeric — 检测变量是否为数字或数字字符串
  • is_object — 检测变量是否是一个对象
  • is_real — is_float 的别名
  • is_resource — 检测变量是否为资源类型
  • is_scalar — 检测变量是否是一个标量
  • is_string — 检测变量是否是字符串
  • isset — 检测变量是否已设置并且非 null
  • print_r — 以易于理解的格式打印变量。
  • serialize — 产生一个可存储的值的表示
  • settype — 设置变量的类型
  • strval — 获取变量的字符串值
  • unserialize — 从已存储的表示中创建 PHP 的值
  • unset — 释放给定的变量
  • var_dump — 打印变量的相关信息
  • var_export — 输出或返回一个变量的字符串表示

User Contributed Notes

aldemarcalazans@gmail 06-Oct-2019 08:57
I thought the PHP developers should include in this section, the operator "identity" ( see http://php.net/manual/en/language.operators.arithmetic.php).

From an arithmetic point of view, this operator is useless but, as a converter from string to number, it is great. It does not force the numerical string to have an integer or float type, instead, it automatically determines the adequate type, depending on the numerical quantity represented by the string.


获取变量的布尔值

  • ? Variable handling 函数
  • debug_zval_dump ?
  • PHP Manual
  • Variable handling 函数
  • 获取变量的布尔值

boolval

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

boolval — 获取变量的布尔值

说明

boolval ( mixed $value ) : bool

返回 value 的 bool 值。

参数

value

标量值会被转化成 bool 值。

返回值

value 的 bool 值。

范例

Example #1 boolval() examples

<?php
echo '0:        '.(boolval(0) ? 'true' : 'false')."\n";
echo '42:       '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0:      '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2:      '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"":       '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0":      '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1":      '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]:   '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]:       '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>

以上例程会输出：

0:        false
42:       true
0.0:      false
4.2:      true
"":       false
"string": true
"0":      false
"1":      true
[1, 2]:   true
[]:       false
stdClass: true

参见

  • floatval() - 获取变量的浮点值
  • intval() - 获取变量的整数值
  • strval() - 获取变量的字符串值
  • settype() - 设置变量的类型
  • is_bool() - 检测变量是否是布尔值
  • 类型转换的判别

User Contributed Notes

uasenior at gmail dot com 28-Jan-2020 08:02
<?

// Some way to print boolean value as string

$b = true;

echo ['false', 'true'][$b];

?>
raphael.satyago 20-Jan-2015 09:20
function is_true($val, $return_null=false){
    $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
    return ( $boolval===null && !$return_null ? false : $boolval );
}

// Return Values:

is_true(new stdClass);      // true
is_true([1,2]);             // true
is_true([1]);               // true
is_true([0]);               // true
is_true(42);                // true
is_true(-42);               // true
is_true('true');            // true
is_true('on')               // true
is_true('off')              // false
is_true('yes')              // true
is_true('no')               // false
is_true('ja')               // false
is_true('nein')             // false
is_true('1');               // true
is_true(NULL);              // false
is_true(0);                 // false
is_true('false');           // false
is_true('string');          // false
is_true('0.0');             // false
is_true('4.2');             // false
is_true('0');               // false
is_true('');                // false
is_true([]);                // false
Matt M 09-Jan-2015 05:27
To anyone like me who came here looking for a way to turn any value into a 0/1 that will fit into a MySQL boolean (tinyint) field:

<?php
$tinyint = (int) filter_var($valToCheck, FILTER_VALIDATE_BOOLEAN);
?>

tinyint will be 0 (zero) for values like string "false", boolean false, int 0

tinyint will be 1 for values like string "true", boolean true, int 1

Useful if you are accepting data that might be from a language like Javascript that sends string "false" for a boolean false.
Babak Bandpey 13-May-2014 09:14
I believe that the double negation !! can perform the same task with the same result if your PHP is not up2date

var_dump(!!1, !!0, !!"test", !!"");

outputs:
boolean true

boolean false

boolean true

boolean false

May the life be good to you.
Anonymous 30-Dec-2013 05:12
A misspell in v2.0.
:-)

Hack v2.1

<?php

if( ! function_exists('boolval'))
{
    /**
     * Get the boolean value of a variable
     *
     * @param mixed The scalar value being converted to a boolean.
     * @return boolean The boolean value of var.
     */
    function boolval($var)
    {
        return !! $var;
    }
}

?>
info at lomalkin dot ru 15-Mar-2013 11:08
<?

// Hack for old php versions to use boolval()

if (!function_exists('boolval')) {
        function boolval($val) {
                return (bool) $val;
        }
}
?>


Dumps a string representation of an internal zend value to output

  • ? boolval
  • doubleval ?
  • PHP Manual
  • Variable handling 函数
  • Dumps a string representation of an internal zend value to output

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

debug_zval_dump — Dumps a string representation of an internal zend value to output

说明

debug_zval_dump ( mixed $value , mixed ...$values ) : void

Dumps a string representation of an internal zend value to output.

参数

value

The variable to dump.

values

Further variables to dump.

返回值

没有返回值。

范例

Example #1 debug_zval_dump() example

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump(&$var1);
?>

以上例程会输出：

&string(11) "Hello World" refcount(3)

Note: Beware the refcount

The refcount value returned by this function is non-obvious in certain circumstances. For example, a developer might expect the above example to indicate a refcount of 2. The third reference is created when actually calling debug_zval_dump().

This behavior is further compounded when a variable is not passed to debug_zval_dump() by reference. To illustrate, consider a slightly modified version of the above example:

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump($var1); // not passed by reference, this time
?>

以上例程会输出：

string(11) "Hello World" refcount(1)

Why refcount(1)? Because a copy of $var1 is being made, when the function is called.

This function becomes even more confusing when a variable with a refcount of 1 is passed (by copy/value):

<?php
$var1 = 'Hello World';

debug_zval_dump($var1);
?>

以上例程会输出：

string(11) "Hello World" refcount(2)

A refcount of 2, here, is extremely non-obvious. Especially considering the above examples. So what's happening?

When a variable has a single reference (as did $var1 before it was used as an argument to debug_zval_dump()), PHP's engine optimizes the manner in which it is passed to a function. Internally, PHP treats $var1 like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."

So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.

参见

  • var_dump() - 打印变量的相关信息
  • debug_backtrace() - 产生一条回溯跟踪(backtrace)
  • References Explained
  • » References Explained (by Derick Rethans)

User Contributed Notes

Hayley Watson 09-Jul-2019 11:01
If you're finding the interpretation of refcount confusing, the Xdebug extension offers a function similar to this one, but because the variable name is passed as a string, xdebug_debug_zval() doesn't scribble on the refcount with its own references to the zval.


floatval 的别名

  • ? debug_zval_dump
  • empty ?
  • PHP Manual
  • Variable handling 函数
  • floatval 的别名

doubleval

(PHP 4, PHP 5, PHP 7, PHP 8)

doubleval — floatval() 的别名

描述

此函数是 floatval() 的别名。

Note:

此别名是函数改名之后的遗留问题。在 PHP 旧的版本中由于还没有 floatval() 函数，所以你可能需要用到这个 floatval() 的别名函数。

User Contributed Notes

There are no user contributed notes for this page.


检查一个变量是否为空

  • ? doubleval
  • floatval ?
  • PHP Manual
  • Variable handling 函数
  • 检查一个变量是否为空

empty

(PHP 4, PHP 5, PHP 7, PHP 8)

empty — 检查一个变量是否为空

说明

empty ( mixed $var ) : bool

判断一个变量是否被认为是空的。当一个变量并不存在，或者它的值等同于false，那么它会被认为不存在。如果变量不存在的话，empty()并不会产生警告。

参数

var

待检查的变量

Note:

在 PHP 5.5 之前，empty() 仅支持变量；任何其他东西将会导致一个解析错误。换言之，下列代码不会生效： empty(trim($name))。 作为替代，应该使用trim($name) == false.

没有警告会产生，哪怕变量并不存在。 这意味着 empty() 本质上与 !isset($var) || $var == false 等价。

返回值

当var存在，并且是一个非空非零的值时返回 false 否则返回 true.

以下的东西被认为是空的：

  • "" (空字符串)
  • 0 (作为整数的0)
  • 0.0 (作为浮点数的0)
  • "0" (作为字符串的0)
  • null
  • false
  • array() (一个空数组)
  • $var; (一个声明了，但是没有值的变量)

更新日志

版本 | 说明
5.5.0 | empty() 现在支持表达式了，而不仅仅是变量。
5.4.0 | 检查非数字的字符串偏移量会返回 true.

范例

Example #1 一个简单的 empty() 与 isset() 的比较。

<?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

Example #2 在字符串偏移量上使用empty()

PHP 5.4 修改了当传入的是字符串偏移量时， empty() 的行为

<?php
$expected_array_got_string = 'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));
?>

以上例程在 PHP 5.3 中的输出：

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

以上例程在 PHP 5.4 中的输出：

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

注释

Note: 因为是一个语言构造器而不是一个函数，不能被 可变函数 调用。

Note:

当对一个不可见的对象属性使用 empty() 时， __isset() 方法如果存在的话，它将会被调用。

参见

  • isset() - 检测变量是否已设置并且非 null
  • __isset()
  • unset() - 释放给定的变量
  • array_key_exists() - 检查数组里是否有指定的键名或索引
  • count() - 计算数组中的单元数目，或对象中的属性个数
  • strlen() - 获取字符串长度
  • The type comparison tables

User Contributed Notes

pm1625637 at gmail dot com 05-Dec-2019 02:11
Be careful about this  :

<?php
$del = '';
echo empty($del);
?>

Output : 1
markmanning at gmail dot com 23-Mar-2019 09:15
I normally count() an array, so I wanted to see how empty() would stack up.

<?php
    $test = array();
    $test2 = array();
    for ($x = 0; $x < 1000; $x++)  $test[] = $x;

    $ts = microtime(true);
    for ($x = 0; $x < 100000000; $x++)
    {
        if (count($test))
        {
        }
    }

    echo "Time taken:  " . (microtime(true) - $ts) . " sec\n";
?>

For 100,000,000 comparisons, here are the results against PHP 7.2.16 on my hardware:

count($test):  2.697 sec
count($test2):  2.596 sec
$test === array():  2.579 sec
$test2 === array():  2.552 sec
empty($test):  3.085 sec
empty($test2):  3.113 sec

In short, it doesn't matter what method is used although empty() is actually just ever so slightly slower despite it being a language construct.  YMMV.
fahimcseiiuc at gmail dot com 25-Feb-2019 10:02
<?php

    /*"" (an empty string)
      0 (0 as an integer)
      0.0 (0 as a float)
      "0" (0 as a string)
      NULL
      FALSE
      array() (an empty array)*/

$anEmptyString = "";
empty($anEmptyString);
if(empty($anEmptyString) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";         //line break

$anIntegerNumber = 0;
empty($anIntegerNumber);
if(empty($anIntegerNumber) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";         //line break

$aFloatNumber = 0.0;
empty($aFloatNumber);
if(empty($aFloatNumber) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";       //line break

$aZeroValuedString = "0";
empty($aZeroValuedString);
if(empty($aZeroValuedString) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$aNULL = NULL;
empty($aNULL);
if(empty($aNULL) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$aBooleanFALSE = FALSE;
empty($aBooleanFALSE);
if(empty($aBooleanFALSE) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$anEmptyArray = array();
empty($anEmptyArray);
if(empty($anEmptyArray) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";       //line break

?>
GazetteSDF 21-Sep-2018 09:02
For the verification of a form, to "block" entries such as a simple space or other, I thought of this combination:

function isEmpty($string){
    $val = preg_replace('#[^A-Za-z0-9]+#', '', $string) ;
    $val = trim($string, '');
    return ($string=='') ;
}

This protects entries like: ' ' ,'  -  ', '. - +', ... On entries like name, profession, ... it's helpful
aditycse at gmail dot com 10-Nov-2017 03:58
<?php

/**
 * Used for checking empty objects/array
 * @uses How to check empty objects and array in php code
 * @author Aditya Mehrotra<aditycse@gmail.com>
 */

/**
 * Empty class
 */
class EmptyClass {

}

$obj = new stdClass();
//or any other class empty object
$emptyClassObj = new EmptyClass();
$array = array();

if (empty($array)) {
    echo 'array is empty'; //expected result
} else {
    echo 'array is not empty'; //unexpected result
}
echo "<br>";

if (empty($obj)) {
    echo 'object is empty'; //expected result
} else {
    echo 'object is not empty'; //unexpected result
}
echo "<br>";

if (empty($emptyClassObj)) {
    echo 'EmptyClass is empty'; //expected result
} else {
    echo 'EmptyClass is not empty'; //unexpected result
}
echo "<br>";

//Result SET 1
//array is empty      => expected result
//object is not empty => ouch what happened
//EmptyClass is not empty => ouch what happened

/**
 * So what we do for checking empty object
 * @solution use any known property or check property count
 * Or you can use below method
 * Count function will not return 0 in empty object
 */

//Below line print "Object count:1"
echo 'Object count:' . count($obj);

echo "<br>";

/**
 * This function is used to get object item counts
 * @function getCount
 * @access public
 * @param object|array $var
 * @return integer
 */
function getCount($var) {
    $count = 0;
    if (is_array($var) || is_object($var)) {
        foreach ($var as $value) {
            $count++;
        }
    }
    unset($value);
    return $count;
}

//Running code again with new logic
if (getCount($array) === 0) {
    echo 'array is empty'; //expected result
} else {
    echo 'array is not empty'; //unexpected result
}
echo "<br>";

if (getCount($obj) === 0) {
    echo 'object is empty'; //expected result
} else {
    echo 'object is not empty'; //unexpected result
}

echo "<br>";

if (getCount($emptyClassObj) === 0) {
    echo 'EmptyClass is empty'; //expected result
} else {
    echo 'EmptyClass is not empty'; //unexpected result
}

//Result SET 2
//array is empty    => expected result  ##everything is all right
//object is empty   => expected result  ##everything is all right
//EmptyClass is empty   => expected result  ##everything is all right
xzero at elite7hackers dot net 13-Jul-2017 11:36
Note that empty() will return false on null byte. Eg.

<?php
// Save to variable, so it works on older PHP versions
$null_byte = chr(0); // === \0

var_dump(
    empty(null),
    empty($null_byte)
);
/**
 * Results:
 *
 * bool(true)
 * bool(false)
 */
wranvaud at gmail dot com 02-Jul-2017 06:22
Note that if your variable only has an "end of line" (aka carriage return), PHP_EOL it is not considered as empty. Since end of lines are not always easy to spot this can be confusing.
Claudio Galdiolo 25-Mar-2017 12:20
Warning: an "empty" object is NOT considered to be empty
<?php
$var = new stdClass(); // "empty" object
var_dump(empty($var)); // bool(false)
?>

I don't know if there is a standard way to test for "empty" objects, I personally use array casting:
<?php
$var = new stdClass(); // "empty" object
$var = (array) $var; // cast to empty array
var_dump(empty($var)); // bool(true)
?>
mcfogw at gmail dot com 08-May-2016 02:40
I'm comparing behavior of `!` and `empty()`, find an undocumented behavior here.

just like cast-to-boolean, `empty()` cares about if SimpleXML object is made from emty tags.

`empty(simplexml_load_string('<root />'))` is TRUE

this behavior begins from php 5.1.0~7, in 5.0.x that's FALSE

proof here => https://3v4l.org/74Tc4
Javier Alfonso 11-Mar-2016 01:05
If you test an element of an array (like $_POST['key]), it test if the key doesn't exist or if it exist if its value is empty and never emit a warning.

For who don't want to test what happen if passed an array element here is my test and result.

<?php
$a = array();
$b = array('key');
$c = array('key' => false);
$d = array('key' => 'La verdad nos hace libres');

echo (empty($a['key'])?'A empty':'A not empty'), ' - ', (empty($b['key'])?'B empty':'B not empty'), ' - ', (empty($c['key'])?'C empty':'C not empty'), ' - ', (empty($d['key'])?'D empty':'D not empty');
?>

And the result is:

    A empty - B empty - C empty - D not empty
your dot brother dot t at hotmail dot com 25-Dec-2014 09:38
(experienced in PHP 5.6.3) The `empty()` can't evaluate `__get()` results explicitly, so the `empty()` statement bellow always renders true
<?php
class Juice extends Liquid{
   protected $apple;
   protected $orange;
   public function __get($name) {
      return $this->$name;
   }
   public function __construct($apple, $orange) {
      $this->apple = $apple;
      $this->orange = $orange;
   }
}

class Glass {
   protected $liquid;
   public function __get($name) {
      return $name == "liquid" ? $this->liquid : false;
   }
   public function __construct() {
      $this->juice = new Juice(3, 5);
   }
}

$glass = new Glass();
var_dump(empty($this->liquid->apple));

/**
 * The output is:
 * bool(true)
 */
?>

The correct way is to force the evaluation of `__get()` first, by using extra braces around implicit statements like this:
<?php
var_dump(empty(($this->liquid->apple)));

/**
 * The output is:
 * bool(false)
 */
?>

So if you are using packages that utilize object oriented designs and magic methods like `__get()`, it's a good practice to always use double braces for `empty()` calls.
chrisdmiddleton at gmail dot com 09-Sep-2014 08:37
If you want to use empty() to evaluate an expression (not a variable), and you don't have PHP 5.5+, you can do it by wrapping the call to empty in a function, like so:
<?php
function is_empty($var) {

    return empty($var);

}
?>
Then you can do something like
<?php
if(is_empty(NULL)) {
 /* ... */
}
?>
without issue, since the local variable $var is being tested rather than the expression in the function call itself.
Nanhe Kumar 31-Jan-2014 10:17
<?php
/**
* @author :  Nanhe Kumar <nanhe.kumar@gmail.com>
* List of all empty values
**/

$testCase = array(
    1 => '',
    2 => "",
    3 => null,
    4 => array(),
    5 => FALSE,
    6 => NULL,
    7=>'0',
    8=>0,

);

foreach ($testCase as $k => $v) {
    if (empty($v)) {
        echo "<br> $k=>$v is empty";
    }
}
/**
Output
1=> is empty
2=> is empty
3=> is empty
4=>Array is empty
5=> is empty
6=> is empty
7=>0 is empty
8=>0 is empty
**/
?>
martin dot aarhof at gmail dot com 15-Mar-2012 08:38
<?php
$str = '            ';
var_dump(empty($str)); // boolean false
?>

So remember to trim your strings first!

<?php
$str = '        ';
$str = trim($str);
var_dump(empty($str)); // boolean true
?>
qeremy 07-Mar-2012 03:33
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _empty($val) { return empty($val); }
?>
chris dot wisefool at gmail dot com 09-Sep-2011 12:44
Note that checking the existence of a subkey of an array when that subkey does not exist but the parent does and is a string will return false for empty.

i.e.

<?php
$params = array('search'=>'1');
empty($params['search']['filter']); # returns false
?>

This is correct, per the documentation (http://php.net/manual/en/language.types.string.php); quite a bit down the page is the Warning: "Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer." ) I didn't receive a warning but perhaps that's correct too...depends on whether the string -> integer conversion is considered "illegal": "Illegal offset type emits E_NOTICE."

(i.e. since $params['search'] is a string, the 'filter' subscript is converted to 0, so the test becomes empty($params['search'][0]), which is obviously false), but it tripped me up enough to mistakenly file a bug report (which I've since closed).
steven at nevvix dot com 02-May-2011 09:16
When you need to accept these as valid, non-empty values:
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)

<?php
function is_blank($value) {
    return empty($value) && !is_numeric($value);
}
?>

This is similar to Rails' blank? method.
phpsort 21-Jan-2011 11:13
I'm summarising a few points on empty() with inaccessible properties, in the hope of saving others a bit of time. Using PHP 5.3.2.
<?php
class MyClass {
    private $foo = 'foo';
}
$myClass = new MyClass;
echo $myClass->foo;
?>
As expected, this gives "Fatal error: Cannot access private property MyClass::$foo".
But substitute the line
if (empty($myClass->foo)) echo 'foo is empty'; else echo 'foo is not empty';
and we get the misleading result "foo is empty".
There is NO ERROR OR WARNING, so this is a real gotcha. Your code will just go wrong silently, and I would say it amounts to a bug.
If you add two magic functions to the class:
public function __get($var) { return $this->$var; }
public function __isset($var) { return isset($this->$var); }
then we get the expected result. You need both functions.
For empty($myClass->foo), I believe PHP calls __isset, and if that is true returns the result of empty on the result of __get. (Some earlier posts wrongly suggest PHP just returns the negation of __isset).
BUT ...
See the earlier post by php at lanar dot com. I confirm those results, and if you extend the test with isset($x->a->b->c) it appears that __isset is only called for the last property in the chain. Arguably another bug. empty() behaves in the same way. So things are not as clear as we might hope.
See also the note on empty() at
http://uk3.php.net/manual/en/language.oop5.overloading.php
Clear as mud!
e dot klerks at i-bytes dot nl 08-Nov-2010 06:16
To make an empty function, which only accepts arrays, one can use type-hinting:

<?php
// emptyArray :: [a] -> Bool

function emptyArray(array $xs){
 return empty($xs);
}
?>

Type hinting is a good thing to use in your code, because it makes it more easy to reason about your code. Besides that, it automatically documents the code.
rodolphe dot bodeau at free dot fr 25-Oct-2010 06:37
Be careful, if "0" (zero as a string), 0 (zero as an integer) and -0 (minus zero as an integer) return true, "-0" (minus zero as a string (yes, I already had some customers that wrote -0 into a form field)) returns false. You need to cast your variable before testing it with the empty() function :

<?php
$var = "-0";
echo empty($var);  // returns false
$var = (int) $var; // casts $var as an integer
echo empty($vat);  // returns true
?>
ehsmeng 21-Sep-2010 05:25
I can't use empty() in all situations because '0' is usually not considered empty to me. I did a quick benchmark over the most common ways of testing it. '' == var suffers from '' == 0 is true so that's just there for curiosity.

<?php
    $microtimeref = microtime(true);
    $a = 0;
    $b = 'asd';
    for ($i = 0; $i < 5000000; $i++)
    {
        if (0 == mb_strlen ($b))
        {
            $a++;
        }
    }
    echo "Total time 0 == mb_strlen(var): <b>" . round(microtime(true) - $microtimeref,3) . 's</b><br />';
?>

The results:

Total time 0 == mb_strlen(var): 3.141s
Total time 0 === strlen(var): 2.904s
Total time 0 == strlen(var): 2.878s
Total time '' == var: 1.774s
Total time '' === var: 1.706s
Total time empty(var): 1.496s

Thus '' === var will be my zero length string test.
marko dot crni at gmail dot com 16-Sep-2010 11:06
Calling non existing object property, empty($object->prop), will trigger __isset(), the same way as isset($object->prop) does, but there is one difference. If __isset() returns TRUE, another call to __get() will be made and actual return value will be result of empty() and result of __get().
aidan1103 at yahoo dot com 26-Mar-2010 10:11
empty() should not necessarily return the negation of the __isset() magic function result, if you set a data member to 0, isset() should return true and empty should also return true.  A simpler implementation of the __isset magic function would be:

public function __isset($key) {
  return isset($this->{$key});
}

I don't understand why this isn't included in stdClass and inherited by default.
Janci 24-Aug-2009 08:57
Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it's noted in the documentation above, I think it's worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add  __isset() magic function to your class:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
    public function __isset($key)
    {
        if (isset($this->_items[$key])) {
            return (false === empty($this->_items[$key]));
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // false, finally!
?>

It actually seems that empty() is returning negation of the __isset() magic function result, hence the negation of the empty() result in the __isset() function above.
denobasis-bozic et yahoo.com 18-Jul-2009 04:54
test if all multiarray's are empty

<?php
function is_multiArrayEmpty($multiarray) {
    if(is_array($multiarray) and !empty($multiarray)){
        $tmp = array_shift($multiarray);
            if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
                return false;
            }
            return true;
    }
    if(empty($multiarray)){
        return true;
    }
    return false;
}

$testCase = array (
0 => '',
1 => "",
2 => null,
3 => array(),
4 => array(array()),
5 => array(array(array(array(array())))),
6 => array(array(), array(), array(), array(), array()),
7 => array(array(array(), array()), array(array(array(array(array(array(), array())))))),
8 => array(null),
9 => 'not empty',
10 => "not empty",
11 => array(array("not empty")),
12 => array(array(),array("not empty"),array(array()))
);

foreach ($testCase as $key => $case ) {
    echo "$key is_multiArrayEmpty= ".is_multiArrayEmpty($case)."<br>";
}
?>

OUTPUT:
========

0 is_multiArrayEmpty= 1
1 is_multiArrayEmpty= 1
2 is_multiArrayEmpty= 1
3 is_multiArrayEmpty= 1
4 is_multiArrayEmpty= 1
5 is_multiArrayEmpty= 1
6 is_multiArrayEmpty= 1
7 is_multiArrayEmpty= 1
8 is_multiArrayEmpty= 1
9 is_multiArrayEmpty=
10 is_multiArrayEmpty=
11 is_multiArrayEmpty=
12 is_multiArrayEmpty=
mlibazisi mabandla 28-May-2009 02:47
in cases when "0" is not intended to be empty, here is a simple function to safely test for an empty string (or mixed variable):

<?php
function _empty($string){
     $string = trim($string);
     if(!is_numeric($string)) return empty($string);
     return FALSE;
}
?>
thomas at thomasnoest dot nl 28-Nov-2008 01:54
Note on the selfmade empty function below:

function_exists() returns false on language constructs and empty is a language construct.
Anonymous 20-Aug-2008 02:41
To add on to what anon said, what's happening in john_jian's example seems unusual because we don't see the implicit typecasting going on behind the scenes.  What's really happening is:

$a = '';
$b = 0;
$c = '0';

(int)$a == $b -> true, because any string that's not a number gets converted to 0
$b==(int)$c -> true, because the int in the string gets converted
and
$a==$c -> false, because they're being compared as strings, rather than integers.  (int)$a==(int)$c should return true, however.

Note: I don't remember if PHP even *has* typecasting, much less if this is the correct syntax.  I'm just using something for the sake of examples.
tom at tomwardrop dot com 22-May-2008 05:01
In reply to "admin at ninthcircuit dot info",

Using str_replace is unnecessary. I would encourage the use of trim which would most likely be faster (haven't tested) and easier. Trim also takes care of other white space like line breaks and tabs. Actually, in most of the applications I code, I use a multi-dimensional array map function with trim on the Super Globals such as $_POST, $_GET and $_COOKIE as so far, there hasn't been an instance where I would want any user input to begin or end with whitespace. The good thing about doing this is that you never have to worry about 'trimming' your input which makes your code easier and more reliable (incase you forget to trim some input).
Greg Hartwig 02-May-2008 02:55
David from CodeXplorer:
>> The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check.
>> So, don't bother using EMPTY in the real world.

This is NOT true.  empty() will not generate warnings if you're testing against an undefined variable as a simple boolean check will.  On production systems, warnings are usually shut off, but they are often active on development systems.

You could test a flag with
   <?php if ($flagvar)  ... ?>
but this can generate a warning if $flagvar is not set.

Instead of
   <?php if (isset($flagvar) && $flagvar)  ... ?>
you can simply use
   <?php if (!empty($flagvar))  ... ?>

for easy readability without warnings.
EllisGL 04-Oct-2007 02:48
Here's what I do for the zero issue issue:
if($val == '' && $val !== 0 && $val !== '0')
rkulla2 at gmail dot com 05-Sep-2007 03:57
Since I didn't like how empty() considers 0 and "0" to be empty (which can easily lead to bugs in your code), and since it doesn't deal with whitespace, i created the following function:

<?php
function check_not_empty($s, $include_whitespace = false)
{
    if ($include_whitespace) {
        // make it so strings containing white space are treated as empty too
        $s = trim($s);
    }
    return (isset($s) && strlen($s)); // var is set and not an empty string ''
}
?>

Instead of saying if (!empty($var)) { // it's not empty } you can just say if (check_not_empty($var)) { // it's not empty }.

If you want strings that only contain whitespace (such as tabs or spaces) to be treated as empty then do: check_not_empty($var, 1)

If you want to check if a string IS empty then do: !check_not_empty($var).

So, whenever you want to check if a form field both exists and contains a value just do: if (check_not_empty($_POST['foo'], 1))

no need to do if (isset() && !empty()) anymore =]
jmarbas at hotmail dot com 01-Jul-2005 09:10
empty($var) will return TRUE if $var is empty (according to the definition of 'empty' above) AND if $var is not set.

I know that the statement in the "Return Values" section of the manual already says this in reverse:

"Returns FALSE if var has a non-empty and non-zero value."

but I was like "Why is this thing returning TRUE for unset variables???"... oh i see now... Its supposed to return TRUE for unset variables!!!

<?php
  ini_set('error_reporting',E_ALL);
  ini_set('display_errors','1');
  empty($var);
?>
paul at worldwithoutwalls dot co dot uk 22-May-2004 10:09
Note the exceptions when it comes to decimal numbers:

<?php
$a = 0.00;
$b = '0.00';
echo (empty($a)? "empty": "not empty"); //result empty
echo (empty($b)? "empty": "not empty"); //result not empty
//BUT...
$c = intval($b);
echo (empty($c)? "empty": "not empty"); //result empty
?>

For those of you using MySQL, if you have a table with a column of decimal type, when you do a SELECT, your data will be returned as a string, so you'll need to do apply intval() before testing for empty.

e.g.
TABLE t has columns id MEDIUMINT and d DECIMAL(4,2)
and contains 1 row where id=1, d=0.00
<?php
$q = "SELECT * FROM t";
$res = mysql_query($q);
$row = mysql_fetch_assoc($res);
echo (empty($row['d'])? "empty": "not empty"); //result not empty
?>


获取变量的浮点值

  • ? empty
  • get_defined_vars ?
  • PHP Manual
  • Variable handling 函数
  • 获取变量的浮点值

floatval

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

floatval — 获取变量的浮点值

描述

floatval ( mixed $var ) : float

返回变量 var 的 float 数值。

var 可以是任何标量类型。你不能将 floatval() 用于数组或对象。

<?php
$var = '122.34343The';
$float_value_of_var = floatval ($var);
print $float_value_of_var; // 打印出 122.34343
?>

参见 intval()、strval()、settype() 和 类型戏法。

User Contributed Notes

iliyazelenkog at gmail dot com 02-Nov-2018 10:51
(float) would be more performant here (up to 6x times faster).

intval, floatval, doubleval, strva for PHP4 functions (intval, floatval, doubleval, strval), in PHP5 use type casting construction (i.e. '(type) parameter').
radler63 at hotmail dot com 16-Feb-2018 12:27
I get the following disturbing results:
var_dump string(10) "?0.01333"
echo the string=?0.01333
echo (float)string=0
echo floatval(string)=0

The string is an outcome of array_map('str_getcsv', file(...
I can't find the characters 8-10

thanks
T-Soloveychik at ya.ru 03-Mar-2017 02:23
Float value less than 0.0001 (0.0000999999999999995) will be converted by floatval to scientific notation (exponential notation):
<?php

var_dump(floatval(0.0000999999999999995)); # >> float(0,0001)

var_dump(floatval("0.000099")); # >> float(9.9E-5)

var_dump((string)floatval(0.000099)); # >> string(6) "9.9E-5"
pierpaolocira 15-Nov-2016 11:41
Be aware the last tofloat($num).

In theory it is very useful to have a function "separator-agnostic" (I think "locale based" solutions are useless if you have to parse a user file that can have a locale different to the server).

But this can lead to misinterpretations; in short: "123,456" is "123.456" (so comma used as decimal separator) or "123456" (comma used as thousand separator).

In any case, if you really want to use it, please don't forget that this function doesn't manage negative numbers.
movila dot e dot v at gmail dot com 05-Jul-2016 08:05
<?php
       $price = '1.299,00 EUR';
    //$price = 'EUR 1.299,00';
    //$price = '$1,745.09';
    //$price = '$14';
    //$price = '$.14';

    function floatValue($str){
        if(preg_match("/([0-9\.,-]+)/", $str, $match)){
            $value = $match[0];
            if( preg_match("/(\.\d{1,2})$/", $value, $dot_delim) ){
                $value = (float)str_replace(',', '', $value);
            }
            else if( preg_match("/(,\d{1,2})$/", $value, $comma_delim) ){
                $value = str_replace('.', '', $value);
                $value = (float)str_replace(',', '.', $value);
            }
            else
                $value = (int)$value;
        }
        else {
            $value = 0;
        }
        return $value;
    }

    echo floatValue($price);
/*
    1.299,00
    1.299,00
    1,745.09
    14
    0.14
*/
?>
Alexey M 23-Mar-2016 02:28
There is much easier way to deal with formatted numbers:

<?php
$str = '13,232.95';
$var = (double)filter_var($str, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
var_dump($var);
?>
double(13232.95)
zfcb13 at gmail dot com 24-Oct-2015 10:18
More elegant function with selection of decimal point (deafault ,):
<?php
function floatvaldec($v, $dec=',') { return floatval(ereg_replace("," , "." , ereg_replace("[^-0-9$dec]","",$v))); }

// examples:
echo '<br>'.floatvaldec('somthing123.456.789,12Euro') ;
echo '<br>'.floatvaldec('x123,456 789.12 Euro', '.') ;
echo '<br>'.floatvaldec('123.456 789,12$') ;
?>
brewal dot renault at gmail dot com 26-Feb-2014 09:25
This function takes the last comma or dot (if any) to make a clean float, ignoring thousand separator, currency or any other letter :

function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
        ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);

    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    }

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
        preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
    );
}

$num = '1.999,369�';
var_dump(tofloat($num)); // float(1999.369)
$otherNum = '126,564,789.33 m2';
var_dump(tofloat($otherNum)); // float(126564789.33)

Demo : http://codepad.org/NW4e9hQH
PapaPinguoin 31-Oct-2011 07:26
To view the very large and very small numbers (eg from a database DECIMAL), without displaying scientific notation, or leading zeros.

FR : Pour afficher les très grand et très petits nombres (ex. depuis une base de données DECIMAL), sans afficher la notation scientifique, ni les zéros non significatifs.

<?php
function floattostr( $val )
{
    preg_match( "#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o );
    return $o[1].sprintf('%d',$o[2]).($o[3]!='.'?$o[3]:'');
}
?>

<?php
echo floattostr("0000000000000001");
echo floattostr("1.00000000000000");
echo floattostr("0.00000000001000");
echo floattostr("0000.00010000000");
echo floattostr("000000010000000000.00000000000010000000000");
echo floattostr("-0000000000000.1");
echo floattostr("-00000001.100000");

// result
// 1
// 1
// 0.00000000001
// 0.0001
// 10000000000.0000000000001
// -0.1
// -1.1

?>
secretr at NOSPAM dot e107 dot org 03-Jan-2011 08:37
setlocale() and floatval() duo could break your DB queries in a very simple way:

<?php
setlocale(LC_ALL, 'bg_BG', 'bgr_BGR');
echo floatval(0.15); // output 0,15
?>

You would need simple workaround like:

<?php
function number2db($value)
{
    $larr = localeconv();
    $search = array(
        $larr['decimal_point'],
        $larr['mon_decimal_point'],
        $larr['thousands_sep'],
        $larr['mon_thousands_sep'],
        $larr['currency_symbol'],
        $larr['int_curr_symbol']
    );
    $replace = array('.', '.', '', '', '', '');

    return str_replace($search, $replace, $value);
}

setlocale(LC_ALL, 'bg_BG', 'bgr_BGR');
$testVal = floatval(0.15); // result 0,15
var_dump($testVal, number2db($testVal));

// Result:
// float(0,15)
// string(4) "0.15"
?>
chris at georgakopoulos dot com 29-Jul-2009 08:12
locale aware floatval:

<?php
function ParseFloat($floatString){
    $LocaleInfo = localeconv();
    $floatString = str_replace($LocaleInfo["mon_thousands_sep"] , "", $floatString);
    $floatString = str_replace($LocaleInfo["mon_decimal_point"] , ".", $floatString);
    return floatval($floatString);
}
?>
ted devito 09-Mar-2009 09:10
i noticed all (well, unless i missed something) the functions working with decimals destroy trailing decimal places. this function restores them in case you want to be able to display a consistent precision for users.

<?php
function decimal($val, $precision = 0) {
    if ((float) $val) :
        $val = round((float) $val, (int) $precision);
        list($a, $b) = explode('.', $val);
        if (strlen($b) < $precision) $b = str_pad($b, $precision, '0', STR_PAD_RIGHT);
        return $precision ? "$a.$b" : $a;
    else : // do whatever you want with values that do not have a float
        return $val;
    endif;
}
?>
info at marc-gutt dot de 26-Aug-2008 03:55
<?php
function floatvalue($value) {
     return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}
?>

It is much shorter and able to handle those one, too:
xx,-
xx,--
xx'xxx,xx

After using floatvalue() you can go forward with number_format() as usual.
Michiel 30-Jul-2008 05:21
The last getFloat() function is not completely correct.

1.000.000 and 1,000,000 and its negative variants are not correctly parsed. For the sake of comparing and to make myself clear I use the name parseFloat in stead of getFloat for the new function:

<?php
function parseFloat($ptString) {
            if (strlen($ptString) == 0) {
                    return false;
            }

            $pString = str_replace(" ", "", $ptString);

            if (substr_count($pString, ",") > 1)
                $pString = str_replace(",", "", $pString);

            if (substr_count($pString, ".") > 1)
                $pString = str_replace(".", "", $pString);

            $pregResult = array();

            $commaset = strpos($pString,',');
            if ($commaset === false) {$commaset = -1;}

            $pointset = strpos($pString,'.');
            if ($pointset === false) {$pointset = -1;}

            $pregResultA = array();
            $pregResultB = array();

            if ($pointset < $commaset) {
                preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
            }
            preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
            if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
                    || strstr($preResultA[0],$pregResultB[0]) == 0
                    || !$pointset))) {
                $numberString = $pregResultA[0];
                $numberString = str_replace('.','',$numberString);
                $numberString = str_replace(',','.',$numberString);
            }
            elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
                    || strstr($pregResultB[0],$preResultA[0]) == 0
                    || !$commaset)) {
                $numberString = $pregResultB[0];
                $numberString = str_replace(',','',$numberString);
            }
            else {
                return false;
            }
            $result = (float)$numberString;
            return $result;
}
?>

Comparing of float parsing functions with the following function:

<?php
function testFloatParsing() {
    $floatvals = array(
        "22 000,76",
        "22.000,76",
        "22,000.76",
        "22 000",
        "22,000",
        "22.000",
        "22000.76",
        "22000,76",
        "1.022.000,76",
        "1,022,000.76",
        "1,000,000",
        "1.000.000",
        "1022000.76",
        "1022000,76",
        "1022000",
        "0.76",
        "0,76",
        "0.00",
        "0,00",
        "1.00",
        "1,00",
        "-22 000,76",
        "-22.000,76",
        "-22,000.76",
        "-22 000",
        "-22,000",
        "-22.000",
        "-22000.76",
        "-22000,76",
        "-1.022.000,76",
        "-1,022,000.76",
        "-1,000,000",
        "-1.000.000",
        "-1022000.76",
        "-1022000,76",
        "-1022000",
        "-0.76",
        "-0,76",
        "-0.00",
        "-0,00",
        "-1.00",
        "-1,00"
    );

    echo "<table>
        <tr>
            <th>String</th>
            <th>floatval()</th>
            <th>getFloat()</th>
            <th>parseFloat()</th>
        </tr>";

    foreach ($floatvals as $fval) {
        echo "<tr>";
        echo "<td>" . (string) $fval . "</td>";

        echo "<td>" . (float) floatval($fval) . "</td>";
        echo "<td>" . (float) getFloat($fval) . "</td>";
        echo "<td>" . (float) parseFloat($fval) . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}
?>
steve at opilo dot net 20-Jul-2008 06:07
Most of the functions listed here that deal with $ and , are unnecessarily complicated. You can use ereg_replace() to strip out ALL of the characters that will cause floatval to fail in one simple line of code:

<?php $output = floatval(ereg_replace("[^-0-9\.]","",$input)); ?>
leprau at leprau dot de 19-Jul-2007 09:26
For those of you, who are looking for a function that rips the first,
but longest possible float (or at least integer) from a string,
like 123.45 from the string "Price: 123,45$"

If no useable value is found, the function returns false.

Checks for both comma and dot as decimal-separator,
but does not check for 3 digits between thousands,
so 1,234.5 is as valid as 1,23,4.5 (both will return 1234.5)

12,.3 will return 12
1,000,000 will return 1000.0 !

(if thousands separator is defined,
decimals should be defined too ...
in fact I was too lazy to check for that too)

Here you go, and feel free to optimize the function ;)
<?php
function getFloat($pString) {
    if (strlen($pString) == 0) {
            return false;
    }
    $pregResult = array();

    $commaset = strpos($pString,',');
    if ($commaset === false) {$commaset = -1;}

    $pointset = strpos($pString,'.');
    if ($pointset === false) {$pointset = -1;}

    $pregResultA = array();
    $pregResultB = array();

    if ($pointset < $commaset) {
        preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
    }
    preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
    if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
            || strstr($preResultA[0],$pregResultB[0]) == 0
            || !$pointset))) {
        $numberString = $pregResultA[0];
        $numberString = str_replace('.','',$numberString);
        $numberString = str_replace(',','.',$numberString);
    }
    elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
            || strstr($pregResultB[0],$preResultA[0]) == 0
            || !$commaset)) {
        $numberString = $pregResultB[0];
        $numberString = str_replace(',','',$numberString);
    }
    else {
        return false;
    }
    $result = (float)$numberString;
    return $result;
}
?>
aa at geb-team dot de 04-Sep-2006 08:03
@pillepop2003 at yahoo dot de

<?php
float('-100.00', array('single_dot_as_decimal' => true)); // whoops, returns -10000
?>

use: "/^[0-9-]*[\.]{1}[0-9-]+$/"
instead of: "/^[0-9]*[\.]{1}[0-9-]+$/"
19-Apr-2005 05:30
you can also use typecasting instead of functions:

(float) $value;
pillepop2003 at yahoo dot de 14-Dec-2004 02:38
Use this snippet to extract any float out of a string. You can choose how a single dot is treated with the (bool) 'single_dot_as_decimal' directive.
This function should be able to cover almost all floats that appear in an european environment.

<?php

    function float($str, $set=FALSE)
    {
        if(preg_match("/([0-9\.,-]+)/", $str, $match))
        {
            // Found number in $str, so set $str that number
            $str = $match[0];

            if(strstr($str, ','))
            {
                // A comma exists, that makes it easy, cos we assume it separates the decimal part.
                $str = str_replace('.', '', $str);    // Erase thousand seps
                $str = str_replace(',', '.', $str);    // Convert , to . for floatval command

                return floatval($str);
            }
            else
            {
                // No comma exists, so we have to decide, how a single dot shall be treated
                if(preg_match("/^[0-9]*[\.]{1}[0-9-]+$/", $str) == TRUE && $set['single_dot_as_decimal'] == TRUE)
                {
                    // Treat single dot as decimal separator
                    return floatval($str);

                }
                else
                {
                    // Else, treat all dots as thousand seps
                    $str = str_replace('.', '', $str);    // Erase thousand seps
                    return floatval($str);
                }
            }
        }

        else
        {
            // No number found, return zero
            return 0;
        }
    }

// Examples

echo float('foo 123,00 bar'); // returns 123.00
echo float('foo 123.00 bar' array('single_dot_as_decimal'=> TRUE)); //returns 123.000
echo float('foo 123.00 bar' array('single_dot_as_decimal'=> FALSE)); //returns 123000
echo float('foo 222.123.00 bar' array('single_dot_as_decimal'=> TRUE)); //returns 222123000
echo float('foo 222.123.00 bar' array('single_dot_as_decimal'=> FALSE)); //returns 222123000

// The decimal part can also consist of '-'
echo float('foo 123,-- bar'); // returns 123.00

?>

Big Up.
Philipp
anonymous at start dot be 15-Jun-2004 07:00
Easier-to-grasp-function for the ',' problem.

<?php
function Getfloat($str) {
  if(strstr($str, ",")) {
    $str = str_replace(".", "", $str); // replace dots (thousand seps) with blancs
    $str = str_replace(",", ".", $str); // replace ',' with '.'
  }

  if(preg_match("#([0-9\.]+)#", $str, $match)) { // search for number that may contain '.'
    return floatval($match[0]);
  } else {
    return floatval($str); // take some last chances with floatval
  }
}

echo Getfloat("$ 19.332,35-"); // will print: 19332.35
?>
vickers at hotpop dot com 26-Jan-2004 03:45
floatval() does not work with "$35,234.43", as it could not handle the '$' and the ','.  The following takes care of all values, such that only numeric and the decimal sign are input into floatval().  (It probably shows I'm an old 'c' guy)...this function only lightly tested.

<?php
function strtflt($str) {
    $il = strlen($str);
    $flt = "";
    $cstr = "";

    for($i=0;$i<$il;$i++) {
        $cstr = substr($str, $i, 1);
        if(is_numeric($cstr) || $cstr == ".")
            $flt = $flt.$cstr;
    }
    return floatval($flt);
}
?>

Richard Vickers
vickers@hotpop.com
Zipi 25-Apr-2003 02:51
This function converts a string to a float no matter is the decimal separator dot (.) or comma (,). It also converts integers correctly. It takes the digits from the beginning of the string and ignores all other characters.

<?php
function floatval($strValue) {
   $floatValue = ereg_replace("(^[0-9]*)(\\.|,)([0-9]*)(.*)", "\\1.\\3", $strValue);
   if (!is_numeric($floatValue)) $floatValue = ereg_replace("(^[0-9]*)(.*)", "\\1", $strValue);
   if (!is_numeric($floatValue)) $floatValue = 0;
   return $floatValue;
  }
?>

-Zipi (Finland)
jason at shadonet dot com 07-Mar-2003 07:07
Instead of using floatval which only appeared in PHP 4.2 you could juse use $variable = (float)$variable

This function doesn't seem to add any functionality that wasn't already there.


返回由所有已定义变量所组成的数组

  • ? floatval
  • get_resource_id ?
  • PHP Manual
  • Variable handling 函数
  • 返回由所有已定义变量所组成的数组

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

get_defined_vars — 返回由所有已定义变量所组成的数组

描述

get_defined_vars ( ) : array

此函数返回一个包含所有已定义变量列表的多维数组，这些变量包括环境变量、服务器变量和用户定义的变量。

<?php
$b = array(1,1,2,3,5,8);

$arr = get_defined_vars();

// 打印 $b
print_r($arr["b"]);

// 打印 PHP 解释程序的路径（如果 PHP 作为 CGI 使用的话）
// 例如：/usr/local/bin/php
echo $arr["_"];

// 打印命令行参数（如果有的话）
print_r($arr["argv"]);

// 打印所有服务器变量
print_r($arr["_SERVER"]);

// 打印变量数组的所有可用键值
print_r(array_keys(get_defined_vars()));
?>

参见 get_defined_functions() 和 get_defined_constants()。

User Contributed Notes

antonfedonyuk at gmail dot com 05-Feb-2021 09:29
NOTE: when you call code by eval() PHP append self vars to result, they have "__" prefix ("__source_code" and "__bootstrap_file" in PHP 7.3).

Fix:
<?php
function filter_eval_vars(array $vars): array
{
    foreach ($vars as $key => $value) {
         if ($key[0] === '_' && $key[1] === '_') {
              unset($vars[$key]);
         }
    }
    return $vars;
}

?>
npelov at croler dot net 02-Feb-2021 12:35
get_defined_vars() returns all variables - locally defined vars and global vars (well actually only super globals). If you need local vars only  - for example you need to get variables from a file - let's say config.php and you don't want a missing value to be replaced with a global defined somewhere else.

<?php

  /**
   * Filters out global vars from get_defined_vars() in order to get local vars only
   * @param array $localVars pass get_defined_vars() here
   *
   * @return array local vars only
   */
  function removeGlobals(array $localVars) {
    return array_diff_key($localVars, $GLOBALS);
  }

  define('CONFIG_FILE_PATH', '/path/to/config.php');
  function readConfig() {
    require CONFIG_FILE_PATH;
    $config = removeGlobals(get_defined_vars());
    return $config;
  }

?>
Joey 11-Jun-2018 07:22
I posted here before about "this" being in get_defined_vars.

It turns out it's not always there but in certain cases it will inexplicably appear.

    php -r '
    class Test {
        public function a() {var_dump(array_keys(get_defined_vars()));$a = 123;}
        public function b() {var_dump(array_keys(get_defined_vars()));$this;}
    }
    $t = new Test();
    $t->a();
    $t->b();
    '

    array()
    array('this')

This does not happen in PHP 7.2 but will happen in PHP 5.6.
Joey 24-Apr-2018 08:30
Some comments here point out that this function wont return references. It does however return names and names are "references".

I would not recommend the suggestions here that convert it to references.

Instead...

    public function x($a, $b, $c) {
        foreach(array_keys(get_defined_vars()) as $key)
            if($key !== 'this')
                $this->y(${$key});
    }

    public function y(&$input) {
        $input++;
    }

Instead of ${} you can also use $$.

I have done some whacky things in my time to make extremely generic code but I've never had to do anything like the above. It might not even work (but should since it's no different to $a[$key]).

You could also do $$key++ but I've never seen code like that which wasn't horrifically bad (using dynamic where dynamic isn't beneficial).

If you're doing something like that then give it additional scrutiny.
Joey 24-Apr-2018 08:20
I occasionally use this as a hack to convert arguments to an array where terseness is needed (dealing with legacy code, etc).

However in an object context it'll also pull in $this.

Make sure to unset it. If you map it to properties or an array then setting the key this wont be an error.

I recommend using a wrapper function that strips this from the result.
istiaquealamjoy at gmail dot com 23-May-2017 05:37
for all those who don't know how to us this function. copy and run this code in your computer  .

note: you need to know what superglobals are.....

<?php

$A = 5  ;
$B = 10 ;
$C = 15 ;
$D = 20 ;

$F = get_defined_vars($A);

var_dump($F);  //don't use echo. it will show error

?>

Result : will show all superglobals status along with your defined
variables along with its values
sergeyzuzic at mail dot ru 14-Nov-2015 10:35
dirty code sample:

print_r(compact(array_keys(get_defined_vars())));
mail at mkharitonov dot net 01-Jun-2014 07:14
Reference variables are returned by reference (tested on PHP 5.5.11):
<?php
$a = null;
$b = &$a;
get_defined_vars()['b'] = 4;
var_dump($b); // int(4)
?>
ryanlwh at yahoo dot com 02-Apr-2013 05:28
Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.

<?php
// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$foo = 'foo';
$bar = 'bar';

// Get all the variables defined in current scope
$vars = array_diff(get_defined_vars(),$vars);

echo '<pre>';
print_r($vars);
echo '</pre>';
?>
Anonymous 18-Apr-2011 05:32
get_defined_vars() returns ALL the vars (in the current scope), what if you just want all YOUR vars, not PHP's super-globals?

<?php
    var_export(array_diff(get_defined_vars(), array(array())));
?>

Example...

<?php
    $TOP_LEVEL_VAR=1;
    var_export(array_diff(get_defined_vars(), array(array())));
?>

The output (with register_globals off) should be...

array (
  'TOP_LEVEL_VAR' => 1,
)

...it perfectly eliminated all the super-globals, without me having to specify them! (note with register_globals on, the output includes those globals, then TOP_LEVEL_VAR).

Here it is, as a function...(it's the best I could do {I can't call get_defined_vars() inside get_user_defined_vars() cuz of the scope issue}).

<?php
    header('Content-type: text/plain');

    $TOP_LEVEL_VAR=1;

    echo 'register_globals(';
    echo ini_get('register_globals');
    echo ') '.phpversion()."\n";

    var_export(get_user_defined_vars(get_defined_vars()));

    function get_user_defined_vars($vars) {
        return array_diff($vars, array(array()));
    }
?>

Note that originally I had an array of the super-globals I wanted removed from get_defined_vars()'s array, then I noticed even an empty double-array, array(array()), made it give me the correct result. Weird.

This was tested on PHP 5.2.9.
meint at meint dot net 11-Jan-2011 12:46
Please be aware that function_get_vars only returns the variables defined at the point before you call the function_get_vars function, it does not scan the entire function for you, only the lines before you call it.
Johan de Vries 17-Jun-2010 08:09
Note that this only returns things you've used. See http://bugs.php.net/bug.php?id=52110 . So don't expect this to have the $this entry, unless you assign $this to return $this.
donovan at example dot com 21-Oct-2008 09:15
As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

<?php

// define a variable
$my_var = "foo";

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars["my_var"] = "bar";

echo $my_var, "\n";

?>

will output "foo" (the original value). It'd be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

<?php

$defined_vars = array();
$var_names = array_keys(get_defined_vars());

foreach ($var_names as $var_name)
{
    $defined_vars[$var_name] =& $$var_name;
}

?>
SyCo 21-Aug-2008 03:52
Here's a very simple function for debugging. It's far from perfect but I find it very handy. It outputs the var value and the var name on a new line. The problem is it'll echo any vars and their name if they share the same value. No big deal when debugging and saves the hassle of writing the HTML and var name when echoing a variable. (ev=echo variable). Using get_defined_vars() inside a function renames the var name to the functions variable so isn't as useful for debugging. Of course, you'll need access to the $GLOBALS array
<?
function ev($variable){
    foreach($GLOBALS as $key => $value){
        if($variable===$value){
            echo '<p>'.$key.' - '.$value.'</p>';
        }
    }
}

$a=0;
ev($a);
$b=0;
ev($b);
$c=0;
ev($c);
?>
Will output
a - 0

a - 0
b - 0

a - 0
b - 0
c - 0
zabmilenko at hotmail dot com 31-Aug-2006 07:32
A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

<?php
Array
(
    [GLOBALS] => Array
        (
            [GLOBALS] => Array
 *RECURSION*
            [_POST] => Array()
            [_GET] => Array()
            [_COOKIE] => Array()
            [_FILES] => Array()
        )

    [_POST] => Array()
    [_GET] => Array()
    [_COOKIE] => Array()
    [_FILES] => Array()

)
?>

Notice that $_SERVER isn't there.  It seems that php only loads the superglobal $_SERVER if it is used somewhere.  You could do this:

<?php
print '<pre>' . htmlspecialchars(print_r(get_defined_vars(), true)) . '</pre>';
print '<pre>' . htmlspecialchars(print_r($_SERVER, true)) . '</pre>';
?>

And then $_SERVER will appear in both lists.  I guess it's not really a gotcha, because nothing bad will happen either way, but it's an interesting curiosity nonetheless.
lbowerh at adelphia dot net 04-Jun-2004 08:19
Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

<?php
function generateDebugReport($method,$defined_vars,$email="undefined"){
    // Function to create a debug report to display or email.
    // Usage: generateDebugReport(method,get_defined_vars(),email[optional]);
    // Where method is "browser" or "email".

    // Create an ignore list for keys returned by 'get_defined_vars'.
    // For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
    // redundant (same as _POST, _GET)
    // Also include vars you want ignored for security reasons - i.e. PHPSESSID.
    $ignorelist=array("HTTP_POST_VARS","HTTP_GET_VARS",
    "HTTP_COOKIE_VARS","HTTP_SERVER_VARS",
    "HTTP_ENV_VARS","HTTP_SESSION_VARS",
    "_ENV","PHPSESSID","SESS_DBUSER",
    "SESS_DBPASS","HTTP_COOKIE");

    $timestamp=date("m/d/y h:m:s");
    $message="Debug report created $timestamp\n";

    // Get the last SQL error for good measure, where $link is the resource identifier
    // for mysql_connect. Comment out or modify for your database or abstraction setup.
    global $link;
    $sql_error=mysql_error($link);
    if($sql_error){
      $message.="\nMysql Messages:\n".mysql_error($link);
    }
    // End MySQL

    // Could use a recursive function here. You get the idea ;-)
    foreach($defined_vars as $key=>$val){
      if(is_array($val) && !in_array($key,$ignorelist) && count($val) > 0){
        $message.="\n$key array (key=value):\n";
        foreach($val as $subkey=>$subval){
          if(!in_array($subkey,$ignorelist) && !is_array($subval)){
            $message.=$subkey." = ".$subval."\n";
          }
          elseif(!in_array($subkey,$ignorelist) && is_array($subval)){
            foreach($subval as $subsubkey=>$subsubval){
              if(!in_array($subsubkey,$ignorelist)){
                $message.=$subsubkey." = ".$subsubval."\n";
              }
            }
          }
        }
      }
      elseif(!is_array($val) && !in_array($key,$ignorelist) && $val){
        $message.="\nVariable ".$key." = ".$val."\n";
      }
    }

    if($method=="browser"){
      echo nl2br($message);
    }
    elseif($method=="email"){
      if($email=="undefined"){
        $email=$_SERVER["SERVER_ADMIN"];
      }

      $mresult=mail($email,"Debug Report for ".$_ENV["HOSTNAME"]."",$message);
      if($mresult==1){
        echo "Debug Report sent successfully.\n";
      }
      else{
        echo "Failed to send Debug Report.\n";
      }
    }
}
?>
jgettys at gnuvox dot com 22-Feb-2002 07:09
Simple routine to convert a get_defined_vars object to XML.

<?php
function obj2xml($v, $indent='') {
  while (list($key, $val) = each($v)) {
    if ($key == '__attr') continue;
    // Check for __attr
    if (is_object($val->__attr)) {
      while (list($key2, $val2) = each($val->__attr)) {
        $attr .= " $key2=\"$val2\"";
      }
    }
    else $attr = '';
    if (is_array($val) || is_object($val)) {
      print("$indent<$key$attr>\n");
      obj2xml($val, $indent.'  ');
      print("$indent</$key>\n");
    }
    else print("$indent<$key$attr>$val</$key>\n");
  }
}

//Example object
$x->name->first = "John";
$x->name->last = "Smith";
$x->arr['Fruit'] = 'Bannana';
$x->arr['Veg'] = 'Carrot';
$y->customer = $x;
$y->customer->__attr->id='176C4';

$z = get_defined_vars();
obj2xml($z['y']);
?>

will output:
<customer id="176C4">
  <name>
    <first>John</first>
    <last>Smith</last>
  </name>
  <arr>
    <Fruit>Bannana</Fruit>
    <Veg>Carrot</Veg>
  </arr>
</customer>


Returns an integer identifier for the given resource

  • ? get_defined_vars
  • get_resource_type ?
  • PHP Manual
  • Variable handling 函数
  • Returns an integer identifier for the given resource

get_resource_id

(PHP 8)

get_resource_id — Returns an integer identifier for the given resource

说明

get_resource_id ( resource $res ) : int

This function provides a type-safe way for generating the integer identifier for a resource.

参数

res

The evaluated resource handle.

返回值

The int identifier for the given res.

This function is essentially an int cast of res to make it easier to retrieve the resource ID.

范例

Example #1 get_resource_id() example

<?php
$handle = fopen('./storage/logs/lumen.log', 'rt');

echo (int) $handle . "\n\n";

echo get_resource_id($handle);

?>

以上例程会输出：

698

698

参见

  • get_resource_type() - 返回资源（resource）类型

User Contributed Notes

There are no user contributed notes for this page.


返回资源（resource）类型

  • ? get_resource_id
  • gettype ?
  • PHP Manual
  • Variable handling 函数
  • 返回资源（resource）类型

get_resource_type

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

get_resource_type — 返回资源（resource）类型

描述

get_resource_type ( resource $handle ) : string

此函数返回一个字符串，用于表示传递给它的 resource 的类型。如果参数不是合法的 resource，将产生错误。

<?php
$c = mysql_connect();
echo get_resource_type($c)."\n";
// 打印：mysql link

$fp = fopen("foo","w");
echo get_resource_type($fp)."\n";
// 打印：file

$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc)."\n";
// 打印：domxml document
?>

User Contributed Notes

CertaiN 17-Jan-2014 05:04
Try this to know behavior:

<?php
function resource_test($resource, $name) {
    echo
        '[' . $name. ']',
        PHP_EOL,
        '(bool)$resource => ',
        $resource ? 'TRUE' : 'FALSE',
        PHP_EOL,
        'get_resource_type($resource) => ',
        get_resource_type($resource) ?: 'FALSE',
        PHP_EOL,
        'is_resoruce($resource) => ',
        is_resource($resource) ? 'TRUE' : 'FALSE',
        PHP_EOL,
        PHP_EOL
    ;
}

$resource = tmpfile();
resource_test($resource, 'Check Valid Resource');

fclose($resource);
resource_test($resource, 'Check Released Resource');

$resource = null;
resource_test($resource, 'Check NULL');
?>

It will be shown as...

[Check Valid Resource]
(bool)$resource => TRUE
get_resource_type($resource) => stream
is_resoruce($resource) => TRUE

[Check Released Resource]
(bool)$resource => TRUE
get_resource_type($resource) => Unknown
is_resoruce($resource) => FALSE

[Check NULL]
(bool)$resource => FALSE
get_resource_type($resource) => FALSE
Warning:  get_resource_type() expects parameter 1 to be resource, null given in ... on line 10
is_resoruce($resource) => FALSE


获取变量的类型

  • ? get_resource_type
  • intval ?
  • PHP Manual
  • Variable handling 函数
  • 获取变量的类型

gettype

(PHP 4, PHP 5, PHP 7, PHP 8)

gettype — 获取变量的类型

说明

gettype ( mixed $value ) : string

返回 PHP value 变量的类型。 对于类型检查，请使用 is_* 函数。

参数

value

要检查类型的变量。

返回值

返回字符串，可能值为：

  • "boolean"
  • "integer"
  • "double" （由于历史原因，如果是浮点型，则返回 "double"，而不仅仅是 "float"）
  • "string"
  • "array"
  • "object"
  • "resource"
  • "resource (closed)" 自 PHP 7.2.0 起
  • "NULL"
  • "unknown type"

范例

Example #1 gettype() 示例

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

?>

以上例程的输出类似于：

integer
double
NULL
object
string

更新日志

版本 | 说明
7.2.0 | 现在，已关闭的资源报告为 'resource (closed)'。 此前，已关闭的资源报告为 'unknown type'。

参见

  • settype() - 设置变量的类型
  • get_class() - 返回对象的类名
  • is_array() - 检测变量是否是数组
  • is_bool() - 检测变量是否是布尔值
  • is_callable() - 检测参数是否为合法的可调用结构
  • is_float() - 检测变量是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_null() - 检测变量是否为 null
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_object() - 检测变量是否是一个对象
  • is_resource() - 检测变量是否为资源类型
  • is_scalar() - 检测变量是否是一个标量
  • is_string() - 检测变量是否是字符串
  • function_exists() - 如果给定的函数已经被定义就返回 true
  • method_exists() - 检查类的方法是否存在

User Contributed Notes

matt at appstate 16-Dec-2004 11:10
Here is something that had me stumped with regards to gettype and is_object.
Gettype will report an incomplete object as such, whereas is_object will return FALSE.

<?php
if (!is_object($incomplete_obj)) {
   echo 'This variable is not an object, it is a/an ' . gettype($incomplete_obj);
}
?>

Will print:
This variable is not an object, it is a/an object


获取变量的整数值

  • ? gettype
  • is_array ?
  • PHP Manual
  • Variable handling 函数
  • 获取变量的整数值

intval

(PHP 4, PHP 5, PHP 7, PHP 8)

intval — 获取变量的整数值

说明

intval ( mixed $value , int $base = 10 ) : int

通过使用指定的进制 base 转换（默认是十进制），返回变量 value 的 int 数值。 intval() 不能用于 object，否则会产生 E_NOTICE 错误并返回 1。

参数

value

要转换成 integer 的数量值

base

转化所使用的进制

Note:

如果 base 是 0，通过检测 value 的格式来决定使用的进制：

  • 如果字符串包括了 "0x" (或 "0X") 的前缀，使用 16 进制 (hex)；否则，
  • 如果字符串以 "0" 开始，使用 8 进制(octal)；否则，
  • 将使用 10 进制 (decimal)。

返回值

成功时返回 value 的 integer 值，失败时返回 0。 空的 array 返回 0，非空的 array 返回 1。

最大的值取决于操作系统。 32 位系统最大带符号的 integer 范围是 -2147483648 到 2147483647。举例，在这样的系统上，intval('1000000000000') 会返回 2147483647。64 位系统上，最大带符号的 integer 值是 9223372036854775807。

字符串有可能返回 0，虽然取决于字符串最左侧的字符。 使用 整型转换 的共同规则。

范例

Example #1 intval() 例子

下面的例子运行于 32 位系统上。

<?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
echo intval(array());                 // 0
echo intval(array('foo', 'bar'));     // 1
echo intval(false);                   // 0
echo intval(true);                    // 1
?>

注释

Note:

除非 value 是一个字符串，否则 base 不会起作用。

参见

  • boolval() - 获取变量的布尔值
  • floatval() - 获取变量的浮点值
  • strval() - 获取变量的字符串值
  • settype() - 设置变量的类型
  • is_numeric() - 检测变量是否为数字或数字字符串
  • 类型转换的判别
  • BCMath 任意精度数学函数

User Contributed Notes

Anony Moose 15-May-2020 03:46
As a warning, do not use this function alone for input validation.

Vulnerable example:
<?php
if(isset($_GET['id']) && intval($_GET['id']) > 0){
    echo $id;
}
?>

The following requests would pass this filter:

/page.php?id=10
/page.php?id=10oops
/page.php?id=10<script>alert(1)</script>
/page.php?id=1' OR '1'='1
/page.php?id[]=<script>alert(1)</script>

Instead use the is_numeric() function for integer validation:

<?php
echo intval("10oops"); // 10
echo is_numeric("10oops");  // false
?>

Secure example:
<?php
if(isset($_GET['id']) && is_numeric($_GET['id']) && intval($_GET['id']) > 0){
    echo $id;
}
?>
Anonymous 12-Feb-2020 05:14
PHP 7.2

$test = intval(150.20*100); //15019
$test2 = intval(15020); //15020
$test3 = intval(15020.0); //15020
$test4 = 150.20*100; //15020.0
chinmay235 at gmail dot com 10-May-2018 05:57
<?php
echo intval("10 days");          //10
echo intval("days 10");          //0
?>
Anthony 21-Apr-2018 12:28
The binary notation is NOT supported until php7.2
<?php
                         // PHP <7.2 | PHP >=7.2
echo intval(0b11);       //    3     |     3
echo intval(-0b11);      //   -3     |    -3
echo intval('0b11');     //    0     |     0
echo intval('-0b11');    //    0     |     0
echo intval('0b11', 0);  //    0     |     3
echo intval('-0b11', 0); //    0     |    -3
?>
leon at leonidasjp dot nl 27-Jan-2017 03:35
It seems intval is interpreting valid numeric strings differently between PHP 5.6 and 7.0 on one hand, and PHP 7.1 on the other hand.

<?php
echo intval('1e5');
?>

will return 1 on PHP 5.6 and PHP 7.0,
but it will return 100000 on PHP 7.1.
taylorsarrafian at gmail dot com 11-Jul-2015 04:45
beware:

<?php

   // observe the following
   echo intval( strval( -0.0001 ) ); // 0
   echo intval( strval( -0.00001 ) ); // -1

   // this is because
   echo strval( -0.0001 ); // -.0001
   echo strval( -0.00001 ); // -1.0E-5

   // thus beware when using
   function trunc2_bad( $n ) {
      return intval( strval( $n * 100 ) / 100 );
   }

   // use this instead
   function trunc2_good( $n ) {
      return intval( floatval( strval( $n * 100 )  ) / 100 );
   }

?>
pfreet at gmail dot com 25-Apr-2013 05:27
Do not use intval() when you really want round(). This is due to how PHP handles precision.

echo number_format(8.20*100, 20), "<br />";
echo intval(8.20*100), "<br />";
echo floor(8.20*100), "<br />";
echo round(8.20*100), "<br />";

819.99999999999988631316
819
819
820
espertalhao04 at hotmail dot com 06-Mar-2013 09:58
if you want to take a number from a string, no matter what it may contain, here is a good solution:

<?php
function int($s){return(int)preg_replace('/[^\-\d]*(\-?\d*).*/','$1',$s);}

echo int('j18ugj9hu0gj5hg');
//output: 18
?>
this example returns an int, so it will follow the int rules, and has support for negative values.

<?php
function int($s){return($a=preg_replace('/[^\-\d]*(\-?\d*).*/','$1',$s))?$a:'0';}

echo int('j-1809809808908099878758765ugj9hu0gj5hg');
//output: -1809809808908099878758765
?>

this one returns a string with just the numeric value.
it also supports negative values.

the latter is better when you have a 32 bit system and you want a huge int that is higher than PHP_MAX_INT.
Ken 11-Nov-2011 11:50
Not mentioned elsewhere: intval(NULL) also returns 0.
yves 27-Dec-2010 08:53
The behaviour of intval() is interesting when supplying a base, and you better check your intval base-based expressions, as it is counter-intuitive.
As the example shows
<?php
  intval('42', 8); // => 34
  intval(42, 8);   // => 42 !
?>
PHP considers the 42 as being already an integer, and doesn't apply any conversion. And supplying
<?php
  intval(49, 8);  // => 49 !
?>
produces no error and no warning.
winbill at hotmail dot com 16-Dec-2010 08:31
Be careful :

<?php
$n="19.99";
print intval($n*100); // prints 1998
print intval(strval($n*100)); // prints 1999
?>
spoon_reloaded at gmail dot com 21-Jun-2009 10:35
Here is a really useful undocumented feature:

You can have it automatically deduce the base of the number from the prefix of the string using the same syntax as integer literals in PHP ("0x" for hexadecimal, "0" for octal, non-"0" for decimal) by passing a base of 0 to intval():

<?php
echo intval("0x1a", 0), "\n"; // hex; prints "26"
echo intval("057", 0), "\n"; // octal; prints "47"
echo intval("42", 0), "\n"; // decimal; prints "42"
?>
mkamerma at science dot uva dot nl 06-Mar-2006 11:48
As addendum, the "if ($int > 0)" check in the encode function is redundant. It doesn't do anything bad to keep it in since it will always be true when reaching that point, but it's a meaningless conditional this way. It's a remnant from when I tried to write the function in terms of bitshifts, which could lead to negative ints when shifting if the 32nd bit was set (instead of always padding with 0's when using >> it pads with 1's leading to negative ints).
simon at npkk dot cz 30-Jan-2006 08:03
Still have on mind, that if you convert big numbers by adding zero, PHP makes automatic "to a float" conversion, so it is same as floatVal(). So if the number is realy big (over 13 digits), you can lose preciosity. Do not use it for such long numbers, if all bits do matter (IPv6 addresses and similar).
Ben Laurienti 16-Jan-2006 01:21
You guys are going to love this.  I found something that I found quite disturbing.

$test1 = intVal(1999);

$amount = 19.99 * 100;
$test2 = intVal($amount);
$test3 = intVal("$amount");

echo $test1 . "<br />\n";
echo $test2 . "<br />\n";
echo $test3 . "<br />\n";

expected output:
1999
1999
1999

actual output
1999
1998
1999

Appears to be a floating point issue, but the number 1999 is the only number that I was able to get to do this.  19.99 is the price of many things, and for our purpose we must pass it as 1999 instead of 19.99.
tuxedobob at mac dot com 07-Feb-2004 04:56
Sometimes intval just won't cut it. For example if you want to use an unsigned 32-bit int and need all 32 bits. Recently, I wrote a little script that took and integer and converted it to an IP address. After realizing I couldn't just mod the whole thing, since the sign bit throws it off (and compensating for that), we ran into a problem where if it was entered into a form, the value somehow wasn't converted to an integer properly, at least not implicitly. The solution for this, and the way I recommend converting a string to an integer, is:

$num = $num + 0;

and PHP will leave your number alone; it'll just know it's a number. Such is the fun of a loosely-typed language. :)
zak at php dot net 12-Aug-2000 01:38
intval converts doubles to integers by truncating the fractional component of the number.

When dealing with some values, this can give odd results.  Consider the following:

print intval ((0.1 + 0.7) * 10);

This will most likely print out 7, instead of the expected value of 8.

For more information, see the section on floating point numbers in the PHP manual (http://www.php.net/manual/language.types.double.php)

Also note that if you try to convert a string to an integer, the result is often 0.

However, if the leftmost character of a string looks like a valid numeric value, then PHP will keep reading the string until a character that is not valid in a number is encountered.

For example:

"101 Dalmations" will convert to 101

"$1,000,000" will convert to 0 (the 1st character is not a valid start for a number

"80,000 leagues ..." will convert to 80

"1.4e98 microLenats were generated when..." will convert to 1.4e98

Also note that only decimal base numbers are recognized in strings.

"099" will convert to 99, while "0x99" will convert to 0.

One additional note on the behavior of intval.  If you specify the base argument, the var argument should be a string - otherwise the base will not be applied.

For Example:

print intval (77, 8);   // Prints 77
print intval ('77', 8); // Prints 63


检测变量是否是数组

  • ? intval
  • is_bool ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否是数组

is_array

(PHP 4, PHP 5, PHP 7, PHP 8)

is_array — 检测变量是否是数组

描述

is_array ( mixed $var ) : bool

如果 var 是 array，则返回 true，否则返回 false。

参见 is_float()、is_int()、is_integer()、is_string() 和 is_object()。

User Contributed Notes

Daniel 14-Jul-2019 06:54
The next post is not correct because has problems with blank array index:
https://www.php.net/manual/es/function.is-array.php#89332

The next code use the above link php code

<?php
function is_assoc($var)
{
        return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

function test($var)
{
        echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}

// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);

// maybe assoc array?
$b = array(0 => "aaa", 1 => 1, 3 => true); // Index 2 not exist
test($b);
?>

# Output
I'm an assoc array.
I'm an assoc array.

"Associative arrays are arrays that use named keys that you assign to them."
https://www.w3schools.com/php/php_arrays.asp

Solution:

<?php
function is_assoc(array $array)
{
    return count(array_filter(array_keys($array), 'is_string')) > 0;
}
function test(array $array)
{
    echo is_assoc($array) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}
// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);
// an array
$b = array(0=>"aaa",1=>1,3=>true);
test($b);
?>

# Output
I'm an assoc array.
I'm not an assoc array.

If you want check pure assoc. array replace > 0 by === count($array)
lrgbx0 at gmail dot com 10-May-2018 08:48
is_assoc() Benchmark:

<?php

function is_assoc1($array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) unset($array[--$i]);
    return (bool)$array;
}

function is_assoc2(&$array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) {
        if (!isset($array[--$i])) return true;
    }
    return false;
}

function is_assoc3(&$array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) {
        if (!array_key_exists(--$i, $array)) return true;
    }
    return false;
}

function is_assoc4($array) {
    if (!is_array($array)) return false;
    ksort($array);
    foreach (array_keys($array) as $k => $v) {
        if ($k !== $v) return true;
    }
    return false;
}

function is_assoc5(&$array) {
    return is_array($array) && array_diff_key($array, array_keys($array));
}

$arr1 = array(); // not associative
$arr2 = $arr3 = array('foo', 'bar', 'baz', 'foo', 'bar', 'baz', 'foo', 'bar', 'baz', 'foo'); // not associative
asort($arr3); // not associative, shuffled keys
$arr4 = array('foo', 'bar', 'baz', 'foo', 'bar', null, 'foo', 'bar', 'baz', 'foo'); // not associative but is_assoc2() thinks it is
$arr5 = array(0 => 'foo', 1 => 'bar', 2 => 'baz', 3 => 'foo', 4 => 'bar', 5 => 'baz', 'foo3' => 'foo', 'bar3' => 'bar', 'baz3' => 'baz', 'foo4' => 'foo'); // associative

$i = $j = 0;
$time = array(0.0, 0.0, 0.0, 0.0, 0.0);

for ($j = 0; $j < 2000; $j++) {
    $time[0] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc1($arr1) || is_assoc1($arr2) || is_assoc1($arr3) || is_assoc1($arr4) || !is_assoc1($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[0] += microtime(true);
    $time[1] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc2($arr1) || is_assoc2($arr2) || is_assoc2($arr3) || !is_assoc2($arr4) || !is_assoc2($arr5)) { // $arr4 tweaked
            echo 'error';
            break;
        }
    }
    $time[1] += microtime(true);
    $time[2] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc3($arr1) || is_assoc3($arr2) || is_assoc3($arr3) || is_assoc3($arr4) || !is_assoc3($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[2] += microtime(true);
    $time[3] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc4($arr1) || is_assoc4($arr2) || is_assoc4($arr3) || is_assoc4($arr4) || !is_assoc4($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[3] += microtime(true);
    $time[4] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc5($arr1) || is_assoc5($arr2) || is_assoc5($arr3) || is_assoc5($arr4) || !is_assoc5($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[4] += microtime(true);
}

echo 'is_assoc1(): ' . $time[0] . "\n";
echo 'is_assoc2(): ' . $time[1] . "\n";
echo 'is_assoc3(): ' . $time[2] . "\n";
echo 'is_assoc4(): ' . $time[3] . "\n";
echo 'is_assoc5(): ' . $time[4] . "\n";

?>

is_assoc1() - uses unset(), a bit slow, but mem friendly and no function calls
is_assoc2() - uses isset(), fastest one, but returns TRUE whenever array contains NULL
is_assoc3() - fixed is_assoc2(), uses array_key_exists(), fast and memory friendly, and much smarter than the following (no need to check all those keys)
is_assoc4() - alex' version with proper check and key sorting
is_assoc5() - fixed a bit JTS' version, really nice one, but uses too many functions and checks all keys

Results:

is_assoc1(): 2.1628699302673
is_assoc2(): 1.1079933643341
is_assoc3(): 1.7120850086212
is_assoc4(): 3.9194552898407
is_assoc5(): 1.9509885311127
rik at mmod dot co 12-Apr-2018 05:39
Using is_array prior to an in_array within an if clause will safely escape a check against a variable that could potentially be a non-array when using in_array.  For instance:

NOTE: A real use case might be that we have a list of possible flags which  in a database we have stored whether each of the flags are 0 or 1.  We want a list of the flags which have the value of 1 to be returned.

Our example here will not use so many technical artifacts, but will be based on similar logic just to get the point across.

<?php

// We have a list of known values
$knownVars = ['apple', 'orange'];

// A list of values to check
$listToCheck = ['pear', 'banana'];

// And a method that takes a list of values to check and returns a new list
// of the items from said list that are found to be valid...
public function getValidItemsList( $listToCheck /*['pear', 'banana']*/)
{
    $returnList = [];
    foreach($listToCheck as $key => $val)
    {
        if(in_array($val, $knownVars))
        {
            array_push($returnList, $val);
        }
    }

    if(empty($returnList))
    {
        // We have a special case if there were no valid items found, which is the case we are going over
        return  -1;
    }

    // Otherwise, normally returns a list of the items that were found to be valid
    return $returnList;
}

// Call the method and check for any valid items that can be used for some purpose
$validItemsList =  getValidItemsList($listToCheck);

// In this usage we could potentially get an exception because
// in_array() expects an array for argument #2, checking that the value != -1 does not escape the if statement:
if(isset($validItemsList) && $validItemsList != -1 && in_array('apple', $validItemsList))
{
    //...
}

// In this usage, we break free from the if statement safely:
if(isset($validItemsList) && $validItemsList != -1 && is_array($validItemsList) && in_array('apple', $validItemsList))
{
    //...
}

?>

Hope that can help someone, I know it helped me.
gwschnell at ewe dot net 22-Mar-2018 04:58
An error will be thrown If is_array() is applied to a nonexisting varble.
carren at AngieBecker dot ch 26-Sep-2017 08:48
This is probably the best way to test for associative arrays:

<?php
function is_assoc($test) {
        if (empty($test)) { return(false); }
        if (!is_array($test)) { return(false); }
        return ($test !== array_values($test));
}
?>

This version is based on the one from dmitry dot sushilov, which is unfortunately exactly opposite and misses the is_array and empty test.
http://php.net/manual/en/function.is-array.php#115901
marko at newvibrations dot net 20-Oct-2016 12:08
hperrin at gmail dot com
i tested modified version of your code:

<?php
$test = array_fill(0, $size, rand());
$test3 = (object) $test;
?>

Results are quite different!

PHP 5.5:
is_array - execution time is constant over different $size
cast, === - execution time is proportional with $size, for small arrays, it's faster than is_array, but for bigger arrays, it's way slower. Also, bigger memory allocation because casting actually allocates memory

PHP 7.0:
is_array and cast, === have constant execution time over different $size:
is_array  :  0.12564396858215
cast, === :  0.24629783630371

Looks like casting is optimised, but still slower.

Bottom line is: optimisation is not done for special scenario, but for average use and scalability. Don't reinvent wheel.
Rob Thomas 05-Oct-2016 10:40
Please note that the 'cast to array' check is horrendously out of date.

Running that code against PHP 5.6 results in this:

is_array  :  0.93975400924683
cast, === :  1.2425191402435

So, please use 'is_array', not the horrible casting hack.
mt at banita dot de 08-Sep-2016 09:30
I'm using PHP 5.3.10 and the remark from hperrin is not (no longer?) valid

is_array is (now?) faster than if ( (array) $unknown !== $unknown )

my result of hperrins test script

is_array  :  0.61710119247437
cast, === :  1.1551909446716
ari at umbrella dot bz 05-Sep-2016 08:34
hperrin's results have indeed changed in PHP 7. The opposite is now true, is_array is faster than comparison:

is_array  :  0.52148389816284
cast, === :  0.84179711341858

Tested 1000000 iterations.
mbrodala at pagemachine dot de 24-Aug-2016 01:22
Notice that the benchmark results from hperrin at gmail dot com have changed in the meantime:

is_array  :  0.31888604164124
cast, === :  0.58448791503906

(Using PHP 5.6.24, I expect other results with PHP 7)
dmitry dot sushilov at gmail dot com 12-Oct-2014 12:49
function is_associate_array($array)
{
    return $array === array_values($array);
}

or you can add check is_array in functions
joksnet at gmail dot com 08-Oct-2013 10:17
Here is something for compare `is_assoc` functions.

<?php
function is_assoc1($var)
{
    return is_array($var) && array_diff_key($var, array_keys(array_keys($var)));
}

function is_assoc2($var)
{
    return is_array($var) && array_diff_key($var, array_fill(0, count($var), null));
}

$count = 1000000;

$a = array('a' => 'foo', 'b' => 1, 'c' => true);
$b = array('a', 'b', 'c');

$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    assert(is_assoc1($a) === true);
    assert(is_assoc1($b) === false);
}
$end_time = microtime(true);
echo 'is_assoc1  :  ' . ($end_time - $start_time) . "\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    assert(is_assoc2($a) === true);
    assert(is_assoc2($b) === false);
}
$end_time = microtime(true);
echo 'is_assoc2  :  ' . ($end_time - $start_time) . "\n";
?>

It prints something like this:

```
% php is_assoc.php
is_assoc1  :  19.36315202713
is_assoc2  :  18.954080104828
```

The first one is from
skaimauve (http://www.php.net/manual/en/function.is-array.php#89332). The second one is mine.
magentix at gmail dot com 26-Feb-2011 09:12
If you wanted to have 'pure' associative arrays,
you could filter out non-string keys and then compare the count of the original array with the count of the filtered array.

<?php
    // Only validates empty or completely associative arrays
    function is_assoc ($arr) {
        return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
    }

    $a = '';
    $b = 'z';
    $c = array();
    $d = array('x','y','z');
    $e = array('x','y','zed'=>'z');
    $f = array('ex'=>'x','why'=>'y','zed'=>'z');

    echo '$a: ' . ( (is_assoc($a)) ? 'true' : 'false' ) ."\n"; // False
    echo '$b: ' . ( (is_assoc($b)) ? 'true' : 'false' ) ."\n"; // False
    echo '$c: ' . ( (is_assoc($c)) ? 'true' : 'false' ) ."\n"; // True
    echo '$d: ' . ( (is_assoc($d)) ? 'true' : 'false' ) ."\n"; // False
    echo '$e: ' . ( (is_assoc($e)) ? 'true' : 'false' ) ."\n"; // False
    echo '$f: ' . ( (is_assoc($f)) ? 'true' : 'false' ) ."\n"; // True
?>

I've tested the point of checking whether the array is empty first.
The overall result was a 200% speed increase when the array was indeed empty,
but an average 10% slow when it had elements inside.

<?php
    /***********************************************************
     *    Benchmarks: checking for empty array vs. not checking  *
     ***********************************************************/

    // With empty check
    function is_assoc ($arr) {
        return (is_array($arr) && (!count($arr) || count(array_filter(array_keys($arr),'is_string')) == count($arr)));
    }

    function test_speed($arr) {
        $t = microtime(true);
        for($i = 0; $i < 100000; ++$i) is_assoc($arr);
        return (microtime(true) - $t);
    }

    echo '$a: ' . test_speed($a) ."\n"; // 0.20597505569458
    echo '$b: ' . test_speed($b) ."\n"; // 0.19199514389038
    echo '$c: ' . test_speed($c) ."\n"; // 0.28803396224976
    echo '$d: ' . test_speed($d) ."\n"; // 0.94685983657837
    echo '$e: ' . test_speed($e) ."\n"; // 0.96698403358459
    echo '$f: ' . test_speed($f) ."\n"; // 0.98052096366882

    // Without empty check
    function is_assoc_2 ($arr) {
        return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
    }

    function test_speed_2($arr) {
        $t = microtime(true);
        for($i = 0; $i < 100000; ++$i) is_assoc_2($arr);
        return (microtime(true) - $t);
    }

    echo '$a: ' . test_speed_2($a) ."\n"; // 0.18811202049255 = FASTER:  91.3% of is_assoc
    echo '$b: ' . test_speed_2($b) ."\n"; // 0.18782901763916 = FASTER:  97.8% of is_assoc
    echo '$c: ' . test_speed_2($c) ."\n"; // 0.64437484741211 = SLOWER: 223.7% of is_assoc
    echo '$d: ' . test_speed_2($d) ."\n"; // 0.84632205963135 = FASTER:  89.4% of is_assoc
    echo '$e: ' . test_speed_2($e) ."\n"; // 0.86739897727966 = FASTER:  89.7% of is_assoc
    echo '$f: ' . test_speed_2($f) ."\n"; // 0.87963700294495 = FASTER:  89.7% of is_assoc
?>
JTS 08-Jun-2010 04:22
I would change the order of the comparison, because if it is really an empty array, it is better to stop at that point before doing several 'cpu & memory intensive' function calls.

In the end on a ratio of 3 not empty arrays to 1 empty array computed for 1000000 iterations it needed 10% less time.
Or the other way round:
It needed approx 3% to 4% more time if the array is not empty, but was at least 4 times faster on empty arrays.

Additionally the memory consumption veritably lesser.

<?php
function is_assoc($array) {
    return (is_array($array) && (count($array)==0 || 0 !== count(array_diff_key($array, array_keys(array_keys($array))) )));
}
?>
hperrin at gmail dot com 28-May-2010 10:02
I've found a faster way of determining an array. If you use is_array() millions of times, you will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using is_array().

Cast the value to an array, then check (using ===) if it is identical to the original.

<?php
if ( (array) $unknown !== $unknown ) {
    echo '$unknown is not an array';
} else {
    echo '$unknown is an array';
}
?>

You can use this script to test the speed of both methods.

<pre>
What's faster for determining arrays?

<?php

$count = 1000000;

$test = array('im', 'an', 'array');
$test2 = 'im not an array';
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'is_array  :  '.($end_time - $start_time)."\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'cast, === :  '.($end_time - $start_time)."\n";

echo "\nTested $count iterations."

?>
</pre>

Prints something like:

What's faster for determining arrays?

is_array  :  7.9920151233673
cast, === :  1.8978719711304

Tested 1000000 iterations.
Anonymous 16-May-2009 02:18
Using empty() in the previous example posted by Anonymous will result in a "Fatal error: Can't use function return value in write context".  I suggest using count() instead:

<?php
function is_assoc($array) {
    return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
?>
skaimauve at yahoo dot ca 03-Mar-2009 12:12
Or you could make use of the array_diff_key and array_key function:

<?php

function is_assoc($var)
{
        return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

function test($var)
{
        echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}

// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);

// an array
$b = array_values($a);
test($b);

// an object
$c = (object)$a;
test($c);

// other types
test($a->a);
test($a->b);
test($a->c);

?>

The above code outputs:
I'm an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
Matthias Loitsch 03-Dec-2008 11:36
Or you could make use of the array_diff_key and range functions:

<?php

function isVector($var) { return count(array_diff_key($var, range(0, count($var) - 1))) == 0; }

function isAssociative($var) { return !isVector($var); }

?>
jim at akubo dot net 28-Oct-2008 11:02
yousef's example was wrong because is_vector returned true instead of false if the key was found
here is the fixed version (only 2 lines differ)
<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return false;
      $next++;
   }
   return true;
}
?>
yousuf at philipz dot com 16-Oct-2008 03:41
alex frase's example is fast but elanthis at awesomeplay dot com's example is faster and Ilgar's modification of alex's code is faulty (the part " || $_array[$k] !== $v"). Also, Ilgar's suggestion of giving a false return value when the variable isnt an array is not suitable in my opinion and i think checking if the array is empty would also be a suitable check before the rest of the code runs.

So here's the modified (is_vector) version

<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return true;
      $next++;
   }
   return false;
}
?>

and the modified (alex's is_assoc) version

<?php
function is_assoc($_array) {
    if ( !is_array($_array) || empty($array) ) {
        return -1;
    }
    foreach (array_keys($_array) as $k => $v) {
        if ($k !== $v) {
            return true;
        }
    }
    return false;
}
?>
alex frase 16-Jul-2008 08:05
Yet another simpler, faster is_assoc():

<?php
function is_assoc($array) {
  foreach (array_keys($array) as $k => $v) {
    if ($k !== $v)
      return true;
  }
  return false;
}
?>

In my tests it runs about twice as fast as Michael/Gabriel's array_reduce() method.

(Speaking of which: Gabriel's version doesn't work as written; it reports associative arrays as numeric if only the first key is non-numeric, or if the keys are numeric but ordered backwards.  Michael solves this problem by comparing array_reduce() to count(), but that costs another function call; it also works to just compare to -1 instead of 0, and therefore return -1 as the ternary else from the callback).
Michael 11-Sep-2007 12:37
A slight modification of what's below:

<?php

function is_assoc($array)
{
    return is_array($array) && count($array) !== array_reduce(array_keys($array), 'is_assoc_callback', 0);
}

function is_assoc_callback($a, $b)
{
    return $a === $b ? $a + 1 : 0;
}

?>
gabriel at bumpt dot nothing-here dot net 29-Aug-2007 08:34
Yet another safer, faster way of detecting whether an array is associative.

The principle is: using array reduction on the keys, we verify that each key is numeric and is equal to its rank.

Beware: integer keys that are not in sequence, or are negative, or with "holes", still make an associative array.

<?php
/**
  * @param array $arr
  * @returns boolean
  */
function isNotAssocArray($arr)
{
    return (0 !== array_reduce(
        array_keys($arr),
        create_function('$a, $b', 'return ($b === $a ? $a + 1 : 0);'),
        0
        )
    );
}
?>

Of course, it is still faster if the callback for array_reduce is not an anonymous function:

<?php
function callbackReduceNotArray($a, $b)
{
    return ($b === $a ? $a + 1 : 0);
}
function isVector($arr)
{
    return (0 !== array_reduce(
        array_keys($arr),
        'callbackReduceNotArray',
        0
        )
    );
}
?>
Alfred J Fazio <alfred dot fazio at gmail dot com> 04-Apr-2007 04:32
Yet another associative array test:

<?php
function binary_nand ($a, $b) { return !$a && !$b; }
function binary_nor ($a, $b)  { return !$a || !$b; }

// Returns true if array has elements with non-numeric keys
function is_associative_array ($arr) {
  return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nor", true);
}

// Returns true if all elements of array have a non-numeric key
function is_strict_associative_array ($arr) {
  return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nand", false);
}
?>
angelo [at] mandato <dot> com 26-Feb-2007 01:32
The is_associative_array() and is_sequential_array() functions posted by 'rjg4013 at rit dot edu' are not accurate.

The functions fail to recognize indexes that are not in sequence or in order.  For example, array(0=>'a', 2=>'b', 1=>'c') and array(0=>'a', 3=>'b', 5=>'c') would be considered as sequential arrays. A true sequential array would be in consecutive order with no gaps in the indices.

The following solution utilizes the array_merge properties. If only one array is given and the array is numerically indexed, the keys get re-indexed in a continuous way.  The result must match the array passed to it in order to truly be a numerically indexed (sequential) array.  Otherwise it can be assumed to be an associative array (something unobtainable in languages such as C).

The following functions will work for PHP >= 4.

<?php
    function is_sequential_array($var)
    {
        return (array_merge($var) === $var && is_numeric( implode( array_keys( $var ) ) ) );
    }

    function is_assoc_array($var)
    {
        return (array_merge($var) !== $var || !is_numeric( implode( array_keys( $var ) ) ) );
    }
?>

If you are not concerned about the actual order of the indices, you can change the comparison to == and != respectively.
jupiter at nospam dot com 29-May-2006 11:42
Will check a Multi-Dimentional Array to any specified level.  This is a fix to 11/16/05 submission, which would break since you must supply a foreach with an array. Beware recursive functions shouldn't go over 100 deep or could break the memory stack on server.

<?php
// checks for multiarray to defined depth level recursively
// original $level must be 2 or more, else will instantly return true
function isDeepMultiArray($multiarray, $level = 2) {  // default is simple multiarray
    if (is_array($multiarray)) {  // confirms array
        if ($level == 1) {  // $level reaches 1 after specified # of recursions
            return true;  // returns true to recursive function conditional
        }  // end conditional
        foreach ($multiarray as $array) {  // goes one level deeper into array
            if (isDeepMultiArray($array, $level - 1)) {  // check subarray
                $message = "I'm a multiarray";  // optional message
                return $message;  // best if $message = true so function returns boolean
            }  // end recursive function
        }  // end loop
    } else {  // not an array at specified level
    return false;  // is also used recursively so can't change to message
    }
}

if (isDeepMultiArray(array(array()), 2)); // beware this returns true eventhough arrays are empty

?>
BTW my notation is consistent with the PEAR manual on coding standards, which is what php.net says to follow. I hope a function like this gets included in PHP6.
jupiter at nospam dot com 29-May-2006 09:15
Simple check for a Multi-Dimentional Array of any depth
<?php
// checks for multiarray (2 or more levels deep)
function isMultiArray($multiarray) {
  if (is_array($multiarray)) {  // confirms array
    foreach ($multiarray as $array) {  // goes one level deeper
      if (is_array($array)) {  // is subarray an array
        return true;  // return will stop function
      }  // end 2nd check
    }  // end loop
  }  // end 1st check
  return false;  // not a multiarray if this far
}
?>
March 30-Mar-2006 06:28
And here is another variation for a function to test if an array is associative. Based on the idea by mot4h.

<?php
function is_associative($array)
{
  if (!is_array($array) || empty($array))
    return false;

  $keys = array_keys($array);
  return array_keys($keys) !== $keys;
}
?>
dan at cain dot sh 10-Dec-2004 05:05
is_array() under PHP 5.0.2 will return FALSE when passed an object descended from the internal class interface ArrayAccess(http://www.php.net/spl) even though said object behaves as an array would in most instances.

I've found the following user function helpful with my own classes and functions that expect array(s) as arguments, but work fine with objects that behave as an array would.

<?php
function is_array_abled(&$x)
{
    return (bool)($x instanceof ArrayAccess or is_array($x));
}
?>
vhermecz at ixpert dot hu 01-Apr-2004 04:58
Mike's function is quite cool, it is just the one, I was searching for. Using range is a great idea! But it's a bit long for me. Here is a shorter version:

<?php
function is_assoc_array($var) {
    if (!is_array($var)) {
        return false;
    }
    return array_keys($var)!==range(0,sizeof($var)-1);
}
?>

Or, if you don't want to type that much:

<?php
function is_assoc($var) {
    return is_array($var) && array_keys($var)!==range(0,sizeof($var)-1);
}
?>


检测变量是否是布尔值

  • ? is_array
  • is_callable ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否是布尔值

is_bool

(PHP 4, PHP 5, PHP 7, PHP 8)

is_bool — 检测变量是否是布尔值

说明

is_bool ( mixed $value ) : bool

检查变量是否为布尔值。

参数

value

要检查的变量。

返回值

如果 value 是布尔值则返回 true，否则返回 false。

范例

Example #1 is_bool() 示例

<?php
$a = false;
$b = 0;

// 因为 $a 是布尔值，所以结果为 true
if (is_bool($a) === true) {
    echo "Yes, this is a boolean";
}

// 因为 $b 不是布尔值，所以结果为 false
if (is_bool($b) === false) {
    echo "No, this is not a boolean";
}
?>

参见

  • is_float() - 检测变量是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_string() - 检测变量是否是字符串
  • is_object() - 检测变量是否是一个对象
  • is_array() - 检测变量是否是数组

User Contributed Notes

Julio Marchi 08-Sep-2019 12:32
The function Michael Smith published doesn't do the work as it should.

To check if a variable is boolean is one thing, to evaluate if the value of a variable represents a boolean condition (true or false) is another.

Here a simple function that checks the status of the received variable in regards to boolean equivalencies (case insensitive).

<?php
/**
 * Check "Booleanic" Conditions :)
 *
 * @param  [mixed]  $variable  Can be anything (string, bol, integer, etc.)
 * @return [boolean]           Returns TRUE  for "1", "true", "on" and "yes"
 *                             Returns FALSE for "0", "false", "off" and "no"
 *                             Returns NULL otherwise.
 */
function is_enabled($variable)
{
    if (!isset($variable)) return null;
    return filter_var($variable, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
?>

Of course, it is a simplistic approach, but for the majority of cases it will do the job right.

And, just to put thing in the right perspective, here's a real function that does what Phill disclosed:

<?php
/**
 * Convert $variable to boolean (adapted from Phill answer)
 *
 * @param  [mixed]  $variable  Can be anything
 * @return [boolean]           Returns the booelan equivalent to $variable based on Zend Enegine interpretation
 */
function to_bool($variable)
{
    return (bool)$variable;
}
?>

I hope it helps someone. Happy coding.
phil 10-Jan-2019 06:21
It should be stated that this function returns true if the _type_ of it's argument is boolean. It does not convert or coerce the value to a boolean type, not sure why so many comments focus on how to do this.
However, if you arrived here looking for a solution to convert a value to a boolean type, use this:

to_bool($x) { return (bool)$x; }
Michael Smith 17-Nov-2013 01:17
The function in the last comment also converts the string 'false' to a true boolean. Here's a function that does what I think was intended:

<?php
function toBool($var) {
  if (!is_string($var)) return (bool) $var;
  switch (strtolower($var)) {
    case '1':
    case 'true':
    case 'on':
    case 'yes':
    case 'y':
      return true;
    default:
      return false;
  }
}


检测参数是否为合法的可调用结构

  • ? is_bool
  • is_countable ?
  • PHP Manual
  • Variable handling 函数
  • 检测参数是否为合法的可调用结构

is_callable

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

is_callable — 检测参数是否为合法的可调用结构

说明

is_callable ( callable $name , bool $syntax_only = false , string &$callable_name = ? ) : bool

验证变量的内容能否作为函数调用。 这可以检查包含有效函数名的变量，或者一个数组，包含了正确编码的对象以及函数名。

参数

name

要检查的回调函数。

syntax_only

如果设置为 true，这个函数仅仅验证 name 可能是函数或方法。 它仅仅拒绝非字符，或者未包含能用于回调函数的有效结构。有效的应该包含两个元素，第一个是一个对象或者字符，第二个元素是个字符。

callable_name

接受"可调用的名称"。下面的例子是"someClass::someMethod"。 注意，尽管 someClass::SomeMethod() 的含义是可调用的静态方法，但例子的情况并不是这样的。

返回值

如果 name 可调用则返回 true，否则返回 false。

范例

Example #1 is_callable() 例子

<?php
//  How to check a variable to see if it can be called
//  as a function.

//
//  Simple variable containing a function
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name));  // bool(true)

echo $callable_name, "\n";  // someFunction

//
//  Array containing a method
//

class someClass {

  function someMethod()
  {
  }

}

$anObject = new someClass();

$methodVariable = array($anObject, 'someMethod');

var_dump(is_callable($methodVariable, true, $callable_name));  //  bool(true)

echo $callable_name, "\n";  //  someClass::someMethod

?>

参见

  • function_exists() - 如果给定的函数已经被定义就返回 true
  • method_exists() - 检查类的方法是否存在

User Contributed Notes

jlh 22-Mar-2019 09:28
The story about __call() is a bit more complicated unfortunately. It will always return true ONLY if you pass an instance of a class, not if you pass the class name itself:

<?php
class MyClass {
    public function method() { }
    public function __call($name, $arguments) { }
}

is_callable([MyClass::class, 'method']); // true
is_callable([new MyClass(), 'method']); // true
is_callable([MyClass::class, 'other']); // false!!!
is_callable([new MyClass(), 'other'])); // true
bienvenunet at yaho dot com 06-Mar-2018 10:29
It's not immediately evident from the content of the article, but implementing __invoke() makes an object callable.

<?php
class ObjectWithInvoke {
  public function __invoke() {}
}

$o = new ObjectWithInvoke();
if (is_callable($o)) echo "true"; else echo "false";
// echoes "true"
?>
roland at mxchange dot org 27-Feb-2017 10:17
Please note that the example at comment #104633 is no longer valid with PHP 7 as it seems to be fixed:

PHP 7.0.16-1~dotdeb+8.1

correctly outputs:
bool(true)
mikko dot rantalainen at peda dot net 03-Feb-2017 08:29
Some additional notes about the implementation (PHP 5.6):

- <?php is_callable(array("myclass", "f1")) ?> will return true even if myclass::f1() is not a static method. As such, even if is_callable() will return true, the method cannot be called.

- <?php is_callable(array($object, "f2")) ?> will return true even if $object->f2() cannot be called because of method visibility (e.g. f2() is private or protected).
heah at heahprod dot com 20-Apr-2016 11:48
I don't know if it is a bug but when you test an array with a class and method, is_callable returns true for non static method.

Consider the following code:
<?php

class A
{
    public static function test()
    {
        echo 'test', '<br>';
    }

    public function hello()
    {
        echo 'hello', '<br>';
    }
}

echo "Static #1: call_user_func(array('A', 'test')) => ", call_user_func(array('A', 'test')), '<br>';
echo 'expect is_callable TRUE => ',
    is_callable(array('A', 'test'))
        ? 'TRUE, A::test() is callable statically'
        : 'FALSE, A::test() is not callable statically',
    '<br><br>'
;

echo "Static #2: call_user_func(array('A', 'hello')) => ", call_user_func(array('A', 'hello')), '<br>';
echo 'expect is_callable FALSE => ',
    is_callable(array('A', 'hello'))
        ? 'TRUE, A::hello() is callable statically'
        : 'FALSE, A::hello() is not callable statically',
    '<br><br>'
;

$a = new A();

echo "Instance #1: call_user_func(array(\$a, 'test')) => ", call_user_func(array($a, 'test')), '<br>';
echo 'expect is_callable TRUE => ',
    is_callable(array($a, 'test'))
        ? 'TRUE, $a::test() is callable'
        : 'FALSE, $a::test() is not callable',
    '<br><br>'
;

echo "Instance #2: call_user_func(array(\$a, 'hello')) => ", call_user_func(array($a, 'hello')), '<br>';
echo 'expect is_callable FALSE => ',
    is_callable(array($a, 'hello'))
        ? 'TRUE, $a::hello() is callable'
        : 'FALSE, $a::hello() is not callable',
    '<br><br>'
;

?>

Will output:
Static #1: call_user_func(array('A', 'test')) => test

expect is_callable TRUE => TRUE, A::test() is callable statically

Static #2: call_user_func(array('A', 'hello')) =>
Strict Standards: call_user_func() expects parameter 1 to be a valid callback, non-static method A::hello() should not be called statically in test.php on line 24
hello

expect is_callable FALSE => TRUE, A::hello() is callable statically

Instance #1: call_user_func(array($a, 'test')) => test

expect is_callable TRUE => TRUE, $a::test() is callable

Instance #2: call_user_func(array($a, 'hello')) => hello

expect is_callable TRUE => TRUE, $a::hello() is callable

------------------------------------------------------------

Also note that this works the same for inherited methods (I read other posts suggesting otherwise), and that private methods (static, inherited or both) always return false in any case as expected.

Tested with php 5.6.20.
izharaazmi at gmail dot com 11-Jan-2016 06:50
If the target class has __call() magic function implemented, then is_callable will ALWAYS return TRUE for whatever method you call it.
is_callable does not evaluate your internal logic inside __call() implementation (and this is for good).
Therefore every method name is callable for such classes.

Hence it is WRONG to say (as someone said):
...is_callable will correctly determine the existence of methods made with __call...

Example:
<?php
class TestCallable
{
    public function testing()
    {
          return "I am called.";
    }

    public function __call($name, $args)
    {
        if($name == 'testingOther')
        {
                return call_user_func_array(array($this, 'testing'), $args);
        }
    }
}

$t = new TestCallable();
echo $t->testing();      // Output: I am called.
echo $t->testingOther(); // Output: I am called.
echo $t->working();      // Output: (null)

echo is_callable(array($t, 'testing'));       // Output: TRUE
echo is_callable(array($t, 'testingOther'));  // Output: TRUE
echo is_callable(array($t, 'working'));       // Output: TRUE, expected: FALSE
?>
ffalek at banfi dot pl 13-Mar-2015 05:42
Example how is_callable works:

<?php
$counter = 0;

class TestClassOne {
    function testMethod(){
        global $counter;
        return ++$counter;
    }
    static function testMethodStatic(){
        global $counter;
        return ++$counter;
    }
}

class TestClassTwo {
    function __invoke() {
        global $counter;
        return ++$counter;
    }
}

function test_function() {
    global $counter;
    return ++$counter;
}

$p1 = 'test_function';
$p2 = new TestClassOne();
$p3 = ['TestClassOne', 'testMethodStatic'];
$p4 = [new TestClassOne(), 'testMethod'];
$p5 = new TestClassTwo();
$p6 = function() {
    global $counter;
    return ++$counter;
};

foreach ([$p1, $p2, $p3, $p4, $p5, $p6] as $p) {
    if(is_callable($p)){
        echo 'is invokable: yes '.$p().PHP_EOL;
    } else {
        echo 'is invokable: no'.PHP_EOL;
    }
}
?>

And output is:

is invokable: yes 1
is invokable: no
is invokable: yes 2
is invokable: yes 3
is invokable: yes 4
is invokable: yes 5
wowkise at gmail dot com 07-Mar-2013 10:10
beware calling is_callable on class that has the same method name will return false, i filed a bug report to be included in function description as example

<?php
class test {
 function test() {
 }
}
$class = new test();
var_dump(is_callable([$class, 'test']));
?>

will return false
np dot liamg at gmail dot com 08-Dec-2012 01:52
is_callable() will try __autoload(), if have one.
Athari 13-May-2012 03:58
For closures, the function will return true and $callable_name will be set to "Closure::__invoke".
passivesmoking AT yahoo DOT com 07-Jan-2012 06:06
is_callable doesn't seem able to resolve namespaces.  If you're passing a string, then the string has to include the function's full namespace.

<?php
namespace foo\bar\baz;

function something ()
{
    return (42);
}

var_dump (is_callable ('something')); // false
var_dump (is_callable ('foo\bar\baz\something')); // true
?>

It's easy to forget, but if you just prepend __NAMESPACE__ to your function name strings you should be fine in most cases.
fgm at osinet dot fr 27-Jun-2011 05:03
Note that, for the purpose of this function, an abstract method, although necessarily non-callable since it does not have a body, is still considered to be callable:

<?php
abstract class Foo {
  abstract function bar();
}

echo is_callable(array('Foo', 'bar'));
// display: 1
?>
Andy at txtNation dot com 27-Jun-2011 03:50
Note that is_callable is aware of context, and you can ask it things like parent::__construct from within a child constructor

<?php

    class TestClass extends TestClassParent {

        /** @brief Object initialisation callback
            @returns void */
        public function __construct() {

            # do initialisation

            # ...

            # if we have a parent

            if(is_callable('parent::__construct')) {

                # then bubble up

                parent::__construct();
            }
        }
    }
?>
colin 03-Oct-2010 11:30
I haven't seen anyone note this before, but is_callable will correctly determine the existence of methods made with __call. The method_exists function will not.

Example:
<?php

class Test {

    public function testing($not = false) {
        $not = $not ? 'true' : 'false';
        echo "testing - not: $not<br/>";
    }

    public function __call($name, $args) {
        if(preg_match('/^not([A-Z]\w+)$/', $name, $matches)) {
            $fn_name = strtolower($matches[1]);
            if(method_exists($this, $fn_name)) {
                $args[] = true; // add NOT boolean to args
                return call_user_func_array(array($this, $matches[1]), $args);
            }
        }
        die("No method with name: $name<br/>");
    }

}

$t = new Test();
$t->testing();
$t->notTesting();

echo "exists: ".method_exists($t, 'notTesting').'<br/>';
echo "callable: ".is_callable(array($t, 'notTesting'));

?>

Output:

testing - not: false
testing - not: true
exists:
callable: 1
Constantin Kpplinger 10-Jun-2010 12:16
It seems the only issue left with is_callable() is the disable_functions ini-setting. Apart from that, is_callable() will reliably evaluate whether the passed function or method can be called from within the same context is_callable() was called from, taking visibility and inheritance into account. This includes functions, regular and static methods, magic functions and methods and implemented interfaces (which are regular methods within the implementing class anyway).

<?php
function regular_function() {}

abstract class ParentTest
{
    public function public_parent_method() {}
    protected function protected_parent_method() {}
    public static function static_method() {}
    protected static function protected_static_method() {}
}

class CallableTest extends ParentTest implements Countable
{
    public function __invoke() { } // Introduced in 5.3, see http://php.net/manual/language.oop5.magic.php
    protected function protected_method() { }
    public function is_callable($args)
    {
        return is_callable($args);
    }
    // Countable
    public function count()
    {
        return 1;
    }
}

$o = new CallableTest();

// Regular function:
var_dump(is_callable('regular_function')); // true

// Magic __invoke method:
var_dump(is_callable($o)); // true if PHP >= 5.3, false otherwise

// Countable implementation (regular method really):
var_dump(is_callable(array($o, 'count'))); // true

// Protected method from outside the object's scope:
var_dump(is_callable(array($o, 'protected_method'))); // false

// Protected method from inside the object's scope via public proxy method:
var_dump($o->is_callable(array($o, 'protected_method'))); // true

// Parent's public method
var_dump(is_callable(array($o, 'public_parent_method'))); // true

// Parent's protected method
var_dump(is_callable(array($o, 'protected_parent_method'))); // false

// Parent's protected method via proxy
var_dump($o->is_callable(array($o, 'protected_parent_method'))); // true

// Parent's static public method
var_dump(is_callable('CallableTest::static_method')); // true

// Parent's static protected method
var_dump(is_callable('CallableTest::protected_static_method')); // false

// Parent's static protected method via proxy
var_dump($o->is_callable('CallableTest::protected_static_method')); // true
?>

Tested PHP versions were 5.2.9 on openSUSE 10.3 (x64) and 5.3.1 on Windows Server 2003 (x86).
juand at softwarecubes dot com 21-Feb-2009 11:39
Revised function with static support:

<?php
    /**
    * The is_callable php function only considers methods declared in the class itself, and ignores the parent's.
    * This version considers all of the hierarchy.
    *
    * @param (string|Object) $class_name
    * @param string $method_name
    * @param bool $static the method being tested is static.
    */
    public static function isCallable( $class_name, $method_name, $static = false ){

        if( !is_string( $class_name ) ){
            $class_name = get_class( $class_name );
        }

        // Define Callable
        if( $static ){
            $callable = "{$class_name}::{$method_name}";
        }else{
            $callable = array( $class_name, $method_name );
        }

        // Check class itself
            if( @is_callable( $callable ) === true ){
                if( $method_name == 'setEmailAddressTypeHash' ) {
                    ErrorHandler::preDump($callable);
                }
                return true;
            }

        // Check all parents
            while( $parent_class = get_parent_class( $class_name ) ){
                if( @is_callable( $callable ) === true ){
                    return true;
                }
                $class_name = $parent_class;
            }

        return false;
    }
?>
Rafael M. Salvioni 20-May-2008 09:10
The PHP's function is_callable not verify the visibility of the tested method.

The following function uses the Reflection classes of the PHP5 to check it.

<?php

/**
 * Function is_callback().
 *
 * @param mixed $var Var
 * @return bool
 */
function is_callback($var)
{
    if (is_array($var) && count($var) == 2) {
        $var = array_values($var);
        if ((!is_string($var[0]) && !is_object($var[0])) || (is_string($var[0]) && !class_exists($var[0]))) {
            return false;
        }
        $isObj = is_object($var[0]);
        $class = new ReflectionClass($isObj ? get_class($var[0]) : $var[0]);
        if ($class->isAbstract()) {
            return false;
        }
        try {
            $method = $class->getMethod($var[1]);
            if (!$method->isPublic() || $method->isAbstract()) {
                return false;
            }
            if (!$isObj && !$method->isStatic()) {
                return false;
            }
        } catch (ReflectionException $e) {
            return false;
        }
        return true;
    } elseif (is_string($var) && function_exists($var)) {
        return true;
    }
    return false;
}

?>
rahadotaboulfethatgmail.com 01-Mar-2008 04:44
is_callable generates an [E_STRICT] error if the  tested method cannot be called staticly. (and returns the good value)

I used @is_called
i'm using php 5.2.1
Quis strrev TA omicidio strrev TOD com 13-Nov-2007 03:50
is_callable() does _not_ check wheter this function is disabled by php.ini's disable_functions

use:

<?PHP
function is_disabled($function) {
  $disabled_functions=explode(',',ini_get('disable_functions'));
  return in_array($function, $disabled_functions);
}
?>

I`m running PHP 5.2.4
mw at NO-SPAM hire mason wolf dot com 19-Oct-2007 07:35
As empyone noted, early versions of php 5 incorrectly returned true if is_callable checked on a protected or private method. Later versions of php 5 will now only return true if the method is public and can be called externally. I do not know precisely when this behavior was changed, so you may have to test on your own. But sometime between 5.0.4, which empyone said he was using, and 5.2.4 where I tested it myself, the behavior was modified.
hcblue 24-Aug-2006 01:51
True that method_exists() is faster than is_callable(). However, is_callable() will be able to correctly recognize method calls handled by __call() in PHP 5, while method_exists() will not.
jphp at dsf dot org dot uk 12-Feb-2006 03:38
bob at theshirdshift:

"function_exists" doesn't do this, no, but "method_exists" works fine, and is still faster than is_callable:

<?php
function doTimes($start, $end)
  {
   $start_time = explode (" ", $start);
   $start_time = $start_time[1] + $start_time[0];
   $end_time = explode (" ", $end);
   $end_time = $end_time[1] + $end_time[0];
   $time = $end_time - $start_time;
   return $time;
  }

class test
  {
     function test()
     {
         return true;
     }
  }

$test = new test;

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
     if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
     if(method_exists('test', 'test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists    = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>method_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 method_exists in ".$timeExists." seconds";
?>

is_callable = TRUE, method_exists = TRUE

Did 10000 is_callables in 0.410346984863 seconds
Did 10000 method_exists in 0.175447940826 seconds
yetanotheruser at hotmail etc 15-Dec-2005 06:47
I have come across a strange oddity in versions around the 4.3.11 mark - I may have missunderstood the purpose of this function but hope this'll be helpful for some.

The point the code below is supposed to illustrate is that in some cases with

    <? $myFunc = Array( $myObj, 'myMethod' ); ?>

    <? is_callable( $myFunc, true, $callMe ); ?>

will return true, and give you $callMe set to myObj::myMethod but calling

    <? $callMe(); ?>

doesn't work... however calling

    <? $myFunc[0]->$myFunc[1](); ?>

seems to work fine..

... the reason all the code is down there is I think this oddity is due to how/the order in which I've instantiated my classes or something...

anyhow... HTH someone! :-)

Code follows:

FILE 1 :
<?
    include('myTools');

    $foo = new myClass();

    print $foo->getMySource();

    class myClass{

        var $flibble = 'wibble';

        function myClass(
            // Initialise loads of stuff.. including..
            $this->tools = new myTools();
        )

        function getMySource(){
            // This just returns the source.. ok, like some HTML to go into an email for example.
            // Some arguments;
            $args   = $this->flibble;
            // Call our Tool that returns the source..
            $source = $this->tools->returnSource( Array ( $this, 'someHTML' ), $args );
            // and return it..
            return ( $source );
        }

        function someHTML($args){
            // Leave PHP
            ?>
            Here is some HTML.. that we want to build outside a PHP block,
            possibly just cos it's tidier in <B>your favourite text editor</B>..
            .. or you want this function to be elsewhere.. for your designers
            to play with etc.. ... incidentally I'd like to say "<?=$args?>" etc.
            <?
            // .. and we're back.
        }
    }

?>

FILE 2:

<?
    /* OK - this is some other big library and a whole load more
       faff but this is the particular function in question... it
       just calls the function it's been asked to and uses an output
       buffer to grab the output and return it as a string rather than
       letting it go to terminal/browser.... useful for grabbing PHP pages
       for spidering, emailing etc. etc. etc..
    */

    class myTools(){

        function returnSource($func, $args){

            if ( is_callable ( $func, true, $callMe ){
                // Start a buffer
                ob_start();
                // Calling the function like this DOESN'T seem to work:
                // ~~~~~~~~
                // "Command not found : myClass::someHTML"
                // $callMe($args);
                // ~~~~~~~~
                // But - what I've discovered is that this behaves fine..
                if ( is_array($func) ){
                    $func[0]->$func[1]($args);
                } else {
                    $func($args);
                }
                // Then we just carry on with our code..
                $rtn =     ob_get_contents();
                ob_clean();
                return ( $rtn );
            } else {
                error_log("Doh!");
            }
        }
    }

?>
empyone at tiscalinet dot it 08-Nov-2005 12:41
To corey at eyewantmedia dot com:

your misunderstanding lies in passing in the naked $object parameter. It is correct for is_callable to return FALSE since you cannot 'call an object', you can only call one of its methods, but you don't specify which one. Hence:

is_callable(array($object, 'some_function'), [true or false], $callable_name)

will yield the correct result.

Notice, though, that a quick test I made (PHP 5.0.4) showed that is_callable incorrectly returns TRUE also if you specify the name of a protected/private method from outside of the context of the defining class, so, as wasti dot redl at gmx dot net pointed out, reflection is the way to go if you want to take visibility into account (which you should for true OOP, IMHO).
wasti dot redl at gmx dot net 09-Oct-2005 04:14
The way to discover whether a method exists in face of a __call is reflection.

It should be mentioned that although array('Test', 'func') is callable according to this function (where func is a public static method of Test), actually calling this construct as $fn() fails.
corey at eyewantmedia dot com 18-Mar-2005 03:39
I've been spending a month on and off trying to figure out why

is_callable($object, [true or false], $varContainingFunctionName)

returned false when it should not have (ie: $object->FunctionName() was callable), I realized I must have misunderstood its purpose. If you find yourself in the same situation, try

function_exists(string functionname)

or

method_exists ( object object, string method_name )

before you rip your hair out :)
mcroghan at digitalkeg dot com 10-Feb-2005 07:36
Be careful when using this function and __call (PHP5).  This function will always report true when using __call.

Need a specific function for the purpose of checking if a class method exists explicitly even when using __call.

Haven't ruled out the possibility of the existence of such a function yet.  So if someone knows of one, please point it out.
bob at thethirdshift dot net 23-Jun-2004 09:54
I, too, was wondering whether is_callable or function exists is faster when checking class methods.  So, I setup the following test:

<?php
function doTimes($start, $end)
  {
    $start_time = explode (" ", $start);
    $start_time = $start_time[1] + $start_time[0];
    $end_time = explode (" ", $end);
    $end_time = $end_time[1] + $end_time[0];
    $time = $end_time - $start_time;
    return $time;
  }

class test
  {
      function test()
      {
          return true;
      }
  }

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(function_exists('test::test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists     = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>function_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 function_exists in ".$timeExists." seconds";
?>

This gives the output :

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0640790462494 seconds
Did 10000 function_exists in 0.0304429531097 seconds

So the fact that function_exists is twice as fast is slightly over shadowed by the fact that it doesn't work on class methods, at least not as far as I can tell.


Verify that the contents of a variable is a countable value

  • ? is_callable
  • is_double ?
  • PHP Manual
  • Variable handling 函数
  • Verify that the contents of a variable is a countable value

is_countable

(PHP 7 >= 7.3.0, PHP 8)

is_countable — Verify that the contents of a variable is a countable value

说明

is_countable ( mixed $value ) : bool

Verify that the contents of a variable is an array or an object implementing Countable

参数

value

The value to check

返回值

Returns true if value is countable, false otherwise.

更新日志

版本 | 说明
7.3.0 | is_countable() has been added.

范例

Example #1 is_countable() examples

<?php
var_dump(is_countable([1, 2, 3])); // bool(true)
var_dump(is_countable(new ArrayIterator(['foo', 'bar', 'baz']))); // bool(true)
var_dump(is_countable(new ArrayIterator())); // bool(true)
var_dump(is_countable(new stdClass())); // bool(false)

参见

  • is_array() - 检测变量是否是数组
  • is_object() - 检测变量是否是一个对象
  • is_iterable() - Verify that the contents of a variable is an iterable value
  • is_bool() - 检测变量是否是布尔值

User Contributed Notes

info at ensostudio dot ru 25-Oct-2020 06:29
Note: if is_countable() return true is does not guarantee that the it can be calculated recursively and correctly:
<?php
$iterator = new ArrayIterator(['one', 'two', new ArrayIterator(['three', 'four'])]);
var_dump(is_countable($iterator), count($iterator, COUNT_RECURSIVE));
// return TRUE and 3!
?>
Anonymous 25-Oct-2020 04:58
Fixed polyfill:
<?php
if (! function_exists('is_countable')) {
    /**
      * @param mixed $value The value to check
      * @return bool
      */
    function is_countable($value): bool
    {
        return is_array($value) || (is_object($value) && $value instanceof Countable);
    }
}
?>
renic 12-Jun-2019 08:33
be wary of using is_object($var) and assuming that the object has implemented Countable.  Not all objects are countable directly with count().
danmichaelo at gmail dot com 08-Apr-2019 08:33
Note that a polyfill for this method is also provided by the symfony/polyfill project.
deoomen 01-Apr-2019 11:58
Polyfill written by arisendrake is not quite good. It return FALSE when checking an Simple XML Node but count() works properly on PHP 7.1 and 7.3.
Better is this one:

<?php
if (version_compare(PHP_VERSION, "7.3") < 0 && !function_exists("is_countable")) {
    function is_countable($var): bool
    {
        return (is_array($var) || is_object($var) || is_iterable($var) || $var instanceof Countable);
    }
}
?>
info at arisendrake dot de 30-Aug-2018 11:10
If you are unable to upgrade to PHP 7.3 (not released at the time of writing), you can use this simple polyfill:

<?php
if (!function_exists('is_countable')) {
    function is_countable($var) {
        return (is_array($var) || $var instanceof Countable);
    }
}
?>


is_float 的别名

  • ? is_countable
  • is_float ?
  • PHP Manual
  • Variable handling 函数
  • is_float 的别名

is_double

(PHP 4, PHP 5, PHP 7, PHP 8)

is_double — is_float() 的别名

描述

此函数是 is_float() 的别名函数。

User Contributed Notes

There are no user contributed notes for this page.


检测变量是否是浮点型

  • ? is_double
  • is_int ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否是浮点型

is_float

(PHP 4, PHP 5, PHP 7, PHP 8)

is_float — 检测变量是否是浮点型

描述

is_float ( mixed $var ) : bool

如果 var 是 float 则返回 true，否则返回 false。

Note:

若想测试一个变量是否是数字或数字字符串（如表单输入，它们通常为字符串），必须使用 is_numeric()。

参见 is_bool()、is_int()、is_integer()、is_numeric()、is_string()、is_array() 和 is_object()。

User Contributed Notes

Anonymous 28-Jan-2021 10:38
is_float() returns true for NAN, INF and -INF. You may want to test is_float($value) && is_finite($value), or alternatively filter_var($value, FILTER_VALIDATE_FLOAT) !== false.
ivan dot maruca at gmail dot com 19-Oct-2015 11:31
check if string/numeric is float or not :

<?php
function isFloat($value){
  return ((int)$value != $value) ;
}

isFloat('1.5') ;//return true
isFloat('15');//return false
isFloat('1e16');//return true
isFloat('foo');//return false
isFloat(5.98);//return true
isFloat(5);//return false
?>
Erutan409 at Hotmail dot com 19-May-2015 02:37
Boylett's solution is elegant (http://php.net/manual/en/function.is-float.php#85848), but won't work for long float's or variables that are not explicitly type of 'string' or for long floats that are encased in quotes, making it a string that will be truncated/rounded when cast to a float.  So, further logic must be completed to test for the case.  Take the following example:

<?php

if (!function_exists("test_float")) {

    function test_float($test) {

        if (!is_scalar($test)) {return false;}

        $type = gettype($test);

        if ($type === "float") {
            return true;
        } else {
            return preg_match("/^\\d+\\.\\d+$/", $test) === 1;
        }

    }

}

$test = "3.14159265358979323846264338g32795";

var_dump($test);
var_dump((float)$test);
var_dump($test == (string)(float)$test);
var_dump(test_float($test));

?>

Will produce (32-bit):

string(34) "3.14159265358979323846264338g32795"
float(3.1415926535898)
bool(false)
bool(false)

So far, so good, right?  Yeah, but it's misleading, because the string is so long, that when it's converted to a float, it won't be equivalent to the comparison of the value being cast back into a string .  So the aforementioned short function works.  Look at this next example:

<?php

$test = 3.1415926535897932384626433832795;

var_dump($test);
var_dump((float)$test);
var_dump($test == (string)(float)$test);
var_dump(test_float($test));

?>

Will produce (32-bit):

float(3.1415926535898)
float(3.1415926535898)
bool(false)
bool(true)

Why is it not working now, but the value is truly a float?  Same reasoning as mentioned before.  The float is so long that it's truncated/rounded and doesn't match the comparison being done with the short-hand function.

So, as you can see, more logic should be applied to the variable you're testing.
nonzer0value 26-Mar-2015 08:20
Coercing the value to float and back to string was a neat trick. You can also just add a literal 0 to whatever you're checking.

<?php
function isfloat($value) {
  // PHP automagically tries to coerce $value to a number
  return is_float($value + 0);
}
?>

Seems to work ok:

<?php
isfloat("5.0" + 0);  // true
isfloat("5.0");  // false
isfloat(5 + 0);  // false
isfloat(5.0 + 0);  // false
isfloat('a' + 0);  // false
?>

YMMV
KIVagant at gmail dot com 21-Aug-2012 12:04
Yet another regular expression for float in real life:

<?php
function isTrueFloat($val)
{
    $pattern = '/^[-+]?(((\\\\d+)\\\\.?(\\\\d+)?)|\\\\.\\\\d+)([eE]?[+-]?\\\\d+)?$/';

    return (!is_bool($val) && (is_float($val) || preg_match($pattern, trim($val))));
}
?>

// Matches:
1, -1, 1.0, -1.0, '1', '-1', '1.0', '-1.0', '2.1', '0', 0, ' 0 ', ' 0.1 ', ' -0.0 ', -0.0, 3., '-3.', '.27', .27, '-0', '+4', '1e2', '+1353.0316547', '13213.032468e-13465', '-8E+3', '-1354.98879e+37436'

// Non-matches:
false, true, '', '-', '.a', '-1.a', '.a', '.', '-.', '1+', '1.3+', 'a1', 'e.e', '-e-4', 'e2', '8e', '3,25'
Mitch 12-Jun-2012 08:27
Another RegEx for matching floats:
/^[+-]?(\d*\.\d+([eE]?[+-]?\d+)?|\d+[eE][+-]?\d+)$/

Matches:
1e2
+1353.0316547
13213.032468e-13465
-8E+3
-1354.98879e+37436

Non-matches:
8
e2
-e-4
E
asdf.safd
8e

Enjoy.
Boylett 20-Sep-2008 09:29
If you want to test whether a string is containing a float, rather than if a variable is a float, you can use this simple little function:

function isfloat($f) return ($f == (string)(float)$f);
ckelley at the ca - cycleworks dot com 14-Jul-2008 03:39
Personally, I use an implicit cast:

if( is_float($value+1) ){
    $value=sprintf("%.2f",$value);
}

Which turns 22.0000000 query result into 22.00 for display to users.
kshegunov at gmail dot com 31-Mar-2008 01:32
As celelibi at gmail dot com stated, is_float checks ONLY the type of the variable not the data it holds!

If you want to check if string represent a floating point value use the following regular expression and not is_float(),
or poorly written custom functions.

/^[+-]?(([0-9]+)|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*)|
(([0-9]+|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*))[eE][+-]?[0-9]+))$/
phper 25-Jan-2006 12:08
A better way to check for a certain number of decimal places is to use :

$num_dec_places = 2;
number_format($value,$num_dec_places);


检测变量是否是整数

  • ? is_float
  • is_integer ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否是整数

is_int

(PHP 4, PHP 5, PHP 7, PHP 8)

is_int — 检测变量是否是整数

说明

is_int ( mixed $value ) : bool

检测变量的类型是否为整数（integer）。

Note:

若想检测变量是否是数字或数字字符串（如表单输入，它们通常为字符串），则必须使用 is_numeric() 。

参数

value

要检测的变量。

返回值

如果 value 是 int，则返回 true，否则返回 false。

范例

Example #1 is_int() 示例

<?php
$values = array(23, "23", 23.5, "23.5", null, true, false);
foreach ($values as $value) {
    echo "is_int(";
    var_export($value);
    echo ") = ";
    var_dump(is_int($value));
}
?>

以上例程会输出：

is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)

参见

  • is_bool() - 检测变量是否是布尔值
  • is_float() - 检测变量是否是浮点型
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_string() - 检测变量是否是字符串
  • is_array() - 检测变量是否是数组
  • is_object() - 检测变量是否是一个对象

User Contributed Notes

lksunny at live dot hk 24-Aug-2017 09:19
<?
function check_num($num){
    if (preg_match("#^(-[0-9]{1,}|[0-9]{1,})$#", $num)){
        return true;
    }else{
        return false;
    }
}
var_dump(-1); //True
var_dump("-1"); //True
var_dump("1"); //True
var_dump("-999999999999999999"); //True
var_dump("999999999999999999"); //True
?>

negative number will be true :)
Hector (hector-ordonez.com) 25-Jul-2016 12:00
Simon Neaves's answer is incomplete: negative integers will return false.

I recommend checking stackoverflow's answers:
http://stackoverflow.com/questions/6416763/checking-if-a-variable-is-an-integer-in-php
Vasiliy Makogon 08-Apr-2016 10:10
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:

<?php
function isInteger($val)
{
    if (!is_scalar($val) || is_bool($val)) {
        return false;
    }
    if (is_float($val + 0) && ($val + 0) > PHP_INT_MAX) {
        return false;
    }
    return is_float($val) ? false : preg_match('~^((:?+|-)?[0-9]+)$~', $val);
}

function isFloat($val)
{
    if (!is_scalar($val)) {
        return false;
    }
    return is_float($val + 0);
}

foreach ([
    '11111111111111111', 11111111111111111, // > PHP_INT_MAX - presents in PHP as float
    1, '10', '+1', '1.1', 1.1, .2, 2., '.2', '2.',
    '-2.', '-.2', null, [], true, false, 'string'
] as $value) {
    echo $value . ':' . gettype($value) . ' is Integer? - '  . (isInteger($value) ? 'yes' : 'no') . PHP_EOL;
    echo $value . ':' . gettype($value) . ' is Float? - '  . (isFloat($value) ? 'yes' : 'no') . PHP_EOL;
}
?>
davide dot renzi at gmail dot com 16-Dec-2015 12:32
I've found a faster way of determining an integer.
On my env, this method takes about half the time of using is_int().

Cast the value then check if it is identical to the original.

<?php
if ( (int) $n !== $n ) {
    echo 'not is int';
} else {
    echo 'is int';
}
?>
PHPDev esurf er s >dot 15-Apr-2015 02:32
This will check if something has an acceptable integer value, such as

a string with int value like "1" or "1.0"
a float with int value like 1.0
an int like 12e5

The same as is_numeric, but with integer values.

<?php

    function isIntValued($var) {
        if(is_numeric($var)) {
            $var=(float)$var;
            return ((float)(int)$var)===$var;
        }
        return FALSE;
    }

?>
felix dot b at outlook dot com 16-Mar-2015 02:13
((int)$foo === $foo) does exactly the same as is_int($foo), but is faster performancewise, because PHP has quite an overhead on function calls.

As you can see the expression only returns true if the type (and value) of $foo is the same as int-casted $foo, which is only the case when foo is an int.

This applies to all the other is* functions aswell.
Anonymous 07-Mar-2015 04:20
Sometimes, we need to validate if a DECIMAL returned by a SQL database is an int or not. DECIMAL always return .000 at end of the string.

Then i use:
<?php
function isInteger($input){
{
    if(strpos($input,"."))
        $input=preg_replace("/\.$/","",rtrim(strval($input),"0"));
    return (ctype_digit($input));
}
?>
ing dot alpi at gmail dot com 18-Sep-2013 03:18
Remember that some source of data always give a string data type.
That's the case with cookies and $_GET.
if you need to check against those values, try to convert them into numbers first.
The easiest way of doing so is adding a zero before your var, just like:

<?php
$var = '15'; // ...or $var = $_COOKIE['myvar'] or $var =
$_GET['myvar']...

is_int($var);  // now returns FALSE

$var += 0;

is_int($var);  // now returns TRUE
?>
some at somewhere dot com 02-Jul-2013 03:35
<?php
// check if input is a valid number
// first number must be 1 thru 9, followed by a number 0-9, no decimals
// true for "1", "1000"
// false for "01", "-1", "1.2"
function isInteger($input){
  return preg_match('@^[1-9][0-9]*$@',$input) === 1;
}
?>
petepostma at gmail dot spam dot com 17-Jul-2012 06:38
There is a versa to the vice of this int only type check.

is_int( $integer_type) will only return true, if the TYPE is int, not the value
ctype_digit( $string_type) will only return true if the TYPE is string, and its value is INT

therefore:
 return ( is_int($value) || ctype_digit($value) );
nicolas dot giraud at actiane dot com 27-Jun-2012 09:24
Just a shorter way to check if your variable is an int or a string containing a int without others digit than 0 to 9 :

<?php
$bool = ( !is_int($value) ? (ctype_digit($value)) : true );

$value = 42; //true
$value = '42'; //true
$value = '1e9'; //false
$value = '0155'; //true
$value = 0155; //true
$value = 0xFF; //true while it's just the same as 255
$value = '0xFF'; //false
$value = 'a'; //false
$value = array(); //false
$value = array('5'); //false
$value = array(5); false
$value = ''; //false
$value = NULL; //false

?>

Short & cool :)
arturs at indigo dot lv 04-May-2012 11:31
Sometime needed check if string containing numbers is integer or not. Then I created this small function:
<?php
function is_integer2($v) {
  $i = intval($v);
  if ("$i" == "$v") {
    return TRUE;
  } else {
    return FALSE;
  }
}
?>
andre dot roesti at 7flex dot net 27-Jul-2010 05:51
With this function you can check if every of multiple variables are int. This is a little more comfortable than writing 'is_int' for every variable you've got.

<?php
function are_int ( ) {
    $args = func_get_args ();
    foreach ( $args as $arg )
        if ( ! is_int ( $arg ) )
            return false;
    return true;
}

// Example:
are_int ( 4, 9 ); // true
are_int ( 22, 08, 'foo' ); // false
?>
Robin 27-Mar-2010 08:22
Keep in mind that is_int() operates in signed fashion, not unsigned, and is limited to the word size of the environment php is running in.

In a 32-bit environment:

<?php
is_int( 2147483647 );           // true
is_int( 2147483648 );           // false
is_int( 9223372036854775807 );  // false
is_int( 9223372036854775808 );  // false
?>

In a 64-bit environment:

<?php
is_int( 2147483647 );           // true
is_int( 2147483648 );           // true
is_int( 9223372036854775807 );  // true
is_int( 9223372036854775808 );  // false
?>

If you find yourself deployed in a 32-bit environment where you are required to deal with numeric confirmation of integers (and integers only) potentially breaching the 32-bit span, you can combine is_int() with is_float() to guarantee a cover of the full, signed 64-bit span:

<?php
$small = 2147483647;         // will always be true for is_int(), but never for is_float()
$big = 9223372036854775807;  // will only be true for is_int() in a 64-bit environment

if( is_int($small) || is_float($small) );  // passes in a 32-bit environment
if( is_int($big) || is_float($big) );      // passes in a 32-bit environment
?>
thierryreeuwijk at hotmail dot com 14-Jan-2010 02:04
If you only want integer values like 23 or 0155, or form/string integer values like "23" or "0155" to be valid, this should work just fine.

<?php

    function int($int){

        // First check if it's a numeric value as either a string or number
        if(is_numeric($int) === TRUE){

            // It's a number, but it has to be an integer
            if((int)$int == $int){

                return TRUE;

            // It's a number, but not an integer, so we fail
            }else{

                return FALSE;
            }

        // Not a number
        }else{

            return FALSE;
        }
    }

    print("155".int(155)."<br>");
    print("15.5".int(15.5)."<br>");
    print("\"155\"".int("155")."<br>");
    print("\"15.5\"".int("15.5")."<br>");
    print("\"0155\"".int("0155")."<br>");
    print("\"I'm 155\"".int("I'm 155")."<br>");
    print("\"test\"".int("test")."<br>");
    print("\"\"".int(""));
?>

The above returns:

155        TRUE
15.5       FALSE
"155"      TRUE
"15.5"     FALSE
"0155"     TRUE
"I'm 155"  FALSE
"test"     FALSE
""         FALSE
me at rexxars dot com 16-Sep-2009 05:23
I was looking for the fastest way to check for an unsigned integer which supported large numbers like 4318943448871348 or 0xFFFFFFFF.

Fastest I came up with is this:
<?php
function is_unsigned_int($val) {
    return ctype_digit((string) $value));
}
?>

Will return true on 1515, 0xFFFFFFFF, '3515' and '1365158185855141'.
Will return false on 0.1515, '415.4134' and '-616'.

Be aware though, before PHP 5.1.0 this will return true on an empty string.

According to my benchmarks this is about 30% faster than the regex ^\d+$.
Roberto Rama 21-Jul-2009 11:39
Use this instead if you wanna know if a string is explicitly a number:

<?php

function isint( $mixed )
{
    return ( preg_match( '/^\d*$/'  , $mixed) == 1 );
}

var_export( isint( '123' ) ); //This will return true

var_export( isint( 123 ) ); //This will return true

var_export( isint( 'asd' ) ); //This will return false

var_export( isint( '123asd123' ) ); //This will return false

?>
e dot sand at elisand dot com 09-Apr-2009 08:27
Simon Neaves was close on explaining why his function is perfect choice for testing for an int (as possibly most people would need).  He made some errors on his ctype_digit() output though - possibly a typo, or maybe a bug in his version of PHP at the time.

The correct output for parts of his examples should be:

<?php
var_dump(ctype_digit(23)); //bool(false)
var_dump(ctype_digit("23")); //bool(true)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(false)
?>

As you can see, the reason why using *just* ctype_digit() may not always work is because it only returns TRUE when given a string as input - given a number value and it returns FALSE (which may be unexpected).
leonix at motd dot ru 16-Dec-2008 12:08
another_is_int() is almost perfect, but it treats boolean true as int because
1 == (int) true == (string) true == '1'.

Fixed version:

<?php
/**
 * Checks if the given value represents integer
 */
function int_ok($val)
{
    return ($val !== true) && ((string)(int) $val) === ((string) $val);
}
?>
paulo dot koch at g_mail dot com 17-Oct-2008 12:30
Don't over-engineer it.

<?php
function another_is_int($a){
    return ((string) $a) === ((string)(int) $a);
}
?>
Wryel Covo - ryryel[at]gmail[dot]com 14-Oct-2008 11:53
<?php
function onlyNumbers($string){
    //This function removes all characters other than numbers
    //Esta fun??o limpa a url e conserva apenas os numeros
    $string = preg_replace("/[^0-9]/", "", $string);
    return (int) $string;
}

echo $test = onlyNumbers("as87d68a6db8a7d686dx8a6dx"); //2147483647
echo "<br/>";
echo onlyNumbers("xn89d9x797d9a8x7-"); //899797987
echo "<br/>";
if(is_int($test)){
    echo "Is int ! - é inteiro !"; // This OK !
} else {
    echo "Not int ! - N?o é inteiro";
}
?>
mark at codedesigner dot nl 26-Jun-2008 06:34
updated version from Simon Neaves

<?php
function isInteger($input){
  return preg_match('@^[-]?[0-9]+$@',$input) === 1;
}
?>

this function checks if the string:
- starts with a - sign (optional)
- ends with 1 or more numeric chars
Julien Picalausa 11-May-2008 02:44
To check if a string ($s) is a representation of an integer (including representations is scientific notation and negative numbers), you can use the following test, provided that you don't expect values that are out of bounds for an integer.

is_numeric($s) && floatval($s) == intval(floatval($s))

If the test returns true, the string is a representation of an integer.
is_numeric (if it works as intended) protects from strings that are not proper numbers.
The comparison filters anything that is non_integer

If, for performance reasons, you want to avoid converting to float twice, it can also be written:
is_numeric($s) && ($f = floatval($s)) == intval($f)

If you plan to get values that cannot be representated with an integer and are ready to deal with a float, you can use floor instead of intval, as long as you are ready to deal with floats. Even so, that method will become unreliable when the precision of the float becomes insufficient for getting to the fractional part of the number
Simon Neaves 29-Apr-2008 11:14
I've found that both that is_int and ctype_digit don't behave quite as I'd expect, so I made a simple function called isInteger which does. I hope somebody finds it useful.

<?php
function isInteger($input){
    return(ctype_digit(strval($input)));
}

var_dump(is_int(23)); //bool(true)
var_dump(is_int("23")); //bool(false)
var_dump(is_int(23.5)); //bool(false)
var_dump(is_int(NULL)); //bool(false)
var_dump(is_int("")); //bool(false)

var_dump(ctype_digit(23)); //bool(true)
var_dump(ctype_digit("23")); //bool(false)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(true)

var_dump(isInteger(23)); //bool(true)
var_dump(isInteger("23")); //bool(true)
var_dump(isInteger(23.5)); //bool(false)
var_dump(isInteger(NULL)); //bool(false)
var_dump(isInteger("")); //bool(false)
?>
qlimmax at gmail dot com 07-Apr-2008 10:58
function is_natural($natural,$zero=true)
{
if(ctype_digit($natural))
{
    if($zero)
    {
        $natural_test=(int)$natural;
        if((string)$natural_test !== $natural) return false;
        else return true;
    }
    else return true;
}
else return false;
}

true for ("0","1","2","3",...) false for("-1","01","adS","#@!$%^&*-...","0.7","0,7", "0x12",...)
if $zero=false
true for("0","00","1","01",...) false("-1","#@!$%^&*-...","adS","0.7","0,7", "0x12",...)
tudor at tudorholton dot com 04-Jul-2007 06:27
Please note this from the Integer datatype page:

"The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined from PHP_INT_SIZE, maximum value from PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5."

This is particularly important if you are doing validation of large keys or any number larger than 2,000,000,000 (e.g. telephone numbers)
Ender at soldat dot nl 16-Feb-2006 03:38
Be aware that is_numeric (mentioned in this article as the proper way to validate string numbers) also allows numbers in scientific and hexadecimal annotation. Thus DO NOT USE that function to validate user input that will be used as id number for in a query for example, this could cause mysql errors. Use ctype_digit instead.
ludvig dot ericson at gmail dot com 06-Jan-2006 01:00
I would like to say that is_int() is pretty helpfull when looking for neat proper ways to check functions that return either integers or booleans (false) on failure (strpos, socket_select, etc.)
<?php
function mySelect() {
    global $someSockets;
    $ret = socket_select($someSockets, $o = array(), $e = array(), 0);
    if (!$ret)
        return is_int($ret);
    /* FURTHER PROCESSING HERE */
    return true;    // Return true if the function proceeded as expected.
}
?>
The point of doing this is that if you put this in a while() loopo, you'll break it when the select fails.
<?php
while (mySelect());
?>

Hope you get the point
 - toxik
lclkk at urbanvagabond dot net 15-Sep-2003 07:24
I think the function below is a robust test for integers working on all datatypes. It works by first checking that a number can be evaluated numerically, and then secondly that the integer evaluation matches the original number.

Test cases are included.

<?
function myIsInt ($x) {
    return (is_numeric($x) ? intval($x) == $x : false);
}

function Test($x) {
    echo "$x is " . ( myIsInt($x) ? ('an integer. The integer value is ' . intval($x)) : 'not an integer.');
    echo "\n";
}

echo "These should be integers...\n";
Test(1);
Test(5);
Test(10);
Test(10.0);
Test(20.0);
Test(-20.0);
Test(0+4+4.5+4.5);
Test("10.0");
Test("+14");
Test("-15");
Test("0");

echo "\nThese should not be integers...\n";
Test(true); // watch out, this displays as '1'
Test(false);
Test("moose");
Test("3.5");
Test("-214235.5");
Test(""); // empty string
Test(array(1,2,3));
Test(dir('.')); // object
Test(null);
?>
gabe at websaviour dot com 14-Jul-2003 11:08
Although this can be inferred from the documentation, beware of numeric strings.  I ran into the problem in a MySQL app where I would either SELECT an INT PRIMARY KEY or INSERT a new record and use mysql_insert_id() to get the KEY before continuing onto the new section.

I used is_int() to make sure the subsequent queries wouldn't break when using the key variable.  Unfortunately I failed to realize that while mysql_insert_id() returns an int, mysql_result() always returns a string even if you are SELECTing from an INT field.

Spent at least 30 minutes trying to figure out why existing records weren't getting linked, but new records would link fine.  I ended up using intval() on mysql_result() to make sure subsequent queries still always work.


is_int 的别名

  • ? is_int
  • is_iterable ?
  • PHP Manual
  • Variable handling 函数
  • is_int 的别名

is_integer

(PHP 4, PHP 5, PHP 7, PHP 8)

is_integer — is_int() 的别名

描述

此函数是 is_int() 的别名函数。

User Contributed Notes

ru dot mahmoud at mail dot ru 17-Jan-2019 08:05
using function :

if(is_integer($_POST[mobile_number])){
 return true; //// 0-9
}else{
 echo "Wrong number";
return false;
}
gldbrzent at gmail dot com 24-Sep-2017 07:37
There are two different functions.  But, the reason why is beyond the scope of this article!
being dot juan at icloud dot com 26-Jul-2017 05:07
There is no difference, per se. is_integer() is an alias of is_int().


Verify that the contents of a variable is an iterable value

  • ? is_integer
  • is_long ?
  • PHP Manual
  • Variable handling 函数
  • Verify that the contents of a variable is an iterable value

is_iterable

(PHP 7 >= 7.1.0, PHP 8)

is_iterable — Verify that the contents of a variable is an iterable value

说明

is_iterable ( mixed $value ) : bool

Verify that the contents of a variable is accepted by the iterable pseudo-type, i.e. that it is either an array or an object implementing Traversable

参数

value

The value to check

返回值

Returns true if value is iterable, false otherwise.

范例

Example #1 is_iterable() examples

<?php

var_dump(is_iterable([1, 2, 3]));  // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3])));  // bool(true)
var_dump(is_iterable((function () { yield 1; })()));  // bool(true)
var_dump(is_iterable(1));  // bool(false)
var_dump(is_iterable(new stdClass()));  // bool(false)

?>

参见

  • is_array() - 检测变量是否是数组

User Contributed Notes

mopsyd at me dot com 01-Apr-2018 04:24
A slight correction to brcontainer's polyfill, which prevents errors on a non-object in a non-blocking way, and also corrects the issue of  the conditional checking "file_exists" instead of the correct "function_exists":

if ( !function_exists(  'is_iterable' ) )
{

    function is_iterable( $obj )
    {
        return is_array( $obj ) || ( is_object( $obj ) && ( $obj instanceof \Traversable ) );
    }

}

The original answer would not have resolved correctly, because it was looking for a file instead of a function, and the provided method would error if given a non-iterable non-object value such as false.
brcontainer at yahoo dot com dot br 09-Mar-2018 08:35
Polyfill for PHP5.6 and PHP7.0

    if (!file_exists('is_iterable')) {
        function is_iterable($obj)
        {
            return is_array($obj) || $obj instanceof \Traversable;
        }
    }
anatoly dot pashin at gmail dot com 01-Feb-2018 07:02
Here is more details on iterable type: http://php.net/manual/en/language.types.iterable.php


is_int 的别名

  • ? is_iterable
  • is_null ?
  • PHP Manual
  • Variable handling 函数
  • is_int 的别名

is_long

(PHP 4, PHP 5, PHP 7, PHP 8)

is_long — is_int() 的别名

描述

此函数是 is_int() 的别名函数。

User Contributed Notes

There are no user contributed notes for this page.


检测变量是否为 null

  • ? is_long
  • is_numeric ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否为 null

is_null

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

is_null — 检测变量是否为 null

描述

is_null ( mixed $var ) : bool

如果 var 是 null 则返回 true，否则返回 false。

查看 null 类型获知变量什么时候被认为是 null，而什么时候不是。

参见 null、is_bool()、is_numeric()、is_float()、is_int()、is_string()、is_object()、is_array()、is_integer() 和 is_real()。

User Contributed Notes

etimjoshua4 at gmail dot com 20-Jan-2021 05:09
I've found that for HTTP requests such as POST, is_null isn't the most reliable choice for checking if empty.

Try using

if(trim($var) == ""){
    // do something
}

instead.

I think the request does something to the input that makes it definitely not NULL.
contact dot 01834e2c at renegade334 dot me dot uk 25-May-2015 06:57
In PHP 7 (phpng), is_null is actually marginally faster than ===, although the performance difference between the two is far smaller.

PHP 5.5.9
is_null - float(2.2381200790405)
===     - float(1.0024659633636)
=== faster by ~100ns per call

PHP 7.0.0-dev (built: May 19 2015 10:16:06)
is_null - float(1.4121870994568)
===     - float(1.4577329158783)
is_null faster by ~5ns per call
normadize (a) gmail (d) com 07-Jul-2012 10:08
Using === NULL instead of is_null(), is actually useful in loaded server scenarios where you have hundreds or thousands of requests per second. Saving microseconds on a lot of "simple" operations in the entire PHP execution chain usually results in being able to serve more pages per second at the same speed, or lowering your cpu usage. People usually write very bad and slow code.
george at fauxpanels dot com 01-Dec-2008 01:58
See how php parses different values. $var is the variable.

$var        =    NULL    ""    0    "0"    1

strlen($var)    =    0    0    1    1    1
is_null($var)    =    TRUE    FALSE    FALSE    FALSE    FALSE
$var == ""    =    TRUE    TRUE    TRUE    FALSE    FALSE
!$var        =    TRUE    TRUE    TRUE    TRUE    FALSE
!is_null($var)    =    FALSE    TRUE    TRUE    TRUE    TRUE
$var != ""    =    FALSE    FALSE    FALSE    TRUE    TRUE
$var        =    FALSE    FALSE    FALSE    FALSE    TRUE

Peace!
Malfist 01-Jul-2008 07:54
Micro optimization isn't worth it.

You had to do it ten million times to notice a difference, a little more than 2 seconds

$a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s

difference = 2.46449494362
difference/10,000,000 = 0.000000246449494362

The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters.
strrev xc.noxeh@ellij 03-Jun-2008 05:42
$var===NULL is much faster than is_null($var) (with the same result)

I did some benchmarking with 10 million iterations:

$a=null;
 isset($a); Took: 1.71841216087s
 $a==NULL; Took: 1.27205181122s
 $a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s
$a=5;
 isset($a); Took: 1.15165400505s
 $a==NULL; Took: 1.41901302338s
 $a===NULL; Took: 1.21655392647s
 is_null($a); Took: 3.78501200676s
error_reporting(E_ALL&~E_NOTICE);
unset($a);
 isset($a); Took: 1.51441502571s
 $a==NULL; Took: 16.5414860249s
 $a===NULL; Took: 16.1273870468s
 is_null($a); Took: 23.1918480396s

Please note, that isset is only included because it gives a good performance in any case; HOWEVER isset is NOT the same, or the opposite.
But you might be able to use isset() instead of null-checking.

You should not use is_null, except when you need a callback-function, or for conformity with is_int, is_float, etc.
ai dot unstmann at combase dot de 14-Jan-2008 12:17
For what I realized is that  is_null($var)  returns exactly the opposite of  isset($var) , except that is_null($var) throws a notice if $var hasn't been set yet.

the following will prove that:

<?php

$quirks = array(null, true, false, 0, 1, '', "\0", "unset");

foreach($quirks as $var) {
    if ($var === "unset") unset($var);

    echo is_null($var) ? 1 : 0;
    echo isset($var) ? 1 : 0;
    echo "\n";
}

?>

this will print out something like:

10    // null
01    // true
01    // false
01    // 0
01    // 1
01    // ''
01    // "\0"
Notice:  Undefined variable: var in /srv/www/htdocs/sandbox/null/nulltest.php on line 8
10    // (unset)

For the major quirky types/values is_null($var) obviously always returns the opposite of isset($var), and the notice clearly points out the faulty line with the is_null() statement. You might want to examine the return value of those functions in detail, but since both are specified to return boolean types there should be no doubt.

A second look into the PHP specs tells that is_null() checks whether a value is null or not. So, you may pass any VALUE to it, eg. the result of a function.
isset() on the other hand is supposed to check for a VARIABLE's existence, which makes it a language construct rather than a function. Its sole porpuse lies in that checking. Passing anything else will result in an error.

Knowing that, allows us to draw the following unlikely conclusion:

isset() as a language construct is way faster, more reliable and powerful than is_null() and should be prefered over is_null(), except for when you're directly passing a function's result, which is considered bad programming practice anyways.
michael at cannonbose dot com 30-Dec-2003 09:42
Regarding avoidance of NULLs in your MySQL queries, why not use  IS NULL and IS NOT NULL in your WHERE clauses.

SELECT *
FROM someDatabase
WHERE someAttribute IS NOT NULL

Cheers,

Michael
uioreanu at hotmail dot com 23-Mar-2001 06:36
Don't try to test
if ($intSomething==NULL) {
 ...
}
use is_null() instead.
The first statement misses 0 values.

Regards,
Calin

[Ed. note: this is because == tests for equivalence of value, but not type. NULL evaluates to
false, as does 0, so NULL == 0 is true--even though 0 is type int and NULL is type null.
You should use either is_null() as noted or ===, which returns true only if its operands are
equal and of the same type.]


检测变量是否为数字或数字字符串

  • ? is_null
  • is_object ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否为数字或数字字符串

is_numeric

(PHP 4, PHP 5, PHP 7, PHP 8)

is_numeric — 检测变量是否为数字或数字字符串

描述

is_numeric ( mixed $var ) : bool

如果 var 是数字和数字字符串则返回 true，否则返回 false。

参见 is_bool()、is_float()、is_int()、is_string()、is_object()、is_array() 和 is_integer()。

User Contributed Notes

rds88 10-Mar-2021 01:46
Notice that not only are leading spaces valid, but pretty much all whitespace characters and any combination thereof seems to be valid.

Examples (999 is the actual number), verified in PHP 7.3.x:

%09999 - a leading horizontal tabulator followed by the number
%20999 - a leading space followed by the number
%09%20999 - a leading tab, followed by a space, followed by the number
orcinus 22-Aug-2019 09:37
This page is a hot mess.

The changes note states:

"7.0.0    Strings in hexadecimal (e.g. 0xf4c3b00c) notation are no longer regarded as numeric strings, i.e. is_numeric() returns FALSE now."

Meanwhile, the description says:

"Hexadecimal (e.g. 0xf4c3b00c) *and binary* (e.g. 0b10100111001) notation is not allowed."

And finally, the examples section claims both are TRUE for is_binary.
What the hell?
sandreas 21-Feb-2019 10:48
Note that strings with leading zeros containing only digits also return true on check with is_numeric, although they might be not a valid number. Example:

<?php
$x = 009; // this is invalid php code, 009 is not octal
$y = 007; // this is valid php code, 007 is octal
$z = 01.12; // this also is valid php code

var_dump(is_numeric("009")); // outputs true
var_dump(is_numeric("007")); // outputs true
var_dump(is_numeric("00.12")); // outputs true
?>
Ray.Paseur sometimes uses Gmail 19-Dec-2018 08:50
intval() appears to be helpful with hex strings:

<?php // is_hex_numeric.php
/**
 * PHP 7.0.0+ Strings in hexadecimal (e.g. 0xf4c3b00c) notation
 * are no longer regarded as numeric strings, i.e. is_numeric() returns FALSE now.
 * See: http://php.net/manual/en/function.intval.php
 */
error_reporting(E_ALL);

var_dump( PHP_VERSION );              // string(6) "7.1.25"
var_dump( PHP_INT_SIZE );             // int(8)

$x = 0xf4c3b00c;                      // --> Assignment of hex value
var_dump($x);                         // int(4106465292)
var_dump( is_numeric($x) );           // bool(true)

$y = '0x' . dechex($x);               // --> Convert hex value to a string
var_dump($y);                         // string(10) "0xf4c3b00c"
var_dump( is_numeric($y) );           // bool(false)

$z = intval($y, 0);                   // --> intval() with base zero recognizes hex notation
var_dump($z);                         // int(4106465292)
var_dump( is_numeric($z) );           // bool(true)
var_dump($x == $z);                   // bool(true)
phil at kiwilimon dot com 07-May-2018 04:43
There is another not documented big difference between PHP 5 and PHP 7:
is_numeric("45 "); // with a space at the end
will return true on PHP 5 and false on PHP 7
za at byza dot it 26-Sep-2017 02:21
To check if a numeric string is a valid integer or float number:

function is_valid_number($a) {
   return $a==(float)$a && strlen($a)==strlen((float)$a);
}

This returns false for "0012345" and true for "0.12345"
cottton 05-Feb-2017 02:20
As of http://php.net/manual/de/function.is-numeric.php#111709
' 12345' is considered numeric.

BUT '12345 ' NOT.

Test:
<?php
foreach (
    [
        ' 12345',
        '12345 ',
        ' 12345 ',
    ] as $value

) {
    echo "'{$value}'\t" . var_export(is_numeric($value), true) . PHP_EOL;
}
/**
 * Output:
 *
 *  ' 12345'        true
 *  '12345 '        false
 *  ' 12345 '       false
 */
?>
tanguy_barsik at hotmail dot com 03-Feb-2017 03:22
for strings, it return true only if float number has a dot

is_numeric( '42.1' )//true
is_numeric( '42,1' )//false
Vasiliy Makogon 08-Apr-2016 08:22
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:

<?php
function isInteger($val)
{
    if (!is_scalar($val) || is_bool($val)) {
        return false;
    }
    if (is_float($val + 0) && ($val + 0) > PHP_INT_MAX) {
        return false;
    }
    return is_float($val) ? false : preg_match('~^((?:\+|-)?[0-9]+)$~', $val);
}

function isFloat($val)
{
    if (!is_scalar($val)) {
        return false;
    }
    return is_float($val + 0);
}

foreach ([
    '11111111111111111', 11111111111111111, // > PHP_INT_MAX - presents in PHP as float
    1, '10', '+1', '1.1', 1.1, .2, 2., '.2', '2.',
    '-2.', '-.2', null, [], true, false, 'string'
] as $value) {
    echo $value . ':' . gettype($value) . ' is Integer? - '  . (isInteger($value) ? 'yes' : 'no') . PHP_EOL;
    echo $value . ':' . gettype($value) . ' is Float? - '  . (isFloat($value) ? 'yes' : 'no') . PHP_EOL;
}
?>

Output:

11111111111111111:string is Integer? - no
11111111111111111:string is Float? - yes
1,1111111111111E+16:double is Integer? - no
1,1111111111111E+16:double is Float? - yes
1:integer is Integer? - yes
1:integer is Float? - no
10:string is Integer? - yes
10:string is Float? - no
+1:string is Integer? - yes
+1:string is Float? - no
1.1:string is Integer? - no
1.1:string is Float? - yes
1,1:double is Integer? - no
1,1:double is Float? - yes
0,2:double is Integer? - no
0,2:double is Float? - yes
2:double is Integer? - no
2:double is Float? - yes
.2:string is Integer? - no
.2:string is Float? - yes
2.:string is Integer? - no
2.:string is Float? - yes
-2.:string is Integer? - no
-2.:string is Float? - yes
-.2:string is Integer? - no
-.2:string is Float? - yes
:NULL is Integer? - no
:NULL is Float? - no
Array:array is Integer? - no
Array:array is Float? - no
1:boolean is Integer? - no
1:boolean is Float? - no
:boolean is Integer? - no
:boolean is Float? - no
string:string is Integer? - no
string:string is Float? - no
vikramverma214 at gmail dot com 26-Dec-2015 06:24
check if given string is mobile number

function filterNumber($str)
        {
            //remove non number
            $count = strlen($str);
            $newNumber = "";
            for($i = 0; $i<$count; $i++)
            {
                if(is_numeric($str[$i]))
                    $newNumber .= $str[$i];
            }

            //removes leading 0s
            $newNumber = ltrim($newNumber, '0');

            //remove 91 in starting, 91 is specific to Indian Numbers
            if(strlen($newNumber) == 12)
            {
                if(substr($newNumber, 0, 2) == '91')
                    $newNumber = substr($newNumber, 2);
            }

            //final check for length 10
            if(strlen($newNumber) != 10 )
                return null;
            else
                return $newNumber;
        }
lihatskiym at gmail dot com 30-Sep-2015 11:26
Check that value is whole numeric or is whole integer.
<?php
function whole_numeric($val)
{
    if (is_numeric($val)
        && floor($val) == $val)
    {
        if ((string)$val === (string)0)
            return true;
        elseif(ltrim((string)$val, '0') === (string)$val)
            return true;
    }

    return false;
}

function whole_int($val)
{
    $val = strval($val);
    $val = str_replace('-', '', $val);

    if (ctype_digit($val))
    {
        if ($val === (string)0)
            return true;
        elseif(ltrim($val, '0') === $val)
            return true;
    }

    return false;
}
?>

Result will be like this:

<?php
whole_numeric('-1.0');  // true
whole_numeric(0);        // true
whole_numeric('0');      // true
whole_numeric('00');     // false
whole_numeric(1);        // true
whole_numeric('1');      // true
whole_numeric('1.0');    // true
whole_numeric('1,0');    // false
whole_numeric('1.2');    // false
whole_numeric('001');    // false
whole_numeric(array()); // false

whole_int('-1.0');    // false
whole_int('-1');       // true
whole_int(0);          // true
whole_int('0');        // true
whole_int('00');      // false
whole_int(1);          // true
whole_int('1');         // true
whole_int('1.0');      // false
whole_int('1.2');      // false
whole_int('001');     // false
whole_int(array()); // false
?>
Tim Robert-Fitzgerald 26-Jun-2015 11:17
Be careful when using `is_numeric()` to validate user input and protect against SQL injection. According to wiki.hashphp.org,

"Many people reach for is_numeric() thinking this is a good approach, and it will seem to work just fine. However the problem with is_numeric() isn't that it can't detect an integer, it is that it detects a lot more than just integers. All of the following are valid numbers to is_numeric():

- 1
- 1.123
- 0xFF
- +0123.45e6

See the problem? If we really want just an integer, this function is too broad."

Source: http://wiki.hashphp.org/Validation#Why_is_numeric.28.29_is_bad
charlike dot mike at mail dot bg 03-Feb-2014 04:24
I think that is best check solution if u want to create real calculator for example :)

<?php
function is_number($var)
{
    if ($var == (string) (float) $var) {
        return (bool) is_numeric($var);
    }
    if ($var >= 0 && is_string($var) && !is_float($var)) {
        return (bool) ctype_digit($var);
    }
    return (bool) is_numeric($var);
}

is_number(12); // true
is_number(-12); // true
is_number(-12.2); // true
is_number("12"); // true
is_number("-124.3"); // true
is_number(0.8); // true
is_number("0.8"); // true
is_number(0); // true
is_number("0"); // true
is_number(NULL); // false
is_number(true); // false
is_number(false); // false
is_number("324jdas32"); // false
is_number("123-"); // false
is_number(1e7); // true
is_number("1e7"); // true
is_number(0x155); // true
is_number("0x155"); // false
?>
ben at chico dot com 07-Jan-2014 11:20
Apparently NAN (Not A Number) is a number for the sake of is_numeric().

<?php
echo "is ";
if (!is_numeric(NAN))
 echo "not ";
 echo "a number";
?>

Outputs "is a number". So something that is NOT a number (by defintion) is a number...
jsnell at e-normous dot com 19-Mar-2013 09:38
Note that this function handles leading spaces differently than is_int(), is_float(), is_real(), is_long(), and is_double().

is_numeric(" 12345") = true
is_int(" 12345") = false
is_float(" 12345") = false
is_real(" 12345") = false
is_long(" 12345") = false
is_double(" 12345") = false
jeffvanhees at gmail dot com 19-Jun-2012 05:20
Function for checking all the values in an array for being numeric:

<?php
function is_numeric_array($array) {
    foreach ($array as $key => $value) {
        if (!is_numeric($value)) return false;
    }
    return true;
}

$array_not_numeric = array('1', '2', 3, 'a'); // returns false
$array_numeric = array('1', '2', 3, 4); // returns true
?>
dave dot marr at gmail dot com 31-Jan-2012 04:30
If you want the numerical value of a string, this will return a float or int value:

<?php
function get_numeric($val) {
  if (is_numeric($val)) {
    return $val + 0;
  }
  return 0;
}
?>

Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>
akam at akameng dor com 22-Jan-2012 09:22
<?php
$d = @$_GET['d'];

/*
assuming that passing value of d in the mysql
$sql = "select * from books where bookid = '$d' "
*/

/*
now check if $d is numeric?
*/

if(!is_numeric($d)){
 $d = preg_replace("/[^0-9]+/", "", $d);
}
echo "Cleared value: $d \n<br />Original Vlaue:".@$_GET['d'];
//then using clear value of $d in the mysql query
$sql = "select * from books where bookid = '$d' ";
?>
Example:
?d=52;d;s;s'2233l'[[22

Outpt:

Cleared value: 52223322
Original Vlaue:52;d;s;s'2233l'[[22
sobolanx at gmail dot com 22-Jan-2011 03:55
Note that the function accepts extremely big numbers and correctly evaluates them.

For example:

<?php
    $v = is_numeric ('58635272821786587286382824657568871098287278276543219876543') ? true : false;

    var_dump ($v);
?>

The above script will output:

bool(true)

So this function is not intimidated by super-big numbers. I hope this helps someone.

PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
Martyn Ranyard 10-Jan-2011 04:14
The documentation does not clarify what happens if you the input is an empty string - it correctly returns false in my experience.  Useful to state these odd cases, for when you see code that checks for an empty string and is_numeric, you can tell it's a waste of a comparison.
Nitrogen 11-Sep-2010 10:40
I find it a little weird that people are having issues with ordinal numbers, it's pretty easy..
Notes are in the commenting, check out the example outputs.

<?php

function ordinal($i='') {
  // a temporary value we can change, and keep the original value.
  $o=$i;

  // suffixes = 0th, 1st, 2nd, third == zeroth, first, second, third
  $s=array('th','st','nd','rd');

  // if input just so happens to be a string, we check to make sure it
  // still holds a numeric value and only acquire the last 2 numbers.
  // if it's not a string, nor an integer, we freak out and say no.
  if(!is_int($o))
    if(ctype_digit($o))
      $o=(int)substr($o,-2,2);
    else
      return(false);

  // basically, if $o is between 11 and 19, we use 'th'
  // otherwise we use the last digit and if it's over
  // 4 then we use 0 (for the $s array index).
  return($i.$s[($o%100>10&&$o%100<20)?0:($o%10<4?$o%10:0)]);
}

var_dump(ordinal(5));

/* Example Outputs of ordinal():
  0th, 1st, 2nd, 3rd, 4th, ..., 9th,
  10th, 11th, 12th, 13th, 14th, ..., 19th,
  110th, 111th, ..., 199th, 200th, 201st.

  ordinal('-1'); returns false because ctype_digit hates anything that
  isn't strictly 0 through 9 and '-' trips it to false.

  ordinal('asdf'); returns false for the exact same reason.

  ordinal(); returns false because it's blank.

  signed integers on a 32-bit system (and the same issue on a 64-bit
  system using 0x7FFFFFFFFFFFFFFF because of two's compliment,
  anything higher will become a negative number):
  ordinal(0x7FFFFFFF  ); returns 2147483647th (which is correct)
  ordinal(0x7FFFFFFF+1); returns false.
*/

?>
Kiam 23-Jul-2009 11:02
empty(trim($test, '+-.,0123456789')) doesn't assure you $test contains a number. It returns TRUE also for a string containing ".+1234.56", which is not a valid number.
codeslinger at compsalot dot com 15-Jul-2009 01:34
if speed is important, the liberal use of regex should be avoided, especially complex ones like those here.

For most purposes, this will be sufficient and has the advantages of both speed and clarity.

$BoolResult = empty(trim($Test, '+-.,0123456789'));

If the $Test contains any character that is not a valid part of a number the remaining string will not be empty.

if you want to be more restrictive of the '+-'  then you can use a separate trim for that and nest it.  Keep in mind that some notations pt the sign to the right of the number instead of to the left.  Depending upon your specific application you can also choose to ignore spaces and allow for 'e' notation.

I also use this approach when testing for other character sets such as Hex.
Magnus Deininger, dma05 at web dot de 07-Jan-2009 06:01
regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren't grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim's regexen are slightly suboptimal at one point having an unescaped '.' operator, and the whole thing could easily be combined into a single regex (speed and all).

adjustments:

<?php
$eng_or_world = preg_match
  ('/^[+-]?'. // start marker and sign prefix
  '(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'. // american
  '((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'. // world
  '(e[0-9]+)?'. // exponent
  '$/', // end marker
  $str) == 1;
?>

i'm sure this still isn't optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.
Elwin van Huissteden 27-Mar-2007 04:05
To James holwell:

Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world's way:

<?php
  function my_is_numeric($value)
  {
   return (preg_match ("/\A(-){0, 1}([0-9]+)((,|.)[0-9]{3, 3})*((,|.)[0-9]){0, 1}([0-9]*)\z/" ,$value) == 1);
  }
?>

Other than that, i'd recommend using yours, if it works (i havent tested either yours or mine)
By using mine, there might be a slight chance to not being able to do calculations with the numeric string if it's not the English/American way.

(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02
james.holwell( at )exeter.ox.ac.uk 20-Mar-2007 02:07
In reply to www.kigoobe.com, a more strict expression is

<?php
  function my_is_numeric($value)
  {
    return (preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/", $value) == 1);
  }
?>

This will not match strings like -6,77.8,8 which are matched by the below expression, and instead requires a single decimal point, with at least one character following, and only permits comma-separation when the right hand side is a triplet.
Stephen 25-Jan-2007 09:31
The documentation is not completely precise here. is_numeric will also return true if the number begins with a decimal point  and/or a space, provided a number follows (rather than a letter or punctuation). So, it doesn't necessarily have to start with a digit.
moskalyuk at gmail dot com 21-Aug-2006 10:18
is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number
rontarrant at NO_SPAMsympatico dot ca 23-Jul-2006 07:15
Here's an even simpler pair of functions for finding out if a number is odd or even:

function IS_ODD($number) { return($number & 1); }

function IS_EVEN($number) { return(!($number & 1)); }

Test:
$myNumber = 151;

if(IS_ODD($myNumber))
    echo("number is odd\n");
else
    echo("number is NOT odd\n");

if(IS_even($myNumber))
    echo("number is even\n");
else
    echo("number is NOT even\n");

Results:
number is odd
number is NOT even
andrea dot vacondio at gmail dot com 13-Dec-2005 07:52
Two simple functions using is_numeric:

<?php

 function is_odd($num){
     return (is_numeric($num)&($num&1));
 }

 function is_even($num){
     return (is_numeric($num)&(!($num&1)));
 }

 //examples
echo "1: odd? ".(is_odd(1)? "TRUE": "FALSE")."<br />";
//is_numeric(0) returns true
echo "0: odd? ".(is_odd(0)? "TRUE": "FALSE")."<br />";
echo "6: odd? ".(is_odd(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": odd? ".(is_odd("italy")? "TRUE": "FALSE")."<br />";
echo "null: odd? ".(is_odd(null)? "TRUE": "FALSE")."<br /><br />";
echo "1: even? ".(is_even(1)? "TRUE": "FALSE")."<br />";
echo "0: even? ".(is_even(0)? "TRUE": "FALSE")."<br />";
echo "6: even? ".(is_even(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": even? ".(is_even("italy")? "TRUE": "FALSE")."<br />";
echo "null: even? ".(is_even(null)? "TRUE": "FALSE")."<br />";

?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
"italy": odd? FALSE
null: odd? FALSE

1: even? FALSE
0: even? TRUE
6: even? TRUE
"italy": even? FALSE
null: even? FALSE
jamespam at hotmail dot com 08-Aug-2005 02:31
Here's a function to determine if a variable represents a whole number:

function is_whole_number($var){
  return (is_numeric($var)&&(intval($var)==floatval($var)));
}

just simple stuff...
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true
namik at hub-cafe dot net 29-Jul-2005 06:11
I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function).  Note that this doesn't properly handle decimals.

Example:
<?= number_suffix('1,021') ?> returns: 1,021st

Also, increasing the range above the condition statements increases efficiency.  That's almost 20% of the numbers between 0 and 100 that get to end early.

<?
  function number_suffix($number)
  {
    // Validate and translate our input
    if ( is_numeric($number) )
    {
      // Get the last two digits (only once)
      $n = $number % 100;
    } else {
     // If the last two characters are numbers
     if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches ) )
     {
       // Return the last one or two digits
       $n = array_pop($matches);
     } else {
       // Return the string, we can add a suffix to it
       return $number;
     }
    }
    // Skip the switch for as many numbers as possible.
    if ( $n > 3 && $n < 21 )
      return $number . 'th';

    // Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
    switch ( $n % 10 )
    {
      case '1': return $number . 'st';
      case '2': return $number . 'nd';
      case '3': return $number . 'rd';
      default:  return $number . 'th';
    }
  }
?>
sebu 28-Jul-2005 04:37
Referring to previous post "Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')":

This is totally wrong!

This was the example code:

-----
  set_locale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return False
  is_numeric(12,25); // Return True
  is_float(12.25); //Return False
  is_float(12,25); //Return True
-----

This is nonsense!

- set_locale() does not exist, you must use setlocale() instead
- you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
- if you don't enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE

Corrected Example:

----
  setlocale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return True
  is_numeric("12,25"); // Return False
  is_float(12.25); //Return True
  is_float("12,25"); //Return False
----

Remarks:
- is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a "value") and the way PHP interpretes files is definitely _not_ affected by the locale
- is_float("12,25") is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats

And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.
mdallaire at virtuelcom dot com 17-Nov-2004 04:23
Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:

    function new_is_unsigned_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_unsigned_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+$",$val);
    }

    function new_is_signed_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_signed_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+$",$val);
    }

It returns 1 if okay and returns nothing "" if it's bad number formating.
renimar no spam at nospam yahoo dot com 03-May-2004 12:54
A little function to ordinalize numbers using is_numeric() and accounting for the numbers in the teens.

<?php
function ordinalize($num) {

        if (!is_numeric($num))
                return $num;

        if ($num >= 11 and $num <= 19)
                return $num."th";
        elseif ( $num % 10 == 1 )
                return $num."st";
        elseif ( $num % 10 == 2 )
                return $num."nd";
        elseif ( $num % 10 == 3 )
                return $num."rd";
        else
                return $num."th";

}

// Demo
for ($i=1; $i<=25; $i++) {
        print ordinalize($i) . " ";
}

// The loop returns:
// 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th
// 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd
// 23rd 24th 25th

?>
joe at kewlmail dot net 16-Jan-2004 03:12
Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:

$userString = "$654.4r5";

function numpass_filter($userString){
    $money = explode(".", $userString);
    //now $money[0] = "$645" and $money[1] = "4r5"

    //next remove all characters save 0 though 9
    //in both elements of the array
    $dollars = eregi_replace("[^0-9]", null, $money[0]);
    $cents = eregi_replace("[^0-9]", null, $money[1]);

    //if there was a decimal in the original string, put it back
    if((string)$cents!=null){
        $cents = "." . $cents;
    }

   $result = $dollars . $cents;

    return($result);
}

The output in this case would be '654.45'.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.
kouber at saparev dot com 24-Nov-2003 03:05
Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.

However, this behaviour is platform-specific.

http://www.php.net/manual/en/language.types.float.php

In such a case, it is suitable to use regular expressions:

function is_numeric_big($s=0) {
  return preg_match('/^-?\d+$/', $s);
}
stew_wilde at hotmail dot com 07-Aug-2003 01:25
When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.

ie : two scripts test.php:

<?php
$val = trim($argv[1]);
echo is_string($val);
?>

and testwrapper.php:

<?php
$tmp = 5;
exec("php ./test.php ".$tmp);
?>

Executing testwrapper.php on the command line will echo nothing (ie false), and false will be returned regardless of any escaping of parameters or other such attempts to overcome this.  The solution then is to explicitly cast $val in test.php to be an int and then is_numeric will work.  But as stated the same test was performed using a string for $val and the is_string() function and the same thing occurs.  Not the end of the world, but something to be aware of :)
andi_nrw at hotmail dot com 12-Feb-2003 08:25
<?php
/* This function is not useful if you want
to check that someone has filled in only
numbers into a form because for example
4e4 and 444 are both "numeric".

I used a regular expression for this problem
and it works pretty good. Maybe it is a good
idea to write a function and then to use it.

$input_number = "444"; // Answer 1
$input_number = "44 "; // Answer 2
$input_number = "4 4"; // Answer 2
$input_number = "4e4"; // Answer 2
$input_number = "e44"; // Answer 2
$input_number = "e4e"; // Answer 2
$input_number = "abc"; // Answer 2
*/
$input_number = "444";

if (preg_match ("/^([0-9]+)$/", $input_number)) {
     print "Answer 1";
} else {
     print "Answer 2";
}
?>
eagleflyer2 at lycos dot com 06-Sep-2002 01:02
Hi !
Many of you may have experienced that the 'is_numeric' function seems to fail always when form entries are checked against their variable type. So the function seems to return  'false' even if the form entry was aparently a number or numeric string.

The solution is pretty simple and no subroutines or fancy operations are necessary to make the 'is_numeric' function usable for form entry checks:

Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.

Just use the 'trim' function before 'is_numeric'.

Example:

$variable = trim($variable);
if (is_numeric($variable)
{...#do something#...}
else
{...#do something else#...}


检测变量是否是一个对象

  • ? is_numeric
  • is_real ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否是一个对象

is_object

(PHP 4, PHP 5, PHP 7, PHP 8)

is_object — 检测变量是否是一个对象

描述

is_object ( mixed $var ) : bool

如果 var 是一个 object 则返回 true，否则返回 false。

参见 is_bool()、is_int()、is_integer()、is_float()、is_string() 和 is_array()。

User Contributed Notes

wadih at creationmw dot com 29-Jul-2017 06:47
Note that closures return true when passed to is_object():

<?php

echo
    is_object(
        function(){return "hello";}
    );

?>

Returns true (1)
shadow_games at abv dot bg 11-Jun-2014 03:42
here i created one function that i wanted to find but i had never found :X

    function compare_two_object_recursive($object_1, $object_2, $object_1_Identifier = false, $object_2_Identifier = false){
        $object1 = (array)$object_1;
        $object2 = (array)$object_2;
        $object3 = array();

        $o1i = $object_1_Identifier ? $object_1_Identifier : 1;
        $o2i = $object_2_Identifier ? $object_2_Identifier : 2;

        foreach($object1 as $key => $value){
            if(is_object($object1[$key])){
                $object1[$key] = (array)$object1[$key];
                $object2[$key] = (array)$object2[$key];
                $object3[$key] = (object)compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }elseif(is_array($object1[$key])){
                $object3[$key] = compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }else{
                if($object1[$key] == $object2[$key]){
                    $object3[$key]['comparison_status'] = "SAME";
                }else{
                    $object3[$key]['comparison_status'] = "NOT THE SAME";
                    $object3[$key][$o1i] = $object1[$key];
                    $object3[$key][$o2i] = $object2[$key];
                }
            }
        }
        return $object3;
    }
mark at not4you dot com 21-Sep-2011 12:23
Unserializes data as returned by the standard PHP serialize() function. If the unserialized object is not an array, it will be converted to one, particularily useful if it returns a __PHP_Incomplete_Class.

<?php
/**
 *
 * @param string $data Serialized data
 *
 * @return array    Unserialized array
 */
function unserialize2array($data) {
    $obj = unserialize($data);
    if(is_array($obj)) return $obj;
    $arr = array();
    foreach($obj as $k=>$v) {
        $arr[$k] = $v;
    }
    unset($arr['__PHP_Incomplete_Class_Name']);
    return $arr;
}
?>
peter dot nagel at portavita dot nl 22-Mar-2011 01:46
Note: is_object(null) returns false

This should actually be part of the input/output specification at the top of this page.
will 20-Mar-2010 02:36
Just discovered:
is_a  (  object $object  ,  string $class_name  )
Which checks if the object is of this class or has this class as one of its parents

Which seems to do what a lot here are trying to replicate
ldean at saleamp dot com 01-Sep-2009 07:16
Use instanceof() to check for a specific type.
Senthryl 17-Mar-2009 06:03
Cleaning it up even more:

<?php
function is_obj(&$object, $className = null, $caseSensitive = true) {
    return is_object($object) && (!is_string($className) || preg_match('/^'.$className.'$/D'.($caseSensitive ? '' : 'i'), get_class($object)));
}
?>
gregdangelo at gmail dot com 14-Apr-2008 12:03
cleaned up peter's code... use only one return statement

function is_obj( &$object, $check=null, $strict=true )
{
$result = false;
  if (is_object($object)) {
      if ($check == null) {
          $result =  true;
      } else {
           $object_name = get_class($object);
           $result =  ($strict === true)?
               ( $object_name == $check ):
               ( strtolower($object_name) == strtolower($check) );
      }
  }
return $result;
}
corychristison[aT-]lavacube(.dot)com 02-Feb-2005 05:06
Thank you victor AT fourstones DOT net.

I have written a function to do what victor has suggested, with the ease of use of is_object. It can be used to replace is_object(), but has an extra field [$check], to compare to a certain name. If $check is left empty, it will just check if &$object is an object.

<?php

function is_obj( &$object, $check=null, $strict=true )
{
    if( $check == null && is_object($object) )
    {
        return true;
    }
    if( is_object($object) )
    {
        $object_name = get_class($object);
        if( $strict === true )
        {
            if( $object_name == $check )
            {
                return true;
            }
        }
        else
        {
            if( strtolower($object_name) == strtolower($check) )
            {
                return true;
            }
        }
    }
}

?>

This could probably be cleaned up, but it's spaced out to be easy to read.
victor AT fourstones DOT net 01-Jan-2005 03:49
er, I don't think that's right, especially if calling from another object instance:

<?

function test_this()
{
    $c2 = new C2();
    $c2->func();
    $c1 = new C1();
    $c1->func();
    C1::func();
}

class C2
{
    function func()
    {
        C1::func();
    }
}

class C1
{
    function func()
    {
        if( isset($this) )
        {
            if( strtolower(get_class($this)) != 'c1' )
                print("oops\n");
            else
                print("this is ok\n" );
        }
        else
        {
            print("static call\n");
        }
    }
}

test_this();
?>

yields:
---------- run-php ----------

oops
this is ok
static call
corychristison[aT-]lavacube(.dot)com 01-Jan-2005 07:47
You can use is_object($this) to detect if the function is being called via instance or procedure.

Example:

<?php

class mrClass {

    function test( )
    {
        if( is_object($this) )
        {
         // do something for instance method
            echo 'this is an instance call <br />' . "\n";
        }
        else
        {
         // do something different for procedural method
            echo 'this is a procedure call <br />' . "\n";
        }
    }

}

$inst = new mrClass();
$inst->test();

mrClass::test();

?>

This would output:
this is an instance call <br />
this is a procedure call <br />

:-) Happy coding!
lbjay can be emailed at reallywow dot com 02-May-2003 12:18
I'm not even sure how to articulate this, so I'm going to just include test code. Maybe someone else will someday wonder the same thing.

<?
    error_reporting(E_ALL);
    class testParent
    {
        var $child;

        function testParent()
        {
            $this->child = new testChild();
        }
    }

    class testChild
    {
        function testChild()
        {
        }
    }

    $parent = new testParent();
    $parent2 = 'foobar';

    print join(',', Array(
        is_object($parent) ? 'yes' : 'no',
        is_object($parent->child) ? 'yes' : 'no',
        is_object($parent2) ? 'yes' : 'no',
        is_object($parent2->child) ? 'yes' : 'no'
    ));

?>

This prints "yes,yes,no,no". Basically this shows that you can use is_object to test if the child object is an object without worrying about an error if the parent object isn't an object either.


is_float 的别名

  • ? is_object
  • is_resource ?
  • PHP Manual
  • Variable handling 函数
  • is_float 的别名

is_real

(PHP 4, PHP 5, PHP 7, PHP 8)

is_real — is_float() 的别名

描述

此函数是 is_float() 的别名函数。

User Contributed Notes

There are no user contributed notes for this page.


检测变量是否为资源类型

  • ? is_real
  • is_scalar ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否为资源类型

is_resource

(PHP 4, PHP 5, PHP 7, PHP 8)

is_resource — 检测变量是否为资源类型

描述

is_resource ( mixed $var ) : bool

如果给出的参数 var 是 resource 类型，is_resource() 返回 true，否则返回 false。

查看 resource 类型文档获取更多的信息。

User Contributed Notes

Anonymous 29-Sep-2017 11:16
Note that is_resource() is unreliable. It considers closed resources as false:

<?php

$a = fopen('http://www.google.com', 'r');
var_dump(is_resource($a)); var_dump(is_scalar($a));
//bool(true)
//bool(false)

fclose($a);
var_dump(is_resource($a)); var_dump(is_scalar($a));
//bool(false)
//bool(false)

?>

That's the reason why some other people here have been confused and devised some complex (bad) "solutions" to detect resources...

There's a much better solution... In fact, I just showed it above, but here it is again with a more complete example:

<?php

$a = fopen('http://www.google.com', 'r');
var_dump(is_resource($a)); var_dump(is_scalar($a)); var_dump(is_object($a)); var_dump(is_array($a)); var_dump(is_null($a));
//bool(true)
//bool(false)
//bool(false)
//bool(false)
//bool(false)

?>

So how do you check if something is a resource?

Like this!

<?php

$a = fopen('http://www.google.com', 'r');
$isResource = is_resource($a) || ($a !== null && !is_scalar($a) && !is_array($a) && !is_object($a));
var_dump($isResource);
//bool(true)

fclose($a);

var_dump(is_resource($a));
//bool(false)

$isResource = is_resource($a) || ($a !== null && !is_scalar($a) && !is_array($a) && !is_object($a));
var_dump($isResource);
//bool(true)

?>

How it works:

- An active resource is a resource, so check that first for efficiency.
- Then branch to check what the variable is NOT:
- A resource is never NULL. (We do that check via `!== null` for efficiency).
- A resource is never Scalar (int, float, string, bool).
- A resource is never an array.
- A resource is never an object.
- Only one variable type remains if all of the above checks succeeded: IF it's NOT any of the above, then it's a closed resource!

Just surfed by and saw the bad and hacky methods other people had left, and wanted to help out with this proper technique. Good luck, everyone!

PS: The core problem is that is_resource() does a "loose" check for "living resource". I wish that it had a $strict parameter for "any resource" instead of these user-workarounds being necessary.
CertaiN 17-Jan-2014 05:05
Try this to know behavior:

<?php
function resource_test($resource, $name) {
    echo
        '[' . $name. ']',
        PHP_EOL,
        '(bool)$resource => ',
        $resource ? 'TRUE' : 'FALSE',
        PHP_EOL,
        'get_resource_type($resource) => ',
        get_resource_type($resource) ?: 'FALSE',
        PHP_EOL,
        'is_resource($resource) => ',
        is_resource($resource) ? 'TRUE' : 'FALSE',
        PHP_EOL,
        PHP_EOL
    ;
}

$resource = tmpfile();
resource_test($resource, 'Check Valid Resource');

fclose($resource);
resource_test($resource, 'Check Released Resource');

$resource = null;
resource_test($resource, 'Check NULL');
?>

It will be shown as...

[Check Valid Resource]
(bool)$resource => TRUE
get_resource_type($resource) => stream
is_resource($resource) => TRUE

[Check Released Resource]
(bool)$resource => TRUE
get_resource_type($resource) => Unknown
is_resource($resource) => FALSE

[Check NULL]
(bool)$resource => FALSE
get_resource_type($resource) => FALSE
Warning:  get_resource_type() expects parameter 1 to be resource, null given in ... on line 10
is_resource($resource) => FALSE
btleffler [AT] gmail [DOT] com 12-May-2011 01:55
I was recently trying to loop through some objects and convert them to arrays so that I could encode them to json strings.

I was running into issues when an element of one of my objects was a SoapClient. As it turns out, json_encode() doesn't like any resources to be passed to it. My simple fix was to use is_resource() to determine whether or not the variable I was looking at was a resource.

I quickly realized that is_resource() returns false for two out of the 3 resources that are typically in a SoapClient object. If the resource type is 'Unknown' according to var_dump() and get_resource_type(), is_resource() doesn't think that the variable is a resource!

My work around for this was to use get_resource_type() instead of is_resource(), but that function throws an error if the variable you're checking isn't a resource.

So how are you supposed to know when a variable is a resource if is_resource() is unreliable, and get_resource_type() gives errors if you don't pass it a resource?

I ended up doing something like this:

<?php

function isResource ($possibleResource) { return !is_null(@get_resource_type($possibleResource)); }

?>

The @ operator suppresses the errors thrown by get_resource_type() so it returns null if $possibleResource isn't a resource.

I spent way too long trying to figure this stuff out, so I hope this comment helps someone out if they run into the same problem I did.


检测变量是否是一个标量

  • ? is_resource
  • is_string ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否是一个标量

is_scalar

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

is_scalar — 检测变量是否是一个标量

说明

is_scalar ( mixed $value ) : bool

检测变量是否为标量

标量变量是指 int、float、string 或 bool 类型的变量。 array、object 和 resource 类型不是标量。

Note:

is_scalar() 不会将 resource 类型值视为标量， 因为当前 resources 是基于整数（integer）的抽象数据类型。 不能依赖该执行细节，因为它可能会改变。

Note:

is_scalar() 不会将 NULL 检测为标量。

参数

value

需要检测的变量。

返回值

如果 value 是标量，则返回 true ，否则返回 false 。

范例

Example #1 is_scalar() 示例

<?php
function show_var($var)
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
show_var($proteins)

?>

以上例程会输出：

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

参见

  • is_float() - 检测变量是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_real() - is_float 的别名
  • is_string() - 检测变量是否是字符串
  • is_bool() - 检测变量是否是布尔值
  • is_object() - 检测变量是否是一个对象
  • is_array() - 检测变量是否是数组

User Contributed Notes

31-Jul-2006 08:59
Another warning in response to the previous note:
> just a warning as it appears that an empty value is not a scalar.

That statement is wrong--or, at least, has been fixed with a later revision than the one tested.  The following code generated the following output on PHP 4.3.9.

CODE:
<?php
    echo('is_scalar() test:'.EOL);
    echo("NULL: "      . print_R(is_scalar(NULL),     true) . EOL);
    echo("false: "    . print_R(is_scalar(false),   true) . EOL);
    echo("(empty): "  . print_R(is_scalar(''),      true) . EOL);
    echo("0: "         . print_R(is_scalar(0),       true) . EOL);
    echo("'0': "      . print_R(is_scalar('0'),     true) . EOL);
?>

OUTPUT:
is_scalar() test:
NULL:
false: 1
(empty): 1
0: 1
'0': 1

THUS:
   * NULL is NOT a scalar
   * false, (empty string), 0, and "0" ARE scalars
efelch at gmail dot com 17-Aug-2005 02:31
A scalar is a single item or value, compared to things like arrays and objects which have multiple values. This tends to be the standard definition of the word in terms of programming. An integer, character, etc are scalars. Strings are probably considered scalars since they only hold "one" value (the value represented by the characters represented) and nothing else.
Dr K 14-Aug-2005 03:48
Having hunted around the manual, I've not found a clear statement of what makes a type "scalar" (e.g. if some future version of the language introduces a new kind of type, what criterion will decide if it's "scalar"? - that goes beyond just listing what's scalar in the current version.)

In other lanuages, it means "has ordering operators" - i.e. "less than" and friends.

It (-:currently:-) appears to have the same meaning in PHP.
popanowel HAT hotmailZ DOT cum 14-May-2004 12:31
Hi ... for newbees here, I just want to mention that reference and scalar variable aren't the same. A reference is a pointer to a scalar, just like in C or C++.

<? php  // simple reference to scalar

  $a = 2;
  $ref = & $a;

  echo "$a <br> $ref";

?>
this should print out: "2 <br> 2".

Scalar class also exists. Look below:
<? php

  class Object_t {

     var $a;

     function Object_t ()  // constructor
     {
        $this->a = 1;
     }

  }

  $a = new Object_t; // we define a scalar object

  $ref_a = &a;

  echo "$a->a <br> $ref->a";

?>
again, this should echo: "1 <br> 1";

Here is another method isued in OOP to acheive on working only over reference to scalar object. Using this, you won't ever have to  ask yourself if you work on a copy of the scalar or its reference. You will only possess reference to the scalar object. If you want to duplicate the scalar object, you will have to create a function for that purpose that would read by the reference the values and assign them to another scalar of the same type... or an other type, it is as you wish at that moment.
<?php

  class objet_t {
     var $a;

     function object_t
     {
        $this->a = "patate_poil";
     }
  }

   function &get_ref($object_type)
   {
      // here we create a scalar object in memory
      // and we return it by reference to the calling
      // control scope.
      return &new $object_type;
   }

   $ref_object_t = get_ref(object_t);

   echo "$ref_object_t->a <br>";

?>
this should echo: "patate_poit <br>".

The only thing that I try to demonstrate is that scalar variable ARE object in memory while a reference is usualy a variable (scalar object) that contain the address of another scalar object, which contain the informations you want by using the reference.

Good Luck!

otek is popanowel HAT hotmailZ DOT cum


检测变量是否是字符串

  • ? is_scalar
  • isset ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否是字符串

is_string

(PHP 4, PHP 5, PHP 7, PHP 8)

is_string — 检测变量是否是字符串

描述

is_string ( mixed $var ) : bool

如果 var 是 string 则返回 true，否则返回 false。

参见 is_bool()、is_int()、is_integer()、is_float()、is_real()、is_object() 和 is_array()。

User Contributed Notes

jcours at numifinancial dot com 15-Jul-2020 07:59
is_string() of an integer or float returns false, so it might be useful to include an is_numeric() when checking if a value is stringy:

<?php
function is_stringy($val) {
  return (is_string($val) || is_numeric($val)
    || (is_object($val) && method_exists($val, '__toString')));
}
?>

Test code (which should print "vector N OK" for each test vector):
<?php
foreach ([[NULL, false], [false, false], [true, false],
  [0, true], [[], false], [0.1, true], ["x", true],
  ["", true], [new Exception("x"), true]] as $idx => $vector) {
  list ($val, $expected) = $vector;
  if (is_stringy($val) != $expected) {
    print ("mismatch at $idx\n");
    var_dump($val);
  } else {
    print ("vector $idx OK\n");
  }
}
?>
Peter Barney 13-Sep-2017 10:47
As noted earlier, is_string() returns false on an object that has a __toString() method. Here is a simple way to do a check that will work:

<?php
// determine if the passed argument can be treated like a string.
function is_stringy($text) {
    return (is_string($text) || (is_object($text) && method_exists($text, '__toString' ));
}
laszlo dot heredy shift-two gmail etc 27-Feb-2014 09:22
Using is_string() on an object will always return false (even with __toString()).

<?php
class B {
  public function __toString() {
    return "Instances of B() can be treated as a strings!\n";
  }
}

$b = new B();
print($b); //Instances of B() can be treated as a strings!
print(is_string($b) ? 'true' : 'false'); //false
?>


检测变量是否已设置并且非 null

  • ? is_string
  • print_r ?
  • PHP Manual
  • Variable handling 函数
  • 检测变量是否已设置并且非 null

isset

(PHP 4, PHP 5, PHP 7, PHP 8)

isset — 检测变量是否已设置并且非 null

说明

isset ( mixed $var , mixed $... = ? ) : bool

检测变量是否设置，并且不是 null。

如果已经使用 unset() 释放了一个变量之后，它将不再是 isset()。若使用 isset() 测试一个被设置成 null 的变量，将返回 false。同时要注意的是 null 字符（"\0"）并不等同于 PHP 的 null 常量。

如果一次传入多个参数，那么 isset() 只有在全部参数都以被设置时返回 true 计算过程从左至右，中途遇到没有设置的变量时就会立即停止。

参数

var

要检查的变量。

...

其他变量。

返回值

如果 var 存在并且值不是 null 则返回 true，否则返回 false。

更新日志

版本 | 说明
5.4.0 | 检查字符的非数字偏移量将会返回 false。

范例

Example #1 isset() 例子

<?php

$var = '';

// 结果为 TRUE，所以后边的文本将被打印出来。
if (isset($var)) {
    echo "This var is set so I will print.";
}

// 在后边的例子中，我们将使用 var_dump 输出 isset() 的返回值。
// the return value of isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?>

这对于数组中的元素也同样有效：

<?php

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// 键 'hello' 的值等于 NULL，所以被认为是未置值的。
// 如果想检测 NULL 键值，可以试试下边的方法。
var_dump(array_key_exists('hello', $a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>

Example #2 在字符串位移中使用 isset()

PHP 5.4 改变了传入字符串位移时 isset() 的行为。

<?php
$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));
?>

以上例程在 PHP 5.3 中的输出：

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

以上例程在 PHP 5.4 中的输出：

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

注释

Warning

isset() 只能用于变量，因为传递任何其它参数都将造成解析错误。若想检测常量是否已设置，可使用 defined() 函数。

Note: 因为是一个语言构造器而不是一个函数，不能被 可变函数 调用。

Note:

如果使用 isset() 来检查对象无法访问的属性，如果 __isset() 方法已经定义则会调用这个重载方法。

参见

  • empty() - 检查一个变量是否为空
  • __isset()
  • unset() - 释放给定的变量
  • defined() - 检查某个名称的常量是否存在
  • the type comparison tables
  • array_key_exists() - 检查数组里是否有指定的键名或索引
  • is_null() - 检测变量是否为 null
  • 错误控制 @ 运算符。

User Contributed Notes

razvan_bc at yahoo dot com 13-Feb-2019 07:25
In these days you can use ISSET to compare a sting length
COOOL! I love php !!!!

<?php
//FIRST:try to run the script like this,
//THEN: try to uncomment the seccond $str=

$yes="SURE!!!";
$no="NOPE !";

$str="12345";//the string is long 5 bytes ?
//$str="123456";

echo !isset($str{5}) ? $yes : $no;

?>
borshak at gmail dot com 24-Jun-2018 03:13
Would be nice to have is_set() alias for more language consistency (alike of is_int, is_bull so on).
venimus at gmail dot com 27-Apr-2018 11:46
Be warned that before checking an array key existence with isset() the key will be typecasted to integer if it is not a string or integer!

See Example #2 in http://php.net/manual/en/language.types.array.php

I.e.

$a = ['test']; // 'test' will have key 0
$key = false;

var_dump(isset($a[$key]) ); // true, because false will be typecasted to 0

It is not a problem with isset but rather the lose typing when you access keys in arrays
Hayley Watson 30-Jul-2017 01:12
If you regard isset() as indicating whether the given variable has a value or not, and recall that NULL is intended to indicate that a value is _absent_ (as said, somewhat awkwardly, on its manual page), then its behaviour is not at all inconsistent or confusing.

It's not just to check for uninitialised variables - a lot of the time those are just due to sloppy coding. There are other ways a variable could fail to have a value (e.g., it's meant to hold the value returned from a function call but the function didn't have a value to return) where uninitialising the variable would not be an option nor even make sense (e.g., depending on what was to be done with the returned value).
kurdtpage at gmail dot com 21-Dec-2016 01:03
The new (as of PHP7) 'null coalesce operator' allows shorthand isset. You can use it like so:

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Quoted from http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
p_ignorethis_lbowers at gmail dot com 06-Oct-2016 07:26
I, too, was dismayed to find that isset($foo) returns false if ($foo == null). Here's an (awkward) way around it.

unset($foo);
if (compact('foo') != array()) {
  do_your_thing();
}

Of course, that is very non-intuitive, long, hard-to-understand, and kludgy. Better to design your code so you don't depend on the difference between an unset variable and a variable with the value null. But "better" only because PHP has made this weird development choice.

In my thinking this was a mistake in the development of PHP. The name ("isset") should describe the function and not have the desciption be "is set AND is not null". If it was done properly a programmer could very easily do (isset($var) || is_null($var)) if they wanted to check for this!

A variable set to null is a different state than a variable not set - there should be some easy way to differentiate. Just my (pointless) $0.02.
ayyappan dot ashok at gmail dot com 24-Mar-2016 07:23
Return Values :
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

<?php
$a=NULL;
$b=FALSE; //The out put was TRUE.
$c=TRUE;
$d='';
$e="";
if(isset($b)):
echo "TRUE";
else:
echo "FALSE";
endif;
?>
Could any one explain me in clarity.
andreasonny83 at gmail dot com 12-May-2015 11:26
Here is an example with multiple parameters supplied

<?php
$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset( $var['val1'], $var['val2'] ) && $var['val2'] === 'on' ) {
    unset( $var['val1'] );
}
print_r( $var );
?>

This will output:
Array
(
    [val2] => on
)

The following code does the same calling "isset" 2 times:

<?php
$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset( $var['val1'] ) && isset( $var['val2'] ) && $var['val2'] === 'on' ) {
    unset( $var['val1'] );
}
print_r( $var );
?>
uramihsayibok, gmail, com 25-Apr-2013 11:32
Note that isset() is not recursive as of the 5.4.8 I have available here to test with: if you use it on a multidimensional array or an object it will not check isset() on each dimension as it goes.

Imagine you have a class with a normal __isset and a __get that fatals for non-existant properties. isset($object->nosuch) will behave normally but isset($object->nosuch->foo) will crash. Rather harsh IMO but still possible.

<?php

class FatalOnGet {

    // pretend that the methods have implementations that actually try to do work
    // in this example I only care about the worst case conditions

    public function __get($name) {
        echo "(getting {$name}) ";

        // if property does not exist {
            echo "Property does not exist!";
            exit;
        // }
    }

    public function __isset($name) {
        echo "(isset {$name}?) ";
        // return whether the property exists
        return false;
    }

}

$obj = new FatalOnGet();

// works
echo "Testing if ->nosuch exists: ";
if (isset($obj->nosuch)) echo "Yes"; else echo "No";

// fatals
echo "\nTesting if ->nosuch->foo exists: ";
if (isset($obj->nosuch->foo)) echo "Yes"; else echo "No";

// not executed
echo "\nTesting if ->irrelevant exists: ";
if (isset($obj->irrelevant)) echo "Yes"; else echo "No";

?>

    Testing if ->nosuch exists: No
    Testing if ->nosuch->foo exists: Property does not exist!

Uncomment the echos in the methods and you'll see exactly what happened:

    Testing if ->nosuch exists: (isset nosuch?) No
    Testing if ->nosuch->foo exists: (getting nosuch) Property does not exist!

On a similar note, if __get always returns but instead issues warnings or notices then those will surface.
Daniel Klein 29-May-2012 03:49
How to test for a variable actually existing, including being set to null. This will prevent errors when passing to functions.

<?php
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

$myvar;
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

$myvar = null;
// true
var_export(
  array_key_exists('myvar', get_defined_vars())
);

unset($myvar);
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

if (array_key_exists('myvar', get_defined_vars())) {
  myfunction($myvar);
}
?>

Note: you can't turn this into a function (e.g. is_defined($myvar)) because get_defined_vars() only gets the variables in the current scope and entering a function changes the scope.
Cuong Huy To 23-Mar-2011 05:08
1) Note that isset($var) doesn't distinguish the two cases when $var is undefined, or is null. Evidence is in the following code.

<?php
unset($undefined);
$null = null;
if (true === isset($undefined)){echo 'isset($undefined) === true'} else {echo 'isset($undefined) === false'); // 'isset($undefined) === false'
if (true === isset($null)){echo 'isset($null) === true'} else {echo 'isset($null) === false');              // 'isset($null)      === false'
?>

2) If you want to distinguish undefined variable with a defined variable with a null value, then use array_key_exist

<?php
unset($undefined);
$null = null;

if (true !== array_key_exists('undefined', get_defined_vars())) {echo '$undefined does not exist';} else {echo '$undefined exists';} // '$undefined does not exist'
if (true === array_key_exists('null', get_defined_vars())) {echo '$null exists';} else {echo '$null does not exist';}                // '$null exists'
?>
francois vespa 22-Dec-2010 07:21
Now this is how to achieve the same effect (ie, having isset() returning true even if variable has been set to null) for objects and arrays

<?php

// array

$array=array('foo'=>null);

return isset($array['foo']) || array_key_exists('foo',$array)
  ? true : false ; // return true

return isset($array['inexistent']) || array_key_exists('inexistent',$array)
  ? true : false ; // return false

// static class

class bar

{
  static $foo=null;
}

return isset(bar::$foo) || array_key_exists('foo',get_class_vars('bar'))
  ? true : false ; // return true

return isset(bar::$inexistent) || array_key_exists('inexistent',get_class_vars('bar'))
  ? true : false ; // return false

// object

class bar
{
    public $foo=null;
}

$bar=new bar();

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

// stdClass

$bar=new stdClass;
$bar->foo=null;

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

?>
Anl zselgin 14-Aug-2009 03:30
Note: Because this is a language construct and not a function, it cannot be called using variable functions.

So why it is under "Variable handling Functions". Maybe there should be some good documentation field for language constructs.
Ashus 08-Dec-2008 01:05
Note that array keys are case sensitive.

<?php
$ar['w'] = true;

var_dump(isset($ar['w']),
      isset($ar['W']));
?>

will report:
bool(true) bool(false)
a dot schaffhirt at sedna-soft dot de 12-Oct-2008 08:01
You can safely use isset to check properties and subproperties of objects directly. So instead of writing

    isset($abc) && isset($abc->def) && isset($abc->def->ghi)

or in a shorter form

    isset($abc, $abc->def, $abc->def->ghi)

you can just write

    isset ($abc->def->ghi)

without raising any errors, warnings or notices.

Examples
<?php
    $abc = (object) array("def" => 123);
    var_dump(isset($abc));                // bool(true)
    var_dump(isset($abc->def));           // bool(true)
    var_dump(isset($abc->def->ghi));      // bool(false)
    var_dump(isset($abc->def->ghi->jkl)); // bool(false)
    var_dump(isset($def));                // bool(false)
    var_dump(isset($def->ghi));           // bool(false)
    var_dump(isset($def->ghi->jkl));      // bool(false)

    var_dump($abc);                       // object(stdClass)#1 (1) { ["def"] => int(123) }
    var_dump($abc->def);                  // int(123)
    var_dump($abc->def->ghi);             // null / E_NOTICE: Trying to get property of non-object
    var_dump($abc->def->ghi->jkl);        // null / E_NOTICE: Trying to get property of non-object
    var_dump($def);                       // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi);                  // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi->jkl);             // null / E_NOTICE: Trying to get property of non-object
?>
mark dot fabrizio at gmail dot com 15-Sep-2008 07:01
I know this is probably not the recommended way to do this, but it seems to work fine for me. Instead of the normal isset check to extract variables from arrays (like $_REQUEST), you can use the @ prefix to squelch any errors.

For example, instead of:
<?php
$test = isset($_REQUEST['test']) ? $_REQUEST['test'] : null;
?>
you can use:
<?php
$test = @$_REQUEST['test'];
?>

It saves some typing, but doesn't give the opportunity to provide a default value. If 'test' is not an assigned key for $_REQUEST, the assigned value will be null.
mandos78 AT mail from google 29-Jul-2008 02:40
Careful with this function "ifsetfor" by soapergem, passing by reference means that if, like the example $_GET['id'], the argument is an array index, it will be created in the original array (with a null value), thus causing posible trouble with the following code. At least in PHP 5.

For example:

<?php
$a = array();
print_r($a);
ifsetor($a["unsetindex"], 'default');
print_r($a);
?>

will print

Array
(
)
Array
(
    [unsetindex] =>
)

Any foreach or similar will be different before and after the call.
anonymousleaf at gmail dot com 25-Feb-2008 10:16
isset expects the variable sign first, so you can't add parentheses or anything.

<?php
    $foo = 1;
    if(isset(($foo))) { // Syntax error at isset((
        $foo = 2;
    }
?>
muratyaman at gmail dot com 07-Feb-2008 04:40
To organize some of the frequently used functions..

<?php

/**
 * Returns field of variable (arr[key] or obj->prop), otherwise the third parameter
 * @param array/object $arr_or_obj
 * @param string $key_or_prop
 * @param mixed $else
 */
function nz($arr_or_obj, $key_or_prop, $else){
  $result = $else;
  if(isset($arr_or_obj)){
    if(is_array($arr_or_obj){
      if(isset($arr_or_obj[$key_or_prop]))
        $result = $arr_or_obj[$key_or_prop];
    }elseif(is_object($arr_or_object))
      if(isset($arr_or_obj->$key_or_prop))
        $result = $arr_or_obj->$key_or_prop;
    }
  }
  return $result;
}

/**
 * Returns integer value using nz()
 */
function nz_int($arr_or_obj, $key_or_prop, $else){
  return intval(nz($arr_or_obj, $key_or_prop, $else));
}

$my_id = nz_int($_REQUEST, 'id', 0);
if($my_id > 0){
  //why?
}
?>
packard_bell_nec at hotmail dot com 25-Dec-2007 11:18
Note: isset() only checks variables as anything else will result in a parse error. In other words, the following will not work: isset(trim($name)).

isset() is the opposite of is_null($var) , except that no warning is generated when the variable is not set.
talbutt(at)mail(dot)med(dot)upenn(edu) 13-Aug-2007 08:30
In PHP 5.2.3, really returns true if the variable is set to null.
beuc at beuc dot net 16-Dec-2006 12:35
"empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set."

So essentially
<?php
if (isset($var) && $var)
?>
is the same as
<?php
if (!empty($var))
?>
doesn't it? :)

!empty() mimics the chk() function posted before.
randallgirard at hotmail dot com 27-Sep-2006 11:51
The unexpected results of isset has been really frustrating to me. Hence, it doesn't work how you'd think it would, (as documented) a var currently in the scope with a null value will return false.

Heres a quick solution, perhaps there are better ways of going about this, but heres my solution...

<?php
function is_set( $varname, $parent=null ) {
  if ( !is_array( $parent ) && !is_object($parent) ) {
    $parent = $GLOBALS;
  }
  return array_key_exists( $varname, $parent );
}
?>

Hence, $varname should be a mixed value of var's to check for, and $parent can be an array or object, which will default to the GLOBAL scope. See the documentation of array_key_exists for further information.

This will allow to check if a var is in the current scope, object, or array... Whether it's a null, false, true, or any value. It depends on ARRAY_KEY_EXISTS for it's functionality which also works with Objects. Feel free to improve on this anyone ;D
Tee Cee 20-Aug-2006 05:20
In response to 10-Feb-2006 06:02, isset($v) is in all (except possibly buggy) cases equivalent to !is_null($v). And no, it doesn't actually test if a variable is set or not by my definition "$v is set if unset($v) has no effect".

<?php
unset($c); //force $c to be unset
var_dump($a=&$c); // NULL, but this actually sets $a and $c to the 'same' NULL.
var_dump(isset($c)); // bool(false)
var_dump($a = 5); // int(5)
var_dump($c); // int(5)

unset($c);
var_dump($a=&$c); // NULL
var_dump(isset($c)); // bool(false)
unset($c);
var_dump($a = 5); // int(5)
var_dump($c); // NULL
?>

In the following example, we see an alternate method of testing if a variable is actually set or not:
<?php
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump(isset($c));                                // also false
var_dump($c);                                       // manipulate $c a bit...
var_dump((string)$c);
var_dump(print_r($c,true));
var_dump($a=$c);
var_dump(array_key_exists('c',get_defined_vars())); // ... still false
var_dump($c = NULL);                                // this sets $c
var_dump(array_key_exists('c',get_defined_vars())); // true!
var_dump(isset($c));                                // false; isset() still says it's unset
unset($c);                                          // actually unset it
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump($a=&$c);
var_dump(array_key_exists('c',get_defined_vars())); // true!
unset($c);                                          // unset it again
var_dump(&$c);                                      // &NULL
var_dump(array_key_exists('c',get_defined_vars())); // true!
?>

Obviously, null values take up space (or they wouldn't show up in get_defined_vars). Also, note that &$v sets $v to NULL if it is unset.
21-Jul-2006 07:08
I tried the example posted previously by Slawek:

$foo = 'a little string';
echo isset($foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';

He got yes yes, but he didn't say what version of PHP he was using.

I tried this on PHP 5.0.5 and got:  yes no

But on PHP 4.3.5 I got:  yes yes

Apparently, PHP4 converts the the string 'aaaa' to zero and then returns the string character at that position within the string $foo, when $foo is not an array. That means you can't assume you are dealing with an array, even if you used an expression such as isset($foo['aaaa']['bbb']['cc']['d']), because it will return true also if any part is a string.

PHP5 does not do this. If $foo is a string, the index must actually be numeric (e.g. $foo[0]) for it to return the indexed character.
soywiz at php dot net 14-Apr-2006 06:12
Sometimes you have to check if an array has some keys. To achieve it you can use "isset" like this: isset($array['key1'], $array['key2'], $array['key3'], $array['key4'])
You have to write $array all times and it is reiterative if you use same array each time.

With this simple function you can check if an array has some keys:

<?php
function isset_array() {
    if (func_num_args() < 2) return true;
    $args = func_get_args();
    $array = array_shift($args);
    if (!is_array($array)) return false;
    foreach ($args as $n) if (!isset($array[$n])) return false;
    return true;
}
?>

Use: isset_array($array, 'key1', 'key2', 'key3', 'key4')
First parameter has the array; following parameters has the keys you want to check.
Slawek Petrykowski 29-Nov-2005 03:06
<?php
$foo = 'a little string';
echo isset($foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';
>

results with unexpected values:
yes yes

Well, it is necessary to check type of $foo first !
Andrew Penry 11-May-2005 08:17
The following is an example of how to test if a variable is set, whether or not it is NULL. It makes use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL will not.

<?php

function var_exists($var){
    if (empty($GLOBALS['var_exists_err'])) {
        return true;
    } else {
        unset($GLOBALS['var_exists_err']);
        return false;
    }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
   $GLOBALS['var_exists_err'] = true;
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
restore_error_handler();

?>

Outputs:
True False

The problem is, the set_error_handler and restore_error_handler calls can not be inside the function, which means you need 2 extra lines of code every time you are testing. And if you have any E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they will not be dealt with properly. One solution:

<?php

function var_exists($var){
   if (empty($GLOBALS['var_exists_err'])) {
       return true;
   } else {
       unset($GLOBALS['var_exists_err']);
       return false;
   }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
    $filearr = file($errfile);
    if (strpos($filearr[$errline-1], 'var_exists') !== false) {
        $GLOBALS['var_exists_err'] = true;
        return true;
    } else {
        return false;
    }
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
is_null($j);
restore_error_handler();

?>

Outputs:
True False
Notice: Undefined variable: j in filename.php on line 26

This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an E_NOTICE error happens, the file it originated from will be loaded into an array.
yaogzhan at gmail dot com 20-Mar-2005 04:52
in PHP5, if you have

<?PHP
class Foo
{
    protected $data = array('bar' => null);

    function __get($p)
    {
        if( isset($this->data[$p]) ) return $this->data[$p];
    }
}
?>

and
<?PHP
$foo = new Foo;
echo isset($foo->bar);
?>
will always echo 'false'. because the isset() accepts VARIABLES as it parameters, but in this case, $foo->bar is NOT a VARIABLE. it is a VALUE returned from the __get() method of the class Foo. thus the isset($foo->bar) expreesion will always equal 'false'.
pianistsk8er at gmail dot com 09-Dec-2004 06:23
This function is very useful while calling to the URL to specify which template to be used on certain parts of your application.

Here is an example...

<?php

    $cat = $_GET['c'];
    $id = $_GET['id'];
    $error = 'templates/error.tpl';

    if( isset($cat))
    {
        if( isset($id))
        {
            $var = 'templates/pics/' . $cat . '-' . $id . '.tpl';
            if (is_file($var))
            {
                include($var);
            }
            else
            {
                include($error);
            }
        }
        else
        {
            $var = 'templates/pics/' . $cat . '.tpl';
            if (is_file($var))
            {
                include($var);
            }
            else
            {
                include($error);
            }
        }
    }
    else
    {
        include('templates/alternative.'.tpl);
    }

?>

You can see several uses of the isset function being used to specify wheter a template is to be called upon or not.  This can easily prevent other generic PHP errors.


以易于理解的格式打印变量。

  • ? isset
  • serialize ?
  • PHP Manual
  • Variable handling 函数
  • 以易于理解的格式打印变量。

print_r

(PHP 4, PHP 5, PHP 7, PHP 8)

print_r — 以易于理解的格式打印变量。

说明

print_r ( mixed $expression , bool $return = false ) : mixed

print_r() 以人类易读的格式显示一个变量的信息。

print_r()、
var_dump()、
var_export()
都会显示对象 protected 和 private 的属性。
Class 的静态属性（static） 则不会显示。

参数

expression

要打印的表达式。

return

想要获取 print_r() 输出的内容，使用 return 参数。 当此参数为 true，print_r() 会直接返回信息，而不是输出。

返回值

如果输入的内容是 string、 integer 或 float，会直接输出值本身。 如果输入的内容是 array，展示的格式会显示数组的键和包含的元素。object 也类似。

当 return 参数设置成 true，本函数会返回 string 格式。否则返回 true。

注释

Note:

当使用了return 参数时，本函数使用其内部输出缓冲，因此不能在 ob_start() 回调函数的内部使用。

范例

Example #1 print_r() 例子

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

以上例程会输出：

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Example #2 return 参数的例子

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results 包含了 print_r 的输出
?>

参见

  • ob_start() - 打开输出控制缓冲
  • var_dump() - 打印变量的相关信息
  • var_export() - 输出或返回一个变量的字符串表示

User Contributed Notes

ajaykwatra at gmail dot com 12-Mar-2018 08:33
easier and better readability with print_r and vardump for php developers

https://gist.github.com/akwatra/b6a2f21b33e7a86d148618d8a83276b0
Soaku 28-Sep-2017 04:47
liamtoh6@hotmail.com posted a function that will echo print_r output with proper new lines in HTML files. He used <pre> for it to work, but that might not be always the best method to go. For example, it is not valid to place <pre> inside <p>.

Here is my way to do this:

<?php

function print_rbr ($var, $return = false) {
  $r = nl2br(htmlspecialchars(print_r($var, true)));
  if ($return) return $r;
  else echo $r;
}

?>

This function will:

- Place <br> where newlines are,
- Escape unsecure characters with HTML entities.
Soaku 28-Jul-2017 10:24
Remember to always htmlspecialchars print_r output, if it can contain html characters.

<?php

$array = array("<some>html<tags>");

print_r($array); // Invalid output, HTML breaks.
echo htmlspecialchars(print_r($array, true)); // Works and doesn't break the output.
?>
simivar at gmail dot com 21-Jun-2017 01:31
I've fixed function wrote by Matt to reverse print_r - it had problems with null values. Created a GIST for that too so please add any future fixes in there instead of this comment section:
https://gist.github.com/simivar/037b13a9bbd53ae5a092d8f6d9828bc3

<?php
/**
  * Matt: core
  * Trixor: object handling
  * lech: Windows suppport
  * simivar: null support
  *
  * @see http://php.net/manual/en/function.print-r.php
  **/
function print_r_reverse($input) {
        $lines = preg_split('#\r?\n#', trim($input));
        if (trim($lines[ 0 ]) != 'Array' && trim($lines[ 0 ] != 'stdClass Object')) {
            // bottomed out to something that isn't an array or object
            if ($input === '') {
                return null;
            }

            return $input;
        } else {
            // this is an array or object, lets parse it
            $match = array();
            if (preg_match("/(\s{5,})\(/", $lines[ 1 ], $match)) {
                // this is a tested array/recursive call to this function
                // take a set of spaces off the beginning
                $spaces = $match[ 1 ];
                $spaces_length = strlen($spaces);
                $lines_total = count($lines);
                for ($i = 0; $i < $lines_total; $i++) {
                    if (substr($lines[ $i ], 0, $spaces_length) == $spaces) {
                        $lines[ $i ] = substr($lines[ $i ], $spaces_length);
                    }
                }
            }
            $is_object = trim($lines[ 0 ]) == 'stdClass Object';
            array_shift($lines); // Array
            array_shift($lines); // (
            array_pop($lines); // )
            $input = implode("\n", $lines);
            $matches = array();
            // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
            preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $input, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
            $pos = array();
            $previous_key = '';
            $in_length = strlen($input);
            // store the following in $pos:
            // array with key = key of the parsed array's item
            // value = array(start position in $in, $end position in $in)
            foreach ($matches as $match) {
                $key = $match[ 1 ][ 0 ];
                $start = $match[ 0 ][ 1 ] + strlen($match[ 0 ][ 0 ]);
                $pos[ $key ] = array($start, $in_length);
                if ($previous_key != '') {
                    $pos[ $previous_key ][ 1 ] = $match[ 0 ][ 1 ] - 1;
                }
                $previous_key = $key;
            }
            $ret = array();
            foreach ($pos as $key => $where) {
                // recursively see if the parsed out value is an array too
                $ret[ $key ] = print_r_reverse(substr($input, $where[ 0 ], $where[ 1 ] - $where[ 0 ]));
            }

            return $is_object ? (object)$ret : $ret;
        }
    }
?>
anymix dot services at gmail dot com 28-May-2017 04:31
// New var export option

function varExp($E,$vE){
    $vE.="=array(";$sep="";
    foreach ($E as $veK => $veV) {
        $vE.=$sep."'$veK'=>'$veV'";$sep=",";
    }
    $vE.=");";
    return $vE;
}

print varExp($I,"\$I");
lech 02-May-2017 08:30
A slight amendment to Matt's awesome print_r_reverse function (Thank You, a life-saver - data recovery :-) . If the output is copied from a Windows system, the end of lines may include the return character "\r" and so the scalar (string) elements will include a trailing "\r" character that isn't suppose to be there. To resolve, replace the first line in the function with...

<?php $lines = preg_split('#\r?\n#', trim($in)); ?>

This will work for both cases (Linux and Windows).

I include the entire function below for completeness, but all credit to Matt, the original author, Thank You.

<?php
//Author: Matt (http://us3.php.net/print_r)
function print_r_reverse($in) {
    $lines = preg_split('#\r?\n#', trim($in));
    if (trim($lines[0]) != 'Array') {
        // bottomed out to something that isn't an array
        return $in;
    } else {
        // this is an array, lets parse it
        if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
            // this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
            $spaces = $match[1];
            $spaces_length = strlen($spaces);
            $lines_total = count($lines);
            for ($i = 0; $i < $lines_total; $i++) {
                if (substr($lines[$i], 0, $spaces_length) == $spaces) {
                    $lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
        array_shift($lines); // Array
        array_shift($lines); // (
        array_pop($lines); // )
        $in = implode("\n", $lines);
        // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
        preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $pos = array();
        $previous_key = '';
        $in_length = strlen($in);
        // store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
        foreach ($matches as $match) {
            $key = $match[1][0];
            $start = $match[0][1] + strlen($match[0][0]);
            $pos[$key] = array($start, $in_length);
            if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
            $previous_key = $key;
        }
        $ret = array();
        foreach ($pos as $key => $where) {
            // recursively see if the parsed out value is an array too
            $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return $ret;
    }
}
?>
Trixor 01-Feb-2017 07:12
I've made a small improvement to the print_r_reverse function to also handle objects. Thanks to Matt for making the original.

<?php
function print_r_reverse($in) {
  $lines = explode("\n", trim($in));
  if (trim($lines[0]) != 'Array' && trim($lines[0] != 'stdClass Object')) {
// bottomed out to something that isn't an array or object
    return $in;
  } else {
// this is an array or object, lets parse it
    $match = array();
    if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
      $spaces = $match[1];
      $spaces_length = strlen($spaces);
      $lines_total = count($lines);
      for ($i = 0; $i < $lines_total; $i++) {
        if (substr($lines[$i], 0, $spaces_length) == $spaces) {
          $lines[$i] = substr($lines[$i], $spaces_length);
        }
      }
    }
    $is_object = trim($lines[0]) == 'stdClass Object';
    array_shift($lines); // Array
    array_shift($lines); // (
    array_pop($lines); // )
    $in = implode("\n", $lines);
    $matches = array();
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
    preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
    $pos = array();
    $previous_key = '';
    $in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
    foreach ($matches as $match) {
      $key = $match[1][0];
      $start = $match[0][1] + strlen($match[0][0]);
      $pos[$key] = array($start, $in_length);
      if ($previous_key != '') {
        $pos[$previous_key][1] = $match[0][1] - 1;
      }
      $previous_key = $key;
    }
    $ret = array();
    foreach ($pos as $key => $where) {
// recursively see if the parsed out value is an array too
      $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
    }
    return $is_object ? (object) $ret : $ret;
  }
}
?>
ntd at entidi dot it 31-Jul-2015 05:43
Another attempt that tries to overcome the memory blowout when the passed in data has mutual recursion.

<?php
function safe_print_r($data, $nesting = 5, $indent = '') {
    if (! is_object($data) && ! is_array($data)) {
        var_dump($data);
    } elseif ($nesting < 0) {
        echo "** MORE **\n";
    } else {
        echo ucfirst(gettype($data)) . " (\n";
        foreach ((array) $data as $k => $v) {
            echo $indent . "\t[$k] => ";
            safe_print_r($v, $nesting - 1, "$indent\t");
        }
        echo "$indent)\n";
    }
}
?>
Sumit 27-May-2015 01:20
I prefer to use
<?php
printf("<pre>%s</pre>",print_r($_POST, true));
?>
Simon Asika 06-Nov-2013 04:06
Here is a print_r() clone but support max level limit.

When we want to print a big object, this will help us get a clean dumping data.

<?php

/**
 * Recrusive print variables and limit by level.
 *
 * @param   mixed  $data   The variable you want to dump.
 * @param   int    $level  The level number to limit recrusive loop.
 *
 * @return  string  Dumped data.
 *
 * @author  Simon Asika (asika32764[at]gmail com)
 * @date    2013-11-06
 */
function print_r_level($data, $level = 5)
{
    static $innerLevel = 1;

    static $tabLevel = 1;

    static $cache = array();

    $self = __FUNCTION__;

    $type       = gettype($data);
    $tabs       = str_repeat('    ', $tabLevel);
    $quoteTabes = str_repeat('    ', $tabLevel - 1);

    $recrusiveType = array('object', 'array');

    // Recrusive
    if (in_array($type, $recrusiveType))
    {
        // If type is object, try to get properties by Reflection.
        if ($type == 'object')
        {
            if (in_array($data, $cache))
            {
                return "\n{$quoteTabes}*RECURSION*\n";
            }

            // Cache the data
            $cache[] = $data;

            $output     = get_class($data) . ' ' . ucfirst($type);
            $ref        = new \ReflectionObject($data);
            $properties = $ref->getProperties();

            $elements = array();

            foreach ($properties as $property)
            {
                $property->setAccessible(true);

                $pType = $property->getName();

                if ($property->isProtected())
                {
                    $pType .= ":protected";
                }
                elseif ($property->isPrivate())
                {
                    $pType .= ":" . $property->class . ":private";
                }

                if ($property->isStatic())
                {
                    $pType .= ":static";
                }

                $elements[$pType] = $property->getValue($data);
            }
        }
        // If type is array, just retun it's value.
        elseif ($type == 'array')
        {
            $output = ucfirst($type);
            $elements = $data;
        }

        // Start dumping datas
        if ($level == 0 || $innerLevel < $level)
        {
            // Start recrusive print
            $output .= "\n{$quoteTabes}(";

            foreach ($elements as $key => $element)
            {
                $output .= "\n{$tabs}[{$key}] => ";

                // Increment level
                $tabLevel = $tabLevel + 2;
                $innerLevel++;

                $output  .= in_array(gettype($element), $recrusiveType) ? $self($element, $level) : $element;

                // Decrement level
                $tabLevel = $tabLevel - 2;
                $innerLevel--;
            }

            $output .= "\n{$quoteTabes})\n";
        }
        else
        {
            $output .= "\n{$quoteTabes}*MAX LEVEL*\n";
        }
    }

    // Clean cache
    if($innerLevel == 1)
    {
        $cache = array();
    }

    return $output;
}// End function

// TEST ------------------------------------

class testClass
{
    protected $a = 'aaa';

    private $b = 'bbb';

    public $c = array(1, 2, ['a', 'b', 'c'], 4);

    static public $d = 'ddd';

    static protected $e = 'eee';
}

$test = new testClass;

$test->testClass = $test;

echo '<pre>' . print_r_level($test, 3) . '</pre>';

?>

will output
-------------------------------------------------------------

testClass Object
(
    [a:protected] => aaa
    [b:testClass:private] => bbb
    [c] => Array
        (
            [0] => 1
            [1] => 2
            [2] => Array
                *MAX LEVEL*

            [3] => 4
        )

    [d:static] => ddd
    [e:protected:static] => eee
    [testClass] =>
        *RECURSION*

)
preda dot vlad at yahoo dot com 22-Mar-2013 09:40
print_r(), just like var_dump() does NOT cast an object, not even if it has a __toString() method - which is normal.

<?php
class A {
    public function __toString() {
        return 'In class A';
    }
}
$a = new A;
echo $a; // In class A
print_r($a); // A Object()
// you can simulate the echo by casting it manually
print_r((string)$a);  // In class A
henzeberkheij at gmail dot com 28-Jan-2012 03:10
print_r is used for debug purposes. Yet I had some classes where I just wanted the values coming out of the database, not all the other crap. thus i wrote the following function. If your class has an toArray function, that one will be called otherwise it will return the object as is. print_neat_classes_r is the function that should be called!

<?php
print_neat_classes_r($array, $return=false){
        return print_r(self::neat_class_print_r($array), $return);
    }

function do_print_r($array, $return=false){
        if(is_object($array) && method_exists($array, 'toArray')){
            return $array->toArray();
        }else if(is_array($array)){
            foreach($array as $key=>$obj){
                $array[$key] = self::do_print_r($obj, $return);
            }
            return $array;
        }else{
            return $array;
        }
    }
?>
eithed 21-Oct-2011 02:25
Bear in mind that print_r actually reserves some memory to do something - so, for example thing like:

<?php
function shutdown_handler()
{
    file_put_contents($_SERVER['DOCUMENT_ROOT']."/log.txt", print_r($_REQUEST, true));
}

ini_set('memory_limit', '1M');
register_shutdown_function("shutdown_handler");

$array = array();
while(true)
    $array[] = new stdClass();
?>

will just not work. Try using var_export, and presto, everything is fine.
machuidel 03-Feb-2011 04:01
The following will output an array in a PHP parsable format:

<?php
function serialize_array(&$array, $root = '$root', $depth = 0)
{
        $items = array();

        foreach($array as $key => &$value)
        {
                if(is_array($value))
                {
                        serialize_array($value, $root . '[\'' . $key . '\']', $depth + 1);
                }
                else
                {
                        $items[$key] = $value;
                }
        }

        if(count($items) > 0)
        {
                echo $root . ' = array(';

                $prefix = '';
                foreach($items as $key => &$value)
                {
                        echo $prefix . '\'' . $key . '\' => \'' . addslashes($value) . '\'';
                        $prefix = ', ';
                }

                echo ');' . "\n";
        }
}
?>
Alexander 19-Mar-2010 05:20
A simple function to send the output of print_r to firebug.
The script creates a dummy console object with a log method for when firebug is disabled/not available.

<?php
function debug ($data) {
    echo "<script>\r\n//<![CDATA[\r\nif(!console){var console={log:function(){}}}";
    $output    =    explode("\n", print_r($data, true));
    foreach ($output as $line) {
        if (trim($line)) {
            $line    =    addslashes($line);
            echo "console.log(\"{$line}\");";
        }
    }
    echo "\r\n//]]>\r\n</script>";
}
?>
liamtoh6 at hotmail dot com 03-Feb-2010 10:01
I add this function to the global scope on just about every project I do, it makes reading the output of print_r() in a browser infinitely easier.

<?php
function print_r2($val){
        echo '<pre>';
        print_r($val);
        echo  '</pre>';
}
?>

It also makes sense in some cases to add an if statement to only display the output in certain scenarios, such as:

if(debug==true)
if($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
Matt 14-Sep-2009 12:53
Here is another version that parses the print_r() output. I tried the one posted, but I had difficulties with it. I believe it has a problem with nested arrays. This handles nested arrays without issue as far as I can tell.

<?php
function print_r_reverse($in) {
    $lines = explode("\n", trim($in));
    if (trim($lines[0]) != 'Array') {
        // bottomed out to something that isn't an array
        return $in;
    } else {
        // this is an array, lets parse it
        if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
            // this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
            $spaces = $match[1];
            $spaces_length = strlen($spaces);
            $lines_total = count($lines);
            for ($i = 0; $i < $lines_total; $i++) {
                if (substr($lines[$i], 0, $spaces_length) == $spaces) {
                    $lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
        array_shift($lines); // Array
        array_shift($lines); // (
        array_pop($lines); // )
        $in = implode("\n", $lines);
        // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
        preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $pos = array();
        $previous_key = '';
        $in_length = strlen($in);
        // store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
        foreach ($matches as $match) {
            $key = $match[1][0];
            $start = $match[0][1] + strlen($match[0][0]);
            $pos[$key] = array($start, $in_length);
            if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
            $previous_key = $key;
        }
        $ret = array();
        foreach ($pos as $key => $where) {
            // recursively see if the parsed out value is an array too
            $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return $ret;
    }
}

?>
Bob 08-May-2009 03:19
Here is a function that formats the output of print_r as a expandable/collapsable tree list using HTML and JavaScript.
<?php
function print_r_tree($data)
{
    // capture the output of print_r
    $out = print_r($data, true);

    // replace something like '[element] => <newline> (' with <a href="javascript:toggleDisplay('...');">...</a><div id="..." style="display: none;">
    $out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',"'\\1<a href=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'\\0'), 0, 7)).'\');\">\\2</a><div id=\"'.\$id.'\" style=\"display: none;\">'", $out);

    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '</div>
    $out = preg_replace('/^\s*\)\s*$/m', '</div>', $out);

    // print the javascript function toggleDisplay() and then the transformed output
    echo '<script language="Javascript">function toggleDisplay(id) { document.getElementById(id).style.display = (document.getElementById(id).style.display == "block") ? "none" : "block"; }</script>'."\n$out";
}
?>
Pass it a multidimensional array or object and each sub-array/object will be hidden and replaced by a html link that will toggle its display on and off.
Its quick and dirty, but great for debugging the contents of large arrays and objects.
Note: You'll want to surround the output with <pre></pre>
sebasg37 at gmail dot com 25-Jan-2009 09:35
If you have to catch the output without showing it at all at first (for example, if you want to append the print_r output to a file), you can do this:

<?php

ob_start();
print_r( $some_array );
$output = ob_get_clean();

// if you want to append the print_r output of $some_array to, let's say, log.txt:

file_put_contents( 'log.txt', file_get_contents( 'log.txt' ) . $output )

?>
afisher8 at cox dot net 17-Dec-2008 08:53
I use this all the time when debugging objects, but when you have a very large object with big arrays of sub-objects, it's easy to get overwhelmed with the large amount of output....sometimes you don't want to see absolutely every sub-object.

I made this function to debug objects while "hiding" sub-objects of certain types.  This also color codes the output for a more readable printout.

<?php

function wtf($var, $arrayOfObjectsToHide=null, $fontSize=11)
{
    $text = print_r($var, true);

    if (is_array($arrayOfObjectsToHide)) {

        foreach ($arrayOfObjectsToHide as $objectName) {

            $searchPattern = '#('.$objectName.' Object\n(\s+)\().*?\n\2\)\n#s';
            $replace = "$1<span style=\"color: #FF9900;\">--&gt; HIDDEN - courtesy of wtf() &lt;--</span>)";
            $text = preg_replace($searchPattern, $replace, $text);
        }
    }

    // color code objects
    $text = preg_replace('#(\w+)(\s+Object\s+\()#s', '<span style="color: #079700;">$1</span>$2', $text);
    // color code object properties
    $text = preg_replace('#\[(\w+)\:(public|private|protected)\]#', '[<span style="color: #000099;">$1</span>:<span style="color: #009999;">$2</span>]', $text);

    echo '<pre style="font-size: '.$fontSize.'px; line-height: '.$fontSize.'px;">'.$text.'</pre>';
}

// example usage:
wtf($myBigObject, array('NameOfObjectToHide_1', 'NameOfObjectToHide_2'));

?>
kurt krueckeberg 28-Oct-2008 10:53
This is an alternative for printing arrays. It bolds array values.

<?php
function print_array(&$a, $str = "")
{
    if ($str[0]) {
        echo "$str =";
    }
    echo ' array( ';
    foreach ($a as $k => $v) {

        echo "[$k]".' => ';

        if (is_array($v)) {
            print_array($v);
        }
        else {
               echo "<strong>$a[$k]</strong> ";
        }
    }
    echo ')  ';
}
$a1 = array ("apples", "oranges", "pears");
$a2 = array ("potatos", "green beans", "squash");
$a3 = array ("euros", "dollars", "pesos", "dinars");
$test = range(1, 9);
array_push($test, array ("fruit" => $a1, "vegies" => $a2, "money" => $a3));
print_array($test, "test");
?>
schizo do not spamme duckie at gmail dot com 07-Oct-2008 05:00
my take on the highlighted markupped debug function:

<?php
/**
 * print_array()
 * Does a var_export of the array and returns it between <pre> tags
 *
 * @param mixed $var any input you can think of
 * @return string HTML
 */
function print_array($var)
{
    $input =var_export($var,true);
    $input = preg_replace("! => \n\W+ array \(!Uims", " => Array ( ", $input);
    $input = preg_replace("!array \(\W+\),!Uims", "Array ( ),", $input);
    return("<pre>".str_replace('><?', '>', highlight_string('<'.'?'.$input, true))."</pre>");
}
?>
brenden at beagleproductions dot com 28-Aug-2008 01:58
Many developers have submitted bugs to the PHP development team with regards to print_r showing protected and private properties of objects (PHP 5).  This is not a bug; sensitive information (ex. database connection object) should be  encapsulated within a private member function of your class.
admin at swivelgames dot com 17-Aug-2008 01:44
I was having problems using print_r because I didn't like the fact that if tags where included in the array it would still be parsed by the browsers.

Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser's "view source" or CLI.

Script:
<?php

     $MyArray[0]="<div align='center'>My Text</div>";

     echo "<pre>".htmlspecialchars(print_r($MyArray,true))."</pre>";

?>

Output:
<pre>Array
(
    [0] =&gt; &lt;div align='center'&gt;My Text&lt;/div&gt;
)
</pre>
Anonymous 28-Jun-2008 01:21
I have written a nice debugging function.
This function handles arrays beautifully.
<?php
//Debug variables, $i and $k are for recursive use
function DebugDisplayVar($input, $name = "Debug", $i = "0", $k = array("Error")){
    if(is_array($input))
    {    foreach ($input as $i => $value){
            $temp = $k;
            $temp[] = $i;
            DebugDisplayVar($value, $name, $i, $temp);}
    }else{//if not array
        echo "$".$name;//[$k]
        foreach ($k as $i => $value){
            if($value !=="Error"){echo "[$value]";}
        }
        echo " = $input<br>";
}    }

//outputs
Debug[0] = value
Debug[1] = another value
ect...

?>
janci 13-May-2008 02:49
You cannot use print_r(), var_dump() nor var_export() to get static member variables of a class. However, in PHP5 you can use Reflection classes for this:

<?php

$reflection = new ReflectionClass('Static');
print_r($reflection->getStaticProperties());

?>
helpful at maybe dot com 06-Mar-2008 08:13
Another slight modification to the previous post to allow for empty array elements

added the following lines after the first preg_match block
<?php
        } else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\>$/', $trim, $matches)) { // array element
            // the array element is blank
            list ($fullMatch, $key) = $matches;
            $topArray[$key] = $element;
        }

?>
anon at anon dot com 29-Feb-2008 10:30
A slight modification to the previous post to allow for arrays containing mutli line strings. haven't fully tested it with everything, but seems to work great for the stuff i've done so far.

<?php

function print_r_reverse(&$output)
{
    $expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
    $lines = explode("\n", $output);
    $result = null;
    $topArray = null;
    $arrayStack = array();
    $matches = null;
    while (!empty($lines) && $result === null)
    {
        $line = array_shift($lines);
        $trim = trim($line);
        if ($trim == 'Array')
        {
            if ($expecting == 0)
            {
                $topArray = array();
                $expecting = 1;
            }
            else
            {
                trigger_error("Unknown array.");
            }
        }
        else if ($expecting == 1 && $trim == '(')
        {
            $expecting = 2;
        }
        else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)) // array element
        {
            list ($fullMatch, $key, $element) = $matches;
            if (trim($element) == 'Array')
            {
                $topArray[$key] = array();
                $newTopArray =& $topArray[$key];
                $arrayStack[] =& $topArray;
                $topArray =& $newTopArray;
                $expecting = 1;
            }
            else
            {
                $topArray[$key] = $element;
            }
        }
        else if ($expecting == 2 && $trim == ')') // end current array
        {
            if (empty($arrayStack))
            {
                $result = $topArray;
            }
            else // pop into parent array
            {
                // safe array pop
                $keys = array_keys($arrayStack);
                $lastKey = array_pop($keys);
                $temp =& $arrayStack[$lastKey];
                unset($arrayStack[$lastKey]);
                $topArray =& $temp;
            }
        }
        // Added this to allow for multi line strings.
    else if (!empty($trim) && $expecting == 2)
    {
        // Expecting close parent or element, but got just a string
        $topArray[$key] .= "\n".$line;
    }
        else if (!empty($trim))
        {
            $result = $line;
        }
    }

    $output = implode(n, $lines);
    return $result;
}

/**
 * @param string $output : The output of a multiple print_r calls, separated by newlines
 * @return mixed[] : parseable elements of $output
 */
function print_r_reverse_multiple($output)
{
    $result = array();
    while (($reverse = print_r_reverse($output)) !== NULL)
    {
        $result[] = $reverse;
    }
    return $result;
}

$output = '
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
            [3] => Array
            (
                [nest] => yes
                [nest2] => Array
                (
                    [nest] => some more
                    asffjaskkd
                )
                [nest3] => o rly?
            )
        )
)

some extra stuff
';
var_dump(print_r_reverse($output), $output);

?>

This should output

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  array(4) {
    [0]=>
    string(1) "x"
    [1]=>
    string(1) "y"
    [2]=>
    string(1) "z"
    [3]=>
    array(3) {
      ["nest"]=>
      string(3) "yes"
      ["nest2"]=>
      array(1) {
        ["nest"]=>
        string(40) "some more
                    asffjaskkd"
      }
      ["nest3"]=>
      string(6) "o rly?"
    }
  }
}
string(18) "nsome extra stuffn"

Added:
else if (!empty($trim) && $expecting == 2)
{
    // Expecting close parent or element, but got just a string
    $topArray[$key] .= "\n".$line;
}
bart at mediawave dot nl 30-Oct-2007 04:27
Here's a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage:

void u_print_r ( mixed $expression [, array $ignore] )

Use the $ignore parameter to provide an array of property names that shouldn't be followed recursively.

<?php

function u_print_r($subject, $ignore = array(), $depth = 1, $refChain = array())
{
    if ($depth > 20) return;
    if (is_object($subject)) {
        foreach ($refChain as $refVal)
            if ($refVal === $subject) {
                echo "*RECURSION*\n";
                return;
            }
        array_push($refChain, $subject);
        echo get_class($subject) . " Object ( \n";
        $subject = (array) $subject;
        foreach ($subject as $key => $val)
            if (is_array($ignore) && !in_array($key, $ignore, 1)) {
                echo str_repeat(" ", $depth * 4) . '[';
                if ($key{0} == "\0") {
                    $keyParts = explode("\0", $key);
                    echo $keyParts[2] . (($keyParts[1] == '*')  ? ':protected' : ':private');
                } else
                    echo $key;
                echo '] => ';
                u_print_r($val, $ignore, $depth + 1, $refChain);
            }
        echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
        array_pop($refChain);
    } elseif (is_array($subject)) {
        echo "Array ( \n";
        foreach ($subject as $key => $val)
            if (is_array($ignore) && !in_array($key, $ignore, 1)) {
                echo str_repeat(" ", $depth * 4) . '[' . $key . '] => ';
                u_print_r($val, $ignore, $depth + 1, $refChain);
            }
        echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
    } else
        echo $subject . "\n";
}

?>

Example:

<?php

class test {

    public $var1 = 'a';
    protected $var2 = 'b';
    private $var3 = 'c';
    protected $array = array('x', 'y', 'z');

}

$test = new test();
$test->recursiveRef = $test;
$test->anotherRecursiveRef->recursiveRef = $test;
$test->dont->follow = 'me';

u_print_r($test, array('dont'));

?>

Will produce:

test Object (
    [var1] => a
    [var2:protected] => b
    [var3:private] => c
    [array:protected] => Array (
        [0] => x
        [1] => y
        [2] => z
    )
    [recursiveRef] => *RECURSION*
    [anotherRecursiveRef] => stdClass Object (
        [recursiveRef] => *RECURSION*
    )
)
motin at demomusic dot nu 19-Jun-2007 04:01
This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky...):

<?php
/**
  * An alternative to print_r that unlike the original does not use output buffering with
  * the return parameter set to true. Thus, Fatal errors that would be the result of print_r
  * in return-mode within ob handlers can be avoided.
  *
  * Comes with an extra parameter to be able to generate html code. If you need a
  * human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/
  *
  * Support for printing of objects as well as the $return parameter functionality
  * added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in
  * replacement for print_r (Except for that this function does not output
  * paranthesises around element groups... ;) )
  *
  * Based on return_array() By Matthew Ruivo (mruivo at gmail)
  * (http://se2.php.net/manual/en/function.print-r.php#73436)
  */
function obsafe_print_r($var, $return = false, $html = false, $level = 0) {
    $spaces = "";
    $space = $html ? "&nbsp;" : " ";
    $newline = $html ? "<br />" : "\n";
    for ($i = 1; $i <= 6; $i++) {
        $spaces .= $space;
    }
    $tabs = $spaces;
    for ($i = 1; $i <= $level; $i++) {
        $tabs .= $spaces;
    }
    if (is_array($var)) {
        $title = "Array";
    } elseif (is_object($var)) {
        $title = get_class($var)." Object";
    }
    $output = $title . $newline . $newline;
    foreach($var as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $level++;
            $value = obsafe_print_r($value, true, $html, $level);
            $level--;
        }
        $output .= $tabs . "[" . $key . "] => " . $value . $newline;
    }
    if ($return) return $output;
      else echo $output;
}
?>

Built on a function earlier posted in these comments as stated in the Doc comment. Cheers! /Fredrik (Motin)
Enthusiastic PHPers 22-Mar-2007 12:03
We had an interesting problem dumping an object that
contained embedded HTML. The application makes use
of buffer manipulation functions, so print_r's 2nd argument
wasn't helpful. Here is how we solved the problem:

$object = new ObjectContainingHTML();
$savedbuffercontents = ob_get_clean();
print_r($object);
$print_r_output = ob_get_clean();
ob_start();
echo $savedbuffercontents;
echo htmlentities($print_r_output);
Matthew Ruivo (mruivo at gmail) 22-Feb-2007 10:47
For those of you needing to print an array within a buffer callback function, I've created this quick function. It simply returns the array as a readable string rather than printing it. You can even choose whether to return it in normal text-mode or HTML. It's recursive, so multi-dimensial arrays are supported. I hope someone finds this useful!

<?php

    function return_array($array, $html = false, $level = 0) {
        $space = $html ? "&nbsp;" : " ";
        $newline = $html ? "<br />" : "\n";
        for ($i = 1; $i <= 6; $i++) {
            $spaces .= $space;
        }
        $tabs = $spaces;
        for ($i = 1; $i <= $level; $i++) {
            $tabs .= $spaces;
        }
        $output = "Array" . $newline . $newline;
        foreach($array as $key => $value) {
            if (is_array($value)) {
                $level++;
                $value = return_array($value, $html, $level);
                $level--;
            }
            $output .= $tabs . "[" . $key . "] => " . $value . $newline;
        }
        return $output;
    }

?>
reinder at fake-address dot com 31-Jan-2006 09:09
I always use this function in my code, because most of my functions return an Array or Boolean :

<?php

function printr ( $object , $name = '' ) {

    print ( '\'' . $name . '\' : ' ) ;

    if ( is_array ( $object ) ) {
        print ( '<pre>' )  ;
        print_r ( $object ) ;
        print ( '</pre>' ) ;
    } else {
        var_dump ( $object ) ;
    }

}

?>

( print_r gives no output on FALSE and that can be annoying! )
thbley at gmail dot com 16-Nov-2005 12:10
Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)

<?php
header('Content-Type: text/xml; CHARSET=gb2312');
echo print_r_xml($some_var);

function print_r_xml($arr,$first=true) {
  $output = "";
  if ($first) $output .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<data>\n";
  foreach($arr as $key => $val) {
    if (is_numeric($key)) $key = "arr_".$key; // <0 is not allowed
    switch (gettype($val)) {
      case "array":
        $output .= "<".htmlspecialchars($key)." type='array' size='".count($val)."'>".
          print_r_xml($val,false)."</".htmlspecialchars($key).">\n"; break;
      case "boolean":
        $output .= "<".htmlspecialchars($key)." type='bool'>".($val?"true":"false").
          "</".htmlspecialchars($key).">\n"; break;
      case "integer":
        $output .= "<".htmlspecialchars($key)." type='integer'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      case "double":
        $output .= "<".htmlspecialchars($key)." type='double'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      case "string":
        $output .= "<".htmlspecialchars($key)." type='string' size='".strlen($val)."'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      default:
        $output .= "<".htmlspecialchars($key)." type='unknown'>".gettype($val).
          "</".htmlspecialchars($key).">\n"; break;
    }
  }
  if ($first) $output .= "</data>\n";
  return $output;
}

?>
warhog at warhog dot net 11-Aug-2005 05:01
For very long arrays I have written a little function which formats an array quite nice and uses javascript for browsing it like a tree. The function is very customizable with the $style parameter.
For me it's of great use for browsing large array's, for example when those are used in language-files in some script and so on. It may even be used in "real" scripts for the "real" front-end, cause the tree can very easily be styled (look at the function or the outputted source and you'll see what i mean).

Here's the function:

<?php

function print_r_html($arr, $style = "display: none; margin-left: 10px;")
{ static $i = 0; $i++;
  echo "\n<div id=\"array_tree_$i\" class=\"array_tree\">\n";
  foreach($arr as $key => $val)
  { switch (gettype($val))
    { case "array":
        echo "<a onclick=\"document.getElementById('";
        echo array_tree_element_$i."').style.display = ";
        echo "document.getElementById('array_tree_element_$i";
        echo "').style.display == 'block' ?";
        echo "'none' : 'block';\"\n";
        echo "name=\"array_tree_link_$i\" href=\"#array_tree_link_$i\">".htmlspecialchars($key)."</a><br />\n";
        echo "<div class=\"array_tree_element_\" id=\"array_tree_element_$i\" style=\"$style\">";
        echo print_r_html($val);
        echo "</div>";
      break;
      case "integer":
        echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
      break;
      case "double":
        echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
      break;
      case "boolean":
        echo "<b>".htmlspecialchars($key)."</b> => ";
        if ($val)
        { echo "true"; }
        else
        { echo "false"; }
        echo  "<br />\n";
      break;
      case "string":
        echo "<b>".htmlspecialchars($key)."</b> => <code>".htmlspecialchars($val)."</code><br />";
      break;
      default:
        echo "<b>".htmlspecialchars($key)."</b> => ".gettype($val)."<br />";
      break; }
    echo "\n"; }
  echo "</div>\n"; }

?>

The function as it is now does not support the $return parameter as print_r does and will create an endless loop like print_r did in php-versions < 4.0.3 when there is an element which contains a reference to a variable inside of the array to print out :-/

I've tested it with PHP 5.0.6 and PHP 4.2.3 - no problems except those already mentioned.

please e-mail me if you've got a solution for the problems i've mentioned, i myself are not able to solve them 'cause i don't know how the hell i can find out whether a variable is a reference or not.
general at NOSPAMbugfoo dot com 20-Jan-2005 01:23
You can't use print_r($var, TRUE) inside a function which is a callback from ob_start() or you get the following error:
Fatal error: print_r(): Cannot use output buffering in output buffering display handlers


产生一个可存储的值的表示

  • ? print_r
  • settype ?
  • PHP Manual
  • Variable handling 函数
  • 产生一个可存储的值的表示

serialize

(PHP 4, PHP 5, PHP 7, PHP 8)

serialize — 产生一个可存储的值的表示

描述

serialize ( mixed $value ) : string

serialize() 返回字符串，此字符串包含了表示 value 的字节流，可以存储于任何地方。

这有利于存储或传递 PHP 的值，同时不丢失其类型和结构。

想要将已序列化的字符串变回 PHP 的值，可使用 unserialize()。serialize() 可处理除了 resource 之外的任何类型。甚至可以 serialize() 那些包含了指向其自身引用的数组。你正 serialize() 的数组／对象中的引用也将被存储。

当序列化对象时，PHP 将试图在序列动作之前调用该对象的成员函数
__sleep()。这样就允许对象在被序列化之前做任何清除操作。类似的，当使用
unserialize() 恢复对象时， 将调用
__wakeup() 成员函数。

Note:

在 PHP 3 中，对象属性将被序列化，但是方法则会丢失。PHP 4 打破了此限制，可以同时存储属性和方法。请参见类与对象中的序列化对象部分获取更多信息。

Example #1 serialize() 示例

<?php
// $session_data 是包含了当前用户 session 信息的多维数组。
// 我们使用 serialize() 在请求结束之前将其存储到数据库中。

$conn = odbc_connect ("webdb", "php", "chicken");
$stmt = odbc_prepare ($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, &$sqldata)) {
    /* 出错 */
    }
}
?>

参见：unserialize()。

User Contributed Notes

Kantin Charignon 15-Jun-2018 02:50
I did the same test as MiChAeLoKGB but in another version of PHP.
I don't post his code because I executed exactly the same script (after correcting a small variable naming error and add a line to display the PHP version).

PHP version: 7.1.9
PHP serialized in 0.0032186679840088 seconds average
JSON encoded in 0.0035939190387726 seconds average
serialize() was roughly 11.66% faster than json_encode()
Test took 6.8132710456848 seconds with 1000 iterations.

It would seem that in the current version of PHP the serialize function is faster.
lincoln dot du dot j at gmail dot com 11-Jul-2017 05:48
class A{
    public $tumi='Ami';
    public $ami='Tumi';

    public function ami(){
        $this->ami='You love me.';
    }
    public function tumi(){
        $this->tumi="I love you.";
    }
}
$obj=new A;
$serial=serialize($obj);

echo $serial;

echo PHP_EOL;

$uns=unserialize($serial);

print_r($uns);
sinus-php at sinpi dot net 03-Jul-2017 01:49
Here's a serialization function that doesn't serialize objects (it could, I just didn't care for that) but writes straight to a file. Very useful if you run out of memory when trying to serialize that 5-level nested 100000-entry array of strings.

Call it with the subject variable and a file name, it'll do the rest.

<?php
function serialize_to_file($subject,$file,$level=0) {
    if ($level==0) {
        $file=fopen($file,"w");
        if (!$file) return FALSE;
    }
    if (is_numeric($subject))
        fputs($file,"i:".$subject);
    elseif (is_string($subject))
        fputs($file,"s:".strlen($subject).":\"".addslashes($subject)."\"");
    elseif (is_bool($subject))
        fputs($file,"b:".($subject?1:0));
    elseif (is_array($subject)) {
        $keys = array_keys($subject);
        fputs($file,"a:".count($keys).":{");
        foreach ($keys as $key) {
            flat_serialize_to_file($key,$file,$level+1);
            fputs($file,";");
            flat_serialize_to_file($subject[$key],$file,$level+1);
            if (!is_array($subject[$key])) fputs($file,";");
        }
        fputs($file,"}");
    }
    if ($level==0)
        fclose($file);
}
?>
Anonymous 28-Dec-2016 05:10
If you want write something strange, like string array to binary string, and you are afraid 0-days of php's serialize function, you can use this.

Out:

string(88) "031a000a0001004c6f72..."
array(3) {
  [0]=>
  string(26) "Lorem ipsum dolor sit amet"
  [1]=>
  string(10) "8726348723"
  [2]=>
  string(1) "1"
}
string(152) "1c5e108afdec7c27a..."
array(3) {
  [0]=>
  string(26) "Lorem ipsum dolor sit amet"
  [1]=>
  string(10) "8726348723"
  [2]=>
  string(1) "1"
}

<?php

$arrToPack = array('Lorem ipsum dolor sit amet', 8726348723, true);

$packer = new ArraysPack();
$packer->privateKey = hash('sha256', 'k6LYiB8cnr5ESBMpVUBdC3c73Mt52p8w' ,true);

$dataPacked = $packer->pack($arrToPack);
$dataUnpacked = $packer->unPack($dataPacked);

$dataHMACPacked = $packer->hmacPack($arrToPack);
$dataHMACUnpacked = $packer->hmacUnPack($dataHMACPacked);

var_dump(bin2hex($dataPacked));
var_dump($dataUnpacked);

var_dump(bin2hex($dataHMACPacked));
var_dump($dataHMACUnpacked);

class ArraysPack
{
    public $hmacAlgo = 'sha256';
    public $hmacLen = 32;
    public $privateKey = '';

    public function hmacPack($array)
    {
        if(($ret = $this->pack($array)) === false)
            return false;

        $hmacHash = hash_hmac($this->hmacAlgo, $ret, $this->privateKey, true);
        return $hmacHash.$ret;
    }

    public function hmacUnPack($binaryString)
    {
        if(strlen($binaryString) < $this->hmacLen)
            return false;

        $hmacHash = substr($binaryString, 0, $this->hmacLen);
        $binaryString = substr($binaryString, $this->hmacLen);
        $binaryStringHash = hash_hmac($this->hmacAlgo, $binaryString, $this->privateKey, true);

        // Timing attack safe string comparison
        if(hash_equals($hmacHash, $binaryStringHash) === false)
            return false;

        return $this->unPack($binaryString);
    }

    public function pack($array)
    {
        if(!is_array($array))
            return false;

        $cnt = count($array);
        $header = pack('C', $cnt);
        $bin = '';

        for($i=0;$i<$cnt;$i++) {
            if(($strLen = strlen($array[$i])) > 65535 || $strLen === 0)
                return false;

            $header .= pack('S', $strLen);
            $bin .= $array[$i];
        }

        return $header.$bin;
    }

    public function unPack($bin)
    {
        if(empty($bin))
            return false;

        $arr = array();
        $cnt = unpack('C', $bin);
        $cnt = $cnt[1];

        if(!isset($bin[$cnt * 4]))
            return false;

        $header = substr($bin, 1, $cnt * 4);
        $bin = substr($bin, ($cnt * 2)+1);
        $int = unpack('S'.$cnt, $header);

        for($i=1;$i<=$cnt;$i++) {
            $val = substr($bin, 0, $int[$i]);

            if($val === false)
                return false;

            $arr[] = $val;
            $bin = substr($bin, $int[$i]);
        }

        if($bin !== false)
            return false;

        return $arr;
    }
}
?>
MiChAeLoKGB 23-May-2015 05:28
I did some testing to see the speed differences between serialize and json_encode, and my results with 250 iterations are:

PHP serialized in 0.0651714730263 seconds average
JSON encoded in 0.0254955434799 seconds average
json_encode() was roughly 155.62% faster than serialize()
Test took 27.2039430141 seconds with 300 iretations.

PHP serialized in 0.0564563179016 seconds average
JSON encoded in 0.0249140485128 seconds average
json_encode() was roughly 126.60% faster than serialize()
Test took 24.4148340225 seconds with 300 iretations.

From all my tests it looks like json_encode is on average about 120% faster (sometimes it gets to about 85% and sometimes to 150%).

Here is the PHP code you can run on your server to try it out:

<?php

// fillArray function myde by Peter Bailey
function fillArray($depth, $max){
    static $seed;
    if (is_null($seed)){
        $seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
    }
    if ($depth < $max){
        $node = array();
        foreach ($seed as $key){
            $node[$key] = fillArray( $depth + 1, $max );
        }
        return $node;
    }
    return 'empty';
}

function testSpeed($testArray, $iterations = 100){

    $json_time = array();
    $serialize_time = array();
    $test_start = microtime(true);

    for ($x = 1; $x <= $iterations; $x++){
        $start = microtime(true);
        json_encode($testArray);
        $json_time[] = microtime(true) - $start;

        $start = microtime(true);
        serialize($testArray);
        $serialize_time[] = microtime(true) - $start;
    }

    $test_lenght = microtime(true) - $test_start;
    $json_average = array_sum($json_time) / count($json_time);
    $serialize_average = array_sum($serialize_time) / count($serialize_time);

    $result = "PHP serialized in ".$serialize_average." seconds average<br>";
    $result .= "JSON encoded in ".$json_average." seconds average<br>";

    if ($json_average < $serialize_average){
        $result .= "json_encode() was roughly ".number_format( ($serialize_average / $json_average - 1 ) * 100, 2 )."% faster than serialize()<br>";
    } else if ( $serializeTime < $jsonTime ){
        $result .= "serialize() was roughly ".number_format( ($json_average / $serialize_average - 1 ) * 100, 2 )."% faster than json_encode()<br>";
    } else {
        $result .= "No way!<br>";
    }

    $result .= "Test took ".$test_lenght." seconds with ".$iterations." iterations.";

    return $result;

}

// Change the number of iterations (250) to lower if you exceed your maximum execution time
echo testSpeed(fillArray(0, 5), 250);

?>
Anonymous 14-Apr-2015 01:57
For everyone facing the conversion nightmare another Anonymous described here in an older comment (and he took the words out of my mouth), this T-SQL script might be of great help: https://github.com/mjohnsonperl/tsqlphpunserialize/tree/master.

Please do not follow the path of evil by dumping serialized data into relational databases.
tuxedobob 04-Jun-2014 04:36
When using serialize() to convert, say, an array to a string to pass via HTML forms, you will likely run into issues with quoting. This is because serialize() puts values in double quotes. The simplest solution is to quote your HTML form value with single quotes rather than double quotes. (This *is* allowed, according to W3C specs.)

So, instead of:

<?php
$arr = serialize($some_array);
?>
<input type="hidden" name="array" value="$arr" />

you would want to use:

<?php
$arr = serialize($some_array);
?>
<input type="hidden" name="array" value='$arr' />
Nanhe Kumar 27-Dec-2013 05:57
Note : You cannot save the state of a static variable by serializing.
<?php
/*
 * student.class.php
 */
class Student {

    public $name;
    private $roll;
    protected $age;
    static $class;

    public function __construct() {
        $this->name = "Nanhe Kumar";
        $this->roll = 1;
        $this->age = 16;
        Student::$class = "10+2";
    }

}
?>
<?php
/**
 * serialize.php
 */
include_once("student.class.php");

//Serialize
$so = new Student();
$serialized = serialize($so);
file_put_contents("test.txt", $serialized);
echo $serialized; //O:7:"Student":3:{s:4:"name";s:11:"Nanhe Kumar";s:13:"Studentroll";i:1;s:6:"*age";i:16;}
?>
<?php
/**
 * unserialize.php
 */
include_once("student.class.php");
$content = file_get_contents("test.txt");
$unserialized = unserialize($content);
print_r($unserialized);//Student Object ( [name] => Nanhe Kumar [roll:Student:private] => 1 [age:protected] => 16 )
?>
frost at easycast dot ru 23-Sep-2013 10:56
Closures cannot be serialized:
<?php
$func = function () {echo 'hello!';};
$func(); // prints "hello!"

$result = serialize($func);  // Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed'
?>
allan666 at gmail.com 07-Mar-2013 01:28
Oddly, if you serialize a class that was previously unserialized, the class of the variable changes to string... Example:

$R = unserialize($serialized_object);
$R->method(); // this is ok
$str = serialize($R);
echo(get_class($R));

this will output "string"!!!!! whereas if the first line was

$R = new my_class();

it would output "my_class"!

I don't know if that is a bug, but the manual is not clear about that! (somehow $R in serialize($R) is being passed by reference, since it changes class).
nh at ngin dot de 21-Jan-2013 09:59
Serializing floating point numbers leads to weird precision offset errors:

<?php

echo round(96.670000000000002, 2);
// 96.67

echo serialize(round(96.670000000000002, 2));
// d:96.670000000000002;

echo serialize(96.67);
// d:96.670000000000002;

?>

Not only is this wrong, but it adds a lot of unnecessary bulk to serialized data. Probably better to use json_encode() instead (which apparently is faster than serialize(), anyway).
Andrew B 05-Sep-2012 09:42
When you serialize an array the internal pointer will not be preserved. Apparently this is the expected behavior but was a bit of a gotcha moment for me. Copy and paste example below.

<?php
//Internal Pointer will be 2 once variables have been assigned.
$array = array();
$array[] = 1;
$array[] = 2;
$array[] = 3;

//Unset variables. Internal pointer will still be at 2.
unset($array[0]);
unset($array[1]);
unset($array[2]);

//Serialize
$serializeArray = serialize($array);

//Unserialize
$array = unserialize($serializeArray);

//Add a new element to the array
//If the internal pointer was preserved, the new array key should be 3.
//Instead the internal pointer has been reset, and the new array key is 0.
$array[] = 4;

//Expected Key - 3
//Actual Key - 0
echo "<pre>" , print_r($array, 1) , "</pre>";
?>
Anonymous 28-Feb-2012 07:44
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

I've encountered this too many times in my career, it makes for difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
pgl at yoyo dot org 03-Feb-2011 09:13
Another suggestion for coping with binary data in serialize()d variables is just to base64_encode() those fields before serializing. It will increase the size of the variable, but not by too much.
travis at travishegner dot com 02-Mar-2010 12:37
If serializing objects to be stored into a postgresql database, the 'null byte' injected for private and protected members throws a wrench into the system. Even pg_escape_bytea() on the value, and storing the value as a binary type fails under certain circumstances.

For a dirty work around:
<?php

$serialized_object = serialize($my_object);
$safe_object = str_replace("\0", "~~NULL_BYTE~~", $serialized_object);

?>

this allows you to store the object in a readable text format as well. When reading the data back:

<?php

$serialized_object = str_replace("~~NULL_BYTE~~", "\0", $safe_object);
$my_object = unserialize($serialized_object);

?>

The only gotcha's with this method is if your object member names or values may somehow contain the odd "~~NULL_BYTE~~" string. If that is the case, then str_replace() to a string that you are guaranteed not to have any where else in the string that serialize() returns.
Also remember to define the class before calling unserialize().

If you are storing session data into a postgresql database, then this workaround is an absolute must, because the $data passed to the session's write function is already serialized.

Thanks,
Travis Hegner
Anonymous 21-Jan-2010 09:23
you should really use mysql_real_escape_string() for escaping (serialized) strings that got thrown into a query (visit php.net/mysql_real_escape_string for further information)
donotmail at me dot com 02-Sep-2009 11:16
NOTE: php's serialize does not properly serialize arrays with which a slice of the array is a reference to the array itself, observe:

<?php
$a = array();
$a[0] = "blah";
$a[1] =& $a;

$a[1][0] = "pleh"; // $a[0] === "pleh"

$b = unserialize(serialize($a));

// $b[0] == "pleh", $b[1][0] == "pleh"

$b[1][0] = "blah";
?>

now $b[1][0] == "blah", but $b[0] == "pleh"
after serializing and unserializing, slice 1 is no longer a reference to the array itself... I have found no way around this problem... even manually modifying the serialized string from
'a:2:{i:0;s:4:"pleh";i:1;a:2:{i:0;s:4:"pleh";i:1;R:3;}}'
to
'a:2:{i:0;s:4:"pleh";i:1;R:1;}'

to force the second slice to be a reference to the first element of the serialization (the array itself), it seemed to work at first glance, but then unreferences it when you alter it again, observe:

<?php
    $testser = 'a:2:{i:0;s:4:"pleh";i:1;R:1;}';

    $tmp = unserialize($testser);

    print_r($tmp);

    print "\n-----------------------\n";

    $tmp[1][0] = "blah";

    print_r($tmp);

?>

outputs:
Array
(
    [0] => pleh
    [1] => Array
 *RECURSION*
)

-----------------------
Array
(
    [0] => pleh
    [1] => Array
        (
            [0] => blah
            [1] => Array
                (
                    [0] => pleh
                    [1] => Array
 *RECURSION*
                )

        )

)
Alessandro Segala 17-Jul-2009 08:18
I needed to serialize an array to store it inside a database.
I was looking for a fast, simple way to do serialization, and I came out with 2 options: serialize() or json_encode().

I ran some benchmarks to see which is the faster, and, surprisingly, I found that serialize() is always between 46% and 96% SLOWER than json_encode().
So, if you don't need to serialize objects and have the json extension available, consider using it instead of serialize().
barbuj at NOSPAM dot yahoo dot com 14-Nov-2007 02:19
In my specific situation, I wanted to be able to pass some data from page to page, but without relying on a session variable. The answer I came up with was to serialize() the object in question, pass it on to the next page as a hidden form field, then unserialize() it. When ALL class variables are public, this worked fine. However, if there was at least one private/protected variable, the code no longer worked as expected ("Fatal error: Call to a member function display() on a non-object in page2.php on line 4")

As others have already mentioned, private/protected class variables will not behave nicely (private variables are prefixed by class_name + &#65533;, while protected variables are only prefixed by &#65533; - when looking at the page source using Firefox). Internet Explorer does NOT display the extra character between the class name and variable name, but the code still doesn't work as one would expect.

Suppose you have a simple class:

testclass.php
=============
<?php
class TestClass {
  var $i = 1;

  function display() {
    echo "i=" . $this->i;
  }
?>

page1.php
=========
<?php
  require_once 'testclass.php';
  $tc = new TestClass;
  $tc->display();
?>
<form method = "post" action = "page2.php">
<input type = "hidden" name = "str" value = "<?php echo htmlspecialchars( serialize( $tc ) ); ?>">
<input type = "submit">
</form>

page2.php
=========
<?php
  require_once 'testclass.php';
  $tc = unserialize( stripslashes( htmlspecialchars_decode( $_POST["str"] ) ) );
  $tc->display();
?>

The fix, suggested by evulish on #php/irc.dal.net, is to replace htmlspecialchars()/htmlspecialchars_decode() by base64_encode()/base64_decode. The code becomes:

page1.php
=========
<input type = "hidden" name = "str" value = "<?php echo base64_encode( serialize( $tc ) ); ?>">

page2.php
=========
<?php
  $tc = unserialize( base64_decode( $_POST["str"] ) );
?>

Hope this will help someone...
Jeex 06-Nov-2007 02:59
It may be worth noting that, depending on the size of the object you are serializing, the serialize function can take up a lot of memory.

If your script isn't working as expected, your serialize call may have pushed the memory usage over the limit set by memory_limit in php.ini.

More info on memory limits here: http://www.php.net/manual/en/ini.core.php
friday13 at ig dot com dot br 19-Jun-2007 07:15
I have problem to use serialize function with hidden form field and the resolution was use htmlentities.

Ex.:

<?

$lista = array( 'pera', 'ma?a', 'laranja' );

print "< input type='hidden' name='teste' value='htmlentities( serialize( $lista ) )'" >";

?>
Ates Goral 18-Jul-2006 11:59
Corrections/clarifications to  "Anatomy of a serialize()'ed value":

All strings appear inside quotes. This applies to string values, object class names and array key names. For example:

s:3:"foo"
O:7:"MyClass":1:{...
a:2:{s:3:"bar";i:42;...

Object property names and values are delimited by semi-colons, not colons. For example:

O:7:"MyClass":2:{s:3:"foo";i:10;s:3:"bar";i:20}

Double/float values are represented as:

d:0.23241446
egingell at sisna dot com 15-May-2006 05:12
<?
/*
Anatomy of a serialize()'ed value:

 String
 s:size:value;

 Integer
 i:value;

 Boolean
 b:value; (does not store "true" or "false", does store '1' or '0')

 Null
 N;

 Array
 a:size:{key definition;value definition;(repeated per element)}

 Object
 O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}

 String values are always in double quotes
 Array keys are always integers or strings
    "null => 'value'" equates to 's:0:"";s:5:"value";',
    "true => 'value'" equates to 'i:1;s:5:"value";',
    "false => 'value'" equates to 'i:0;s:5:"value";',
    "array(whatever the contents) => 'value'" equates to an "illegal offset type" warning because you can't use an
    array as a key; however, if you use a variable containing an array as a key, it will equate to 's:5:"Array";s:5:"value";',
     and
    attempting to use an object as a key will result in the same behavior as using an array will.
*/
?>
MC_Gurk at gmx dot net 03-Jan-2006 07:44
If you are going to serialie an object which contains references to other objects you want to serialize some time later, these references will be lost when the object is unserialized.
The references can only be kept if all of your objects are serialized at once.
That means:

$a = new ClassA();
$b = new ClassB($a); //$b containes a reference to $a;

$s1=serialize($a);
$s2=serialize($b);

$a=unserialize($s1);
$b=unserialize($s2);

now b references to an object of ClassA which is not $a. $a is another object of Class A.

use this:
$buf[0]=$a;
$buf[1]=$b;
$s=serialize($buf);
$buf=unserialize($s);
$a=$buf[0];
$b=$buf[1];

all references are intact.
Alexander Podgorny 02-Dec-2005 11:47
Here is an example of a base class to implement object persistence using serialize and unserialize:

<?php
class Persistent
{
    var $filename;

    /**********************/
    function Persistent($filename)
    {
        $this->filename = $filename;
        if(!file_exists($this->filename)) $this->save();
    }
    /**********************/
    function save()
    {
        if($f = @fopen($this->filename,"w"))
        {
            if(@fwrite($f,serialize(get_object_vars($this))))
            {
                @fclose($f);
            }
            else die("Could not write to file ".$this->filename." at Persistant::save");
        }
        else die("Could not open file ".$this->filename." for writing, at Persistant::save");

    }
    /**********************/
    function open()
    {
        $vars = unserialize(file_get_contents($this->filename));
        foreach($vars as $key=>$val)
        {
            eval("$"."this->$key = $"."vars['"."$key'];");
        }
    }
    /**********************/
}

?>

When an object is extended from this one it can be easily saved and re-opened using it's own methods as follows:

<?

class foo extends Persistent
{
   var $counter;
   function inc()
   {
       $this->counter++;
   }
}

$fooObj = new $foo;
$foo->open();
print $foo->counter; // displays incrementing integer as page reloads
$foo->inc();
$foo->save();

?>
stephen dot adamson at smius dot com 01-Nov-2005 09:40
If you are serializing an object to store it in the database, using __sleep() can save you some space. The following code will not store empty (null) variables in the serialized string. For my purposes this saved a lot of space, since some of the member variables would not be given values.

function __sleep()
{
    $allVars = get_object_vars($this);
    $toReturn = array();
    foreach(array_keys($allVars) as $name)
    {
        if (isset($this->$name))
        {
            $toReturn[] = $name;
        }
    }
    return $toReturn;
}
wiart at yahoo dot com 16-Dec-2004 03:40
Warning: on 64 bits machines,  if you use a long string only composed of numbers as a key in an array and serialize/unserialize it, you can run into problems:

an example code:
$arr["20041001103319"] = 'test';
var_dump( $arr);
$arr_in_str = serialize($arr);
print "Now result is: $arr_in_str<BR />";
$final_arr = unserialize($arr_in_str);
print "The final unserialized array:<BR />";
var_dump($final_arr);

The result:
array(1) { [20041001103319]=>  string(4) "test" }
Now result is: a:1:{i:20041001103319;s:4:"test";}
The final unserialized array:
array(1) { [683700183]=> string(4) "test" }

As you can see, the original array :
$arr["20041001103319"] = "test"

after serialize/unserialize is:
$arr[683700183] = "test"

As you can see,  the key has changed ...

Apparently a problem of implicit casting + integer overflow (I posted a PHP bug report: http://bugs.php.net/bug.php?id=31117)

I tested with the latest 4.3.10 compiled on my laptop (32 bits, Mandrake 9.1) --> no such problem. But compiled on AMD 64 bits (Red Hat Taroon), the problem is present.

Hope this will help some of you to not loose almost a whole day of debugging ;-)
paul at moveNOtoSPAMiceland DOT com 18-Nov-2004 08:29
I was trying to submit a serialized array through a hidden form field using POST and was having a lot of trouble with the quotes. I couldn't figure out a way to escape the quotes in the string so that they'd show up right inside the form, so only the characters up to the first set of quotes were being sent.

My solution was to base64_encode() the string, put that in the hidden form field, and send that through the POST method. Then I decoded it (using base64_decode()) on the other end. This seemed to solve the problem.
hfuecks at phppatterns dot com 21-Apr-2004 08:20
Regarding serializing PHP data types to Javascript, following Ivans note below, theres an example at http://www.tekool.net/php/js_serializer/.

The basic serialization looks good although, in its current form, it works on the basis of generating Javascript source which a browser executes as a page loads. Using Javascripts eval() the same can be done with strings containing Javascript if youre working with something like XMLHTTPRequest
pli9 at itsa dot ucsf dot edu 31-Jan-2003 11:05
I have also written some code for importing serialized PHP data into PERL and then writing it back into PHP.  I think the similar library posted above is actually more robust for a few select cases, but mine is more compact and a little easier to follow.  I'd really like comments if anyone finds this useful or has improvements.  Please credit me if you use my code.

http://www.hcs.harvard.edu/~pli/code/serialPHP.pm
MarkRoedel at letu dot edu 21-Feb-2000 10:58
A call to serialize() appears to mess with the array's internal pointer.  If you're going to be walking through your array after serializing it, you'll want to make a call to reset() first.


设置变量的类型

  • ? serialize
  • strval ?
  • PHP Manual
  • Variable handling 函数
  • 设置变量的类型

settype

(PHP 4, PHP 5, PHP 7, PHP 8)

settype — 设置变量的类型

说明

settype ( mixed &$var , string $type ) : bool

将变量 var 的类型设置成 type。

参数

var

要转换的变量。

type

type 的可能值为：

  • "boolean" （或为"bool"，从 PHP 4.2.0 起）
  • "integer" （或为"int"，从 PHP 4.2.0 起）
  • "float" （只在 PHP 4.2.0 之后可以使用，对于旧版本中使用的"double"现已停用）
  • "string"
  • "array"
  • "object"
  • "null" （从 PHP 4.2.0 起）

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 settype() 示例

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo 现在是 5   (integer)
settype($bar, "string");  // $bar 现在是 "1" (string)
?>

注释

Note:

Maximum value for "int" is PHP_INT_MAX.

参见

  • gettype() - 获取变量的类型
  • 类型转换
  • 类型戏法

User Contributed Notes

geoffsmiths at hotmail dot com 24-Dec-2019 10:23
Please note:

When using settype to convert indexed arrays to objects, the properties of the typed object will be integers:

A brief example:

$a = ['1', '2'];

settype($a, 'object');

var_dump($a);

// output
object(stdClass)#1 (2) {
  ["0"]=>
  string(1) "1"
  ["1"]=>
  string(1) "2"
}
Anonymous 04-Jan-2019 01:41
If you attempt to convert the special $this variable from an instance method (only in classes) :
* PHP will silently return TRUE and leave $this unchanged if the type was 'bool', 'array', 'object' or 'NULL'
* PHP will generate an E_NOTICE if the type was 'int', 'float' or 'double', and $this will not be casted
* PHP will throw a catchable fatal error when the type is 'string' and the class does not define the __toString() method
Unless the new variable type passed as the second argument is invalid, settype() will return TRUE. In all cases the object will remain unchanged.
<?php
    // This was tested with PHP 7.2
    class Foo {
        function test() {
            printf("%-20s %-20s %s\n", 'Type', 'Succeed?', 'Converted');

            // settype() should throw a fatal error, as $this cannot be re-assigned
            printf("%-20s %-20s %s\n", 'bool', settype($this, 'bool'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'int', settype($this, 'int'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'float', settype($this, 'float'), print_r($this));
            printf("%-20s %-20s %s\n", 'array', settype($this, 'array'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'object', settype($this, 'object'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'unknowntype', settype($this, 'unknowntype'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'NULL', settype($this, 'NULL'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'string', settype($this, 'string'), print_r($this, TRUE));
        }
    }
    $a = new Foo();
    $a->test();
?>
Here is the result :
Type                 Succeed?             Converted
bool                 1                    Foo Object
(
)

Notice: Object of class Foo could not be converted to int in C:\php\examples\oop-settype-this.php on line 9

int                  1                    Foo Object
(
)

Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10

float                1                    Foo Object
(
)

array                1                    Foo Object
(
)

object               1                    Foo Object
(
)

Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14

unknowntype                               Foo Object
(
)

NULL                 1                    Foo Object
(
)

Catchable fatal error: Object of class Foo could not be converted to string in C:\php\examples\oop-settype-this.php on line 15

If the class Foo implements __toString() :
<?php
    class Foo {
        // ...
        function __toString() {
            return 'Foo object is awesome!';
        }
        // ...
    }
?>
So the first code snippet will not generate an E_RECOVERABLE_ERROR, but instead print the same string as for the other types, and not look at the one returned by the __toString() method.

Hope this helps !  :)
Skayo 26-Jul-2017 08:59
$foo = "1";
settype($foo, "bool");
var_dump($foo); // Outputs: bool(true)

$bar = "0";
settype($bar, "bool");
var_dump($bar); // Outputs: bool(false)
marjune 10-Nov-2016 05:31
any digit except 0 or -0 are considered true in boolean, and any string except '0' or '' are also considered true.

<?php

$foo = '0';
settype($foo, 'boolean');
var_dump($foo); // false

$foo = 0;
settype($foo, 'boolean');
var_dump($foo); // false
Special Notes 26-Feb-2012 12:00
Note that you can't use this to convert a string 'true' or 'false' to a boolean variable true or false as a string 'false' is a boolean true. The empty string would be false instead...

<?php
$var = "true";
settype($var, 'bool');
var_dump($var); // true

$var = "false";
settype($var, 'bool');
var_dump($var); // true as well!

$var = "";
settype($var, 'bool');
var_dump($var); // false
?>
Chris Sullins 18-Apr-2010 11:59
settype() has some really strange, potentially buggy behavior.

As noted by Michael Benedict, using settype() on a variable will initialize that variable.  What is stranger is that using settype() on an uninitialized variable that you are treating as an array or object will also initialize the variable.  So:

<?php
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

This works for a chain of any length: $foo->bar['baz']->etc

Next we look at what happens if $foo is already set.

<?php
$foo = false;
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

In and of itself, this wouldn't be problematic.  It might even make sense.  But in all other cases where $foo is defined, even if (boolean) $foo === false, it will throw an error unless $foo->bar is valid (i.e. $foo is an object already).

<?php
$foo = true;
settype($foo->bar,"integer"); // Notice: Trying to get property of non-object
?>
NWdev 17-Nov-2008 09:38
In trying to convert an array of strings to an array of ints,
I attempted to use settype with array_walk.

<?php
//$numArray is generated by another process
$numArray = array('13','14','33');

var_dump($numArray);

//my conversion function
function str_to_int($val){
  //remember: settype($x, 'int') returns boolean (1=success, 0=failure)
  //--> so return $x to return new value
    settype($val,'int');
    echo "<br />gettype = ".gettype($val)."<br />";
    return $val;
}

array_walk($numArray,'str_to_int');

var_dump($numArray);
?>

The var_dumps both return the following:
<?php
array(3) { [0]=> string(2) "13" [1]=> string(2) "14" [2]=> string(2) "33" }
?>

The gettype echo will show the value as an integer.

So it seems that settype($val,'int') makes the conversion,
but the function return value remains a string.
Since settype returns a boolean, using
<?php $val = settype($val, 'int'); ?>
is not a option.

I resolved my array value conversion using this instead:
<?php
$numArray =
      array_map(create_function('$value', 'return (int)$value;'),$numArray);
?>
Thanks to the posting here:
http://usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html

Perhaps this will save someone else spinning wheels a bit.

Also thanks to robin at barafranca dot com for
pointing out the boolean return value of settype.
robin at barafranca dot com 05-Mar-2008 04:20
Just a quick note, as this caught me out very briefly:

settype() returns bool, not the typecasted variable - so:

$blah = settype($blah, "int"); // is wrong, changes $blah to 0 or 1
settype($blah, "int"); // is correct

Hope this helps someone else who makes a mistake.. ;)
ludvig dot ericson gmail.dot com 09-Apr-2006 08:36
To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/

As a part of a framework or something.

Plus, you can probably call this with call_user_func
matt at mattsoft dot net 06-Dec-2005 09:49
using (int) insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.
Michael Benedict 29-Oct-2005 10:55
note that settype() will initialize an undefined variable.  Therefore, if you want to preserve type and value, you should wrap the settype() call in a call to isset().

<?php
settype($foo, "integer");
echo("|$foo|");
?>

prints "|0|", NOT "||".

To get the latter, use:
<?php
if(isset($foo)) settype($foo, "integer");
echo("|$foo|");
?>
nospamplease at veganismus dot ch 22-Jul-2005 07:38
you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.
reinier_deblois at hotmail dot com 13-Mar-2005 09:18
Instead of settype you could use:
<?php

$int=593;  // $int is a integer

$int.="";   // $int is now a string
memandeemail at gmail dot com 09-Dec-2004 05:17
/**
    * @return bool
    * @param array[byreference] $values
    * @desc Convert an array or any value to Escalar Object [not tested in large scale]
    */
    function setobject(&$values) {
        $values = (object) $values;
        foreach ($values as $tkey => $val) {
            if (is_array($val)) {
                setobject($val);
                $values->$tkey = $val;
            }
        }
        return (bool) $values;
    }
sdibb at myway dot com 06-Sep-2003 10:03
Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins.  The function intval($string) does the same thing.

If you're looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes),  try this instead:

<?
     $number=ereg_replace("[^0-9]","",$number);
?>
ns at canada dot com 05-May-2000 04:38
This settype() behaviour seems consistent to me. Quoting two sections from the manual:

"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "
<pre>
2 $var = 'ciao';
3 $arr = (array) $var;
4 echo $arr[0];  // outputs 'ciao'
</pre>

And if (like your code above) you do a settype on an empty variable, you'll end up with a one element array with an empty (not unset!) first element. So appeanding to it will start appending at index 1. As for why reset() doesn't do anything:

"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."

It doesn't matter where the array counter is; values are added at the end, not at the counter.


获取变量的字符串值

  • ? settype
  • unserialize ?
  • PHP Manual
  • Variable handling 函数
  • 获取变量的字符串值

strval

(PHP 4, PHP 5, PHP 7, PHP 8)

strval — 获取变量的字符串值

描述

strval ( mixed $var ) : string

返回 var 的 string 值。 参见 string 文档获取更多关于字符串转换的信息。

var 可以是任何标量类型。不能将 strval() 用于数组或对象。

参见 floatval()、intval()、settype() 和类型戏法。

User Contributed Notes

Mark Clements 02-Jun-2016 01:17
Some notes about how this function has changed over time, with regards the following statement:

> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.

== Arrays ==

In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string "Array" without any sort of error occurring.

From 5.4 and above, the return value is unchanged but you will now get a notice-level error: "Array to string conversion".

== Objects ==

For objects that do not implement __toString(), the behaviour has varied:

PHP 4: "Object"
PHP 5 < 5.2: "Object id #1" (number obviously varies)
PHP >= 5.2: Catchable fatal error:  Object of class X could not be converted to string
Hayley Watson 21-Aug-2007 08:53
As of PHP 5.2, strval() will return the string value of an object, calling its __toString() method to determine what that value is.
NyctoFixer at gmail dot com 11-Jun-2007 12:19
As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

<?

/**
 * Returns the string value of a variable
 *
 * This differs from strval in that it invokes __toString if an object is given
 * and the object has that method
 */
function stringVal ($value)
{
    // We use get_class_methods instead of method_exists to ensure that __toString is a public method
    if (is_object($value) && in_array("__toString", get_class_methods($value)))
        return strval($value->__toString());
    else
        return strval($value);
}

?>
kendsnyder+phpnet at gmail dot com 01-Jun-2007 10:08
The only way to convert a large float to a string is to use printf('%0.0f',$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf('%0.0f',pow(2,50)); // 112589906846624
echo sprintf('%0.0f',pow(2,50)); // 112589906846624
portos_ze_retour at hotmail dot fr 10-Mar-2006 08:15
In complement to Tom Nicholson's contribution, here is the french version (actually it's possible to change the language, but you should check the syntax ;) )

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
     $w = '#';
   else if(fmod($x, 1) != 0)
     $w = '#';
   else {
     if($x < 0) {
         $w = $nwords['minus'].' ';
         $x = -$x;
     } else
         $w = '';
     // ... now $x is a non-negative integer.

     if($x < 21)  // 0 to 20
         $w .= $nwords[$x];
     else if($x < 100) {  // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
           $w .= '-'. $nwords[$r];
     } else if($x < 1000) {  // 100 to 999
         $w .= $nwords[floor($x/100)] .' '.$nwords['hundred'];
         $r = fmod($x, 100);
         if($r > 0)
           $w .= ' '.$nwords['separator'].' '. int_to_words($r);
     } else if($x < 1000000) {  // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' '.$nwords['thousand'];
         $r = fmod($x, 1000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $w .= $nwords['separator'].' ';
           $w .= int_to_words($r);

         }
     } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' '.$nwords['million'];
         $r = fmod($x, 1000000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $word .= $nwords['separator'].' ';
           $w .= int_to_words($r);
         }
     }
   }
   return $w;
}

 // Usage in English
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" , "hundred" => "hundred", "thousand"=> "thousand", "million"=>"million",
                   "separator"=>"and", "minus"=>"minus");

echo 'There are currently '. int_to_words(-120223456) . ' members logged on.<br>';

 //Utilisation en Francais
$nwords = array( "zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept",
                   "huit", "neuf", "dix", "onze", "douze", "treize",
                   "quatorze", "quinze", "seize", "dix-sept", "dix-huit",
                   "dix-neuf", "vingt", 30 => "trente", 40 => "quarante",
                   50 => "cinquante", 60 => "soixante", 70 => "soixante-dix", 80 => "quatre-vingt",
                   90 => "quatre-vingt-dix" , "hundred" => "cent", "thousand"=> "mille", "million"=>"million",
                   "separator"=>"", "minus"=>"moins");

echo 'Il y a actuellement '. int_to_words(-120223456) . ' membres connectés.<br>';
php at ianco dot co dot uk 07-Oct-2005 04:36
I can't help being surprised that

(string)"0" == (string)"0.00"

evaluates to true. It's the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.
Steve Ball 08-Sep-2005 07:18
It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

2326201276 - (-1968766020) =  4294967296.
Tom Nicholson 28-Apr-2004 09:13
If you want to convert an integer into an English word string, eg. 29 -> twenty-nine, then here's a function to do it.

Note on use of fmod()
  I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven't bothered with "billion" because the word means 10e9 or 10e12 depending who you ask.

The function returns '#' if the argument does not represent a whole number.

<?php
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" );

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
      $w = '#';
   else if(fmod($x, 1) != 0)
      $w = '#';
   else {
      if($x < 0) {
         $w = 'minus ';
         $x = -$x;
      } else
         $w = '';
      // ... now $x is a non-negative integer.

      if($x < 21)   // 0 to 20
         $w .= $nwords[$x];
      else if($x < 100) {   // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
            $w .= '-'. $nwords[$r];
      } else if($x < 1000) {   // 100 to 999
         $w .= $nwords[floor($x/100)] .' hundred';
         $r = fmod($x, 100);
         if($r > 0)
            $w .= ' and '. int_to_words($r);
      } else if($x < 1000000) {   // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' thousand';
         $r = fmod($x, 1000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $w .= 'and ';
            $w .= int_to_words($r);
         }
      } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' million';
         $r = fmod($x, 1000000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $word .= 'and ';
            $w .= int_to_words($r);
         }
      }
   }
   return $w;
}

?>

Usage:
<?php
echo 'There are currently '. int_to_words($count) . ' members logged on.';
?>


从已存储的表示中创建 PHP 的值

  • ? strval
  • unset ?
  • PHP Manual
  • Variable handling 函数
  • 从已存储的表示中创建 PHP 的值

unserialize

(PHP 4, PHP 5, PHP 7, PHP 8)

unserialize — 从已存储的表示中创建 PHP 的值

说明

unserialize ( string $str ) : mixed

unserialize() 对单一的已序列化的变量进行操作，将其转换回 PHP 的值。

参数

str

序列化后的字符串。

若被反序列化的变量是一个对象，在成功地重新构造对象之后，PHP 会自动地试图去调用 __wakeup() 成员函数（如果存在的话）。

Note: unserialize_callback_func 指令

如果在反序列化的时候需要实例化一个未定义类，则可以设置回调函数以供调用（以免得到的是不完整的 object "__PHP_Incomplete_Class"）。可通过 php.ini、ini_set() 或 .htaccess 定义'unserialize_callback_func'。每次实例化一个未定义类时它都会被调用。若要禁止这个特性，只需置空此设定。

返回值

返回的是转换之后的值，可为 integer、float、string、array 或 object。

如果传递的字符串不可反序列化，则返回 false，并产生一个 E_NOTICE。

更新日志

版本 | 说明
4.2.0 | 添加了 unserialize_callback_func 指令。

范例

Example #1 unserialize() 例子

<?php
// 这里，我们使用 unserialize() 装载来自数据库的 $session_data 数组中的会话数据。
// 此例是描述 serialize() 的那个例子的补充。

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array($_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) {
    // 如果执行出错或返回错误，则初始化为空数组
    $session_data = array();
} else {
    // 现在我们需要的是 $tmp[0] 中已序列化的数据。
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
        // 出错，初始化为空数组
        $session_data = array();
    }
}
?>

Example #2 unserialize_callback_func 例子

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

// unserialize_callback_func 从 PHP 4.2.0 起可用
ini_set('unserialize_callback_func', 'mycallback'); // 设置您的回调函数

function mycallback($classname)
{
   // 只需包含含有类定义的文件
   // $classname 指出需要的是哪一个类
}
?>

注释

Warning

如果反序列化了 false 的值，或者在过程中发生了错误，都会返回 false。 可以通过 str 和 serialize(false) 进行比较，或者捕捉 E_NOTICE 错误来判断这种特殊情况。

参见

  • serialize() - 产生一个可存储的值的表示
  • 自动加载对象
  • unserialize_callback_func
  • __wakeup()

User Contributed Notes

karsten at dambekalns dot de 27-Nov-2020 07:53
Keep in mind that the allowed_classes does not use inheritance, i.e. allowing an interface is not possible and sub-classes won't pass the check. See https://3v4l.org/tdHfl
hadley8899 at gmail dot com 13-Jan-2020 01:58
For the people who are getting the error

PHP Notice:  unserialize(): Error at offset 191 of 285 bytes in ...

and are getting the data from a database, Make sure that you have the database set the the correct encoding, I had the database set as latin1_swedish_ci and all of the data looked perfect, Infact when i copied it into a online unserialize it worked fine. I changed the collation to utf8mb4_unicode_ci and all worked fine.
Anonymous 11-Mar-2019 06:36
If serialize() is the answer, you're almost certainly asking the wrong question.

JSON is widely available. The only thing it does not do, is the very thing that makes serialization immensely dangerous. All it takes is a crafty hacker to pass a crafted payload to a supposedly 'secured' serialize call, for a database driver to be overwritten with malicious code, for example.

Recreate the object. Normally. With actual data, and a source file, not with serialize. To do otherwise is laziness bordering on malice.
me+phpnet at unreal4u dot com 30-Oct-2017 03:30
Just some reminder which may save somebody some time regarding the `$options` array:

Say you want to be on the safe side and not allow any objects to be unserialized... My first thought was doing the following:

<?php
$lol = unserialize($string, false);
// This will generate:
// Warning: unserialize() expects parameter 2 to be array, boolean given
?>

The correct way of doing this is the following:
<?php
$lol = unserialize($string, ['allowed_classes' => false]);
?>

Hope it helps somebody!
bjd 02-Jan-2017 12:49
Talk on Exploiting PHP7 Unserialize here: https://media.ccc.de/v/33c3-7858-exploiting_php7_unserialize
m.m.j.kronenburg 06-Sep-2016 09:52
You can use the following code to use the php 7 unserialize function in php 5.3 and upwards. This adds the $option argument.

<?php

namespace
{

/**
 * PHP 7 unserialize function for PHP 5.3 upwards.
 * Added the $option argument (allowed_classes).
 * See php unserialize manual for more detail.
 **/
function php7_unserialize($str, $options = array())
{
  if(version_compare(PHP_VERSION, '7.0.0', '>='))
  { return unserialize($str, $options); }

  $allowed_classes = isset($options['allowed_classes']) ?
    $options['allowed_classes'] : true;
  if(is_array($allowed_classes) || !$allowed_classes)
  {
    $str = preg_replace_callback(
      '/(?=^|:)(O|C):\d+:"([^"]*)":(\d+):{/',
      function($matches) use ($allowed_classes)
      {
        if(is_array($allowed_classes) &&
          in_array($matches[2], $allowed_classes))
        { return $matches[0]; }
        else
        {
          return $matches[1].':22:"__PHP_Incomplete_Class":'.
            ($matches[3] + 1).
            ':{s:27:"__PHP_Incomplete_Class_Name";'.
            serialize($matches[2]);
        }
      },
      $str
    );
  }
  unset($allowed_classes);
  return unserialize($str);
}

} // namespace

namespace my_name_space
{
  /**
   * Use the new php7 unserialize in your namespace without
   * renaming all unserialize(...) function calls to
   * php7_unserialize(...).
   **/
  function unserialize($str, $options = array())
  { return php7_unserialize($str, $options); }
}

?>
chris at pollett dot org 02-Jul-2015 03:28
When you serialize an object of a class from a particular namespace, the namespace is recorded as part of the serialization. If you decide to change this namespace's name, it can be hard to read in old serialized objects. I.e., suppose you had serialized an object of type foo\A, you change the namespace of your project to goo but otherwise leave the class definition of A unchanged. You would like to be able to unserialize the object as goo\A, instead unserialization will only create a partial object. To fix this in the case where you don't have nested objects in your class definition, you can use the following simple rename function:
/**
 * Used to change the namespace of a serialized php object (assumes doesn't
 * have nested subobjects)
 *
 * @param string $class_name new fully qualified name with namespace
 * @param string $object_string serialized object
 *
 * @return string serialized object with new name
 */
function renameSerializedObject($class_name, $object_string)
{
    /*  number of digits in the length of name of the object needs to be
        less than 12 digits (probably more like 4) for this to work.
    */
    $name_length = intval(substr($object_string, 2, 14));
    $name_space_info_length = strlen("O:".$name_length.":") +
        $name_length + 2; // 2 for quotes;
    $object_string = 'O:' .
        strlen($class_name) . ':"'. $class_name.'"' .
        substr($object_string, $name_space_info_length);
    return $object_string;
}
ErnestV 03-Aug-2013 01:05
Just a note - if the serialized string contains a reference to a class that cannot be instantiated (e.g. being abstract) PHP will immediately die with a fatal error. If the unserialize() statement is preceded with a '@' to avoid cluttering the logs with warns or notices there will be absolutely no clue as to why the script stopped working. Cost me a couple of hours...
Ray.Paseur often uses Gmail 26-Jul-2013 01:41
In the Classes and Objects docs, there is this: In order to be able to unserialize() an object, the class of that object needs to be defined.

Prior to PHP 5.3, this was not an issue.  But after PHP 5.3 an object made by SimpleXML_Load_String() cannot be serialized.  An attempt to do so will result in a run-time failure, throwing an exception.  If you store such an object in $_SESSION, you will get a post-execution error that says this:

Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in [no active file]:0 Stack trace: #0 {main} thrown in [no active file] on line 0

The entire contents of the session will be lost.  Hope this saves someone some time!

<?php // RAY_temp_ser.php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION);
$_SESSION['hello'] = 'World';
var_dump($_SESSION);

// AN XML STRING FOR TEST DATA
$xml = '<?xml version="1.0"?>
<families>
  <parent>
    <child index="1" value="Category 1">Child One</child>
  </parent>
</families>';

// MAKE AN OBJECT (GIVES SimpleXMLElement)
$obj = SimpleXML_Load_String($xml);

// STORE THE OBJECT IN THE SESSION
$_SESSION['obj'] = $obj;
suman dot jis at gmail dot com 13-Mar-2012 09:12
I was getting unserialize()  Error at offset error.

If you face similar problem  then use the following procedure

$auctionDetails = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $dataArr[$i]['auction_details'] );
$auctionDetails = unserialize($auctionDetails);
walf 22-Aug-2011 08:22
a replacement for unserialize that returns whether it worked and populates the unserialized variable by reference:
<?php
function funserialize($serialized, &$into) {
    static $sfalse;
    if ($sfalse === null)
        $sfalse = serialize(false);
    $into = @unserialize($serialized);
    return $into !== false || rtrim($serialized) === $sfalse;//whitespace at end of serialized var is ignored by PHP
}

$s_foo = 'b:0;';
var_dump(funserialize($s_foo, $foo), $foo);

$s_bar = 'bar';
var_dump(funserialize($s_bar, $bar), $bar);

$s_foo = 'a:0:{};';
var_dump(funserialize($s_foo, $foo), $foo);

?>
gives:

bool(true)
bool(false)

bool(false)
bool(false)

bool(true)
array(0) {
}
MBa 02-Aug-2011 03:49
To check if a string is serialized:

$blSerialized=(@unserialize($sText)||$sText=='b:0;');
chris at colourlovers dot com 16-Jun-2011 05:31
Anyone having trouble serializing data with SimpleXMLElement objects stored within it, check this out:

This will traverse $data looking for any children which are instances of SimpleXMLElement, and will run ->asXML() on them, turning them into a string and making them serializable. Other data will be left alone.

<?php
function exportNestedSimpleXML($data) {
    if (is_scalar($data) === false) {
        foreach ($data as $k => $v) {
            if ($v instanceof SimpleXMLElement) {
                $v = str_replace("&#13;","\r",$v->asXML());
            } else {
                $v = exportNestedSimpleXML($v);
            }

            if (is_array($data)) {
                $data[$k] = $v;
            } else if (is_object($data)) {
                $data->$k = $v;
            }
        }
    }

    return $data;
}

$data = array (
    "baz" => array (
        "foo" => new stdClass(),
        "int" => 123,
        "str" => "asdf",
        "bar" => new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>'),
    )
);

var_dump($data);
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    object(SimpleXMLElement)#4 (1) {
      [0]=>
      string(3) "bar"
    }
  }
}*/

var_dump(exportNestedSimpleXML($data));
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    string(54) "<?xml version="1.0" encoding="UTF-8"?>
<foo>bar</foo>
"
  }
}
*/
?>
daniel at fourstaples dot com 23-Mar-2010 08:46
Here's a simple function to get the class of a serialized string (that is, the type of object that will be returned if it's unserialized):

<?php
function get_serial_class($serial) {
    $types = array('s' => 'string', 'a' => 'array', 'b' => 'bool', 'i' => 'int', 'd' => 'float', 'N;' => 'NULL');

    $parts = explode(':', $serial, 4);
    return isset($types[$parts[0]]) ? $types[$parts[0]] : trim($parts[2], '"');
}
?>

I use this when saving a serialized object to a cookie, to make sure it is the right type when I go to unserialize it.

The type names are the same format/case as you would see if you did a var_dump().
Fagzal 09-Mar-2010 10:10
To all who have problem with quoting and slashes when storing serialized data in MySQL: you are probably doing it wrong.

Use e.g. PDO with placeholders and the blob column type, and it will Just Work.
arbie samong 10-Sep-2009 07:42
__PHP_Incomplete_Class Object Demystified

1. First take note of the output. A simple example:

__PHP_Incomplete_Class Object (
[__PHP_Incomplete_Class_Name] => SomeObject1
[obj1property1] => somevalue1 [obj1property2] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => SomeObject2 [obj2property1] => somevalue1 [obj2property2] => Array (
['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

2. We analyze this and break it down.
__PHP_Incomplete_Class Object tells you there is an object that needs to be declared somehow.
__PHP_Incomplete_Class_Name simply tells you the expected class name. It is just one of the properties for now.

So we have:
a) an unknown object that has a class name SomeObject1 (first class)
b) it has 2 properties, namely obj1property1 and obj2property2
c) obj2property2 is itself an object whose class name is SomeObject2 (the second class)
d) SomeObject2 has two properties, obj2property1 and obj2property2
e) obj2property2 is an array that contains two elements

3. Now that we have an idea of the structure, we shall create class definitions based from it. We will just create properties for now, methods are not required as a minimum.

<?php
class SomeObject1 {
        public $obj1property1;
        public $obj1property2;
}
class SomeObject2 {
        public $obj2property1;
        public $obj2property2;
}
?>

4. Have that accessible to your script and it will solve the __PHP_Incomplete_Class Object problem as far as the output is concerned. Now you will have:

SomeObject1 ( [obj1property1] => somevalue1 [obj1property2] => SomeObject2 ( [obj2property1] => somevalue1 [obj2property2] => Array ( ['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

As you will notice, __PHP_Incomplete_Class Object is gone and replaced by the class name. The property __PHP_Incomplete_Class_Name is also removed.

5. As for the array property obj2property2, we can directly access that and just assume that it is an array and loop through it:

<?php

// this will be SomeObject1
$data = unserialize($serialized_data);

// this will be SomeObject2
$data2 = $data->obj1property2();

foreach($data2->obj2property2 as $key => $value):
         print $key.' : '. $value .'<br>';
endforeach;

?>

Outputs:
key1 : somevalue3
key2 : somevalue4

That's it. You can add more methods on the class declarations for the given properties, provided you keep your original output as basis for the data types.
w dot laurencine at teknoa dot net 07-Apr-2009 05:54
When dealing with a string which contain "\r", it seems that the length is not evaluated correctly. The following solves the problem for me :

<?php
// remove the \r caracters from the $unserialized string
$unserialized = str_replace("\r","",$unserialized);

// and then unserialize()
unserialize($unserialized);
?>
chris AT cmbuckley DOT co DOT uk 14-Aug-2008 06:47
As mentioned in the notes, unserialize returns false in the event of an error and for boolean false. Here is the first solution mentioned, without using error handling:

<?php
function isSerialized($str) {
    return ($str == serialize(false) || @unserialize($str) !== false);
}

var_dump(isSerialized('s:6:"foobar";')); // bool(true)
var_dump(isSerialized('foobar'));        // bool(false)
var_dump(isSerialized('b:0;'));          // bool(true)
?>
BenBE at omorphia dot de 02-Mar-2007 06:20
When trying to serialize or unserialize recursive arrays or otherwise linked data you might find the undocumented R data type quite useful.

If you want a array like the one produced with
<?
$a = array();
$a[0] =& $a;
?>
serialized you can store it using a string simular to this one:
<?
$a = unserialize("a:1:{i:0;R:1;}");
?>

Both sources will make $a hold an array that self-references itself in index 0.

The argument for R is the index of the created sub-variable of the serialize-string beginning with 1.
double at dumpit dot com 19-Dec-2006 05:09
This little function will check whether the serialized string is well formed.

PHP < 6 because i'd heard changes will be made in this php-intern function,
maybe it could be edited easy for it.

<?php

function wd_check_serialization( $string, &$errmsg )
{

    $str = 's';
    $array = 'a';
    $integer = 'i';
    $any = '[^}]*?';
    $count = '\d+';
    $content = '"(?:\\\";|.)*?";';
    $open_tag = '\{';
    $close_tag = '\}';
    $parameter = "($str|$array|$integer|$any):($count)" . "(?:[:]($open_tag|$content)|[;])";
    $preg = "/$parameter|($close_tag)/";
    if( !preg_match_all( $preg, $string, $matches ) )
    {
        $errmsg = 'not a serialized string';
        return false;
    }
    $open_arrays = 0;
    foreach( $matches[1] AS $key => $value )
    {
        if( !empty( $value ) && ( $value != $array xor $value != $str xor $value != $integer ) )
        {
            $errmsg = 'undefined datatype';
            return false;
        }
        if( $value == $array )
        {
            $open_arrays++;
            if( $matches[3][$key] != '{' )
            {
                $errmsg = 'open tag expected';
                return false;
            }
        }
        if( $value == '' )
        {
            if( $matches[4][$key] != '}' )
            {
                $errmsg = 'close tag expected';
                return false;
            }
            $open_arrays--;
        }
        if( $value == $str )
        {
            $aVar = ltrim( $matches[3][$key], '"' );
            $aVar = rtrim( $aVar, '";' );
            if( strlen( $aVar ) != $matches[2][$key] )
            {
                $errmsg = 'stringlen for string not match';
                return false;
            }
        }
        if( $value == $integer )
        {
            if( !empty( $matches[3][$key] ) )
            {
                $errmsg = 'unexpected data';
                return false;
            }
            if( !is_integer( (int)$matches[2][$key] ) )
            {
                $errmsg = 'integer expected';
                return false;
            }
        }
    }
    if( $open_arrays != 0 )
    {
        $errmsg = 'wrong setted arrays';
        return false;
    }
    return true;
}

?>
Are Pedersen 09-Aug-2006 01:46
Be aware that if useing serialize/unserialize in a serverfarm with both 32bit and 64bit servers you can get unexpected results.

Ex: if you serialize an integer with value of 2147483648 on a 64bit system and then unserialize it on a 32bit system you will get the value -2147483648 instead. This is because an integer on 32bit cannot be above 2147483647 so it wraps.
Chris Hayes (chris at hypersites dot com) 23-Oct-2004 09:27
In reply to the earlier post about having to include object definitions *before* using unserialize.  There is a workaround for this.

When an object is serialized, the first bit of the string is actually the name of the class.  When an unknown object is unserialized, this is maintained as a property.  So if you serialize it again, you get back the exact same string as if you'd serialized the original object.  Basically, to cut to the point...

If you use

$_SESSION['my_object'] = unserialize(serialize($_SESSION['my_object']))

then you get back an object of the correct type, even if the session had originally loaded it as an object of type stdClass.
aderyn at nowhere dot tld 30-Oct-2003 10:02
A quick note:
If you store a serialized object in a session, you have to include the class _before_ you initialize (session_start()) the session.


释放给定的变量

  • ? unserialize
  • var_dump ?
  • PHP Manual
  • Variable handling 函数
  • 释放给定的变量

unset

(PHP 4, PHP 5, PHP 7, PHP 8)

unset — 释放给定的变量

说明

unset ( mixed $var , mixed $... = ? ) : void

unset() 销毁指定的变量。

unset() 在函数中的行为会依赖于想要销毁的变量的类型而有所不同。

如果在函数中 unset() 一个全局变量，则只是局部变量被销毁，而在调用环境中的变量将保持调用 unset() 之前一样的值。

<?php
function destroy_foo() {
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

以上例程会输出：

bar

如果您想在函数中 unset() 一个全局变量，可使用 $GLOBALS 数组来实现：

<?php
function foo()
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>

如果在函数中 unset() 一个通过引用传递的变量，则只是局部变量被销毁，而在调用环境中的变量将保持调用 unset() 之前一样的值。

<?php
function foo(&$bar) {
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

以上例程会输出：

something
something

如果在函数中 unset() 一个静态变量，那么在函数内部此静态变量将被销毁。但是，当再次调用此函数时，此静态变量将被复原为上次被销毁之前的值。

<?php
function foo()
{
    static $bar;
    $bar++;
    echo "Before unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "after unset: $bar\n";
}

foo();
foo();
foo();
?>

以上例程会输出：

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23

参数

var

要销毁的变量。

...

其他变量......

返回值

没有返回值。

范例

Example #1 unset() 示例

<?php
// 销毁单个变量
unset ($foo);

// 销毁单个数组元素
unset ($bar['quux']);

// 销毁一个以上的变量
unset($foo1, $foo2, $foo3);
?>

Example #2 使用 (unset) 类型强制转换

(unset) 类型强制转换常常和函数 unset() 引起困惑。 为了完整性，(unset) 是作为一个 NULL 类型的强制转换。它不会改变变量的类型。

<?php
$name = 'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

以上例程会输出：

NULL
string(6) "Felipe"

注释

Note: 因为是一个语言构造器而不是一个函数，不能被 可变函数 调用。

Note:

It is possible to unset even object properties visible in current context.

Note:

在 PHP 5 之前无法在对象里销毁 $this。

Note:

在 unset() 一个无法访问的对象属性时，如果定义了 __unset() 则对调用这个重载方法。

参见

  • isset() - 检测变量是否已设置并且非 null
  • empty() - 检查一个变量是否为空
  • __unset()
  • array_splice() - 去掉数组中的某一部分并用其它值取代

User Contributed Notes

ronan at shopping-feed dot com 04-Feb-2020 08:19
<?php

$list = ['a', 'b', 'c'];
next($list);
unset($list[1]);

echo current($list); // result : "c"
Phantasma_9 at yahoo dot com 08-Aug-2016 06:17
This is probably trivial but there is no error for unsetting a non-existing variable.
magnesium dot oxide dot play+php at gmail dot com 20-Mar-2014 08:10
You can unset superglobals like $GLOBALS, $_GET etc., but causing an unususal behavior (as of PHP 5.3.3).

1) unsetting of superglobals is done globally, i.e. unsetting inside the function affects GLOBALLY.

2) Recreation of unset'ed superglobals can be done (recreated valiables are superglobals), but original functionality (in $GLOBALS, $_SESSION ...) has lost.

<?php

function foo(){
  unset($GLOBALS);
}

function bar(){
  var_dump($GLOBALS);
}

foo();
bar(); //issues E_NOTICE ($GLOBALS not defined)
$GLOBALS=3;
bar(); //displays int(3)

?>
Hayley Watson 05-Mar-2013 09:41
You don't need to check that a variable is set before you unset it.
<?php
unset($a);
?>
is harmless.
<?php
if(isset($a)) {
    unset($a);
}
?>
is pointless complication.

This doesn't apply to properties of objects that have __isset() methods that visibly change object state or __unset() methods that don't properly check their arguments or have extra side effects.

The latter case means that __unset shouldn't do more than what it says on the tin, and also has the responsibility for checking (possibly using __isset()) that what it's being asked to do makes sense.

The former case is just plain bad design.
tigercat at aol dot com 10-Oct-2012 07:55
The combination of "global" and "unset" in functions can lead to some unexpected results.  This is because the "global" function creates a reference to a variable at the time it's executed, so a variable can be deleted out from under a "global $my_variable" declaration in a function.  Accessing data that's been deleted with an obsolete reference is usually a bad thing; in some languages it can generate a machine address fault.

<?php
$my_global_var = "old data";
f1();

function f1() // example of invalid variable reference use
{
  global $my_global_var;   // creates reference to global variable
  f2(); // recreates global variable, so reference is now invalid

// bad...
  echo $my_global_var;     // outputs "old data" (from invalid memory???)

// good...
  global $my_global_var;  // reestablish reference to new global variable
  echo $my_global_var;     // outputs "new data" as expected
}

function f2() // recreate global variable
{
  unset($GLOBALS['my_global_var']); // this syntax works with all variable types including arrays
  global $my_global_var; // must do this after unset to access new global variable
  $my_global_var = "new data";
}
?>
pfreilly at umd dot umich dot edu 29-Sep-2011 04:56
Despite much searching, I have not yet found an explanation as to how one can manually free resources from variables, not so much objects, in PHP.  I have also seen many comments regarding the merits and demerits of unset() versus setting a variable to null.  Thus, here are the results of some benchmarks performed comparing unset() of numerous variables to setting them to null (with regards to memory usage and processing time):

10 variables:
Unset:
Memory Usage: 296
Time Elapsed: 1.0013580322266E-5

Null set:
Memory Usage: 1736
Time Elapsed: 5.9604644775391E-6

50 variables:
Unset:
Memory Usage: 296
Time Elapsed: 3.6001205444336E-5

Null set:
Memory Usage: 8328
Time Elapsed: 3.2901763916016E-5

100 variables:
Unset:
Memory Usage: 296
Time Elapsed: 5.6982040405273E-5

Null set:
Memory Usage: 15928
Time Elapsed: 5.8174133300781E-5

1000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.00041294097900391

Null set:
Memory Usage: 168096
Time Elapsed: 0.00067591667175293

10000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.0042569637298584

Null set:
Memory Usage: 1650848
Time Elapsed: 0.0076930522918701

100000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.042603969573975

Null set:
Memory Usage: 16249080
Time Elapsed: 0.087724924087524

300000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.13177299499512

Null set:
Memory Usage: 49796320
Time Elapsed: 0.28617882728577

Perhaps my test code for the null set was flawed, but despite that possibility it is simple to see that unset() has minimal processing time impact, and no apparent memory usage impact (unless the values returned by memory_get_usage() are flawed).  If you truly care about the ~4 microseconds saved over <50 variables, more power to you.  Otherwise, use unset() to minimize script impact on your system.
Note: Tested on PHP 5.3.8 installed via RPM on Fedora 14
edouard dot berge at gmail dot com 24-Sep-2010 09:09
Warning!

When unset from an array, if you unset all elements, the array is always set

$tab=array('A'=>1,'B'=>2);
unset($tab['A']);
unset($tab['B']);
echo isset($tab)." ".count($tab);

output: 1 0
Andreas 24-Sep-2010 05:51
You can not unset a numeric key of an array, if key is a string. See this example:

// Create a simple array with 3 different key types
$test[1] = array(
    10 => array('apples'),
    "20" => array('bananas'),
    '30' => array('peaches')
);
$test[2] = (array) json_decode(json_encode($test[1]));
$test[3] = (array) (object) $test[1];
// array form a stdClass object
$testClass = new stdClass();
$testClass->{10} =  array('apples');
$testClass->{"20"} =  array('bananas');
$test[4] = (array) $testClass[6];

echo "<pre>";
foreach($test as $testNum => $arr) {

    echo "\nTest: " . $testNum  . " \n";
    var_dump($arr);

    foreach($arr as $key => $fruit) {
        echo "key: " . $key . "\n";
        echo "key exists: ";
        var_dump(array_key_exists(strval($key), $arr));
        echo "typeof key is: " . gettype($key) . "\n";

        unset($arr[$key]);
    }
    var_dump($arr);
    echo "\n" . str_repeat("-", 80);
}
echo "</pre>";

And here is the output:

Test: 1
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 2
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
key: 30
key exists: bool(false)
typeof key is: string
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}

--------------------------------------------------------------
Test: 3
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 4
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}

--------------------------------------------------------------

Fix the problem with a rebuild of the array:
$oldArray = $array();
$array = array();
foreach($oldArray as $key => $item) {
    $array[intval($key)] = $item;
}
j dot vd dot merwe at enovision dot net 26-Aug-2010 05:08
A sample how to unset array elements from an array result coming from a mysql request. In this sample it is checking if a file exists and removes the row from the array if it not exists.

<?php
$db->set_query("select * from documents where document_in_user = 0"); //1
$documents = $db->result_to_array($db->get_result()); //1

foreach ($documents as $key => $row) { //2

    $file     = "uploads/".rawurldecode($row['document_name']);

    if ( file_exists ( $file ) == FALSE ) {
         unset($documents[$key]);  //3
    }
}

$documents = array_values($documents); // reindex the array (4)
?>

variables:
mysql table = documents,
array = $documents
array key (index) = $key
array row (record sort of speak) = $row

explanation:

1.
it gets the array from the table (mysql)

2.
foreach goes through the array $documents

3.
unset if record does not exist

4.
the array_values($documents) reindexes the $documents array, for otherwise you might end up in trouble when your  process will start expecting an array starting with key ($key) 0 (zero).
Anonymous 02-Jul-2010 07:20
further I realized that an object, when getting detroyed, does care about destroying variable in object space visibility but not those in local visibility, be aware of the found pattern:

<?php
class release_test{
  private $buffer;
  private $other_object;
  public function __construct(){
    $this->other_object=new other_object_class();
  }
  public function __destruct(){
    //note that you always have to unset class objects, in order to get the resources released
    unset($this->other_object);
  }
  public allocate_mem_A(){
    $this->buffer=file("/tmp/bigfile");
  }
  public allocate_mem_B(){
    $buffer=file("/tmp/bigfile");
  }
  public allocate_mem_C(){
    $buffer=file("/tmp/bigfile");
    unset($buffer);
  }
  public allocate_mem_D(){
    $this->other_buffer=file("/tmp/bigfile");
  }
}

//this does not lead to a resource problem
$A=new release_test();
$A->allocate_mem_A();
$A->__destruct();
unset($A);

//this DOES lead to a resource problem
$B=new release_test();
$B->allocate_mem_B();
$B->__destruct();
unset($B);

//this does not lead to a resource problem
$C=new release_test();
$C->allocate_mem_C();
$C->__destruct();
unset($C);

//this does not lead to a resource problem
$D=new release_test();
$D->allocate_mem_D();
$D->__destruct();
unset($D);
?>
phpmanual at kennel17 dot co dot uk 26-Feb-2010 08:55
Note that PHP 4 will generate a warning if you try to unset an array index that doesn't exist and whose parent doesn't exist.

Example:

<?php

  $foo = array();

  unset($foo['Bar']['Baz']);

?>

RESULT: "Notice:  Undefined index:  Bar"

On PHP5 no error is raised, which seems to me like the correct behaviour.

Note that using unset($foo['Bar']) in the above example does not generate a warning in either version.

(Tested on 4.4.9 and 5.2.4)
macnimble at gmail dot com 26-Mar-2009 02:39
Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,
);

echo "<pre>Original Array:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
                                    "beets",
                                    "carrots");
echo "<pre>Array after key removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';
?>
lion_cat at mail ru 12-Nov-2008 02:22
about unset for arrays

if you unset the last array member
$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

after addition a new member by $ar[]=7,

you will get
$ar[0]==2
$ar[1]==7
$ar[3]==7,

So, unset has no effect to internal array counter!!!
nox at oreigon dot de 05-Aug-2008 12:24
if you try to unset an object, please be careful about references.

Objects will only free their resources and trigger their __destruct method when *all* references are unsetted.
Even when they are *in* the object... sigh!

<?php

class A {
  function __destruct() {
    echo "cYa later!!\n";
  }
}

$a = new A();
$a -> a = $a;
#unset($a); # Just uncomment, and you'll see

echo "No Message ... hm, what now?\n";
unset($a -> a);
unset($a);

echo "Finally that thing is gone\n";

?>

Of course the object completely dies at the end of the script.
stacionari at gmail dot com 17-Mar-2008 01:41
Sometimes you need to assigne values to an array index in some loop (if, while, foreach etc.) but you wish to set starting index key to some number greater then zero (lets say 5). One idea how to do this is:

<?php
    $values = array(5, 10, 15, 100);  //array of values that we wish to add to our new array

    $myArray = array(4=>0);   //sets starting key to be 4 and assigns some value (lets say 0)
    unset($myArray[4]);   //delete this index key, but preserves further enumeration

    foreach($values as $value){
        $myArray[] = $value;   //asign values to our array
    }

    print_r($myArray);

/* Output:

Array ( [5] => 5 [6] => 10 [7] => 15 [8] => 100 )

*/

?>
pauljamescampbell at gmail dot com 15-Mar-2008 05:22
Here's my variation on the slightly dull unset method. It throws in a bit of 80's Stallone action spice into the mix. Enjoy!

<?php
/**
 * function rambo (first blood)
 *
 * Completely and utterly destroys everything, returning the kill count of victims
 *
 * @param    It don't matter, it's Rambo baby
 * @return    Integer    Body count (but any less than 500 and it's not really worth mentioning)
 */
function rambo() {

    // Get the victims and initiate that body count status
    $victims = func_get_args();
    $body_count = 0;

    // Kill those damn punks
    foreach($victims as $victim) {
        if($death_and_suffering = @unset($victim)) {
            $body_count++;
        }
    }

    // How many kills did Rambo tally up on this mission?
    return($body_count);
}
?>
Kai Kunstmann 10-Mar-2008 05:09
Since unset() is a language construct, it cannot be passed anything other than a variable. It's sole purpose is to "unset" this variable, ie. to remove it from the current scope and destroy it's associated data. This is true especially for reference variables, where not the actual value is destroyed but the reference to that value. This is why you can't wrap 'unset()' in a user defined function: You would either unset a copy of the data if the parameter is passed by value, or you would just unset the reference variable within the functions scope if the parameter is passed by reference. There is no workaround for that, as you cannot pass 'scope' to a function in PHP. Such a function can only work for variables that exist in a common or global scope (compare 'unset($_GLOBALS[variable])').

I don't know how PHP handles garbage collection internally, but I guess this behavior can result in a huge memory leak: if a value variable goes out of scope with a second variable still holding a reference to the in-memory value, then unsetting that reference would still hold the value in memory but potentially unset the last reference to that in-memory data, hence: occupied memory that is rendered useless as you cannot reference it anymore.
Hayley Watson 23-Aug-2007 09:02
In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don't exist....

Unsetting variables that don't exist, as in
<?php
unset($undefinedVariable);
?>
does not trigger an "Undefined variable" notice. But
<?php
unset($undefinedArray[$undefinedKey]);
?>
triggers two notices, because this code is for unsetting an element of an array; neither $undefinedArray nor $undefinedKey are themselves being unset, they're merely being used to locate what should be unset. After all, if they did exist, you'd still expect them to both be around afterwards. You would NOT want your entire array to disappear just because you unset() one of its elements!
chad 0x40 herballure 0x2e com 31-May-2007 07:11
It is observed on PHP 5.1.6 that <?php unset($this); ?> inside of a method will remove the reference to $this in that method. $this isn't considered "special" as far as unset() is concerned.
09-Feb-2007 08:10
Just to confirm, USING UNSET CAN DESTROY AN ENTIRE ARRAY. I couldn't find reference to this anywhere so I decided to write this.

The difference between using unset and using $myarray=array(); to unset is that obviously the array will just be overwritten and will still exist.

<?php

$myarray=array("Hello","World");

echo $myarray[0].$myarray[1];

unset($myarray);
//$myarray=array();

echo $myarray[0].$myarray[1];

echo $myarray;
?>

Output with unset is:
<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Output with $myarray=array(); is:
?>

<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Array
?>
hessodreamy at gmail dot com 17-Jan-2007 03:51
To clarify what hugo dot dworak at gmail dot com said about unsetting things that aren't already set:

unsetting a non-existent key within an array does NOT throw an error.
<?
$array = array();

unset($array[2]);
//this does not throw an error

unset($array[$undefinedVar]);
//Throws an error because of the undefined variable, not because of a non-existent key.
?>
dibakar dot datta at gmail dot com 31-Mar-2006 11:31
Instead of using the unset function  for unregistering your session or other array values you can also do this samll feature and get this task done with just 1 line code.

Suppose, if you like to unregister your session store values.
You can use:

      $_SESSION = array();

Well this syntax saves lot's of time instead of unsetting each values.
clark at everettsconsulting dot com 11-Sep-2005 12:50
In PHP 5.0.4, at least, one CAN unset array elements inside functions from arrays passed by reference to the function.
As implied by the manual, however, one can't unset the entire array by passing it by reference.

<?php
function remove_variable (&$variable)  // pass variable by reference
{
    unset($variable);
}

function remove_element (&$array, $key) // pass array by reference
{
    unset($array[$key]);
}

$scalar = 'Hello, there';
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

remove_variable($scalar); // try to unset the variable
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

$array = array('one' => 1, 'two' => 2, 'three' => 3);
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_variable($array); // try to unset the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_element($array, 'two'); // successfully remove an element from the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [three] => 3 )

?>
no at spam dot com 30-Aug-2005 03:22
In addition to what timo dot hummel at 4fb dot de said;

>For the curious: unset also frees memory of the variable used.
>
>It might be possible that the in-memory size of the PHP Interpreter isn't reduced, but your scripts won't touch the memory_limit boundary. Memory is reused if you declare new variables.

It might be worth adding that functions apparently don't free up memory on exit the same way unset does..
Maybe this is common knowledge, but although functions destroys variables on exit, it (apparently) doesn't help the memory.

So if you use huge variables inside functions, be sure to unset them if you can before returning from the function.

In my case, if I did not unset before return, then the script would use 20 MB more of memory than if I did unset.
This was tested with php 5.0.4 on apache 2 on windows xp, with no memory limit.

Before I did the test, I was under the impression that when you exit from functions, the memory used inside it would be cleared and reused. Maybe this should be made clear in the manual, for either unset() or in the chapter for functions.
muhamad_zakaria at yahoo dot com 04-Jul-2005 07:08
We have experienced when we applied 'unset' to the overloaded properties (PHP5), consider the code below:
<?php
    class TheObj {
        public $RealVar1, $RealVar2, $RealVar3, $RealVar4;
        public $Var = array();

        function __set($var, $val) {
            $this->Var[$var] = $val;
        }
        function __get($var) {
            if(isset($this->Var[$var])) return $this->Var[$var];
            else return -1;
        }
    }

    $SomeObj = new TheObj;

    // here we set for real variables
    $SomeObj->RealVar1 = 'somevalue';
    $SomeObj->{'RealVar2'} = 'othervalue';
    $SomeObj->{'RealVar'.(3)} = 'othervaluetoo';
    $SomeObj->{'RealVar'.'4'} = 'anothervalue';

    // and here we set for virtual variables
    $SomeObj->Virtual1 = 'somevalue';
    $SomeObj->{'Virtual2'} = 'othervalue';
    $SomeObj->{'Virtual'.(3)} = 'othervaluetoo';
    $SomeObj->{'Virtual'.'4'} = 'anothervalue';

    // now we will try to unset these variables
    unset($SomeObj->RealVar1);
    unset($SomeObj->{'RealVar'.(3)});

    //the lines below will catch by '__get' magic method since these variables are unavailable anymore
    print $SomeObj->RealVar1."\n";
    print $SomeObj->{'RealVar'.(3)}."\n";

    // now we will try to unset these variables
    unset($SomeObj->Virtual1);
    unset($SomeObj->{'Virtual'.(3)});

    //but, these variables are still available??? eventhough they're "unset"-ed
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>

Please note that PHP doesn't have magic callback to unset overloaded properties. This is the reason why unset($SomeObj->Virtual1) doesn't work.

But it does work when we set 'null' value such as the following code:
<?php
    // now we will set 'null' value instead of using unset statement
    $SomeObj->Virtual1 = null;
    $SomeObj->{'Virtual'.(3)} = null;

    // and now these variables are no longer available
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>
Sound ugly, yeah?

This applied to the "virtual" array variable too, see more at http://bugs.php.net/bug.php?id=33513 (at feedback) about it.
PS: we used PHP version 5.1.0-dev from the CVS snapshot when we wrote the above codes.
franckraynal at free dot fr 26-Feb-2005 05:02
Here is another way to make 'unset' work with session variables from within a function :

<?php
function unsetSessionVariable ($sessionVariableName) {
   unset($GLOBALS[_SESSION][$sessionVariableName]);
}
?>

May it work with others than me...
F.
dan AT --nospam-- cubeland DOT co DOT uk 04-Nov-2004 11:38
dh at argosign dot de -
it is possible to unset globals from within functions thanks to the $GLOBALS array:

<?php
$x = 10;

function test() {
    // don't need to do ' global $x; '
    unset ($GLOBALS['x']);
    echo 'x: ' . $GLOBALS['x'] . '<br />';
}

test();
echo "x: $x<br />";

// will result in
/*
x:
x:
*/
?>
thorry at thorry dot net 05-Aug-2004 02:15
The documentation is not entirely clear when it comes to static variables. It says:

If a static variable is unset() inside of a function, unset() destroys the variable and all its references.

<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
}

foo();
foo();
foo();
?>

The above example would output:

1
2
3

And it does! But the variable is NOT deleted, that's why the value keeps on increasing, otherwise the output would be:

1
1
1

The references are destroyed within the function, this handeling is the same as with global variables, the difference is a static variable is a local variable.

Be carefull using unset and static values as the output may not be what you expect it to be. It appears to be impossible to destroy a static variable. You can only destroy the references within the current executing function, a successive static statement will restore the references.

The documentation would be better if it would say:
"If a static variable is unset() inside of a function, unset() destroys all references to the variable. "

Example: (tested PHP 4.3.7)
<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
   echo "$a\n";
   static $a;
   echo "$a\n";
}

foo();
foo();
foo();
?>

Would output:

1

1
2

2
3

3
anon at no spam dot no address dot com 16-Jul-2004 09:19
Adding on to what bond at noellebond dot com said, if you want to remove an index from the end of the array, if you use unset, the next index value will still be what it would have been.

Eg you have
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    unset($x[(count($x)-1)]); //remove last set key in the array

    $x[] = $i;
 }
?>

You would expect:
Array([0] => 1, [1] => 4)
as you want it to remove the last set key....

but you actually get
Array ( [0] => 1 [4] => 2 [5] => 3 [6] => 4 )

This is since even though the last key is removed, the auto indexing still keeps its previous value.

The only time where this would not seem right is when you remove a value off the end. I guess different people would want it different ways.

The way around this is to use array_pop() instead of unset() as array_pop() refreshes the autoindexing thing for the array.
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    array_pop($x); // removes the last item in the array

    $x[] = $i;
 }
?>

 This returns the expected value of x = Array([0] => 1, [1] => 4);

Hope this helps someone who may need this for some odd reason, I did.
andre at twg dot com dot au 06-Mar-2004 09:16
Only This works with register_globals being 'ON'.

unset( $_SESSION['variable'] );

The above will not work with register_globals turned on (will only work outside of a function).

$variable = $_SESSION['variable'];
unset( $_SESSION['variable'], $variable );

The above will work with register_globals on & inside a function
warhog at warhog dot net 27-Jan-2004 08:52
you may wan't to unset all variables which are defined, here's one way:

<?php

function unset_all_vars($a)
{ foreach($a as $key => $val)
  { unset($GLOBALS[$key]); }
  return serialize($a); }

unset_all_vars(get_defined_vars());

?>

you can also save than a serialized var of the "memory" and perhaps store this in a temporary file.. very usefull if you work with text files and/or file uploads when you've got very large variables.

greetz


打印变量的相关信息

  • ? unset
  • var_export ?
  • PHP Manual
  • Variable handling 函数
  • 打印变量的相关信息

var_dump

(PHP 4, PHP 5, PHP 7, PHP 8)

var_dump — 打印变量的相关信息

说明

var_dump ( mixed $expression , mixed $... = ? ) : void

此函数显示关于一个或多个表达式的结构信息，包括表达式的类型与值。数组将递归展开值，通过缩进显示其结构。

In PHP 5 all public, private and protected properties of objects will be returned in the output.

Tip

和直接将结果输出到浏览器一样，可使用输出控制函数来捕获当前函数的输出，然后(例如)保存到一个 string 中。

参数

expression

你要打印的变量。

返回值

没有返回值。

范例

Example #1 var_dump() 例子

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

以上例程会输出：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

以上例程会输出：

float(3.1)
bool(true)

参见

  • var_export() - 输出或返回一个变量的字符串表示
  • print_r() - 以易于理解的格式打印变量。

User Contributed Notes

fabien dot villepinte at gmail dot com 27-May-2019 02:59
It's important to note that the output depends on the precision directive.
<?php
var_dump(10000000000000.5); // float(10000000000000)
ini_set('precision',-1);
var_dump(10000000000000.5); // float(10000000000000.5)
?>
Anonymous 18-Jul-2016 06:27
Be careful this outputs to stdout stream (1) instead of the proper stderr stream (2).
b dot bergloev at gmail dot com 31-Oct-2014 11:45
I post a new var_dump function with colors and collapse features. It can also adapt to terminal output if you execute it from there. No need to wrap it in a pre tag to get it to work in browsers.

<?php
function dump_debug($input, $collapse=false) {
    $recursive = function($data, $level=0) use (&$recursive, $collapse) {
        global $argv;

        $isTerminal = isset($argv);

        if (!$isTerminal && $level == 0 && !defined("DUMP_DEBUG_SCRIPT")) {
            define("DUMP_DEBUG_SCRIPT", true);

            echo '<script language="Javascript">function toggleDisplay(id) {';
            echo 'var state = document.getElementById("container"+id).style.display;';
            echo 'document.getElementById("container"+id).style.display = state == "inline" ? "none" : "inline";';
            echo 'document.getElementById("plus"+id).style.display = state == "inline" ? "inline" : "none";';
            echo '}</script>'."\n";
        }

        $type = !is_string($data) && is_callable($data) ? "Callable" : ucfirst(gettype($data));
        $type_data = null;
        $type_color = null;
        $type_length = null;

        switch ($type) {
            case "String":
                $type_color = "green";
                $type_length = strlen($data);
                $type_data = "\"" . htmlentities($data) . "\""; break;

            case "Double":
            case "Float":
                $type = "Float";
                $type_color = "#0099c5";
                $type_length = strlen($data);
                $type_data = htmlentities($data); break;

            case "Integer":
                $type_color = "red";
                $type_length = strlen($data);
                $type_data = htmlentities($data); break;

            case "Boolean":
                $type_color = "#92008d";
                $type_length = strlen($data);
                $type_data = $data ? "TRUE" : "FALSE"; break;

            case "NULL":
                $type_length = 0; break;

            case "Array":
                $type_length = count($data);
        }

        if (in_array($type, array("Object", "Array"))) {
            $notEmpty = false;

            foreach($data as $key => $value) {
                if (!$notEmpty) {
                    $notEmpty = true;

                    if ($isTerminal) {
                        echo $type . ($type_length !== null ? "(" . $type_length . ")" : "")."\n";

                    } else {
                        $id = substr(md5(rand().":".$key.":".$level), 0, 8);

                        echo "<a href=\"javascript:toggleDisplay('". $id ."');\" style=\"text-decoration:none\">";
                        echo "<span style='color:#666666'>" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "</span>";
                        echo "</a>";
                        echo "<span id=\"plus". $id ."\" style=\"display: " . ($collapse ? "inline" : "none") . ";\">&nbsp;&#10549;</span>";
                        echo "<div id=\"container". $id ."\" style=\"display: " . ($collapse ? "" : "inline") . ";\">";
                        echo "<br />";
                    }

                    for ($i=0; $i <= $level; $i++) {
                        echo $isTerminal ? "|    " : "<span style='color:black'>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    }

                    echo $isTerminal ? "\n" : "<br />";
                }

                for ($i=0; $i <= $level; $i++) {
                    echo $isTerminal ? "|    " : "<span style='color:black'>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }

                echo $isTerminal ? "[" . $key . "] => " : "<span style='color:black'>[" . $key . "]&nbsp;=>&nbsp;</span>";

                call_user_func($recursive, $value, $level+1);
            }

            if ($notEmpty) {
                for ($i=0; $i <= $level; $i++) {
                    echo $isTerminal ? "|    " : "<span style='color:black'>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }

                if (!$isTerminal) {
                    echo "</div>";
                }

            } else {
                echo $isTerminal ?
                        $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "  " :
                        "<span style='color:#666666'>" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "</span>&nbsp;&nbsp;";
            }

        } else {
            echo $isTerminal ?
                    $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "  " :
                    "<span style='color:#666666'>" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "</span>&nbsp;&nbsp;";

            if ($type_data != null) {
                echo $isTerminal ? $type_data : "<span style='color:" . $type_color . "'>" . $type_data . "</span>";
            }
        }

        echo $isTerminal ? "\n" : "<br />";
    };

    call_user_func($recursive, $input);
}
?>
stlawson *AT* joyfulearthtech *DOT* com 10-Aug-2011 09:31
<?php
/**
 * Better GI than print_r or var_dump -- but, unlike var_dump, you can only dump one variable.
 * Added htmlentities on the var content before echo, so you see what is really there, and not the mark-up.
 *
 * Also, now the output is encased within a div block that sets the background color, font style, and left-justifies it
 * so it is not at the mercy of ambient styles.
 *
 * Inspired from:     PHP.net Contributions
 * Stolen from:       [highstrike at gmail dot com]
 * Modified by:       stlawson *AT* JoyfulEarthTech *DOT* com
 *
 * @param mixed $var  -- variable to dump
 * @param string $var_name  -- name of variable (optional) -- displayed in printout making it easier to sort out what variable is what in a complex output
 * @param string $indent -- used by internal recursive call (no known external value)
 * @param unknown_type $reference -- used by internal recursive call (no known external value)
 */
function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#666666;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    // So this is always visible and always left justified and readable
    echo "<div style='text-align:left; background-color:white; font: 100% monospace; color:black;'>";

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#666666'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#666666'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#666666'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color\"".htmlentities($avar)."\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> ".htmlentities($avar)."<br>";

        $var = $var[$keyvar];
    }

    echo "</div>";
}
?>
kobrasrealm at gmail dot com 23-Jun-2011 01:28
I wrote this dandy little function for using var_dump() on HTML documents so I don't have to view the source.

<?php
function htmldump($variable, $height="9em") {
echo "<pre style=\"border: 1px solid #000; height: {$height}; overflow: auto; margin: 0.5em;\">";
var_dump($variable);
echo "</pre>\n";
}
?>

You can pass arguments like this:
<?php
$sql = mysql_query("SELECT id, name, value FROM table WHERE cond = 'value'");
$s = mysql_fetch_assoc($sql);

// Dump variable containing the result of the MySQL query
var_dump($s);
?>

The second parameter lets you specify the height of the box. Default is 9em, but if you're expecting a huge output you'll probably want a higher value.

<?php
var_dump($s, "17em");
?>

Happy var_dumping.
divinity76 at gmail dot com 23-Apr-2011 06:53
a html-encoded var_dump

<?php
function htmlvardump(){ob_start(); $var = func_get_args(); call_user_func_array('var_dump', $var); echo htmentities(ob_get_clean());}
?>

(creds: ekneuss / mOo @ irc.freenode.net/#php )
david at exposito dot mobi 07-Feb-2010 11:36
If you want to save exactly the content of an array into a variable to save ir later for example, use this:

<?php $xml = var_export($xml, true); ?>

You'll have in your same variable the content readable, instead of written down or anything else
egorinsk at gmail com 02-Feb-2009 04:08
Note that var_dump reset()'s array internal pointer!
rich dot schu at gmail dot com 09-Apr-2008 05:56
Keep in mind if you have xdebug installed it will limit the var_dump() output of array elements and object properties to 3 levels deep.

To change the default, edit your xdebug.ini file and add the folllowing line:
xdebug.var_display_max_depth=n

More information here:
http://www.xdebug.org/docs/display
highstrike at gmail dot com 08-Jan-2008 05:33
made 2 nifty functions based of what some people contributed here. Hope you find them usefull

usage ... call for the dump function. EG: dump($array, "Array dump");

<?php
////////////////////////////////////////////////////////
// Function:         dump
// Inspired from:     PHP.net Contributions
// Description: Helps with php debugging

function dump(&$var, $info = FALSE)
{
    $scope = false;
    $prefix = 'unique';
    $suffix = 'value';

    if($scope) $vals = $scope;
    else $vals = $GLOBALS;

    $old = $var;
    $var = $new = $prefix.rand().$suffix; $vname = FALSE;
    foreach($vals as $key => $val) if($val === $new) $vname = $key;
    $var = $old;

    echo "<pre style='margin: 0px 0px 10px 0px; display: block; background: white; color: black; font-family: Verdana; border: 1px solid #cccccc; padding: 5px; font-size: 10px; line-height: 13px;'>";
    if($info != FALSE) echo "<b style='color: red;'>$info:</b><br>";
    do_dump($var, '$'.$vname);
    echo "</pre>";
}

////////////////////////////////////////////////////////
// Function:         do_dump
// Inspired from:     PHP.net Contributions
// Description: Better GI than print_r or var_dump

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#eeeeee;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>";

        $var = $var[$keyvar];
    }
}
?>
vladimir at pixeltomorrow dot com 10-Sep-2007 12:45
You can also use the PEAR package available at http://pear.php.net/package/Var_Dump

which parses the variable content in a very pleasant manner, a lot more easier to "follow" than the built-in var_dump() function.

Of course there are many others, but I prefer this one, because it's simply to use.

Just add at the begining of your file:

<?php

require('Var_Dump.php'); // make sure the pear package path is set in php.ini
Var_Dump::displayInit(array('display_mode' => 'HTML4_Text'), array('mode' => 'normal','offset' => 4));
?>

then, instead of simply using var_dump($foo), use:

<?php

Var_Dump::display($foo);

?>

Read the documentation if you're looking for different output layouts.

Cheers!
Vladimir Ghetau
thriller dot ze at gmail dot com 21-Aug-2007 01:49
As Bryan said, it is possible to capture var_dump() output to a string. But it's not quite exact if the dumped variable contains HTML code.

You can use this instead:

<?php
echo '<pre>'; // This is for correct handling of newlines
ob_start();
var_dump($var);
$a=ob_get_contents();
ob_end_clean();
echo htmlspecialchars($a,ENT_QUOTES); // Escape every HTML special chars (especially > and < )
echo '</pre>';
?>
php at mikeboers dot com 28-Jun-2007 01:08
Howdy!

I am working on a pretty large project where I needed to dump a human readable form of whatever into the log files... and I thought var_export was too difficult to read. BigueNique at yahoo dot ca has a nice solution, although I needed to NOT modify whatever was being passed to dump.

So borrowing heavily from BigueNique's (just reworked his function) and someone's idea over in the object cloning page, I came up with the following function.

It makes a complete copy of whatever object you initially pass it, including all recursive definitions and outside objects references, then does the same thing as BigueNique's function. I also heavily reworked what it output, to suit my needs.

<?php

function var_log(&$varInput, $var_name='', $reference='', $method = '=', $sub = false) {

    static $output ;
    static $depth ;

    if ( $sub == false ) {
        $output = '' ;
        $depth = 0 ;
        $reference = $var_name ;
        $var = serialize( $varInput ) ;
        $var = unserialize( $var ) ;
    } else {
        ++$depth ;
        $var =& $varInput ;

    }

    // constants
    $nl = "\n" ;
    $block = 'a_big_recursion_protection_block';

    $c = $depth ;
    $indent = '' ;
    while( $c -- > 0 ) {
        $indent .= '|  ' ;
    }

    // if this has been parsed before
    if ( is_array($var) && isset($var[$block])) {

        $real =& $var[ $block ] ;
        $name =& $var[ 'name' ] ;
        $type = gettype( $real ) ;
        $output .= $indent.$var_name.' '.$method.'& '.($type=='array'?'Array':get_class($real)).' '.$name.$nl;

    // havent parsed this before
    } else {

        // insert recursion blocker
        $var = Array( $block => $var, 'name' => $reference );
        $theVar =& $var[ $block ] ;

        // print it out
        $type = gettype( $theVar ) ;
        switch( $type ) {

            case 'array' :
                $output .= $indent . $var_name . ' '.$method.' Array ('.$nl;
                $keys=array_keys($theVar);
                foreach($keys as $name) {
                    $value=&$theVar[$name];
                    var_log($value, $name, $reference.'["'.$name.'"]', '=', true);
                }
                $output .= $indent.')'.$nl;
                break ;

            case 'object' :
                $output .= $indent.$var_name.' = '.get_class($theVar).' {'.$nl;
                foreach($theVar as $name=>$value) {
                    var_log($value, $name, $reference.'->'.$name, '->', true);
                }
                $output .= $indent.'}'.$nl;
                break ;

            case 'string' :
                $output .= $indent . $var_name . ' '.$method.' "'.$theVar.'"'.$nl;
                break ;

            default :
                $output .= $indent . $var_name . ' '.$method.' ('.$type.') '.$theVar.$nl;
                break ;

        }

        // $var=$var[$block];

    }

    -- $depth ;

    if( $sub == false )
        return $output ;

}

// var_log( $var, '$name' ) ;

?>

Hope it works well for you!
jonbarnett at gmail dot com 02-Oct-2006 12:25
dumping objects that reference each other could lead to infinite recursion
<?php
$brother = new Sibling();
$sister = new Sibling();
$brother->sister = $sister;
$sister->brother = $brother;

var_dump($brother);
/* dumps all of $brother's properties, including "sister", which dumps all of $sister's properties, including "brother", etc. */
?>
edwardzyang at thewritingpot dot com 20-Mar-2005 02:06
If you're like me and uses var_dump whenever you're debugging, you might find these two "wrapper" functions helpful.

This one automatically adds the PRE tags around the var_dump output so you get nice formatted arrays.

<?php

function var_dump_pre($mixed = null) {
  echo '<pre>';
  var_dump($mixed);
  echo '</pre>';
  return null;
}

?>

This one returns the value of var_dump instead of outputting it.

<?php

function var_dump_ret($mixed = null) {
  ob_start();
  var_dump($mixed);
  $content = ob_get_contents();
  ob_end_clean();
  return $content;
}

?>

Fairly simple functions, but they're infinitely helpful (I use var_dump_pre() almost exclusively now).
anon 28-Jan-2005 06:31
var_dump(get_defined_vars());
will dump all defined variables to the browser.


输出或返回一个变量的字符串表示

  • ? var_dump
  • Web 服务 ?
  • PHP Manual
  • Variable handling 函数
  • 输出或返回一个变量的字符串表示

var_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

var_export — 输出或返回一个变量的字符串表示

说明

var_export ( mixed $expression , bool $return = false ) : mixed

var_export() 函数返回关于传递给该函数的变量的结构信息，它和 var_dump() 函数类似，不同的是其返回的表示是合法的 PHP 代码。

参数

expression

想要输出的变量名。

return

此参数为 true 时，var_export() 将返回一个变量，而不是输出它。

返回值

参数 return 为 true 时返回变量，否则返回 null。

注释

Note:

当使用了return 参数时，本函数使用其内部输出缓冲，因此不能在 ob_start() 回调函数的内部使用。

更新日志

版本 | 说明
7.3.0 | Now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState(). The practical effect is that now stdClass is exportable, and the resulting code will even work on earlier versions of PHP.

范例

Example #1 var_export() 示例

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

以上例程会输出：

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?>

以上例程会输出：

3.1

Example #2 输出类 stdClass (自 PHP 7.3.0 起)

<?php
$person = new stdClass;
$person->name = 'ElePHPant ElePHPantsdotter';
$person->website = 'https://php.net/elephpant.php';

var_export($person);

以上例程会输出：

(object) array(
   'name' => 'ElePHPant ElePHPantsdotter',
   'website' => 'https://php.net/elephpant.php',
)

Example #3 输出对象 (自 PHP 5.1.0 起)

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

以上例程会输出：

A::__set_state(array(
   'var' => 5,
))

Example #4 使用 __set_state() (自 PHP 5.1.0 起)

<?php
class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);
?>

以上例程会输出：

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

注释

Note:

类型为 resource 的变量无法通过此函数输出。

Note:

var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().

Warning

When var_export() exports objects, the leading backslash is not included in the class name of namespaced classes for maximum compatibility.

Note:

To be able to evaluate the PHP generated by var_export(), all processed objects must implement the magic __set_state method. The only exception is stdClass, which is exported using an array cast to an object.

参见

  • print_r() - 以易于理解的格式打印变量。
  • serialize() - 产生一个可存储的值的表示
  • var_dump() - 打印变量的相关信息

User Contributed Notes

steven at nevvix dot com 13-Sep-2019 03:52
I improved my previous varexport().

<?php
/**
 * PHP var_export() with short array syntax (square brackets) indented 2 spaces.
 *
 * NOTE: The only issue is when a string value has `=>\n[`, it will get converted to `=> [`
 * @link https://www.php.net/manual/en/function.var-export.php
 */
function varexport($expression, $return=FALSE) {
    $export = var_export($expression, TRUE);
    $patterns = [
        "/array \(/" => '[',
        "/^([ ]*)\)(,?)$/m" => '$1]$2',
        "/=>[ ]?\n[ ]+\[/" => '=> [',
        "/([ ]*)(\'[^\']+\') => ([\[\'])/" => '$1$2 => $3',
    ];
    $export = preg_replace(array_keys($patterns), array_values($patterns), $export);
    if ((bool)$return) return $export; else echo $export;
}

$array = [
    'str' => 'Test
       spaces',
       0 => 33,
       1 => TRUE,
       [3,4,'d',[]],
    'arr' => [
        'text with spaces' => '[Tes\'t"s":
 => [
 =>
  [
   {
      spaces',
    ],
    "str2" => "Test's'
 } spaces",
    'arr2' => [
        'text with spaces' => [
            'arr3' => [
                'text with spaces' => 'Te": "st \' => [
      spaces',
            ],
        ],
    ],
];
varexport($array);
// Result:
```
[
  'str' => 'Test
       spaces',
  0 => 33,
  1 => true,
  2 => [
    0 => 3,
    1 => 4,
    2 => 'd',
    3 => [
    ],
  ],
  'arr' => [
    'text with spaces' => '[Tes\'t"s":
 => [
 => [
   {
      spaces',
  ],
  'str2' => 'Test\'s\'
 } spaces',
  'arr2' => [
    'text with spaces' => [
      'arr3' => [
        'text with spaces' => 'Te": "st \' => [
      spaces',
      ],
    ],
  ],
]
```
NOTE: The only issue is when a string value has `=>\n[`, it will get converted to `=> [`
beverasrilakshmi at gmail dot com 01-May-2019 08:24
Just for fun, trying to understand the definition of "returns parsable string"....any type of variable passed to var_export, the return value will be a typecasted as string...

<?php

$var = 1;
var_dump($var); //type is int as expected
echo "<br>";
$var_after_export = var_export($var,true); //returning $var will now makes it a string
var_dump($var_after_export);

?>
steven at nevvix dot com 18-Jun-2018 06:24
/**
 * var_export() with square brackets and indented 4 spaces.
 */
<?php
function varexport($expression, $return=FALSE) {
    $export = var_export($expression, TRUE);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    if ((bool)$return) return $export; else echo $export;
}
Mark P 29-Jan-2016 09:09
It doesn't appear to be documented, but the behaviour of `var_export()` changed in PHP 7.

Previously, `var_export(3.)` returned "3", now it returns "3.0".
cpmcgrat()uci ! edu 27-Jul-2015 10:45
When trying to use __set_state() to rebuild a huge, tricky class use the following:

class Foo
{
    public $a;
    public $b;
    public $c;
    public $d;
    public $e;
    public $f;
    public $g;
    public $h;
    public $i;

    public function __set_state($array)
    {
        $obj = new ArrayConfig;
        foreach($array as $k => $v) {
            eval('$obj->'.$k.' = '.$v.';');
        }
        return $obj;
    }
}

This will return a reconstructed version of the class without having to manually type each individual object in the class manually (as shown in the __set_state() example)
dan at coders dot co dot nz 10-Jan-2014 02:11
I found that my complex type was exporting with
  stdClass::__set_state()
in places. Not only was that strange and messy, it cannot be eval()-ed back in at all. Fatal error. Doh!

However a quick string-replace tidy-up of the result rendered it valid again.

    $macro = var_export($data, TRUE);
    $macro = str_replace("stdClass::__set_state", "(object)", $macro);
    $macro = '$data = ' . $macro . ';';

And now the string I output *can* be evaluated back in again.
wyattstorch42 at outlook dot com 22-Dec-2013 10:11
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

<?php
/**
 * An implementation of var_export() that is compatible with instances
 * of stdClass.
 * @param mixed $variable The variable you want to export
 * @param bool $return If used and set to true, improved_var_export()
 *     will return the variable representation instead of outputting it.
 * @return mixed|null Returns the variable representation when the
 *     return parameter is used and evaluates to TRUE. Otherwise, this
 *     function will return NULL.
 */
function improved_var_export ($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) '.improved_var_export(get_object_vars($variable), true);
    } else if (is_array($variable)) {
        $array = array ();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true).' => '.improved_var_export($value, true);
        }
        $result = 'array ('.implode(', ', $array).')';
    } else {
        $result = var_export($variable, true);
    }

    if (!$return) {
        print $result;
        return null;
    } else {
        return $result;
    }
}

// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);

improved_var_export((object) array (
    'prop1' => true,
    'prop2' => $obj,
    'assocArray' => array (
        'apple' => 'good',
        'orange' => 'great'
    )
));

/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
chudinov at yahoo dot com 29-Nov-2013 09:55
Looks like since version 5.4.22 var_export uses the serialize_precision ini setting, rather than the precision one used for normal output of floating-point numbers.
As a consequence since version 5.4.22 for example var_export(1.1) will output 1.1000000000000001 (17 is default precision value) and not 1.1 as before.

<?php
//ouput 1.1000000000000001
var_export(1.1)
 ?>
NitPicker 10-Jul-2013 04:33
When it comes to HTML output (as discussed below), it's all fun and games until someone pokes their eye out with a "<".

Surround it with "<pre>", but do remember to wrap it in htmlspecialchars() as well.
sergei dot solomonov at gmail dot com 04-Oct-2012 04:00
<?php
$closure = function(){};

var_export($closure);

// output: Closure::__set_state(array())
?>
kexianbin at diyism dot com 16-Sep-2012 02:33
to use my_var_export(), it is as beautiful as var_export() and as could deal with recursive reference as print_r():

<?php
function my_var_export($var, $is_str=false)
         {$rtn=preg_replace(array('/Array\s+\(/', '/\[(\d+)\] => (.*)\n/', '/\[([^\d].*)\] => (.*)\n/'), array('array (', '\1 => \'\2\''."\n", '\'\1\' => \'\2\''."\n"), substr(print_r($var, true), 0, -1));
          $rtn=strtr($rtn, array("=> 'array ('"=>'=> array ('));
          $rtn=strtr($rtn, array(")\n\n"=>")\n"));
          $rtn=strtr($rtn, array("'\n"=>"',\n", ")\n"=>"),\n"));
          $rtn=preg_replace(array('/\n +/e'), array('strtr(\'\0\', array(\'    \'=>\'  \'))'), $rtn);
          $rtn=strtr($rtn, array(" Object',"=>" Object'<-"));
          if ($is_str)
             {return $rtn;
             }
          else
              {echo $rtn;
              }
         }

?>
jodybrabec at gmail dot com 28-Mar-2012 05:52
WORKAROUND for error "Nesting level too deep - recursive dependency":
ob_start();
var_dump($GLOBALS);
$dataDump = ob_get_clean();
echo $dataDump;
Anonymous 11-Nov-2011 09:13
There is an even simpler way to have clean output from var_export and print_r in html pages:

<?php
function pretty_var($myArray)
{
    echo "<pre>";
    var_export($myArray);
    echo "</pre>";
}
?>
laszlo dot heredy at gmail dot com 06-Oct-2010 01:57
Try this function instead of var_export($GLOBALS) or var_dump($GLOBALS) when all you want to know is the values of the variables you set on the current page.

<?php
function globalvars(){
    $result=array();
    $skip=array('GLOBALS','_ENV','HTTP_ENV_VARS',
                        '_POST','HTTP_POST_VARS','_GET',
                        'HTTP_GET_VARS',
                        '_COOKIE',
                        'HTTP_COOKIE_VARS','_SERVER',
                        'HTTP_SERVER_VARS',
                        '_FILES','HTTP_POST_FILES',
                        '_REQUEST','HTTP_SESSION_VARS',
                        '_SESSION');
    foreach($GLOBALS as $k=>$v)
        if(!in_array($k,$skip))
            $result[$k]=$v;
    return $result;
}//functionglobalvars

var_export(globalvars());
?>
4n4jmza02 at sneakemail dot com 17-Jun-2010 04:50
I learned the hard way that if var_export encounters a resource handle it exports it as "NULL", even if it is a valid handle. The documentation states that a handle cannot be exported, but it does not describe what happens if you try to do so anyway.

I had been using var_export in some debugging code while tracing a problem with a resource handle not being generated and ended up thinking that null handles were still being generated long after the problem had been fixed.
john dot risken at gmail dot com 16-Jan-2010 03:53
I didn't see this simple little item anywhere in the user notes. Maybe I'm blind!

Anyway, var_export and print_r both use spaces and carriage returns for formatting.  Sent to an html page, most of the formatting is lost. This simple function prints a nicely formatted array to an html screen:

<?php
function pretty_var($myArray){
    print str_replace(array("\n"," "),array("<br>","&nbsp;"), var_export($myArray,true))."<br>";
}
?>
rarioj at gmail dot com 28-Oct-2009 10:43
NOTE: If an object Foo has __set_state() method, but if that object contains another object Bar with no __set_state() method implemented, the resulting PHP expression will not be eval()-able.

This is an example (object Test that contains an instance of Exception).

<?php

class Test
{
  public $one;
  public $two;
  public function __construct($one, $two)
  {
    $this->one = $one;
    $this->two = $two;
  }
  public static function __set_state(array $array)
  {
    return new self($array['one'], $array['two']);
  }
}

$test = new Test('one', new Exception('test'));

$string = var_export($test, true);

/* $string =
Test::__set_state(array(
   'one' => 'one',
   'two' =>
  Exception::__set_state(array(
     'message' => 'test',
     'string' => '',
     'code' => 0,
     'file' => 'E:\\xampp\\htdocs\\test.Q.php',
     'line' => 35,
     'trace' =>
    array (
    ),
     'previous' => NULL,
  )),
))
*/

eval('$test2 = '.$string.';'); // Fatal error: Call to undefined method Exception::__set_state

?>

So avoid using var_export() on a complex array/object that contains other objects. Instead, use serialize() and unserialize() functions.

<?php

$string = 'unserialize('.var_export(serialize($test), true).')';

eval('$test2 = '.$string.';');

var_dump($test == $test2); // bool(true)

?>
ravenswd at gmail dot com 07-Jul-2009 10:32
(This replaces my note of 3-July-2009. The original version produced no output if a variable contained an empty array, or an array consisting only of empty arrays. For example, $bigarray['x'] = array(); Also, I have added a second version of the function.)

The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray = array()
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    print $varname . " = array()<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>

For those who want a version that produces valid PHP code, use this version:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
  else:
    print $varname . " = array();<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
    endforeach;
  endif;
}
?>

If your output is to a text file and not an HTML page, remove the <br>s.
ravenswd at gmail dot com 03-Jul-2009 05:21
The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray['firstelement'] = 'something'
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>
cmusicfan (at) gmail (daught) com 11-Jun-2009 09:19
Caution! var_export will add a backslash to single quotes (').

You may want to use stripslashes() to remove the mysteriously added backslashes.
stangelanda at arrowquick dot com 29-Jun-2007 04:20
I have been looking for the best method to store data in cache files.

First, I've identified two limitations of var_export verus serialize.  It can't store internal references inside of an array and it can't store a nested object or an array containing objects before PHP 5.1.0.

However, I could deal with both of those so I created a benchmark.  I used a single array containing from 10 to 150 indexes.  I've generate the elements' values randomly using booleans, nulls, integers, floats, and some nested arrays (the nested arrays are smaller averaging 5 elements but created similarly).  The largest percentage of elements are short strings around 10-15 characters.  While there is a small number of long strings (around 500 characters).

Benchmarking returned these results for 1000 * [total time] / [iterations (4000 in this case)]

serialize 3.656, 3.575, 3.68, 3.933, mean of 3.71
include 7.099, 5.42, 5.185, 6.076, mean of 5.95
eval 5.514, 5.204, 5.011, 5.788, mean of 5.38

Meaning serialize is around 1 and a half times faster than var_export for a single large array.  include and eval were consistently very close but eval was usually a few tenths faster (eval did better this particular set of trials than usual). An opcode cache like APC might make include faster, but otherwise serialize is the best choice.
Glen 23-May-2007 05:47
Like previously reported, i find var_export() frustrating when dealing with recursive structures.  Doing a :

<?php
var_export($GLOBALS);
?>

fails.  Interestingly, var_dump() has some logic to avoid recursive references.  So :

<?php
var_dump($GLOBALS);
?>

works (while being more ugly).  Unlike var_export(), var_dump() has no option to return the string, so output buffering logic is required if you want to direct the output.
Zorro 04-Sep-2005 11:24
This function can't export EVERYTHING. Moreover, you can have an error on an simple recursive array:

$test = array();
$test["oops"] = & $test;

echo var_export($test);

=>

Fatal error:  Nesting level too deep - recursive dependency? in ??.php on line 59
linus at flowingcreativity dot net 04-Jul-2005 09:50
<roman at DIESPAM dot feather dot org dot ru>, your function has inefficiencies and problems. I probably speak for everyone when I ask you to test code before you add to the manual.

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>
paul at worldwithoutwalls dot co dot uk 24-Nov-2004 11:22
var_export() differs from print_r() for variables that are resources, with print_r() being more useful if you are using the function for debugging purposes.
e.g.
<?php
$res = mysql_connect($dbhost, $dbuser, $dbpass);
print_r($res); //output: Resource id #14
var_export($res); //output: NULL
?>
php_manual_note at bigredspark dot com 16-Oct-2003 12:43
[john holmes]
True, but that method would require you to open and read the file into a variable and then unserialize it into another variable.

Using a file created with var_export() could simply be include()'d, which will be less code and faster.

[kaja]
If you are trying to find a way to temporarily save variables into some other file, check out serialize() and unserialize() instead - this one is more useful for its readable property, very handy while debugging.

[original post]
If you're like me, you're wondering why a function that outputs "correct PHP syntax" is useful. This function can be useful in implementing a cache system. You can var_export() the array into a variable and write it into a file. Writing a string such as

<?php
$string = '<?php $array = ' . $data . '; ?>';
?>

where $data is the output of var_export() can create a file that can be easily include()d back into the script to recreate $array.

The raw output of var_export() could also be eval()d to recreate the array.

---John Holmes...


Web 服务

  • OAuth
    • 简介
    • 安装／配置
    • 预定义常量
    • 范例
    • OAuth 函数
    • OAuth — OAuth 类
    • OAuthProvider — OAuthProvider 类
    • OAuthException — OAuthException 类
  • SOAP
    • 简介
    • 安装／配置
    • 预定义常量
    • SOAP 函数
    • SoapClient — The SoapClient class
    • SoapServer — The SoapServer class
    • SoapFault — The SoapFault class
    • SoapHeader — The SoapHeader class
    • SoapParam — The SoapParam class
    • SoapVar — The SoapVar class
  • Yar — Yet Another RPC Framework
    • 简介
    • 安装／配置
    • 预定义常量
    • 范例
    • Yar_Server — The Yar_Server class
    • Yar_Client — The Yar_Client class
    • Yar_Concurrent_Client — The Yar_Concurrent_Client class
    • Yar_Server_Exception — The Yar_Server_Exception class
    • Yar_Client_Exception — The Yar_Client_Exception class
  • XML-RPC
    • 简介
    • 安装／配置
    • 预定义常量
    • XML-RPC 函数

User Contributed Notes

There are no user contributed notes for this page.


OAuth

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
    • FireEagle
  • OAuth 函数
    • oauth_get_sbs — 生成一个签名字符基串
    • oauth_urlencode — 将 URI 编码为 RFC 3986 规范
  • OAuth — OAuth 类
    • OAuth::__construct — 新建一个 OAuth 对象
    • OAuth::__destruct — 析构函数
    • OAuth::disableDebug — 关闭详细的调试
    • OAuth::disableRedirects — 关闭重定向
    • OAuth::disableSSLChecks — 关闭 SSL 检查
    • OAuth::enableDebug — 启用详细调试
    • OAuth::enableRedirects — 启用重定向
    • OAuth::enableSSLChecks — 启用 SSL 检查
    • OAuth::fetch — 获取一个 OAuth 受保护的资源
    • OAuth::generateSignature — 生成一个签名
    • OAuth::getAccessToken — 获取一个访问令牌
    • OAuth::getCAPath — 获取 CA 信息
    • OAuth::getLastResponse — 获取最后一次的响应
    • OAuth::getLastResponseHeaders — 获取最后一次响应的头信息
    • OAuth::getLastResponseInfo — 获取关于最后一次响应的 HTTP 信息
    • OAuth::getRequestHeader — 生成 OAuth 头信息字符串签名
    • OAuth::getRequestToken — 获取一个请求令牌
    • OAuth::setAuthType — 设置授权类型
    • OAuth::setCAPath — 设置 CA 路径和信息
    • OAuth::setNonce — 为后续请求设置现时标志
    • OAuth::setRequestEngine — 设置目标请求引擎
    • OAuth::setRSACertificate — 设置 RSA 证书
    • OAuth::setSSLChecks — 调整特定的SSL请求检查
    • OAuth::setTimestamp — 设置时间戳
    • OAuth::setToken — 设置令牌和 secret
    • OAuth::setVersion — 设置 OAuth 版本
  • OAuthProvider — OAuthProvider 类
    • OAuthProvider::addRequiredParameter — 添加必需的参数
    • OAuthProvider::callconsumerHandler — 调用 consumerNonceHandler 回调函数
    • OAuthProvider::callTimestampNonceHandler — 调用 timestampNonceHandler 回调函数
    • OAuthProvider::calltokenHandler — 调用 tokenNonceHandler 回调函数
    • OAuthProvider::checkOAuthRequest — 检查一个 oauth 请求
    • OAuthProvider::__construct — 新建一个 OAuthProvider 对象
    • OAuthProvider::consumerHandler — 设置 consumerHandler 句柄回调函数
    • OAuthProvider::generateToken — 生成一个随机令牌
    • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint — 设置 isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter — 移除一个必需的参数
    • OAuthProvider::reportProblem — 报告问题
    • OAuthProvider::setParam — 设置一个参数
    • OAuthProvider::setRequestTokenPath — 设置请求令牌路径
    • OAuthProvider::timestampNonceHandler — 设置 timestampNonceHandler 句柄回调函数
    • OAuthProvider::tokenHandler — 设置 tokenHandler 句柄回调函数
  • OAuthException — OAuthException 类

User Contributed Notes

There are no user contributed notes for this page.


简介

此扩展提供 OAuth 消费方和提供方之间的绑定。OAuth 是一种建立在 HTTP 之上的授权协议，用于允许应用程序安全访问数据而无需存储用户名和密码。

User Contributed Notes

ramdan 04-Oct-2019 12:20
OAuth 1 is not secure anymore! Please do not use it! Version 1.0a tries to fix the problem.

Most platforms are using OAuth 2 instead. Both versions are incompatible. If you try to use version 1, you will get frustrated.


需求

PECL/oauth 需要 PHP 5.1 或更高版本，以及 ext/hash 和 ext/pcre 。

如果在构建时选择 PECL/oauth 则可选择性地需要 libcurl 。如果使用 libcurl 配置，则必须构建 HTTPS 支持。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pear.php.net/package/oauth

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

这些常量牵涉到的大部分问题也都在官方的 OAuth » 问题报告 文档里有描述。但是要注意，这些常量名是特定于 PHP 的，尽管这些命名规则看上去相似。

OAUTH_SIG_METHOD_RSASHA1 (字符串)
OAuth RSA-SHA1 签名方法。
OAUTH_SIG_METHOD_HMACSHA1 (字符串)

OAuth HMAC-SHA1 签名方法。

OAUTH_SIG_METHOD_HMACSHA256 (字符串)
OAuth HMAC-SHA256 签名方法。
OAUTH_AUTH_TYPE_AUTHORIZATION (字符串)

此常量代表把 OAuth 参数放在 Authorization 头部。

OAUTH_AUTH_TYPE_NONE (字符串)

此常量标志着一个 NoAuth OAuth 请求。

OAUTH_AUTH_TYPE_URI (字符串)

此常量表示将 OAuth 参数放在请求中。 URI.

OAUTH_AUTH_TYPE_FORM (字符串)

此常量表示将 OAuth 参数作为 HTTP POST 主体的一部分。

OAUTH_HTTP_METHOD_GET (字符串)

为 OAuth 请求使用 GET 方法。

OAUTH_HTTP_METHOD_POST (字符串)

为 OAuth 请求使用 POST 方法。

OAUTH_HTTP_METHOD_PUT (字符串)

为 OAuth 请求使用 PUT 方法。

OAUTH_HTTP_METHOD_HEAD (字符串)

为 OAuth 请求使用 HEAD 方法。

OAUTH_HTTP_METHOD_DELETE (字符串)
为 OAuth 请求使用 DELETE 方法。
OAUTH_REQENGINE_STREAMS (整型)
使用 OAuth::setRequestEngine() 来设置引擎为 PHP 流，与用 OAUTH_REQENGINE_CURL 的 Curl 截然相反。
OAUTH_REQENGINE_CURL (整型)
使用 OAuth::setRequestEngine() 来设置引擎为 Curl，与用 OAUTH_REQENGINE_STREAMS 的 PHP 流 截然相反。
OAUTH_OK (整型)
一切良好。
OAUTH_BAD_NONCE (整型)
oauth_nonce 值已经用于上一个上一个请求，因此现在不能使用了。
OAUTH_BAD_TIMESTAMP (整型)
oauth_timestamp 值不能被服务提供者接受。这种情况下，响应应该也包含 oauth_acceptable_timestamps 参数。
OAUTH_CONSUMER_KEY_UNKNOWN (整型)
oauth_consumer_key 暂时不能被服务提供者接受。比如，服务提供者限流了使用者。
OAUTH_CONSUMER_KEY_REFUSED (整型)
使用者密钥遭拒绝。
OAUTH_INVALID_SIGNATURE (整型)
oauth_signature 无效，因为和服务提供者的签名计算不匹配。
OAUTH_TOKEN_USED (整型)
oauth_token 已经被消费。此令牌不能再被使用，因为在上一次请求中已经使用过。
OAUTH_TOKEN_EXPIRED (整型)
oauth_token 已经过期。
OAUTH_TOKEN_REVOKED (整型)
oauth_token 已经被撤销，且将决不再接受。
OAUTH_TOKEN_REJECTED (整型)
oauth_token 被服务提供者拒绝。原因未知，也许是因为令牌从未发布、已经消费、过期、或服务提供者忘记了。
OAUTH_VERIFIER_INVALID (整型)
oauth_verifier 不正确。
OAUTH_PARAMETER_ABSENT (整型)
一个必需的参数没有接收到。这种情况下，响应也应该包含 oauth_parameters_absent 参数。
OAUTH_SIGNATURE_METHOD_REJECTED (整型)
oauth_signature_method 不能被服务提供者接受。

User Contributed Notes

There are no user contributed notes for this page.


范例

Table of Contents

  • FireEagle

User Contributed Notes

There are no user contributed notes for this page.


FireEagle

<?php
$req_url = 'https://fireeagle.yahooapis.com/oauth/request_token';
$authurl = 'https://fireeagle.yahoo.net/oauth/authorize';
$acc_url = 'https://fireeagle.yahooapis.com/oauth/access_token';
$api_url = 'https://fireeagle.yahooapis.com/api/0.1';
$conskey = 'your_consumer_key';
$conssec = 'your_consumer_secret';

session_start();

//  当 state=1 则下次请求应该包含一个 oauth_token 。
//  如果没有则返回 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
  $oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
  $oauth->enableDebug();
  if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
    $request_token_info = $oauth->getRequestToken($req_url);
    $_SESSION['secret'] = $request_token_info['oauth_token_secret'];
    $_SESSION['state'] = 1;
    header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
    exit;
  } else if($_SESSION['state']==1) {
    $oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
    $access_token_info = $oauth->getAccessToken($acc_url);
    $_SESSION['state'] = 2;
    $_SESSION['token'] = $access_token_info['oauth_token'];
    $_SESSION['secret'] = $access_token_info['oauth_token_secret'];
  }
  $oauth->setToken($_SESSION['token'],$_SESSION['secret']);
  $oauth->fetch("$api_url/user.json");
  $json = json_decode($oauth->getLastResponse());
  print_r($json);
} catch(OAuthException $E) {
  print_r($E);
}
?>

User Contributed Notes

iquark10 at gmail dot com 01-Aug-2019 08:35
Fire Eagle has closed as of February 2013
pierre dot mihawk at gmail dot com 25-Jun-2014 07:09
In the case you're asking an API which gives you a reusable application key, you'll have to use the "verifier" in the getAccessToken() method, but also the "callback" parameter in the getRequestToken().

<?php
     $request_token_info = $oauth->getRequestToken($req_url, "<YOU_CALLBACK_URI>");
?>

In my case, once I accepted the form in the Authorize URI, I was redirected to this callback URI with a "oauth_verifier" GET parameter. I injected it into the access token request :

<?php
    $access_token_info = $oauth->getAccessToken($acc_url, '', $_GET['oauth_verifier']);
?>

I finally obtained an access token that I hardcoded ; it doesn't need any refresh.
brianmoreau at uk2 dot net 09-Mar-2013 12:26
I have just managed to modify this script to work with the Twitter API...

The changes are...

$req_url = 'https://api.twitter.com/oauth/request_token';
$authurl = 'https://api.twitter.com/oauth/authorize';
$acc_url = 'https://api.twitter.com/oauth/access_token';
$api_url = 'https://api.twitter.com/1.1/account';
$conskey = 'YOURAPPconskey';
$conssec = 'YOURAPPconssec';

And change
#$oauth->fetch("$api_url/user.json");
# verify_credentials
# TO
$oauth->fetch("$api_url/verify_credentials.json");


OAuth 函数

Table of Contents

  • oauth_get_sbs — 生成一个签名字符基串
  • oauth_urlencode — 将 URI 编码为 RFC 3986 规范

User Contributed Notes

There are no user contributed notes for this page.


生成一个签名字符基串

  • ? OAuth 函数
  • oauth_urlencode ?
  • PHP Manual
  • OAuth 函数
  • 生成一个签名字符基串

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — 生成一个签名字符基串

说明

oauth_get_sbs ( string $http_method , string $uri , array $request_parameters = ? ) : string

根据 pecl/oauth 生成一个签名字符基串。

参数

http_method

HTTP 方法。

uri

将要编码的 URI 。

request_parameters

请求参数的数组。

返回值

返回一个签名字符基串。

User Contributed Notes

There are no user contributed notes for this page.


将 URI 编码为 RFC 3986 规范

  • ? oauth_get_sbs
  • OAuth ?
  • PHP Manual
  • OAuth 函数
  • 将 URI 编码为 RFC 3986 规范

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — 将 URI 编码为 RFC 3986 规范

说明

oauth_urlencode ( string $uri ) : string

将 URI 编码为 » RFC 3986 规范。

参数

uri

将要编码的 URI 。

返回值

返回一个 » RFC 3986 规范的编码字符串。

User Contributed Notes

bohwaz 30-Mar-2010 07:20
Note that php5.3 rawurlencode will do exactly the same thing.

For PHP 5.2, easy replacement to this function :

<?php

function rfc3986_encode($str)
{
  $str = rawurlencode($str);
  $str = str_replace('%E7', '~', $str);
  return $str;
}

?>


OAuth 类

(PECL OAuth >= 0.99.1)

简介

此 OAuth 扩展提供一个简单接口使用 OAuth HTTP 规范与数据提供者互动，以便保护私有资源。

类摘要

OAuth {
/* 属性 */
public $debug ;
public $sslChecks ;
public $debugInfo ;
/* 方法 */
public __construct ( string $consumer_key , string $consumer_secret , string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 , int $auth_type = 0 )
public __destruct ( ) : void
public disableDebug ( ) : bool
public disableRedirects ( ) : bool
public disableSSLChecks ( ) : bool
public enableDebug ( ) : bool
public enableRedirects ( ) : bool
public enableSSLChecks ( ) : bool
public fetch ( string $protected_resource_url , array $extra_parameters = ? , string $http_method = ? , array $http_headers = ? ) : mixed
public generateSignature ( string $http_method , string $url , mixed $extra_parameters = ? ) : string
public getAccessToken ( string $access_token_url , string $auth_session_handle = ? , string $verifier_token = ? ) : array
public getCAPath ( ) : array
public getLastResponse ( ) : string
public getLastResponseHeaders ( ) : string
public getLastResponseInfo ( ) : array
public getRequestHeader ( string $http_method , string $url , mixed $extra_parameters = ? ) : string
public getRequestToken ( string $request_token_url , string $callback_url = ? ) : array
public setAuthType ( int $auth_type ) : mixed
public setCAPath ( string $ca_path = ? , string $ca_info = ? ) : mixed
public setNonce ( string $nonce ) : mixed
public setRequestEngine ( int $reqengine ) : void
public setRSACertificate ( string $cert ) : mixed
public setSSLChecks ( int $sslcheck ) : bool
public setTimestamp ( string $timestamp ) : mixed
public setToken ( string $token , string $token_secret ) : bool
public setVersion ( string $version ) : bool
}

属性

debug

sslChecks

debugInfo

Table of Contents

  • OAuth::__construct — 新建一个 OAuth 对象
  • OAuth::__destruct — 析构函数
  • OAuth::disableDebug — 关闭详细的调试
  • OAuth::disableRedirects — 关闭重定向
  • OAuth::disableSSLChecks — 关闭 SSL 检查
  • OAuth::enableDebug — 启用详细调试
  • OAuth::enableRedirects — 启用重定向
  • OAuth::enableSSLChecks — 启用 SSL 检查
  • OAuth::fetch — 获取一个 OAuth 受保护的资源
  • OAuth::generateSignature — 生成一个签名
  • OAuth::getAccessToken — 获取一个访问令牌
  • OAuth::getCAPath — 获取 CA 信息
  • OAuth::getLastResponse — 获取最后一次的响应
  • OAuth::getLastResponseHeaders — 获取最后一次响应的头信息
  • OAuth::getLastResponseInfo — 获取关于最后一次响应的 HTTP 信息
  • OAuth::getRequestHeader — 生成 OAuth 头信息字符串签名
  • OAuth::getRequestToken — 获取一个请求令牌
  • OAuth::setAuthType — 设置授权类型
  • OAuth::setCAPath — 设置 CA 路径和信息
  • OAuth::setNonce — 为后续请求设置现时标志
  • OAuth::setRequestEngine — 设置目标请求引擎
  • OAuth::setRSACertificate — 设置 RSA 证书
  • OAuth::setSSLChecks — 调整特定的SSL请求检查
  • OAuth::setTimestamp — 设置时间戳
  • OAuth::setToken — 设置令牌和 secret
  • OAuth::setVersion — 设置 OAuth 版本

User Contributed Notes

There are no user contributed notes for this page.


新建一个 OAuth 对象

  • ? OAuth
  • OAuth::__destruct ?
  • PHP Manual
  • OAuth
  • 新建一个 OAuth 对象

OAuth::__construct

(PECL OAuth >= 0.99.1)

OAuth::__construct — 新建一个 OAuth 对象

说明

public OAuth::__construct ( string $consumer_key , string $consumer_secret , string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 , int $auth_type = 0 )

新建一个 OAuth 对象

参数

consumer_key

由服务提供者提供的 consumer key 。

consumer_secret

由服务提供者提供的 consumer secret 。

signature_method

可选参数，用来定义使用哪种签名方法，默认为 OAUTH_SIG_METHOD_HMACSHA1 （HMAC-SHA1）。

auth_type

可选参数，用来定义如何传递 OAuth 参数给消费方，默认为OAUTH_AUTH_TYPE_AUTHORIZATION （在 Authorization 头部）。

User Contributed Notes

mgfrobozz at gmail dot com 23-Jan-2017 05:29
The authorization type enums as of oauth-1.2.3 are
OAUTH_AUTH_TYPE_AUTHORIZATION
OAUTH_AUTH_TYPE_URI
OAUTH_AUTH_TYPE_FORM
OAUTH_AUTH_TYPE_NONE
mgfrobozz at gmail dot com 23-Jan-2017 05:27
The signature methods available as of oauth-1.2.3 are:
OAUTH_SIG_METHOD_HMACSHA1
OAUTH_SIG_METHOD_HMACSHA256
OAUTH_SIG_METHOD_RSASHA1
OAUTH_SIG_METHOD_PLAINTEXT


析构函数

  • ? OAuth::__construct
  • OAuth::disableDebug ?
  • PHP Manual
  • OAuth
  • 析构函数

OAuth::__destruct

(PECL OAuth >= 0.99.9)

OAuth::__destruct — 析构函数

说明

public OAuth::__destruct ( ) : void

析构函数。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • OAuth::__construct() - 新建一个 OAuth 对象

User Contributed Notes

There are no user contributed notes for this page.


关闭详细的调试

  • ? OAuth::__destruct
  • OAuth::disableRedirects ?
  • PHP Manual
  • OAuth
  • 关闭详细的调试

OAuth::disableDebug

(PECL OAuth >= 0.99.3)

OAuth::disableDebug — 关闭详细的调试

说明

public OAuth::disableDebug ( ) : bool

关闭详细的请求信息（默认为关闭）。或者，将 调试 属性设置为 false 值来关闭调试。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
0.99.8 | 增加相关 调试 属性。

参见

  • OAuth::enableDebug() - 启用详细调试

User Contributed Notes

There are no user contributed notes for this page.


关闭重定向

  • ? OAuth::disableDebug
  • OAuth::disableSSLChecks ?
  • PHP Manual
  • OAuth
  • 关闭重定向

OAuth::disableRedirects

(PECL OAuth >= 0.99.9)

OAuth::disableRedirects — 关闭重定向

说明

public OAuth::disableRedirects ( ) : bool

禁用自动跟随其后的重定向，这样，手动重定向请求。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true

参见

  • OAuth::enableRedirects() - 启用重定向

User Contributed Notes

There are no user contributed notes for this page.


关闭 SSL 检查

  • ? OAuth::disableRedirects
  • OAuth::enableDebug ?
  • PHP Manual
  • OAuth
  • 关闭 SSL 检查

OAuth::disableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::disableSSLChecks — 关闭 SSL 检查

说明

public OAuth::disableSSLChecks ( ) : bool

关闭通常的 SSL 对等证书和主机检查，但不用于生产环境。或者，设置 sslChecks 成员为 false 来关闭 SSL 检查。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
0.99.8 | 增加了 sslChecks 成员

参见

  • OAuth::enableSSLChecks() - 启用 SSL 检查

User Contributed Notes

There are no user contributed notes for this page.


启用详细调试

  • ? OAuth::disableSSLChecks
  • OAuth::enableRedirects ?
  • PHP Manual
  • OAuth
  • 启用详细调试

OAuth::enableDebug

(PECL OAuth >= 0.99.3)

OAuth::enableDebug — 启用详细调试

说明

public OAuth::enableDebug ( ) : bool

打开用于调试的详细请求信息，调试信息存储在 debugInfo 成员中。或者，可以设置 debug 成员为一个非 false 值来打开启用调试。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
0.99.8 | 增加了 debug 和 debugInfo 成员

参见

  • OAuth::disableDebug() - 关闭详细的调试

User Contributed Notes

There are no user contributed notes for this page.


启用重定向

  • ? OAuth::enableDebug
  • OAuth::enableSSLChecks ?
  • PHP Manual
  • OAuth
  • 启用重定向

OAuth::enableRedirects

(PECL OAuth >= 0.99.9)

OAuth::enableRedirects — 启用重定向

说明

public OAuth::enableRedirects ( ) : bool

启用自动重定向，此项默认为启用。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true

参见

  • OAuth::disableRedirects() - 关闭重定向

User Contributed Notes

There are no user contributed notes for this page.


启用 SSL 检查

  • ? OAuth::enableRedirects
  • OAuth::fetch ?
  • PHP Manual
  • OAuth
  • 启用 SSL 检查

OAuth::enableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::enableSSLChecks — 启用 SSL 检查

说明

public OAuth::enableSSLChecks ( ) : bool

启用通常的l SSL 对等证书和主机检查（默认为启用）。或者，可以设置 sslChecks 成员为一个非 false 值来启用 SSL 检查。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
0.99.8 | 增加 sslChecks 成员

参见

  • OAuth::disableSSLChecks() - 关闭 SSL 检查

User Contributed Notes

There are no user contributed notes for this page.


获取一个 OAuth 受保护的资源

  • ? OAuth::enableSSLChecks
  • OAuth::generateSignature ?
  • PHP Manual
  • OAuth
  • 获取一个 OAuth 受保护的资源

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch — 获取一个 OAuth 受保护的资源

说明

public OAuth::fetch ( string $protected_resource_url , array $extra_parameters = ? , string $http_method = ? , array $http_headers = ? ) : mixed

获取一个资源。

参数

protected_resource_url

OAuth 受保护资源的URL

extra_parameters

和资源请求一起发送的额外参数。

http_method

OAUTH_HTTP_METHOD_* 系列 OAUTH 常量之一，GET、POST、PUT、HEAD 或 DELETE 其中的一个。

HEAD （OAUTH_HTTP_METHOD_HEAD ）可以用于先于请求发现信息（如果 OAuth 证书在 Authorization 头部）。

http_headers

HTTP 客户端头信息（像 User-Agent， Accept 等等这样的）。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。
0.99.5 | 新增 http_method 参数
0.99.8 | 新增 http_headers 参数

范例

Example #1 OAuth::fetch() example

<?php
try {
    $oauth = new OAuth("consumer_key","consumer_secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauth->setToken("access_token","access_token_secret");

    $oauth->fetch("http://photos.example.net/photo?file=vacation.jpg");

    $response_info = $oauth->getLastResponseInfo();
    header("Content-Type: {$response_info["content_type"]}");
    echo $oauth->getLastResponse();
} catch(OAuthException $E) {
    echo "Exception caught!\n";
    echo "Response: ". $E->lastResponse . "\n";
}
?>

参见

  • OAuth::getLastResponse() - 获取最后一次的响应
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息
  • OAuth::setToken() - 设置令牌和 secret

User Contributed Notes

Lars Stttrup Nielsen 16-Mar-2016 07:37
So I'm using this to talk to the Woocommerce REST API, and was having a lot of trouble figuring out what exactly $extra_parameters was supposed to look like (which WC REST API expects, besides being of the type OAUTH_AUTH_TYPE_URI).

The multidimensional array I fed it crashed PHP, so don't do that if you're in my shoes.

What ended up solving it was me looking through the OAuth source and noticing that $extra_parameters can also be a string, which, encoded as json (json_encode), solved all my troubles as WC accepted it.
zverik at textual dot ru 31-Mar-2014 08:46
If $extra_parameters is not an array, you have to specify Content-Type header, or else you'll get HTTP 401 error. Example:

<?php
$oauth->fetch(ENDPOINT, '{"action": "get_user_info"}', OAUTH_HTTP_METHOD_PUT, array('Content-Type' => 'application/json'));
?>
chris dot barr at ntlworld dot com 05-Mar-2013 05:59
The fetch() method will throw an OAuthException if the returned http status code is in the 4xx or 5xx range:

<?php
// Querying Twitter with bad login details
try {
  $oauth->fetch('https://api.twitter.com/1.1/favorites/list.json');
}
catch(Exception $e) {
  echo $e->getCode(); // 401
  // Message generated by OAuth class
  echo $e->getMessage(); // Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
  // Message returned from Twitter
  echo $e->lastResponse; // {"errors":[{"message":"Could not authenticate you","code":32}]}
}
sun at drupal dot org 09-Aug-2011 06:40
Make sure that your $extra_parameters is an array.

If it's not, then OAuth will silently skip the malformed data type and produce a signature base string that is invalid (doesn't contain POST parameters, as defined in the RFC).

You should file a critical bug report against any REST API you find in the wild that accepts such a bogus signature to pass authentication.
contact info at mech dot cx 23-Mar-2011 04:00
I was having troubles getting fetch() to post, the remote server (Twitter, in this case) complained at me that their "resource only supports POST". Turned out to be a known bug in OAuth 1.1, downgrading to 1.0 fixed it.

Don't lose as much time over this as I did :-)
Lyuben Penkovski (l_penkovski at yahoo dot com) 26-Aug-2010 11:51
If the provider's web server is configured to use Keep-Alive extension to HTTP protocol (HTTP 1.1), there can be a big delay in the response time from the provider. By default Apache is configured to use Keep-Alive for 5 seconds. This is the delay after which the response will come back to the consumer. If you have this issue of delayed result, you can pass in HTTP headers when calling $consumer->fetch():

<?php
$consumer = new OAuth("consumer_key", "consumer_secret", OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
$consumer->fetch('http://example.com/api/', null, OAUTH_HTTP_METHOD_POST, array('Connection'=>'close'));
?>

Then the provider will send the result immediately after it's ready with the processing and the connection will be closed. Unfortunately, when calling $consumer->getRequestToken() and $consumer->getAccessToken() there's no way provided to pass in HTTP headers and this delay (if present) cannot be avoided, or at least we could not find a way to avoid it.

The solution that worked for us is to send this header from the provider when returning result to the consumer:

<?php
$result = 'oauth_callback_accepted=true&oauth_token=' . $this->urlencode($token->oauth_token) .
          '&oauth_token_secret='.$this->urlencode($token->oauth_token_secret);

header('HTTP/1.1 200 OK');
header('Content-Length: '.strlen($result));
header('Content-Type: application/x-www-form-urlencoded');
header('Connection:close');
echo $result;
?>

This can work if you have the possibility to modify the code of the provider, e.g. if you are the provider yourself or if you can talk with the people that develop it and ask them to send this header for your request.


生成一个签名

  • ? OAuth::fetch
  • OAuth::getAccessToken ?
  • PHP Manual
  • OAuth
  • 生成一个签名

OAuth::generateSignature

(No version information available, might only be in Git)

OAuth::generateSignature — 生成一个签名

说明

public OAuth::generateSignature ( string $http_method , string $url , mixed $extra_parameters = ? ) : string

生成一个基于最终 HTTP 方法、URL 和 一个字符串/数组参数的签名。

参数

http_method

用来请求的 HTTP 方法

url

用来请求的 URL

extra_parameters

字符串或数组的附加参数

返回值

一个包含签名的字符串 或者在失败时返回 false

User Contributed Notes

There are no user contributed notes for this page.


获取一个访问令牌

  • ? OAuth::generateSignature
  • OAuth::getCAPath ?
  • PHP Manual
  • OAuth
  • 获取一个访问令牌

OAuth::getAccessToken

(PECL OAuth >= 0.99.1)

OAuth::getAccessToken — 获取一个访问令牌

说明

public OAuth::getAccessToken ( string $access_token_url , string $auth_session_handle = ? , string $verifier_token = ? ) : array

从服务提供者获取一个访问令牌、secret以及一些附带的响应参数 。

参数

access_token_url

用于访问令牌 API 的 URL。

auth_session_handle

授权会话句柄，此参数在 OAuth 规范核心中没有任何引用， 但可能被大的提供者实现。» 参见 ScalableOAuth 获取更多信息。

verifier_token

对于支持 1.0a 的服务提供者， 当交换请求令牌和访问令牌时，必须传递 verifier_token 。如果 verifier_token 存在于 $_GET 或 $_POST 中，它将被自动传递，且调用者不需要指定一个 verifier_token （通常如果访问令牌在 oauth_callback URL 上被交换 ）。 » 参见 ScalableOAuth 获取更多信息。

返回值

成功则返回一个包含解析过的 OAuth 响应的数组， 失败则返回 false 。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。
0.99.9 | 新增 verifier_token 参数

范例

Example #1 OAuth::getAccessToken() 例子

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $oauth->setToken($request_token,$request_token_secret);
    $access_token_info = $oauth->getAccessToken("https://example.com/oauth/access_token");
    if(!empty($access_token_info)) {
        print_r($access_token_info);
    } else {
        print "Failed fetching access token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

以上例程的输出类似于：

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

参见

  • OAuth::getLastResponse() - 获取最后一次的响应
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息
  • OAuth::setToken() - 设置令牌和 secret

User Contributed Notes

There are no user contributed notes for this page.


获取 CA 信息

  • ? OAuth::getAccessToken
  • OAuth::getLastResponse ?
  • PHP Manual
  • OAuth
  • 获取 CA 信息

OAuth::getCAPath

(PECL OAuth >= 0.99.8)

OAuth::getCAPath — 获取 CA 信息

说明

public OAuth::getCAPath ( ) : array

获取证书授权的信息，其中包括通过 OAuth::setCaPath() 设置的 ca_path 和 ca_info 。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回一个证书授权信息的 数组 ，在返回的关联数组中明确地包含 ca_path 和 ca_info 键。

参见

  • OAuth::setCAPath() - 设置 CA 路径和信息
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息

User Contributed Notes

There are no user contributed notes for this page.


获取最后一次的响应

  • ? OAuth::getCAPath
  • OAuth::getLastResponseHeaders ?
  • PHP Manual
  • OAuth
  • 获取最后一次的响应

OAuth::getLastResponse

(PECL OAuth >= 0.99.1)

OAuth::getLastResponse — 获取最后一次的响应

说明

public OAuth::getLastResponse ( ) : string

获取最近一次请求的原始响应。

参数

此函数没有参数。

返回值

返回一个最后一次响应的字符串。

参见

  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息
  • OAuth::fetch() - 获取一个 OAuth 受保护的资源

User Contributed Notes

There are no user contributed notes for this page.


获取最后一次响应的头信息

  • ? OAuth::getLastResponse
  • OAuth::getLastResponseInfo ?
  • PHP Manual
  • OAuth
  • 获取最后一次响应的头信息

OAuth::getLastResponseHeaders

(No version information available, might only be in Git)

OAuth::getLastResponseHeaders — 获取最后一次响应的头信息

说明

public OAuth::getLastResponseHeaders ( ) : string

获取最后一次响应的头信息。

参数

此函数没有参数。

返回值

返回一个包含最后一次响应头信息的字符串 或者在失败时返回 false 。

User Contributed Notes

There are no user contributed notes for this page.


获取关于最后一次响应的 HTTP 信息

  • ? OAuth::getLastResponseHeaders
  • OAuth::getRequestHeader ?
  • PHP Manual
  • OAuth
  • 获取关于最后一次响应的 HTTP 信息

OAuth::getLastResponseInfo

(PECL OAuth >= 0.99.1)

OAuth::getLastResponseInfo — 获取关于最后一次响应的 HTTP 信息

说明

public OAuth::getLastResponseInfo ( ) : array

获取关于最后一次响应的 HTTP 信息。

参数

此函数没有参数。

返回值

返回一个包含最后一次请求响应信息的数组。可以用到来自 curl_getinfo() 的常量。

参见

  • OAuth::fetch() - 获取一个 OAuth 受保护的资源
  • OAuth::getLastResponse() - 获取最后一次的响应

User Contributed Notes

There are no user contributed notes for this page.


生成 OAuth 头信息字符串签名

  • ? OAuth::getLastResponseInfo
  • OAuth::getRequestToken ?
  • PHP Manual
  • OAuth
  • 生成 OAuth 头信息字符串签名

OAuth::getRequestHeader

(No version information available, might only be in Git)

OAuth::getRequestHeader — 生成 OAuth 头信息字符串签名

说明

public OAuth::getRequestHeader ( string $http_method , string $url , mixed $extra_parameters = ? ) : string

生成基于最终 HTTP 方法、URL 和 一个字符串/数组附加参数的 OAuth 头信息字符串签名。

参数

http_method

请求的 HTTP 方法。

url

请求的 URL 。

extra_parameters

字符串或数组类型的附带参数。

返回值

返回 一个包含生成的请求头信息的字符串 r 或者在失败时返回 false

User Contributed Notes

me at chrishowie dot com 12-Dec-2016 10:03
The documentation does not specify the difference between passing a string and passing an array for the third parameter.  We spent two days debugging before reading the C source code to figure out that there is a significant and undocumented difference between the two.

"a=1" and array("a" => 1) are handled very differently!

If you are making a POST/PUT request (or anything with an entity body) then you should pass that as a string.

If you are making a request with a query string, you should pass that as an associative array.

If you pass "a=1" intending that to specify the query string, the generated signature will be invalid -- it will process this as if you were POSTing the content "a=1" instead.


获取一个请求令牌

  • ? OAuth::getRequestHeader
  • OAuth::setAuthType ?
  • PHP Manual
  • OAuth
  • 获取一个请求令牌

OAuth::getRequestToken

(PECL OAuth >= 0.99.1)

OAuth::getRequestToken — 获取一个请求令牌

说明

public OAuth::getRequestToken ( string $request_token_url , string $callback_url = ? ) : array

从服务提供者那里获取一个请求令牌、secret 、以及一些附带的响应参数。

参数

request_token_url

请求令牌 API 的 URL。

callback_url

OAuth 回调 URL。 如果传递了 callback_url 且为空值，则将其设置为"oob"即到 OAuth 2009.1 咨询的地址。

返回值

成功则返回一个包含解析过了的 OAuth 响应的数组，失败则返回 false 。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。
0.99.9 | 增加 callback_url 参数。

范例

Example #1 OAuth::getRequestToken() 例子

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $request_token_info = $oauth->getRequestToken("https://example.com/oauth/request_token");
    if(!empty($request_token_info)) {
        print_r($request_token_info);
    } else {
        print "Failed fetching request token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

以上例程的输出类似于：

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

参见

  • OAuth::getLastResponse() - 获取最后一次的响应
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息

User Contributed Notes

bohwaz 29-Mar-2010 07:29
Please note that if you don't supply callback_url, the oauth parameter oauth_callback will not be sent to the server and will result in an error from the server, as this parameter is REQUIRED in the OAuth spec.


设置授权类型

  • ? OAuth::getRequestToken
  • OAuth::setCAPath ?
  • PHP Manual
  • OAuth
  • 设置授权类型

OAuth::setAuthType

(PECL OAuth >= 0.99.1)

OAuth::setAuthType — 设置授权类型

说明

public OAuth::setAuthType ( int $auth_type ) : mixed

设置 OAuth 参数应该放在哪里传递。

参数

auth_type

auth_type可能是下列标志之一（在 OAuth 1.0 规范的第 5.2 章节中按优先级降序排列）：

OAUTH_AUTH_TYPE_AUTHORIZATION
在 HTTP Authorization 头部传递 OAuth 参数。
OAUTH_AUTH_TYPE_FORM
将 OAuth 参数附加到 HTTP POST 请求主体中。
OAUTH_AUTH_TYPE_URI
将 OAuth 参数附加到请求的 URI 后面 。
OAUTH_AUTH_TYPE_NONE
无。

返回值

如果参数设置正确则返回 true ，否则返回 false （比如，传递进一个无效的 auth_type ）。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。

User Contributed Notes

There are no user contributed notes for this page.


设置 CA 路径和信息

  • ? OAuth::setAuthType
  • OAuth::setNonce ?
  • PHP Manual
  • OAuth
  • 设置 CA 路径和信息

OAuth::setCAPath

(PECL OAuth >= 0.99.8)

OAuth::setCAPath — 设置 CA 路径和信息

说明

public OAuth::setCAPath ( string $ca_path = ? , string $ca_info = ? ) : mixed

设置证书授权中心（CA ）的路径和信息。

Warning

本函数还未编写文档，仅有参数列表。

参数

ca_path

要设置的 CA 路径。

ca_info

要设置的 CA 信息。

返回值

成功则返回 true ，如果 ca_path 或 ca_info 其中之一被认为无效则返回 false 。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。

参见

  • OAuth::getCaPath() - 获取 CA 信息

User Contributed Notes

There are no user contributed notes for this page.


为后续请求设置现时标志

  • ? OAuth::setCAPath
  • OAuth::setRequestEngine ?
  • PHP Manual
  • OAuth
  • 为后续请求设置现时标志

OAuth::setNonce

(PECL OAuth >= 0.99.1)

OAuth::setNonce — 为后续请求设置现时标志

说明

public OAuth::setNonce ( string $nonce ) : mixed

为所有后续请求设置现时标志。

参数

nonce

oauth_nonce 的值。

返回值

成功返回 true ，如果 nonce 被认为无效，则返回 false 。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。

参见

  • OAuth::setToken() - 设置令牌和 secret
  • OAuth::setAuthType() - 设置授权类型
  • OAuth::setVersion() - 设置 OAuth 版本

User Contributed Notes

There are no user contributed notes for this page.


设置目标请求引擎

  • ? OAuth::setNonce
  • OAuth::setRSACertificate ?
  • PHP Manual
  • OAuth
  • 设置目标请求引擎

OAuth::setRequestEngine

(PECL OAuth >= 1.0.0)

OAuth::setRequestEngine — 设置目标请求引擎

说明

public OAuth::setRequestEngine ( int $reqengine ) : void

设置请求引擎，用于发送 HTTP 请求。

Warning

本函数还未编写文档，仅有参数列表。

参数

reqengine

想要的请求引擎。 设为 OAUTH_REQENGINE_STREAMS 则使用 PHP 流，设为 OAUTH_REQENGINE_CURL 则使用 Curl。

返回值

没有返回值。

错误／异常

如果选择了一个无效的请求引擎，则发出一个 OAuthException 异常。

范例

Example #1 OAuth::setRequestEngine() 例子

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

参见

  • Curl
  • PHP 流
  • OAuthException

User Contributed Notes

There are no user contributed notes for this page.


设置 RSA 证书

  • ? OAuth::setRequestEngine
  • OAuth::setSSLChecks ?
  • PHP Manual
  • OAuth
  • 设置 RSA 证书

OAuth::setRSACertificate

(PECL OAuth >= 1.0.0)

OAuth::setRSACertificate — 设置 RSA 证书

说明

public OAuth::setRSACertificate ( string $cert ) : mixed

设置 RSA 证书。

Warning

本函数还未编写文档，仅有参数列表。

参数

cert

RSA 证书。

返回值

成功则返回 true ，失败返回 false （例如，RSA证书不能被传递）。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。

范例

Example #1 一个 OAuth::setRsaCertificate() 例子

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

参见

  • OAuth::setCaPath() - 设置 CA 路径和信息

User Contributed Notes

There are no user contributed notes for this page.


调整特定的SSL请求检查

  • ? OAuth::setRSACertificate
  • OAuth::setTimestamp ?
  • PHP Manual
  • OAuth
  • 调整特定的SSL请求检查

OAuth::setSSLChecks

(No version information available, might only be in Git)

OAuth::setSSLChecks — 调整特定的SSL请求检查

说明

public OAuth::setSSLChecks ( int $sslcheck ) : bool

调整特定的SSL请求检查。

Warning

本函数还未编写文档，仅有参数列表。

参数

sslcheck

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


设置时间戳

  • ? OAuth::setSSLChecks
  • OAuth::setToken ?
  • PHP Manual
  • OAuth
  • 设置时间戳

OAuth::setTimestamp

(PECL OAuth >= 1.0.0)

OAuth::setTimestamp — 设置时间戳

说明

public OAuth::setTimestamp ( string $timestamp ) : mixed

为后续请求设置时间戳。

Warning

本函数还未编写文档，仅有参数列表。

参数

timestamp

时间戳。

返回值

返回 true ，除非 timestamp 无效，则返回 false 。

更新日志

版本 | 说明
1.0.0 | 以前失败时返回 null，而不是 false。

参见

  • OAuth::setNonce() - 为后续请求设置现时标志

User Contributed Notes

There are no user contributed notes for this page.


设置令牌和 secret

  • ? OAuth::setTimestamp
  • OAuth::setVersion ?
  • PHP Manual
  • OAuth
  • 设置令牌和 secret

OAuth::setToken

(PECL OAuth >= 0.99.1)

OAuth::setToken — 设置令牌和 secret

说明

public OAuth::setToken ( string $token , string $token_secret ) : bool

为后续请求设置令牌和 secret。

参数

token

OAuth 令牌

token_secret

OAuth 令牌 secret。

返回值

true

范例

Example #1 OAuth::setToken() 例子

<?php
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
$oauth->setToken("token","token-secret");
?>

User Contributed Notes

There are no user contributed notes for this page.


设置 OAuth 版本

  • ? OAuth::setToken
  • OAuthProvider ?
  • PHP Manual
  • OAuth
  • 设置 OAuth 版本

OAuth::setVersion

(PECL OAuth >= 0.99.1)

OAuth::setVersion — 设置 OAuth 版本

说明

public OAuth::setVersion ( string $version ) : bool

为随后请求设置 OAuth 版本

参数

version

OAuth 版本，默认值为 "1.0"

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


OAuthProvider 类

(PECL OAuth >= 1.0.0)

简介

管理一个 OAuth 提供者类。

参考一个外部的深入教程 » 写一个 OAuth 提供者服务，用来亲自实践提供服务。也可以参考 OAuth 扩展源代码里的 » OAuth 提供者例子 。

类摘要

OAuthProvider {
/* 方法 */
final public addRequiredParameter ( string $req_params ) : bool
public callconsumerHandler ( ) : void
public callTimestampNonceHandler ( ) : void
public calltokenHandler ( ) : void
public checkOAuthRequest ( string $uri = ? , string $method = ? ) : void
public __construct ( array $params_array = ? )
public consumerHandler ( callable $callback_function ) : void
final public static generateToken ( int $size , bool $strong = false ) : string
public is2LeggedEndpoint ( mixed $params_array ) : void
public isRequestTokenEndpoint ( bool $will_issue_request_token ) : void
final public removeRequiredParameter ( string $req_params ) : bool
final public static reportProblem ( string $oauthexception , bool $send_headers = true ) : string
final public setParam ( string $param_key , mixed $param_val = ? ) : bool
final public setRequestTokenPath ( string $path ) : bool
public timestampNonceHandler ( callable $callback_function ) : void
public tokenHandler ( callable $callback_function ) : void
}

Table of Contents

  • OAuthProvider::addRequiredParameter — 添加必需的参数
  • OAuthProvider::callconsumerHandler — 调用 consumerNonceHandler 回调函数
  • OAuthProvider::callTimestampNonceHandler — 调用 timestampNonceHandler 回调函数
  • OAuthProvider::calltokenHandler — 调用 tokenNonceHandler 回调函数
  • OAuthProvider::checkOAuthRequest — 检查一个 oauth 请求
  • OAuthProvider::__construct — 新建一个 OAuthProvider 对象
  • OAuthProvider::consumerHandler — 设置 consumerHandler 句柄回调函数
  • OAuthProvider::generateToken — 生成一个随机令牌
  • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
  • OAuthProvider::isRequestTokenEndpoint — 设置 isRequestTokenEndpoint
  • OAuthProvider::removeRequiredParameter — 移除一个必需的参数
  • OAuthProvider::reportProblem — 报告问题
  • OAuthProvider::setParam — 设置一个参数
  • OAuthProvider::setRequestTokenPath — 设置请求令牌路径
  • OAuthProvider::timestampNonceHandler — 设置 timestampNonceHandler 句柄回调函数
  • OAuthProvider::tokenHandler — 设置 tokenHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


添加必需的参数

  • ? OAuthProvider
  • OAuthProvider::callconsumerHandler ?
  • PHP Manual
  • OAuthProvider
  • 添加必需的参数

OAuthProvider::addRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::addRequiredParameter — 添加必需的参数

说明

final public OAuthProvider::addRequiredParameter ( string $req_params ) : bool

添加必需的 oauth 提供者参数。

Warning

本函数还未编写文档，仅有参数列表。

参数

req_params

必需的参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • OAuthProvider::removeRequiredParameter() - 移除一个必需的参数

User Contributed Notes

me at thomashunter dot name 06-Jun-2013 03:03
This method can be used for adding non-standard parameters required by your application, as well as parameters within the spec.

<?php
$Provider->addRequiredParameter("permissions");
$Provider->addRequiredParameter("oauth_callback");


调用 consumerNonceHandler 回调函数

  • ? OAuthProvider::addRequiredParameter
  • OAuthProvider::callTimestampNonceHandler ?
  • PHP Manual
  • OAuthProvider
  • 调用 consumerNonceHandler 回调函数

OAuthProvider::callconsumerHandler

(No version information available, might only be in Git)

OAuthProvider::callconsumerHandler — 调用 consumerNonceHandler 回调函数

说明

public OAuthProvider::callconsumerHandler ( ) : void

调用注册的消费者句柄回调函数，此回调函数通过 OAuthProvider::consumerHandler() 设置。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

如回调函数无法被调用或未被指定，会引发一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::consumerHandler() - 设置 consumerHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


调用 timestampNonceHandler 回调函数

  • ? OAuthProvider::callconsumerHandler
  • OAuthProvider::calltokenHandler ?
  • PHP Manual
  • OAuthProvider
  • 调用 timestampNonceHandler 回调函数

OAuthProvider::callTimestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::callTimestampNonceHandler — 调用 timestampNonceHandler 回调函数

说明

public OAuthProvider::callTimestampNonceHandler ( ) : void

调用注册的时间戳句柄回调函数，此回调函数通过 OAuthProvider::timestampNonceHandler() 设置。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

如回调函数无法被调用或未被指定，会引发一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::timestampNonceHandler() - 设置 timestampNonceHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


调用 tokenNonceHandler 回调函数

  • ? OAuthProvider::callTimestampNonceHandler
  • OAuthProvider::checkOAuthRequest ?
  • PHP Manual
  • OAuthProvider
  • 调用 tokenNonceHandler 回调函数

OAuthProvider::calltokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::calltokenHandler — 调用 tokenNonceHandler 回调函数

说明

public OAuthProvider::calltokenHandler ( ) : void

调用注册的令牌句柄回调函数，此回调函数通过 OAuthProvider::tokenHandler() 设置。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

如回调函数无法被调用或未被指定，会引发一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::tokenHandler() - 设置 tokenHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


检查一个 oauth 请求

  • ? OAuthProvider::calltokenHandler
  • OAuthProvider::__construct ?
  • PHP Manual
  • OAuthProvider
  • 检查一个 oauth 请求

OAuthProvider::checkOAuthRequest

(PECL OAuth >= 1.0.0)

OAuthProvider::checkOAuthRequest — 检查一个 oauth 请求

说明

public OAuthProvider::checkOAuthRequest ( string $uri = ? , string $method = ? ) : void

检查一个 OAuth 请求。

Warning

本函数还未编写文档，仅有参数列表。

参数

uri

可选的 URI 或终点。

method

HTTP 方法。 可选 OAUTH_HTTP_METHOD_* OAuth 常量 其中之一传递。

返回值

没有返回值。

错误／异常

如果不能检测到 HTTP 方法，则发出一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::reportProblem() - 报告问题

User Contributed Notes

tim at timlytle dot net 17-Oct-2013 01:30
Seems this method can only be called once per instance (or gives the same result as the first call on repeat calls).

My use case is API endpoints that can be accessed by a user or with 2 legged auth. If normal oAuth failed, I was calling is2LeggedEndpoint(true) and running again.

For that to work the OAuth Provider needs to be created again, simply changing one of the flags seems to have no effect on the next call.
Lyuben Penkovski (l_penkovski at yahoo dot com) 23-Aug-2010 03:59
This function checks if OAuth request is valid and signed correctly.

$provider->checkOAuthRequest();

It does this by first calling timestampNonceHandler and expects result OAUHT_OK from it. If the result is different, an exception is thrown. It's up to you to write the code that checks timestamp/nonce combinations.

Secondly, it calls consumerHandler and expects your code in the consumerHandler function to set $provider->consumer_secret to the correct value (you should take it from your consumer storage location where it's saved with consumer key). If $provider->consumer_secret is not set, or is not set with the proper value an exception is thrown. Proper value means that it should be the same consumer key that was used to sign the request by the consumer before sending it to here (the provider). Again expected result from this function is OAUTH_OK or some OAUTH error code if you want to throw exception.

Third, it calls tokenHandler, but only WHEN you are requesting ACCESS token or requesting protected data with authorized ACCESS TOKEN. In order for the provider to call tokenHandler, before a call to the checkOAuthRequest function is made, the provider should call the method that says that this is not a request token endpoint (this is access token endpoint):

$provider->isRequestTokenEndpoint (false);
$provider->checkOAuthRequest();

Again here OAuthProvider is expecting your code in the tokenHandler to set $provider->token_secret to the correct value (you should take it from your token storage place) because during the signing process it uses CONSUMER SECRET (for request token) and CONSUMER SECRET AND TOKEN SECRET (for access token and fetch of protected data) to sign the request.

After these 3 handler functions are called and return good results (OAUTH_OK) and set the values of the required fields $provider->consumer_secret and $provider->token_secret, then the checkOAuthRequest function signs the request. If something goes wrong, it throws exception, otherwise there comes the place for your code to proceed and handle the request:

- you can create request token (if it's a first request for request token)
- you can create access token (if it's a request for access token)
- you can return protected data to the consumer (if it's a request to fetch protected data)

This is how the functions in my code look like, however please have in mind that I've just implemented it and it's possible that I have something missed or forgotten, but generally I think the idea should be clear:

$this->dbModel is the object for working with database and save/retrieve token and consumer data

<?php

public function timestampNonceHandler ( $provider )
{
    return $this->dbModel->checkTimestampNonce ( $provider->consumer_key,
                                                 $provider->token,
                                                 $provider->timestamp,
                                                 $provider->nonce );
}

public function consumerHandler ( $provider )
{
    $consumer = $this->dbModel->getConsumerSecrets ($provider->consumer_key);

    if($consumer['consumer_key'] != $provider->consumer_key)
    {
        return OAUTH_CONSUMER_KEY_UNKNOWN;
    }

    if( (int)$consumer['disabled'] != 0 )
    {
        return OAUTH_CONSUMER_KEY_REFUSED;
    }

    $provider->consumer_id = $consumer['consumer_id']; # this is not required by OAuthProvider but I use it later in tokenHandler
    $provider->consumer_secret = $consumer['consumer_secret']; # this is REQUIRED

    return OAUTH_OK;
}

public function tokenHandler ( $provider )
{
    $token = $this->dbModel->getToken( $provider->token );

    if( time() > $token['expire'] )
    {
        return OAUTH_TOKEN_EXPIRED;
    }

    if($token['consumer_id'] != $provider->consumer_id)
    {
        return OAUTH_TOKEN_REJECTED;
    }

    if( (int)$token['authorized'] == 0 )
    {
        return OAUTH_TOKEN_REJECTED;
    }

    if($token['token_type'] != 'access')
    {
        if($token['verifier'] != $provider->verifier)
            return OAUTH_VERIFIER_INVALID;
    }

    $provider->token_id = $token['token_id']; # not required to be set by OAuthProvider
    $provider->token_secret = $token['token_secret']; # this is REQUIRED

    return OAUTH_OK;
}

?>


新建一个 OAuthProvider 对象

  • ? OAuthProvider::checkOAuthRequest
  • OAuthProvider::consumerHandler ?
  • PHP Manual
  • OAuthProvider
  • 新建一个 OAuthProvider 对象

OAuthProvider::__construct

(PECL OAuth >= 1.0.0)

OAuthProvider::__construct — 新建一个 OAuthProvider 对象

说明

public OAuthProvider::__construct ( array $params_array = ? )

发起一个新的 OAuthProvider 对象。

Warning

本函数还未编写文档，仅有参数列表。

参数

params_array

设置限制 CLI SAPI 的可选参数。

返回值

返回一个 OAuthProvider 对象。

范例

Example #1 OAuthProvider::__construct() 例子

<?php
try {

    $op = new OAuthProvider();

    // 使用用户定义的回调函数
    $op->consumerHandler(array($this, 'lookupConsumer'));
    $op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
    $op->tokenHandler(array($this, 'myTokenHandler'));

    // 忽略 foo_uri 参数
    $op->setParam('foo_uri', NULL);

    // 对于终点不需要令牌
    $op->setRequestTokenPath('/v1/oauth/request_token');

    $op->checkOAuthRequest();

} catch (OAuthException $e) {

    echo OAuthProvider::reportProblem($e);
}
?>

参见

  • OAuthProvider::setParam() - 设置一个参数

User Contributed Notes

There are no user contributed notes for this page.


设置 consumerHandler 句柄回调函数

  • ? OAuthProvider::__construct
  • OAuthProvider::generateToken ?
  • PHP Manual
  • OAuthProvider
  • 设置 consumerHandler 句柄回调函数

OAuthProvider::consumerHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::consumerHandler — 设置 consumerHandler 句柄回调函数

说明

public OAuthProvider::consumerHandler ( callable $callback_function ) : void

设置消费者句柄回调函数，并将在后面通过 OAuthProvider::callConsumerHandler() 被调用。

Warning

本函数还未编写文档，仅有参数列表。

参数

callback_function

回调类型 函数名。

返回值

没有返回值。

范例

Example #1 OAuthProvider::consumerHandler() 回调的例子

<?php
function lookupConsumer($provider) {

    if ($provider->consumer_key === 'unknown') {
        return OAUTH_CONSUMER_KEY_UNKNOWN;
    } else if($provider->consumer_key == 'blacklisted' || $provider->consumer_key === 'throttled') {
        return OAUTH_CONSUMER_KEY_REFUSED;
    }

    $provider->consumer_secret = "the_consumers_secret";

    return OAUTH_OK;
}
?>

参见

  • OAuthProvider::callConsumerHandler() - 调用 consumerNonceHandler 回调函数

User Contributed Notes

There are no user contributed notes for this page.


生成一个随机令牌

  • ? OAuthProvider::consumerHandler
  • OAuthProvider::is2LeggedEndpoint ?
  • PHP Manual
  • OAuthProvider
  • 生成一个随机令牌

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken — 生成一个随机令牌

说明

final public static OAuthProvider::generateToken ( int $size , bool $strong = false ) : string

生成一个伪随机字节的 字符串 。

参数

size

想要的令牌长度，单位为字节。

strong

设置为 true 则意味着将对熵使用 /dev/random ，否则使用非阻塞的 /dev/urandom。在 Windows 平台将忽略此参数。

返回值

生成的令牌，一个以字节为单位的 字符串 。

错误／异常

如果 strong 参数为 true ， 则当回退到用 rand() 来实现填充剩余的随机字节的时候，将触发一个 E_WARNING 级别的错误（比如，当最初找不到足够的随机数据的时候）。

范例

Example #1 OAuthProvider::generateToken() 例子

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t),  PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

以上例程的输出类似于：

4
b6a82c27

注释

Note:

当系统没有足够的随机数据可用的时候，此函数将使用 PHP 内部的 rand() 来实现填充剩余的随机字节。

参见

  • openssl_random_pseudo_bytes() - 生成一个伪随机字节串
  • mcrypt_create_iv() - 从随机源创建初始向量

User Contributed Notes

carlosouza at me dot com 28-Mar-2012 02:32
Be careful when setting the 'strong' parameter to true.

If you system doesn't have enough entropy your script will block which can cause timeouts in other parts of your code.

In my case, the most serious symptom was my script blocking when trying to read from /dev/random and causing a 'MySQL has gone away' error.

Hopefully this saves someone the trouble when deciding to use /dev/random entropy


is2LeggedEndpoint

  • ? OAuthProvider::generateToken
  • OAuthProvider::isRequestTokenEndpoint ?
  • PHP Manual
  • OAuthProvider
  • is2LeggedEndpoint

OAuthProvider::is2LeggedEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint

说明

public OAuthProvider::is2LeggedEndpoint ( mixed $params_array ) : void

2-legged 流程，或请求签名。不需要令牌。

Warning

本函数还未编写文档，仅有参数列表。

参数

params_array

返回值

返回一个 OAuthProvider 对象.

范例

Example #1 OAuthProvider::is2LeggedEndpoint() 例子

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

参见

  • OAuthProvider::__construct() - 新建一个 OAuthProvider 对象

User Contributed Notes

There are no user contributed notes for this page.


设置 isRequestTokenEndpoint

  • ? OAuthProvider::is2LeggedEndpoint
  • OAuthProvider::removeRequiredParameter ?
  • PHP Manual
  • OAuthProvider
  • 设置 isRequestTokenEndpoint

OAuthProvider::isRequestTokenEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::isRequestTokenEndpoint — 设置 isRequestTokenEndpoint

说明

public OAuthProvider::isRequestTokenEndpoint ( bool $will_issue_request_token ) : void

Warning

本函数还未编写文档，仅有参数列表。

参数

will_issue_request_token

设置是否发布一个请求令牌，从而决定 OAuthProvider::tokenHandler() 是否需要被调用。

返回值

没有返回值。

参见

  • OAuthProvider::setRequestTokenPath() - 设置请求令牌路径
  • OAuthProvider::reportProblem() - 报告问题

User Contributed Notes

There are no user contributed notes for this page.


移除一个必需的参数

  • ? OAuthProvider::isRequestTokenEndpoint
  • OAuthProvider::reportProblem ?
  • PHP Manual
  • OAuthProvider
  • 移除一个必需的参数

OAuthProvider::removeRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::removeRequiredParameter — 移除一个必需的参数

说明

final public OAuthProvider::removeRequiredParameter ( string $req_params ) : bool

移除一个必需的参数。

Warning

本函数还未编写文档，仅有参数列表。

参数

req_params

要被移除的必需参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • OAuthProvider::setParam() - 设置一个参数
  • OAuthProvider::addRequiredParameter() - 添加必需的参数

User Contributed Notes

There are no user contributed notes for this page.


报告问题

  • ? OAuthProvider::removeRequiredParameter
  • OAuthProvider::setParam ?
  • PHP Manual
  • OAuthProvider
  • 报告问题

OAuthProvider::reportProblem

(PECL OAuth >= 1.0.0)

OAuthProvider::reportProblem — 报告问题

说明

final public static OAuthProvider::reportProblem ( string $oauthexception , bool $send_headers = true ) : string

将问题作为一个 OAuthException 异常传入，可能出现的问题在 OAuth 常量 章节里已列出。

Warning

本函数还未编写文档，仅有参数列表。

参数

oauthexception

OAuthException 类。

返回值

没有返回值。

参见

  • OAuthProvider::checkOAuthRequest() - 检查一个 oauth 请求
  • OAuthProvider::isRequestTokenEndpoint() - 设置 isRequestTokenEndpoint

User Contributed Notes

There are no user contributed notes for this page.


设置一个参数

  • ? OAuthProvider::reportProblem
  • OAuthProvider::setRequestTokenPath ?
  • PHP Manual
  • OAuthProvider
  • 设置一个参数

OAuthProvider::setParam

(PECL OAuth >= 1.0.0)

OAuthProvider::setParam — 设置一个参数

说明

final public OAuthProvider::setParam ( string $param_key , mixed $param_val = ? ) : bool

设置一个参数。

Warning

本函数还未编写文档，仅有参数列表。

参数

param_key

参数的 key 。

param_val

参数的值，此为可选项。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • OAuthProvider::addRequiredParameter() - 添加必需的参数

User Contributed Notes

There are no user contributed notes for this page.


设置请求令牌路径

  • ? OAuthProvider::setParam
  • OAuthProvider::timestampNonceHandler ?
  • PHP Manual
  • OAuthProvider
  • 设置请求令牌路径

OAuthProvider::setRequestTokenPath

(PECL OAuth >= 1.0.0)

OAuthProvider::setRequestTokenPath — 设置请求令牌路径

说明

final public OAuthProvider::setRequestTokenPath ( string $path ) : bool

设置请求令牌路径。

Warning

本函数还未编写文档，仅有参数列表。

参数

path

路径。

返回值

true

参见

  • OAuthProvider::tokenHandler() - 设置 tokenHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


设置 timestampNonceHandler 句柄回调函数

  • ? OAuthProvider::setRequestTokenPath
  • OAuthProvider::tokenHandler ?
  • PHP Manual
  • OAuthProvider
  • 设置 timestampNonceHandler 句柄回调函数

OAuthProvider::timestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::timestampNonceHandler — 设置 timestampNonceHandler 句柄回调函数

说明

public OAuthProvider::timestampNonceHandler ( callable $callback_function ) : void

设置时间戳 nonce 句柄回调函数，此函数将在后面被 OAuthProvider::callTimestampNonceHandler() 调用。跟时间戳/nonce相关的错误将被抛给此回调函数。

Warning

本函数还未编写文档，仅有参数列表。

参数

callback_function

回调类型 的函数名。

返回值

没有返回值。

范例

Example #1 OAuthProvider::timestampNonceHandler() 回调的例子

<?php
function timestampNonceChecker($provider) {

    if ($provider->nonce === 'bad') {
        return OAUTH_BAD_NONCE;
    } elseif ($provider->timestamp == '0') {
        return OAUTH_BAD_TIMESTAMP;
    }

    return OAUTH_OK;
}
?>

参见

  • OAuthProvider::callTimestampNonceHandler() - 调用 timestampNonceHandler 回调函数

User Contributed Notes

There are no user contributed notes for this page.


设置 tokenHandler 句柄回调函数

  • ? OAuthProvider::timestampNonceHandler
  • OAuthException ?
  • PHP Manual
  • OAuthProvider
  • 设置 tokenHandler 句柄回调函数

OAuthProvider::tokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::tokenHandler — 设置 tokenHandler 句柄回调函数

说明

public OAuthProvider::tokenHandler ( callable $callback_function ) : void

设置令牌句柄的回调函数，此回调函数将在后面被 OAuthProvider::callTokenHandler() 调用。

Warning

本函数还未编写文档，仅有参数列表。

参数

callback_function

回调类型 的函数名。

返回值

没有返回值。

范例

Example #1 OAuthProvider::tokenHandler() 回调的例子

<?php
function tokenHandler($provider) {

    if ($provider->token === 'rejected') {
        return OAUTH_TOKEN_REJECTED;
    } elseif ($provider->token === 'revoked') {
        return OAUTH_TOKEN_REVOKED;
    }

    $provider->token_secret = "the_tokens_secret";
    return OAUTH_OK;
}
?>

参见

  • OAuthProvider::callTokenHandler() - 调用 tokenNonceHandler 回调函数

User Contributed Notes

There are no user contributed notes for this page.


OAuthException 类

(PECL OAuth >= 0.99.1)

简介

当使用 OAuth 扩展发生异常错误时，抛出此异常和包含了一些有用的调试信息。

类摘要

OAuthException extends Exception {
/* 属性 */
public $lastResponse ;
public $debugInfo ;
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

属性

lastResponse

发生异常时的响应，如果有的话

debugInfo

User Contributed Notes

There are no user contributed notes for this page.


SOAP

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SOAP 函数
    • is_soap_fault — Checks if a SOAP call has failed
    • use_soap_error_handler — Set whether to use the SOAP error handler
  • SoapClient — The SoapClient class
    • SoapClient::__call — Calls a SOAP function (deprecated)
    • SoapClient::__construct — SoapClient constructor
    • SoapClient::__doRequest — Performs a SOAP request
    • SoapClient::__getCookies — Get list of cookies
    • SoapClient::__getFunctions — Returns list of available SOAP functions
    • SoapClient::__getLastRequest — Returns last SOAP request
    • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse — Returns last SOAP response
    • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
    • SoapClient::__getTypes — Returns a list of SOAP types
    • SoapClient::__setCookie — Defines a cookie for SOAP requests
    • SoapClient::__setLocation — Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall — Calls a SOAP function
  • SoapServer — The SoapServer class
    • SoapServer::addFunction — 添加一个或多个函数来处理SOAP请求
    • SoapServer::addSoapHeader — Add a SOAP header to the response
    • SoapServer::__construct — SoapServer constructor
    • SoapServer::fault — Issue SoapServer fault indicating an error
    • SoapServer::getFunctions — Returns list of defined functions
    • SoapServer::handle — Handles a SOAP request
    • SoapServer::setClass — Sets the class which handles SOAP requests
    • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence — Sets SoapServer persistence mode
  • SoapFault — The SoapFault class
    • SoapFault::__construct — SoapFault constructor
    • SoapFault::__toString — Obtain a string representation of a SoapFault
  • SoapHeader — The SoapHeader class
    • SoapHeader::__construct — SoapHeader constructor
  • SoapParam — The SoapParam class
    • SoapParam::__construct — SoapParam constructor
  • SoapVar — The SoapVar class
    • SoapVar::__construct — SoapVar constructor

User Contributed Notes

Luke 08-Sep-2015 07:21
Was calling an asmx method like $success=$x->AuthenticateUser($userName,$password) and this was returning me an error.

However i changed it and added the userName and password in an array and its now KAWA...
spectrumcat at gmail dot com 22-Feb-2015 04:19
In case you'll get a .p12 certificate for your SOAP client to use (or any other actually) make sure to convert it to PEM and merge with the private key.

Convert p12 to PEM with merged private key:
openssl pkcs12 -in supplied_cert.p12 -out php_soap_cert.pem -clcerts

Example:
$wsdl = "./mywsdl.wsdl"; // Or "http://provider.com/api/api.wsdl"

$options = [
        'location'      => "http://provider.com/api/",
        'local_cert'    => "./php_soap_cert.pem",
        'passphrase'    => "certificate_password",
];

try {
    $soapClient = new SoapClient($wsdl, $options);
} catch(Exception $e) {
    var_dump($e);
}
rafinskipg at gmail dot com 14-May-2012 02:54
Support for MTOM addign this code to your project:

<?php
class MySoapClient extends SoapClient
{
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        // parse $response, extract the multipart messages and so on

        //this part removes stuff
        $start=strpos($response,'<?xml');
        $end=strrpos($response,'>');
        $response_string=substr($response,$start,$end-$start+1);
        return($response_string);
    }
}

?>

Then you can do this
<?php
  new MySoapClient($wsdl_url);
?>
dennis at pleasedontspam dot clansman dot nl 02-Dec-2011 03:53
When you receive the soapfault message: "looks like we got no XML document" it might be that you're talking to a server that supports MTOM (http://www.w3.org/TR/soap12-mtom/).

MTOM is, as of yet (5.3.6), not supported by the SoapClient.
mariamr at gmail dot com 16-Oct-2010 06:38
"SOAP-ERROR: Parsing WSDL: Couldn't find in 'PATH/TO/YOUR/WSDL'"

This error occurs because some versions of PHP SOAP client  do not send the user name and password that you pass as the options input parameter of the SoapClient constructor  . Yu need to pass the credentials in the web service URL like this:
$soapClient =new SoapClient("http://user:password@example.com/blahblah.wsdl");
vishal dot thakkar at exateam dot com 22-Feb-2010 06:19
I was trying to figure out for days and days to make SOAP server return an associative array and NOT an object ....

To get an array (not object) in the SOAP response, just serialize the array before returning it to the clent..

hope it helps...
Thanks.....
Vishal Thakkar.
stephenlansell at gmail dot com 03-Feb-2010 07:19
Here is an example of a php client talking to a asmx server:

<?php

        $soapClient = new SoapClient("https://soapserver.example.com/blahblah.asmx?wsdl");

        // Prepare SoapHeader parameters
        $sh_param = array(
                    'Username'    =>    'username',
                    'Password'    =>    'password');
        $headers = new SoapHeader('http://soapserver.example.com/webservices', 'UserCredentials', $sh_param);

        // Prepare Soap Client
        $soapClient->__setSoapHeaders(array($headers));

        // Setup the RemoteFunction parameters
        $ap_param = array(
                    'amount'     =>    $irow['total_price']);

        // Call RemoteFunction ()
        $error = 0;
        try {
            $info = $soapClient->__call("RemoteFunction", array($ap_param));
        } catch (SoapFault $fault) {
            $error = 1;
            print("
            alert('Sorry, blah returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.". We will now take you back to our home page.');
            window.location = 'main.php';
            ");
        }

        if ($error == 0) {
            $auth_num = $info->RemoteFunctionResult;

            if ($auth_num < 0) {
                ....

                // Setup the OtherRemoteFunction() parameters
                $at_param = array(
                            'amount'        => $irow['total_price'],
                            'description'    => $description);

                // Call OtherRemoteFunction()
                $trans = $soapClient->__call("OtherRemoteFunction", array($at_param));
                $trans_result = $trans->OtherRemoteFunctionResult;
            ....
                } else {
                    // Record the transaction error in the database

                // Kill the link to Soap
                unset($soapClient);
            }
        }
    }
}

?>
moazzam at moazzam-khan dot com 05-Oct-2009 09:37
If anyone is trying to use this for accessing Sabre's web services, it won't work. Sabre checks the request header "Content-Type" to see if it is "text/xml" . If it is not text/xml then it sends an error back.

You will need to create a socket connection and use that to send the request over.
Raphal Gertz 18-Apr-2009 09:50
Juste a note to avoid wasting time on php-soap protocol and format support.

Until php 5.2.9 (at least) the soap extension is only capable of understanding wsdl 1.0 and 1.1 format.

The wsdl 2.0, a W3C recommendation since june 2007, ISN'T supported in php soap extension.
(the soap/php_sdl.c source code don't handle wsdl2.0 format)

The wsdl 2.0 is juste the 1.2 version renamed because it has substantial differences from WSDL 1.1.

The differences between the two format may not be invisible if you don't care a lot.

The wsdl 1.0 format structure (see http://www.w3.org/TR/wsdl) :
<definitions ...>
    <types ...>
    </types>
    <message ...>
        <part ...>
    </message>
    <portType ...>
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </portType>
    <binding ...>
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </binding>
    <service ...>
        <port ...>
    </service>
</definitions>

And the wsdl 2.0 format structure (see http://www.w3.org/TR/wsdl20/) :
<description ...>
    <types ...>
    </types>
    <interface ...>
        <fault ... />
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </interface>
    <binding ...>
        <fault ... />
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </binding>
    <service ...>
        <endpoint ...>
    </service>
</description>

The typical error message if you provide a wsdl 2.0 format file :
PHP Fatal error:  SOAP-ERROR: Parsing WSDL: Couldn't find <definitions> in 'wsdl/example.wsdl' in /path/client.php on line 9
jeff at jeffrodriguez dot com 03-Feb-2009 01:37
Named parameters are actually super easy once you know how to do it. No need to bother with SoapParam or SoapVar for the most part.

The code:
<?php
$ws->getAsset(array(
  'assetId' => 5967
));
?>

Generates the following SOAP body: (formatted for readability)
<SOAP-ENV:Body>
  <ns1:getAsset>
    <assetId>5967</assetId>
  </ns1:getAsset>
</SOAP-ENV:Body>
beau dot scott at gmail dot com 22-Oct-2008 03:34
If you've been trying to send null to a service that considers empty property tags as empty strings rather than null, here's an extending class that fixes this using xsi:nil:

<?php
class XSoapClient extends SoapClient
{
    const XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
    const _NULL_ = "xxx_replacedduetobrokephpsoapclient_xxx";

    protected $mustParseNulls = false;

    public function __doRequest($request, $location, $action, $version, $one_way = null)
    {
        if($this->mustParseNulls)
        {
            $this->mustParseNulls = false;
            $request = preg_replace('/<ns1:(\w+)>'.self::_NULL_.'<\/ns1:\\1>/',
                        '<ns1:$1 xsi:nil="true"/>',
                        $request, -1, &$count);

            if ($count > 0)
            {
                $request = preg_replace('/(<SOAP-ENV:Envelope )/',
                    '\\1 xmlns:xsi="'.self::XSI_NS.'" ',
                    $request);
            }
        }
        return parent::__doRequest($request, $location, $action, $version, $one_way);
    }

    public function __call($method, $params)
    {
        foreach($params as $k => $v)
        {
            if($v === null)
            {
                $this->mustParseNulls = true;
                $params[$k] = self::_NULL_;
            }
        }
        return parent::__call($method, $params);
    }
}
?>
Ryan 22-Oct-2008 06:21
If you are having an issue where SOAP cannot find the functions that are actually there if you view the wsdl file, it's because PHP is caching the wsdl file (for a day at a time). To turn this off, have this line on every script that uses SOAP: ini_set("soap.wsdl_cache_enabled", "0"); to disable the caching feature.
ivan dot cubillas at xeridia dot com 08-Aug-2008 01:02
The problem with the PHP WebService Client

We've a JAVA WebService Server which could have attached documents. When the PHP Client send the dates, the Server take it correctly, but when
the server return it to the PHP Client, the client reply always that is not a XML valid document.

The problem could be than the JAVA Server adds (to this type of XML binary files)  the documentType head: xml+xop and the clean doesn't understand
this head as a XML document.

There is some possibility to solve this problem in the PHP Client without doing changes in the JAVA Server?
aeg at mallxs dot nl 28-May-2008 05:19
SoapFault exception: [SOAP-ENV:Client] looks like we got no XML document

This error can have to reasons:
1: Your server script has some hidden output like spaces before or afher <?php ... ?> or echoing some text
2: You have a bug in your server script;
    resulting in a error message output

Test your server script by calling it direct  from the browser.
The result should be a clean output like :

?<SOAP-ENV:Envelope>
?<SOAP-ENV:Body>
?<SOAP-ENV:Fault>
  <faultcode>SOAP-ENV:Server</faultcode>
  <faultstring>Bad Request. Can't find HTTP_RAW_POST_DATA</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

This tell's you there was a request but without data; This is OK
Now if you get the error when calling with your soap client;
remember that your server now will call other functions in the server.php script because it now has some data to process
nodkz at mail dot ru 24-May-2008 02:25
PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

<?php
/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

Function "getAsSoap" call for encoding object for transmission. After encoding it can be properly transmitted.
*/
abstract class SOAPable {
    public function getAsSOAP() {
        foreach($this as $key=>&$value) {
            $this->prepareSOAPrecursive($this->$key);
        }
        return $this;
    }

    private function prepareSOAPrecursive(&$element) {
        if(is_array($element)) {
            foreach($element as $key=>&$val) {
                $this->prepareSOAPrecursive($val);
            }
            $element=new SoapVar($element,SOAP_ENC_ARRAY);
        }elseif(is_object($element)) {
            if($element instanceof SOAPable) {
                $element->getAsSOAP();
            }
            $element=new SoapVar($element,SOAP_ENC_OBJECT);
        }
    }
}

// ------------------------------------------
//  ABSTRACT EXAMPLE
// ------------------------------------------

class PersonList extends SOAPable {
  protected $ArrayOfPerson; // variable MUST be protected or public!
}

class Person extends SOAPable {
   //any data
}

$client=new SoapClient("test.wsdl", array( 'soap_version'=>SOAP_1_2, 'trace'=>1, 'classmap' => array('Person' => "Person", 'PersonList' => "PersonList")  ));

$PersonList=new PersonList;

// some actions

$PersonList->getAsSOAP();

$client->someMethod($PersonList);

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

So in code before transmitting simply call $obj->getAsSOAP()


简介

The SOAP extension can be used to write SOAP Servers and Clients. It supports subsets of » SOAP 1.1, » SOAP 1.2 and » WSDL 1.1 specifications.

User Contributed Notes

There are no user contributed notes for this page.


需求

此扩展需要 libxml PHP 扩展。这表示需要使用 --with-libxml，或在 PHP 7.4 之前的版本中使用 --enable-libxml， 尽管这将隐式完成因为 libxml 是缺省开启的。

User Contributed Notes

There are no user contributed notes for this page.


安装

To enable SOAP support, configure PHP with --enable-soap.

User Contributed Notes

slawkens 04-Jun-2018 08:01
for latest MacOS with brew, where Homebrew/PHP is deprecated:

brew install php@7.2-soap

(change 7.2 to your version)
cdvillagra 09-May-2017 05:39
If you have not yet updated the OS and also the PHP version

for Ubuntu 14.04 LTS
sudo apt-get install php5.6-soap
sudo service apache2 restart
c at cinqs dot net 16-Feb-2017 07:55
If you received a

    E: Couldn't find any package by regex 'php7.1-soap'

when using docker php:apache image

try

    apt-get install php-soap

instead
digimix.co 24-Jan-2017 01:31
On PHP7.1 Ubuntu 16.04 LTS:
$ sudo apt-get install php7.1-soap
$ sudo service php7.1-fpm reload
wally at soggysoftware dot co dot uk 22-Dec-2016 09:40
If you're using official PHP packages shipped with CentOS or RedHat version 6 or 7:

# yum install php-soap

(Restart Apache/nginx too if appropriate.)
dbagnara 20-Aug-2016 10:02
for Ubuntu 16.04 LTS
sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service


运行时配置

这些函数的行为受 php.ini 中的设置影响。

SOAP 配置选项
名字 | 默认 | 可修改范围 | 更新日志
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |

这是配置指令的简短说明。

soap.wsdl_cache_enabled int

Enables or disables the WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where the SOAP extension will put cache files.

soap.wsdl_cache_ttl int

Sets the number of seconds (time to live) that cached files will be used instead of the originals.

soap.wsdl_cache int

If soap.wsdl_cache_enabled is on, this setting determines the type of caching. It can be any of: WSDL_CACHE_NONE (0), WSDL_CACHE_DISK (1), WSDL_CACHE_MEMORY (2) or WSDL_CACHE_BOTH (3). This can also be set via the options array in the SoapClient or SoapServer constructor.

soap.wsdl_cache_limit int

Maximum number of in-memory cached WSDL files. Adding further files into a full memory cache will delete the oldest files from it.

User Contributed Notes

michal-ok at o2 dot pl 06-Mar-2020 03:08
Be aware that wsdl cache may not be compatible across different PHP versions, which may be important to know when you upgrade your PHP on the same system or use a multi-PHP version setup where you run the same scripts from different PHP versions. In other words, when a SOAP request writes a file to the cache and then you make another SOAP request from another PHP version and this cache file is used then *sometimes* you may experience unexpected errors that you will not know where they come from.

I spent hours trying to figure out why I was getting "Encoding: Violation of encoding rules" errors every time I ran some of my SOAP scripts from PHP 7.3 just hours after switching from PHP 7.2. It turned out I needed to clear all cached wsdl files created by PHP 7.2. Downgrading from 7.3 to 7.2 caused the same errors and required clearing the cache, too.

When transitioning to a new PHP version you may turn off the cache or set a very short wsdl_cache_ttl period - if you can't delete the files yourself. If you need your scripts to run on multiple PHP versions with wsdl cache then you'd need to set wsdl_cache_dir that is different for each PHP version.
no dot tehwan dot spam at com dot nospam dot gmail 20-Aug-2014 08:05
Keep in mind if you have memory cache enabled that even if you use an updated WSDL file, it will still be using the one in memory. If you download the WSDL files yourself, avoid using memory cache as you will have no control over it, or set the TTL to a small value (default is 1 day).
martijn at netexpo dot nl 19-Oct-2012 01:37
Please note that these three ini settings will also affect the behaviour of your soap server (and clients as well) :

1. default_socket_timeout default 60 secs
Large or slow requests to your soap server or long processes at your soap server will return soap fault after 60 secs like : Error Fetching http headers.

2. max_execution_time default 30 secs
This can be the next bottleneck (but only when your default_socket_timeout is larger then this setting). Your soap server will not return anything, no faults no output, just an empty string.

3. memory_limit default 128M
Will throw fatal errors when the soap server script itself has low memory or will let your services return empty strings when the data it processes puts memory usage over this limit.

Other max POST settings luckily (but a bit suprisingly to me) have _no_ effect for your soap server. Those are :

max_input_time
max_input_nesting_level
max_input_vars
post_max_size
suhosin.post.max_array_depth
suhosin.post.max_array_index_length
suhosin.post.max_name_length
suhosin.post.max_totalname_length
suhosin.post.max_vars
suhosin.post.max_value_length
hpralow at users dot sf dot net 24-Jul-2008 07:40
If you want to dissable WSDL-caching, you can do so with
<?php
ini_set('soap.wsdl_cache_enabled', '0');
ini_set('soap.wsdl_cache_ttl', '0');
?>
However you must do this before creating a SOAP object (soap_client or soap_server).
Changing the settings like above does not have any effect on already existing soap-objects.

[EDIT BY danbrown AT php DOT net: Typofix provided by (james AT voodoo DOT co DOT uk) on 4-FEB-09.]


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SOAP constants
Constant | Value | Description
SOAP_1_1 (int) | 1 |
SOAP_1_2 (int) | 2 |
SOAP_PERSISTENCE_SESSION (int) | 1 |
SOAP_PERSISTENCE_REQUEST (int) | 2 |
SOAP_FUNCTIONS_ALL (int) | 999 |
SOAP_ENCODED (int) | 1 |
SOAP_LITERAL (int) | 2 |
SOAP_RPC (int) | 1 |
SOAP_DOCUMENT (int) | 2 |
SOAP_ACTOR_NEXT (int) | 1 |
SOAP_ACTOR_NONE (int) | 2 |
SOAP_ACTOR_UNLIMATERECEIVER (int) | 3 |
SOAP_COMPRESSION_ACCEPT (int) | 32 |
SOAP_COMPRESSION_GZIP (int) | 0 |
SOAP_COMPRESSION_DEFLATE (int) | 16 |
SOAP_AUTHENTICATION_BASIC (int) | 0 |
SOAP_AUTHENTICATION_DIGEST (int) | 1 |
SOAP_SSL_METHOD_TLS (int) | 0 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv2 (int) | 1 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv3 (int) | 2 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv23 (int) | 3 | Since PHP 5.5.0.
UNKNOWN_TYPE (int) | 999998 |
XSD_STRING (int) | 101 |
XSD_BOOLEAN (int) | 102 |
XSD_DECIMAL (int) | 103 |
XSD_FLOAT (int) | 104 |
XSD_DOUBLE (int) | 105 |
XSD_DURATION (int) | 106 |
XSD_DATETIME (int) | 107 |
XSD_TIME (int) | 108 |
XSD_DATE (int) | 109 |
XSD_GYEARMONTH (int) | 110 |
XSD_GYEAR (int) | 111 |
XSD_GMONTHDAY (int) | 112 |
XSD_GDAY (int) | 113 |
XSD_GMONTH (int) | 114 |
XSD_HEXBINARY (int) | 115 |
XSD_BASE64BINARY (int) | 116 |
XSD_ANYURI (int) | 117 |
XSD_QNAME (int) | 118 |
XSD_NOTATION (int) | 119 |
XSD_NORMALIZEDSTRING (int) | 120 |
XSD_TOKEN (int) | 121 |
XSD_LANGUAGE (int) | 122 |
XSD_NMTOKEN (int) | 123 |
XSD_NAME (int) | 124 |
XSD_NCNAME (int) | 125 |
XSD_ID (int) | 126 |
XSD_IDREF (int) | 127 |
XSD_IDREFS (int) | 128 |
XSD_ENTITY (int) | 129 |
XSD_ENTITIES (int) | 130 |
XSD_INTEGER (int) | 131 |
XSD_NONPOSITIVEINTEGER (int) | 132 |
XSD_NEGATIVEINTEGER (int) | 133 |
XSD_LONG (int) | 134 |
XSD_INT (int) | 135 |
XSD_SHORT (int) | 136 |
XSD_BYTE (int) | 137 |
XSD_NONNEGATIVEINTEGER (int) | 138 |
XSD_UNSIGNEDLONG (int) | 139 |
XSD_UNSIGNEDINT (int) | 140 |
XSD_UNSIGNEDSHORT (int) | 141 |
XSD_UNSIGNEDBYTE (int) | 142 |
XSD_POSITIVEINTEGER (int) | 143 |
XSD_NMTOKENS (int) | 144 |
XSD_ANYTYPE (int) | 145 |
XSD_ANYXML (int) | 147 |
APACHE_MAP (int) | 200 |
SOAP_ENC_OBJECT (int) | 301 |
SOAP_ENC_ARRAY (int) | 300 |
XSD_1999_TIMEINSTANT (int) | 401 |
XSD_NAMESPACE (int) | http://www.w3.org/2001/XMLSchema |
XSD_1999_NAMESPACE (int) | http://www.w3.org/1999/XMLSchema |
SOAP_SINGLE_ELEMENT_ARRAYS (int) | 1 |
SOAP_WAIT_ONE_WAY_CALLS (int) | 2 |
SOAP_USE_XSI_ARRAY_TYPE (int) | 4 |
WSDL_CACHE_NONE (int) | 0 |
WSDL_CACHE_DISK (int) | 1 |
WSDL_CACHE_MEMORY (int) | 2 |
WSDL_CACHE_BOTH (int) | 3 |

User Contributed Notes

User 01-Oct-2010 08:56
We are casting the values (float) to simulate the 64-bits long. seem to work fine, of course, the values we are using have no decimal point.


SOAP 函数

Table of Contents

  • is_soap_fault — Checks if a SOAP call has failed
  • use_soap_error_handler — Set whether to use the SOAP error handler

User Contributed Notes

vIceBerg 23-Sep-2008 07:18
I have PHP 5.2.5 on my computer. I get this result:

Array
(
    [0] => stdClass Object
        (
            [Client] => stdClass Object
                (
                    [Nom] => LeNom:00000
                    [Prenom] => LePrenom:00000
                )

        )

My host have 5.1.6, the same call returns this result:
Array
(
    [0] => stdClass Object
        (
            [Client] => Array
                (
                    [0] => stdClass Object
                        (
                            [Nom] => LeNom:00000
                            [Prenom] => LePrenom:00000

                        )

5.2.5 is the good structure.

Take care of the version you're using. It can be a lot of work to change all the code
nodkz at mail dot ru 24-May-2008 02:28
PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

<?php
/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

Function "getAsSoap" call for encoding object for transmission. After encoding it can be properly transmitted.
*/
abstract class SOAPable {
    public function getAsSOAP() {
        foreach($this as $key=>&$value) {
            $this->prepareSOAPrecursive($this->$key);
        }
        return $this;
    }

    private function prepareSOAPrecursive(&$element) {
        if(is_array($element)) {
            foreach($element as $key=>&$val) {
                $this->prepareSOAPrecursive($val);
            }
            $element=new SoapVar($element,SOAP_ENC_ARRAY);
        }elseif(is_object($element)) {
            if($element instanceof SOAPable) {
                $element->getAsSOAP();
            }
            $element=new SoapVar($element,SOAP_ENC_OBJECT);
        }
    }
}

// ------------------------------------------
//  ABSTRACT EXAMPLE
// ------------------------------------------

class PersonList extends SOAPable {
  protected $ArrayOfPerson; // variable MUST be protected or public!
}

class Person extends SOAPable {
   //any data
}

$client=new SoapClient("test.wsdl", array( 'soap_version'=>SOAP_1_2, 'trace'=>1, 'classmap' => array('Person' => "Person", 'PersonList' => "PersonList")  ));

$PersonList=new PersonList;

// some actions

$PersonList->getAsSOAP();

$client->someMethod($PersonList);

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

So in code before transmitting simply call $obj->getAsSOAP()
rlee at melbournechapter dot net 01-May-2008 05:38
Just a note on "DTD not recognised..." faults. Check to make sure your wsdl file contains:

<?xml version ='1.0' encoding ='UTF-8' ?>

Also make sure you use full paths, to your service (in the wsdl, client and server)
...
<wsdlsoap:address location='http://www.mysite.com.au/web_services/myserver.php' />
...
<?php
// SOAP Server
$server = new SoapServer('http://www.mysite.com.au/web_services/hello.wsdl');
...
...
?>

<?php
// SOAP Client
 $client = new SoapClient('http://www.mysite.com.au/web_services/hello.wsdl');
...
...
?>

FYI im no SOAP expert but I hope this helps someone out ;)
Drydenmaker 13-Jan-2008 07:59
Working with a third party service I got: "SOAP-ERROR: Parsing Schema: unexpected <text> in restriction"

Thought it would be worth it to share.  What it is saying is that there is some text in an invalid place.  C# seems to ignore it, and if you are using nusoap it doesn't notice it either.  But what was causing my problem was something like:
<types>
    <schema ...

            <simpleType name="some type">
                <restriction base="xsd:string">
                    <enumeration value="foo"/>;
                </restriction>
            </simpleType>

Note the semicolon (;).  Filter that out and your good.
Dominik 07-Dec-2007 01:31
If you are working
- on localhost
- in WSDL mode
and encounter the following error when you try to connect the soap client with the soap server

Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host...

then change "localhost" to "127.0.0.1" in your WSDL file:
<soap:address location='http://127.0.0.1/soap-server.php'/>
AL13N 28-Nov-2007 04:05
this might be helpful, as it took quite some time for me to find this out:

if you're using some .wsdl and there's a sequence that can be there more than once (ie: maxOccurs > 1), you can specify an non-associative array for it if you have more than 1 items OR you could just specify the one item if there is only one:

<?php
'items' => array(
    array(
        'itemId' => 5,
        'name' => 'some name',
    ),
    array(
        'itemId' => 6,
        'name' => 'some other name',
    ),
),
?>

this also works:

<?php
'items' => array(
    'itemId' => 5,
    'name' => 'some name',
),
?>
Anonymous 26-Nov-2007 11:54
when dealing with wsdl and flash soap with php
(not exactly php, but proper wsdl - took me hours to figure it to work properly in flash webservice)

when naming definitions,
don't use "tns:" but use "typens:"

makesure your "definitions/targetNamespace"
is same as your "soap:body" namespace
example: "urn:mynamespace"

makesure your "binding/type" is declared with "typens"

makesure your service/port/binding is set to 'typens:...'

if you did not do it properly, you will end up with
WSDL.UnrecognizedNamespace - in flash
but seems okay in php soapclient...

happy coding :)
hope this help you to save your time on the wsdl :)
james at mercstudio dot com 24-Nov-2007 01:45
If you use wsdl,

makesure you define the input correctly.
if your method does not contain any input parameter,
you got to makesure that you:

 - do not create the message tag for the input..
 - do not put input within porttype / operation
 - do not put input within binding / operation

if not, you will get the error:
[Client] looks like we got no XML

d***, took me several hours figuring that out...
dirk at waferthin dot com 20-Jun-2007 04:31
I hope this will save someone time. When developing and testing your SOAP server, remember to disable WSDL caching in BOTH client and server:

$ini = ini_set("soap.wsdl_cache_enabled", 0);
jochen dot munz at municons dot com 11-Jun-2007 08:56
When encountering an error message like this

[faultstring] => Function ("yourMethod") is not a valid method for this service

although it is present in the WSDL etc., be aware that PHP caches the wsdl locally for better performance. You can disable the caching via php.ini/.htaccess completely or remove the cache file (/tmp/wsdl-.. if you are on Linux) to force regeneration of it.
albert at jool dot nl 27-Mar-2007 02:59
A note for ppl who use certificates with SOAP under a Windows config: it seems to be required to give the full path to the certificate file - and don't prepend 'file://' :

<?php

$wsdl = "test.wsdl";
$local_cert = "c:\htdocs\mycert.pem";
$passphrase = "xyz";

$client = new SoapClient($wsdl, array('local_cert' => $local_cert, 'passphrase' => $passphrase);

?>
kroesjnov at hotmail dot com 09-Feb-2007 07:38
If you dont want to manually maintain the classmap, make sure you use the same names for your PHP object classes and your WSDL complexTypes, and use the following code:

$classmap = array();
$tmpClient = new SoapClient("soapserver.wsdl");

foreach($tmpClient->__getTypes() as $type)
{
    $array = split(" ", $type);
    if($array[0] == "struct" && class_exists($array[1]))
    {
        $classmap[$array[1]] = $array[1];
    }
}
unset($tmpClient);

$server = new SoapServer("soapserver.wsdl", array("classmap" => $classmap));
unset($classmap);
$server->setClass("someclass");
$server->handle();
brephophagist 18-Jan-2007 09:45
For those working from a wsdl full of complex types that just want a class structure to hang your code on and not worry about typing in long parameter lists (or creating a script to do so): wsdl2php is a wonderful time-saver. Gets a structure going so you can go in and add what validation and special data munging you need: http://www.urdalen.no/wsdl2php/

Big up yourself, Knut.
Olaf Krische 21-Nov-2006 01:48
If you use SSL with a cert and password authentication:

$wsdl = "https://ws.ecopatz.de/ProductInfo?wsdl";
$pass = 'a password';
$certFile = "./mycert.pem";

  $client = new SoapClient($wsdl,
    array(
     'local_cert' => $certFile,
     'passphrase' => $pass
    )
  );

If you have problems with the certfile like this:

  Warning: SoapClient::__construct(): Unable to set local cert chain file `./mycert.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in productinfo.php on line 27

then the certFile is probably in the "wrong format" (the wrong format for php maybe). It worked for me, when i appended the content of the private key file and the certificate file to a single file "mycert.pem":

  cat mycert.key >mycert.pem # mycert.key was the private key
  cat mycert.crt >>mycert.pem # mycert.crt was the signed certificate

Thanks to an author somewhere, who pointed to "curl --cert", where this little "so unimportant" dependency has been mentioned.
nico 25-Aug-2006 06:20
If you want to build a Soap Server for Microsoft Office's client (like Microsoft Office Research Service) you need to rewrite SOAP's namespaces :

<?php
// (...)

$server = new SoapServer($wsdl, array('uri' => $uri, 'classmap' => $classmap));
$server->setClass($class);
function callback($buffer)
{
    $s = array('<ns1:RegistrationResponse>', 'ns1:', 'xmlns:ns1="urn:Microsoft.Search"');
    $r = array('<RegistrationResponse xmlns="urn:Microsoft.Search">', '', '');
   return (str_replace($s, $r, $buffer));
}
ob_start('callback');
$server->handle();
ob_end_flush();

// (...)
?>

There are a complete example at this URL : http://touv.ouvaton.org/article.php3?id_article=104
mini at freebsd dot org 08-Jul-2006 04:54
wokan at cox dot net is incorrect about the security of URI-passed values to HTTPS URIs.  HTTPS connections are HTTP inside SSL -- all of the HTTP traffic, including the request, are encrypted.
adm 01-Mar-2006 11:27
Wondering why the function you just added to your WSDL file is not available to your SOAP client? Turn off WSDL caching, which (as the documentation says) is on by default.

At the top of your script, use:

$ini = ini_set("soap.wsdl_cache_enabled","0");
ckl at ecw dot de 16-Jan-2006 11:54
To debug a SOAP service using SoapServer(), a WSDL file and Zend Studio Client/Server, you have to append ?start_debug=1&amp;debug_port=10000 to the service location:
--- snip ---
... method / service definition ....

<service name="SOAPService">
  <port
    name="SOAPServicePort"
    binding="typens:SOAPServiceBinding">
   <soap:address
   location="$URL?start_debug=1&amp;debug_port=10000"/>
  </port>
</service>
--- snap ---
Rui Martins 18-Dec-2005 08:33
Here's an example on how to pass ArrayOfAnyType arguments
containing complex types.

Suppose your WSDL file defines "http://any.url.com/" as the default namespace and a complex type "SomeComplexType".

If you want to call a WebServices which takes an ArrayOfAnyType argument of "SomeComplexType"s you need to perform the following:

<?php
// complexTypes being an array containing several instances of SomeComplexType

myWSParameter = array();
foreach (complexTypes as ct)
{
   // Don't misspell the type or the namespace. Also note that php won't assume the default namespace defined in the WSDL file.
   myWSParameter []= new SoapVar(ct, 0, "SomeComplexType", "http://any.url.com/");
}
?>

On the other hand, when a WebService returns an ArrayOfAnyType you have to do the following to access each of its elements.

<?php
// Here, we will be echoing each return item
$res = $someWS->myFunction($myArgs)

// If only one element is returned, an array won't be built
if (is_array(myFunctionResult->anyType))
{
   foreach (myFunctionResult->anyType as $soapVar)
   {
      echo $soapVar->enc_value;
   }
}
else
{
   echo myFunctionResult->anyType->enc_value;
}
?>

This has all been tested using a .NET WebService.
ChrisB 23-Oct-2005 11:03
Heads up for anyone using PHP Soap + Sessions + PEAR DB classes.

Every time you make a call, via the soap client to your web service, your PEAR DB session is put to sleep and it doesnt by default wake upon the next request.

To fix this I simply called my particular database close call ifx_close() below my $soap->handle();
Bob 11-Oct-2005 01:17
If you are scratching your head why NuSOAP not working on PHP 5.x , the reason is this built-in SOAP Extenstion uses same soapclient() class name as Nusoap.

replace 'soapclient' with 'soapclient_xxx'  in nusoap.php and you are good to go...
johnjawed at gmail dot com 22-Sep-2005 09:29
For those wondering on how to set attributes on nodes with PHP5 SOAP, it would be done as such:

<... soap env/header>
<foo bar="blah">12345</foo>

array("foo" => array("_" => 12345, "bar" => "blah"));
Darryl 20-Jul-2005 11:46
Having trouble passing complex types over SOAP using a PHP SoapServer in WSDL mode?  Not getting decoded properly?  This may be the solution you're looking for!

When using ComplexType in the schema portion of the WSDL file, You need use an additional step to tell PHP SOAP how to encode the objects.  The first method would be to explicitely encapsulate the object in a SoapVar object - telling PHP to use generalized SOAP encoding rules (which encodes all ComplexTypes as Structs).  This won't work, though, if the client is expecting the objects to be encoded according to the WSDL's schema.  So, The actual way to do this is:

* First, define a specific PHP class which is actually just a data structure holding the various properties, and the appropriate  ComplexType in the WSDL.

<?php
 class MyComplexDataType {
     public $myProperty1;
     public $myProperty2;
 }
?>
 <complexType name="MyWSDLStructure">
 <sequence>
    <element name="MyProperty1" type="xsd:integer"/>
    <element name="MyProperty2" type="xsd:string"/>
 </sequence>
 </complexType>

* Next, Tell the SoapServer when you initialize it to map these two structures together.

<?php
 $classmap = array('MyWSDLStructure' => 'MyComplexDataType');
 $server = new SoapServer("http://MyServer/MyService.wsdl", array('classmap' => $classmap))
?>

* Finally, have your method return an instance of your class directly, and let the SoapServer take care of encoding!

<?php
 public function MySoapCall() {
     $o = new MyComplexDataType();

     $o->myProperty1 = 1;
     $o->myProperty2 = "MyString";

     return $o
 }
?>
Jim Plush 12-Jul-2005 04:45
If you're trying to use the SOAP Extension over SSL with a custom PEM file you need to do this:

$client->_local_cert = "C:\\path\myCert.pem";
flobee at gmail dot com 11-May-2005 01:25
wow, actually a cool program and soap is new for me.
I found out some interessting things i can not debug because the scripts exit without any error messages or notes. :-(

you may have problems with the memory and/or especially on "shared servers" when server load is high.
sometimes the script does the job, sometimes it just stopping at any unknown point.
these are the steps my script does:
* get data from remote server ( ~ 4.5 MB)
* parsing requested object and store the data in a database.

the return with debug messages was intressting:
-> check Mem limit: 30M
-> $client = new new SoapClient($url_wsdl, $options);
-> Memory usage: 185888
-> $client->[requested_method_to_get_data]();
-> check: __getLastResponseHeaders() - after:
-> HTTP/1.1 200 OK // remote server is fine with me :-)
-> Content-Length: 4586742  // I got the data
-> check: Memory usage now: 23098872 // ups !!! this can't be true!!

so, and if now someone on the server takes the rest of RAM  the walk thought the data breaks :-(

so, i need to store the xml tree ($client->client->__last_response) and parsing it by the classical way. (if you would request more RAM, you may get in trouble with the admin if you run a script like this more often! (on shared servers)
OrionI 18-Apr-2005 08:12
If you're having problems calling a .NET web service, see the comments over on http://php.net/soap_soapclient_soapcall (the __soapCall method).
kucerar at hhmi dot org 25-Mar-2005 12:04
Here are 73 test cases that detail the kinds of schemas that PHP5 currently supports and the structures you are expected to plug into them for the return value from your services.   Much better than trying to guess!

http://cvs.php.net/co.php/pecl/soap/tests/schema

You can cycle through the listings by changing the main index in the URL below,  rather than go in and out of the pages

http://cvs.php.net/co.php/pecl/soap/tests/schema/schema052.phpt?r=1.2

I downloaded the whole thing with this,  CVS might work too.
http://www.httrack.com/

With them all downloaded I just browse them with Textpad.
Norman Clarke <norman at dontblink dot com> 21-Feb-2005 04:29
Note that if you should need to set the timeout for your soap request,  you can use ini_set to change the value for the default_socket_timeout. I previously used NuSOAP, whose soap client class has a timeout option, and it took me a while to figure out that PHP's soap uses the same socket options as everything else.
wokan at cox dot net 05-Feb-2005 05:06
It's not good security practice to pass the username and password in the URI when the point of SSL is to prevent that information from being intercepted.  Putting that information in the URI makes it interceptable.  HTTPS-Posted values are safe because values passed in the headers are sent after the SSL handshake has been completed.
mikx at mikx dot de 29-Mar-2004 08:12
It took me a while to properly establish a password protected client connection via https on windows/apache1.3. Here my little guide:

1. The SOAP extension isn't activated by default (PHP5 RC1). Just add "extension=php_soap.dll" to the php.ini and don't forget to set the extension_dir properly (in most cases "c:\php\ext").

2. Add "extension=php_openssl.dll" to the php.ini. This module depends on libeay32.dll and ssleay32.dll - copy them from your php folder to your system32 folder.

3. Restart apache

4. The sourcecode

$client = new SoapClient("https://yourLogin:yourPassword@foo.com/bar.wsdl", array(
    "login"      => "yourLogin",
    "password"   => "yourPassword",
    "trace"      => 1,
    "exceptions" => 0));

$client->yourFunction();

print "<pre>\n";
print "Request: \n".htmlspecialchars($client->__getLastRequest()) ."\n";
print "Response: \n".htmlspecialchars($client->__getLastResponse())."\n";
print "</pre>";

Currently it seems to be necessary to add your login and password both in the uri and in the options array. Not sure if this is the expected behavior.


Checks if a SOAP call has failed

  • ? SOAP 函数
  • use_soap_error_handler ?
  • PHP Manual
  • SOAP 函数
  • Checks if a SOAP call has failed

is_soap_fault

(PHP 5, PHP 7, PHP 8)

is_soap_fault — Checks if a SOAP call has failed

说明

is_soap_fault ( mixed $object ) : bool

This function is useful to check if the SOAP call failed, but without using exceptions. To use it, create a SoapClient object with the exceptions option set to zero or false. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).

If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.

参数

object

The object to test.

返回值

This will return true on error, and false otherwise.

范例

Example #1 is_soap_fault() example

<?php
$client = new SoapClient("some.wsdl", array('exceptions' => 0));
$result = $client->SomeFunction();
if (is_soap_fault($result)) {
    trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
}
?>

Example #2 SOAP's standard method for error reporting is exceptions

<?php
try {
    $client = new SoapClient("some.wsdl");
    $result = $client->SomeFunction(/* ... */);
} catch (SoapFault $fault) {
    trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
}
?>

参见

  • SoapClient::__construct() - SoapClient constructor
  • SoapFault::__construct() - SoapFault constructor

User Contributed Notes

There are no user contributed notes for this page.


Set whether to use the SOAP error handler

  • ? is_soap_fault
  • SoapClient ?
  • PHP Manual
  • SOAP 函数
  • Set whether to use the SOAP error handler

use_soap_error_handler

(PHP 5, PHP 7, PHP 8)

use_soap_error_handler — Set whether to use the SOAP error handler

说明

use_soap_error_handler ( bool $enable = true ) : bool

This function sets whether or not to use the SOAP error handler in the SOAP server. It will return the previous value. If set to true, details of errors in a SoapServer application will be sent to the client as a SOAP fault message. If false, the standard PHP error handler is used. The default is to send error to the client as SOAP fault message.

参数

enable

Set to true to send error details to clients.

返回值

Returns the original value.

参见

  • set_error_handler() - 设置用户自定义的错误处理函数
  • set_exception_handler() - 设置用户自定义的异常处理函数

User Contributed Notes

There are no user contributed notes for this page.


The SoapClient class

(PHP 5, PHP 7, PHP 8)

简介

The SoapClient class provides a client for » SOAP 1.1, » SOAP 1.2 servers. It can be used in WSDL or non-WSDL mode.

类摘要

SoapClient {
/* 方法 */
public __construct ( string|null $wsdl , array $options = [] )
public __call ( string $name , array $args ) : mixed
public __doRequest ( string $request , string $location , string $action , int $version , bool $oneWay = false ) : string|null
public __getCookies ( ) : array
public __getFunctions ( ) : array|null
public __getLastRequest ( ) : string|null
public __getLastRequestHeaders ( ) : string|null
public __getLastResponse ( ) : string|null
public __getLastResponseHeaders ( ) : string|null
public __getTypes ( ) : array|null
public __setCookie ( string $name , string|null $value = null ) : void
public __setLocation ( string $location = "" ) : string|null
public __setSoapHeaders ( SoapHeader|array|null $headers = null ) : bool
public __soapCall ( string $name , array $args , array|null $options = null , SoapHeader|array|null $inputHeaders = null , array &$outputHeaders = null ) : mixed
}

Table of Contents

  • SoapClient::__call — Calls a SOAP function (deprecated)
  • SoapClient::__construct — SoapClient constructor
  • SoapClient::__doRequest — Performs a SOAP request
  • SoapClient::__getCookies — Get list of cookies
  • SoapClient::__getFunctions — Returns list of available SOAP functions
  • SoapClient::__getLastRequest — Returns last SOAP request
  • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse — Returns last SOAP response
  • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
  • SoapClient::__getTypes — Returns a list of SOAP types
  • SoapClient::__setCookie — Defines a cookie for SOAP requests
  • SoapClient::__setLocation — Sets the location of the Web service to use
  • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
  • SoapClient::__soapCall — Calls a SOAP function

User Contributed Notes

David 15-Feb-2017 12:57
Under IIS and PHP 7, when creating an new SoapClient, it will through an internal 500 error.

This could be caused by invalid permissions to the wsdl cache directory when using 'cache_wsdl'=>WSDL_CACHE_DISK or WSDL_CACHE_BOTH.

This worked for me:
    try {
        $arrContextOptions=array("ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false,'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT));

        $options = array(
                'soap_version'=>SOAP_1_2,
                'exceptions'=>true,
                'trace'=>1,
                'cache_wsdl'=>WSDL_CACHE_NONE,
                'stream_context' => stream_context_create($arrContextOptions)
        );
        $client = new SoapClient('https://url/dir/file.wsdl', $options);

    } catch (Exception $e) {
        echo "<h2>Exception Error!</h2>";
        echo $e->getMessage();
    }
sheikh303 at gmail dot com 13-Jan-2017 07:51
What is the core method to call remote WSDL file while creating SoapClient object?
is it CURL, wget or anyother?
Ricardo Pedrassani 03-Jun-2016 01:53
If the XML have identities with same name in different levels there is a solution. You don′t have to ever submit a raw XML (this PHP SOAP object don′t allows send a RAW XML), so you have to always translate your XML to a array, like the example below:

$originalXML = "
<xml>
  <firstClient>
      <name>someone</name>
      <adress>R. 1001</adress>
  </firstClient>
  <secondClient>
      <name>another one</name>
      <adress></adress>
  </secondClient>
</xml>"

//Translate the XML above in a array, like PHP SOAP function requires
$myParams = array('firstClient' => array('name' => 'someone',
                                  'adress' => 'R. 1001'),
            'secondClient' => array('name' => 'another one',
                                  'adress' => ''));

$webService = new SoapClient($someURL);
$result = $webService->someWebServiceFunction($myParams);
mcinantyspam at fejm dot pl 13-May-2016 11:32
Please note, that if you provide values that contain illegal xml characters (ASCII codes 0-8,  11-12, 14-15 - or x0-x8, xB-xC, xE-xF in hex), php's SoapClient will do send them in request, although such request is improper because it does not meet XML 1.0 requirements.
You always have to replace or remove these characters in your data before supplying them to SoapClient
info at nospam x valiton x com 13-Apr-2015 08:06
CAUTION:
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url.  I kept getting a 400 Bad Request back from the remote host.  It was receiving the proxy url as the SNI host.  In order to get around this I had to explicity set the SNI host to the domain I was trying to reach.  It's apparently the issue outlined in this bug:

https://bugs.php.net/bug.php?id=63519

<?php
$domain = parse_url($file, PHP_URL_HOST);
$proxy_string = "tcp://" . WP_PROXY_HOST  . ":" . WP_PROXY_PORT;
$opts = array(
    'http' => array( 'proxy' => $proxy_string ),
    'ssl' => array( 'SNI_enabled' => true, 'SNI_server_name' => $domain));
$context = stream_context_create($opts);
$handle = fopen( $file, 'r', false, $context );
?>

src:
http://php.net/manual/en/context.http.php#114314
acopantepuy at gmail dot com 11-Apr-2015 02:45
when they want to pass variables into the http header that is how it is done:

<?php

$aHTTP['http']['header'] =  "User-Agent: PHP-SOAP/5.5.11\r\n";

$aHTTP['http']['header'].= "username: XXXXXXXXXXX\r\n"."password: XXXXX\r\n";

$context = stream_context_create($aHTTP);

$client=new SoapClient("https://ocppws-cert.extra.bcv.org.ve:443/AltoValor/BancoUniversal?WSDL",array('trace' => 1,"stream_context" => $context));

$result = $client->jornadaActiva();
var_dump($result);
?>
acopantepuy at gmail dot com 11-Apr-2015 02:42
when they want to pass variables into the http header that is how it is done:

<?php

$aHTTP['http']['header'] =  "User-Agent: PHP-SOAP/5.5.11\r\n";

$aHTTP['http']['header'].= "username: C1040001760102\r\n"."password: bcv2020\r\n";

$context = stream_context_create($aHTTP);

$client=new SoapClient("https://ocppws-cert.extra.bcv.org.ve:443/AltoValor/BancoUniversal?WSDL",array('trace' => 1,"stream_context" => $context));

$result = $client->jornadaActiva();
var_dump($result);
?>
romuloum at hotmail dot com 19-Feb-2015 04:22
After migrating to PHP 5.6.5, the soap 1.2 did not work anymore. So I solved the problem by adding optional parameters SSL.
My error: failed to load external entity
How to solve:
        // options for ssl in php 5.6.5
        $opts = array(
            'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)
        );
        // SOAP 1.2 client
        $params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );
        $oSoapClient = new SoapClient ( $url . "?WSDL", $params );
softontherocks at gmail dot com 22-Nov-2014 08:32
I posted in this URL http://softontherocks.blogspot.com/2014/02/web-service-soap-con-php.html a full example of a nusoap web service.

There is defined the server and the cliente who calls the web service.

I hope it would be useful for you.
martin dot schenck at plugsurfing dot com 15-Sep-2014 03:34
If you want to connect to a server that only supports SSLv2/3 and/or TLS 1.0 (no TLS 2 or 3), tell the SOAP client if you get a connection error by setting the appropriate stream context:
<?php
  $opts = array(
    'ssl' => array('ciphers'=>'RC4-SHA')
  );

  $objSoapClient = new SoapClient(
    'https://example.com/?wsdl',
    array ( "encoding"=>"ISO-8859-1",
    'stream_context' => stream_context_create($opts)
    // your options
    );
?>

You might need to disable the SOAP caching of WSDLs in order for the SOAP client to use the new context.
Stefan 03-Jun-2014 11:04
There is a known bug with some versions of Xdebug which can cause SoapClient to not throw an exception but instead cause a fatal error.

Surround the SoapClient call with xdebug_disable(); and xdebug_enable();  to work around this problem.

For reference:

http://bugs.xdebug.org/view.php?id=249
https://bugs.php.net/bug.php?id=47584
Anonymous 12-Sep-2013 09:25
I got the following error when trying to load the WSDL file:

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: <message> 'MessageName' already defined

In my case there was no double definitions but it was including other files - I think one of them contained a duplicate message with a different namespace (which SoapClient doesn't like).

I resolved it by loading the WSDL in SoapUI, right-clicking and selecting "Export definition". The WSDL that then got created worked fine. Hope this helps somebody.
Guillermo Prandi 20-Feb-2012 02:10
To make an HTTPS call with a client certificate, you can do it this way:

1) Create a file containing both the key and the signed certificate. I did this by concatenating my (.pem) key and the certificate I've got signed from my CA (also .pem format). The file looked like this:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKagQC1N27Ilb9pWil2NaX2qM8FquXBXK5T1AydOv7sCotsc8MAwbi7
......(snip)......
wAiOCD4K9TyMS76pIS8UyfJl/oIrn7EF24BUpaUfsh8=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIC/zCCAmigAwIBAgIEAIl1JzANBgkqhkiG9w0BAQQuADBQMQswCQYxVQQGEaJV
......(snip)......
eSPds1hLKYSg0bd3uI7LhaDLOC1PPgb77sYe/uYkUWuHBzllts5x/pfue0zaIBKG
Omjy
-----END CERTIFICATE-----

2) Reference your certificate in the creation of the SOAP client, like this:

$protected_url = "https://my-server/?wsdl";
$my_cert_file = "/my/path/to/mycert.pem";

$client = new SoapClient($protected_url, array('local_cert', $my_cert_file) );
egiardina at badatmath dot com 03-Aug-2011 06:05
This one drove me nuts... if you are connecting to a web service run on Cassini, (Visual Studio's web server) from php, you may not be able to call web service functions or load a WSDL out-of-the-box.

My set up is that I am using xampp on my windows development machine, and also using Visual Studio's built in web-server. I built a web service in visual studio. I wrote a simple PHP script, running under xampp, to access this service, so the two projects can 'talk' to each other. What I found was the WSDL was never loaded.

So I moved the WSDL local to the PHP file and accessed it directly. Still no calls. Turns out, PHP's SoapClient seems to have a problem with 'localhost' as a web service endpoint. So I hand-edited the web service endpoint URL to read 127.0.0.1 instead of localhost, and Voila! Web Service calls work:

Here is my PHP, now working:
<?php
$client = new SoapClient("http://localhost/code/soap.wsdl");
$something =  $client->HelloWorld(array());
echo $something->HelloWorldResult;
die();

?>

Here is my modified WSDL:
  <wsdl:service name="MyService">
    <wsdl:port name="MyServiceSoap" binding="tns:MyServiceSoap">
      <soap:address location="http://127.0.0.1:55274/MyService/MyService.asmx" />
....

    </wsdl:port>
stepan dot zarubin at gmail dot com 30-Jun-2011 11:51
Well, this example works fine:

<?php
try {
    $x = @new SoapClient("non-existent.wsdl");
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Just make sure use NEW with @.
jjlopez 09-Mar-2011 11:36
If you are making soap calls in WSDL mode , and the address of your web service includes a port different from 80 (like http://my_ip_address:8080//service.asmx?wsdl), the WSDL file is fetched correctly, but all subsequent requests are made without any port in the host field. This causes a SoapFault exception when trying to call any of the service's methods.

You need to redefine the soapClient class and force the port in each call.

See this example:

http://www.victorstanciu.ro/php-soapclient-port-bug-workaround/
hugues at zonereseau dot com 17-Feb-2011 09:17
When you need to connect to services requiring to send extra header use this method.

Here how we can to it with PHP and SoapClient

<?php
class exampleChannelAdvisorAuth
{
    public $DeveloperKey;
    public $Password;

    public function __construct($key, $pass)
    {
        $this->DeveloperKey = $key;
        $this->Password = $pass;
    }
}

$devKey        = "";
$password    = "";
$accountId    = "";

// Create the SoapClient instance
$url         = "";
$client     = new SoapClient($url, array("trace" => 1, "exception" => 0));

// Create the header
$auth         = new ChannelAdvisorAuth($devKey, $password);
$header     = new SoapHeader("http://www.example.com/webservices/", "APICredentials", $auth, false);

// Call wsdl function
$result = $client->__soapCall("DeleteMarketplaceAd", array(
    "DeleteMarketplaceAd" => array(
        "accountID"        => $accountId,
        "marketplaceAdID"    => "9938745"        // The ads ID
    )
), NULL, $header);

// Echo the result
echo "<pre>".print_r($result, true)."</pre>";
if($result->DeleteMarketplaceAdResult->Status == "Success")
{
    echo "Item deleted!";
}
?>
fourat dot zouari at tritux dot com 20-Jun-2009 08:08
In addition to the KeepAlive trick which is a "server-side" modification, on the "client side" default_socket_timeout should be increased from its default value (60) when you deal with ~slow SOAP servers.
As for the KeepAlive, if creating a new separate vhost for the soap api is not possible, you can add this to your existing vhost: BrowserMatch "^PHP-SOAP" nokeepalive
where PHP-SOAP is the agent name of your soap client, if you dont know what agent name your client use, just checkout the access.log of your apache.
peter dot hansen at fastit dot net 01-May-2009 06:57
When you get errors like:
"Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in"
after a few (time intensive) SOAP-Calls, check your webserver-config.

Sometimes the webservers "KeepAlive"-Setting tends to result in this error. For SOAP-Environments I recommend you to disable KeepAlive.

Hint: It might be tricky to create a dedicated vhost for your SOAP-Gateways and disable keepalive just for this vhost because for normal webpages Keepalive is a nice speed-boost.


Calls a SOAP function (deprecated)

  • ? SoapClient
  • SoapClient::__construct ?
  • PHP Manual
  • SoapClient
  • Calls a SOAP function (deprecated)

SoapClient::__call

(PHP 5, PHP 7, PHP 8)

SoapClient::__call — Calls a SOAP function (deprecated)

说明

public SoapClient::__call ( string $name , array $args ) : mixed

Calling this method directly is deprecated. Usually, SOAP functions can be called as methods of the SoapClient object; in situations where this is not possible or additional options are needed, use SoapClient::__soapCall().

User Contributed Notes

philipp dot gruber at catchoftheday dot com dot au 07-Apr-2014 12:27
If you are using a WSDL, the library will strip out anything from your parameters that is not defined in WSDL, without giving you any notice about this.

So if your parameters are not fully matching the WSDL, it will simply send no parameters at all.
This can be a bit hard to debug if you don't have access to the target server.

__soapCall() expects parameters in an array called 'parameters' as opposed to calling the function via it's WSDL name, where it accepts the parameters as a plain array.

I.e. if a function called sendOrder expects a parameter (array) called orderDetails, you can call it like this:

$orderDetails = array(/* your data */);
$soap->sendOrder(array('orderDetails' => $orderDetails));

Which is equivalent to:

$client->__soapCall('sendOrder', array('parameters' => array('orderDetails' => $orderDetails)));

Note the additional 'parameters' key used in __soapCall().
KRavEN 17-Jun-2009 06:56
extend of __call thats adds a retry to handle the occasional 'Could not connect to host' exceptions

<?php
class LocalSoapClient extends SoapClient
{

  public function __call($function_name, $arguments)
  {
    $result = false;
    $max_retries = 5;
    $retry_count = 0;

    while(! $result && $retry_count < $max_retries)
    {
      try
      {
        $result = parent::__call($function_name, $arguments);
      }
      catch(SoapFault $fault)
      {
        if($fault->faultstring != 'Could not connect to host')
        {
          throw $fault;
        }
      }
      sleep(1);
      $retry_count ++;
    }
    if($retry_count == $max_retries)
    {
      throw new SoapFault('Could not connect to host after 5 attempts');
    }
    return $result;
  }
}
?>
bananos at dev dot co dot ua 11-Apr-2008 05:13
I'm writing PHP SOAP client (based on php_soap extension) which uses Google AdService,
today, I tried to create sample Ad using   AdService::addAds()  and discovered that my SOAP library does not pass
"headline", "description1", "description2"  parameters in SOAP request.

First, I thought that this was something wrong with my data, coz I was getting validation errors like
"One or more input elements failed validation."   Then I decided to take a look at WSDL description
https://adwords.google.com/api/adwords/v11/AdService?wsdl

And voilà !  I've found this:

<complexType name="Ad" abstract="true">
<sequence>
  <element name="adGroupId" type="xsd:int"/>
  <element name="adType" nillable="true" minOccurs="0" type="impl:AdType"/>
  <element name="destinationUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="disapproved" type="xsd:boolean"/>
  <element name="displayUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="exemptionRequest" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="id" type="xsd:long"/>
  <element name="status" nillable="true" minOccurs="0" type="impl:AdStatus"/>
</sequence>

</complexType>

There is no any ''description", "headline1", "headline2", however there is another complexType

<complexType name="TextAd">
    <complexContent>
    <extension base="impl:Ad">
    <sequence>

<element name="description1" nillable="true" type="xsd:string"/>
<element name="description2" nillable="true" type="xsd:string"/>
<element name="headline" nillable="true" type="xsd:string"/>
</sequence>

</extension>
</complexContent>
</complexType>

So, the thing is when you are working with php_soap be aware of complexType extensions which does not work in php_soap when you try to do things like:

<?php

$client = new
    SoapClient(
       "https://adwords.google.com/api/adwords/v11/AdService?wsdl",
        array(  'trace'      => true,
                'exceptions' => true,
             )

    );

$entropy     = substr(md5(rand(0, time())), 0, 10);
//create Ad test structure
$sample_ad =  array(
               "id" => 0,
               "adGroupId" => 0,
               "adType" => 'TextAd',
               "disapproved" => false,
               "destinationUrl" => 'http://test.com',
               "displayUrl" => 'www.Test.com',
               "status" => "Paused", //  Enabled / Disabled
               "descr_iption1" => 'D1_'.$entropy,
               "des_cription2" => 'D2_'.$entropy,
               "head_line" => 'H_'.$entropy
        );

$client->addAds(array('ads' => array($sample_ad) );
?>
Samil Abud 19-Dec-2007 12:00
Hi,
This is a good example, for the SOAP function "__call".
However it is deprecated.

<?php
$wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
$int_zona = 5;
$int_peso = 1001;
$cliente = new SoapClient($wsdl);
print "<p>Envio Internacional: ";
$vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
print $vem;
print "</p>";
?>


SoapClient constructor

  • ? SoapClient::__call
  • SoapClient::__doRequest ?
  • PHP Manual
  • SoapClient
  • SoapClient constructor

SoapClient::__construct

(PHP 5, PHP 7, PHP 8)

SoapClient::__construct — SoapClient constructor

说明

public SoapClient::__construct ( string|null $wsdl , array $options = [] )

This constructor creates SoapClient objects in WSDL or non-WSDL mode.

参数

wsdl

URI of the WSDL file or null if working in non-WSDL mode.

Note:

During development, WSDL caching may be disabled by the use of the soap.wsdl_cache_ttl php.ini setting otherwise changes made to the WSDL file will have no effect until soap.wsdl_cache_ttl is expired.

options

An array of options. If working in WSDL mode, this parameter is optional. If working in non-WSDL mode, the location and uri options must be set, where location is the URL of the SOAP server to send the request to, and uri is the target namespace of the SOAP service.

The style and use options only work in non-WSDL mode. In WSDL mode, they come from the WSDL file.

The soap_version option should be one of either SOAP_1_1 or SOAP_1_2 to select SOAP 1.1 or 1.2, respectively. If omitted, 1.1 is used.

For HTTP authentication, the login and password options can be used to supply credentials. For making an HTTP connection through a proxy server, the options proxy_host, proxy_port, proxy_login and proxy_password are also available. For HTTPS client certificate authentication use local_cert and passphrase options. An authentication may be supplied in the authentication option. The authentication method may be either SOAP_AUTHENTICATION_BASIC (default) or SOAP_AUTHENTICATION_DIGEST.

The compression option allows to use compression of HTTP SOAP requests and responses.

The encoding option defines internal character encoding. This option does not change the encoding of SOAP requests (it is always utf-8), but converts strings into it.

The trace option enables tracing of request so faults can be backtraced. This defaults to false

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

Setting the boolean trace option enables use of the
methods
SoapClient->__getLastRequest,

SoapClient->__getLastRequestHeaders,

SoapClient->__getLastResponse and

SoapClient->__getLastResponseHeaders.

The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault.

The connection_timeout option defines a timeout in seconds for the connection to the SOAP service. This option does not define a timeout for services with slow responses. To limit the time to wait for calls to finish the default_socket_timeout setting is available.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

The user_agent option specifies string to use in User-Agent header.

The stream_context option is a resource for context.

The features option is a bitmask of SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE, SOAP_WAIT_ONE_WAY_CALLS.

The keep_alive option is a boolean value defining whether to send the Connection: Keep-Alive header or Connection: close.

The ssl_method option is one of SOAP_SSL_METHOD_TLS, SOAP_SSL_METHOD_SSLv2, SOAP_SSL_METHOD_SSLv3 or SOAP_SSL_METHOD_SSLv23.

错误／异常

SoapClient::__construct() will generate an E_ERROR error if the location and uri options aren't provided in non-WSDL mode.

A SoapFault exception will be thrown if the wsdl URI cannot be loaded.

范例

Example #1 SoapClient::__construct() example

<?php

$client = new SoapClient("some.wsdl");

$client = new SoapClient("some.wsdl", array('soap_version'   => SOAP_1_2));

$client = new SoapClient("some.wsdl", array('login'          => "some_name",
                                            'password'       => "some_password"));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080,
                                            'proxy_login'    => "some_name",
                                            'proxy_password' => "some_password"));

$client = new SoapClient("some.wsdl", array('local_cert'     => "cert_key.pem"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/",
                                     'style'    => SOAP_DOCUMENT,
                                     'use'      => SOAP_LITERAL));

$client = new SoapClient("some.wsdl",
  array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));

$client = new SoapClient("some.wsdl", array('encoding'=>'ISO-8859-1'));

class MyBook {
    public $title;
    public $author;
}

$client = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

User Contributed Notes

There are no user contributed notes for this page.


Performs a SOAP request

  • ? SoapClient::__construct
  • SoapClient::__getCookies ?
  • PHP Manual
  • SoapClient
  • Performs a SOAP request

SoapClient::__doRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__doRequest — Performs a SOAP request

说明

public SoapClient::__doRequest ( string $request , string $location , string $action , int $version , bool $oneWay = false ) : string|null

Performs SOAP request over HTTP.

This method can be overridden in subclasses to implement different transport layers, perform additional XML processing or other purpose.

参数

request

The XML SOAP request.

location

The URL to request.

action

The SOAP action.

version

The SOAP version.

oneWay

If one_way is set to 1, this method returns nothing. Use this where a response is not expected.

返回值

The XML SOAP response.

更新日志

版本 | 说明
8.0.0 | The type of oneWay is bool now; formerly it was int.

范例

Example #1 SoapClient::__doRequest() example

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version, $one_way = 0) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));
var_dump($x->Add(3,4));
?>

User Contributed Notes

tschallacka 22-Mar-2016 02:01
I just wanted to note in plain english how to build up this request, because I made some assumptions by just misterpreting the parameters.

This is for future reference(for myself) and others that might end up a bit mistified by just not understanding the finesses of soap and are trying to learn.

    $this->__doRequest(string $request , string $location , string $action , int $version [, int $one_way = 0 ] );

$request = The XML Soap enveloppe
$location = The url to the WSDL file. No matter that you defined this before when setting up the object, you need to reuse it here.
$action = the soap action to be performed. This is defined in the wsdl file and can be in the form of a single form or an url. it's just a parameter and might not be an actual valid url
$version = SOAP_1_1 =  content headers (Content-Type: text/xml; CHARSET=gb2312?)
                  SOAP_1_2 = content headers (Content-Type: application/soap+xml; CHARSET=gb2312; action="somesoapaction defined in $action")

If you send a SOAP_1_2 request to a SOAP_1_1 server you might get a reply in the following form

    HTTP/1.1 415 Cannot process the message because the content type 'application/soap+xml; CHARSET=gb2312; action="somesoapaction defined in $action"' was not the expected type 'text/xml; CHARSET=gb2312'.

You need to switch down to SOAP_1_1 in that case to get the proper formatting the server can understand
tbernard at qcsupply dot com 02-Feb-2015 05:08
If you're having trouble connecting to an authenticated SOAP service there's something important to note here.

__doRequest() is only used when a SOAPClient function is called, NOT when the WSDL if fetched and parsed.  That means if your WSDL file is not publicly accessible but also resides behind your authentication it won't be accessible by default.  Instead you'll have to create an overloaded stream wrapper and register it for whatever protocol (probably HTTP) you'll be using.
darren dot yee at emc dot com 13-Mar-2013 10:45
Note when extending __doRequest, calling __getLastRequest will probably report incorrect information unless you make sure to update the internal __last_request variable. Save yourself some headaches.

function __doRequest($request, $location, $action, $version) {
      $request = preg_replace('/abc/', 'def', $request);
      $ret = parent::__doRequest($request, $location, $action, $version);
      $this->__last_request = $request;
      return $ret;
}
alireza dot meskin at gmail 02-Apr-2012 12:29
Change Blocking mode for Socket stream and set Timeout for Soap requests

<?php

class TimeoutSoapClient extends SoapClient
{
    const TIMEOUT = 20;
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $url_parts = parse_url($location);
        $host = $url_parts['host'];
        $http_req = 'POST '.$location.' HTTP/1.0'."\r\n";
        $http_req .= 'Host: '.$host."\r\n";
        $http_req .= 'SoapAction: '.$action."\r\n";
        $http_req .= "\r\n";
        $http_req .= $request;
        $port = 80;
        if ($url_parts['scheme'] == 'https')
        {
            $port = 443;
            $host = 'ssl://'.$host;
        }
        $socket = fsockopen($host, $port);
        fwrite($socket, $request);
        stream_set_blocking($socket, false);
        $response = '';
        $stop = microtime(true) + self::TIMEOUT;
        while (!feof($socket))
        {
            $response .= fread($socket, 2000);
            if (microtime(true) > $stop)
            {
                throw new SoapFault('Client', 'HTTP timeout');
            }
        }
        return $response;
    }
}
bwhitehead at tableausoftware dot no dot com dot spam 12-Aug-2011 02:49
Note that the SoapClient.__doRequest() method circumvents the throwing of SoapFault exceptions.

Specifically, if you call the __doRequest() method and it fails, it would normally throw a SoapFault exception.  However, the __doRequest() method doesn't actually throw the exception. Instead, the exception is saved in a class attribute called SoapFault.__soap_fault, and is actually thrown AFTER the __doRequest method completes (but the call stack will show that the exception was created inside the __doRequest method.

I successfully used the following code to query the locally cached exception object that was not thrown:

<?php
$exception = null;
try {
    $result = parent::__doRequest($request, $location, $action, $version, $one_way);
}
catch (SoapFault $sf) {
    //this code was not reached
    $exception = $sf;
}
catch (Exception $e) {
    //nor was this code reached either
    $exception = $e;
}
if((isset($this->__soap_fault)) && ($this->__soap_fault != null)) {
    //this is where the exception from __doRequest is stored
    $exception = $this->__soap_fault;
}

//decide what to do about the exception here
// [enter code here]
//or throw the exception
if($exception != null) {
    throw $exception;
}
//note: you may want to unset the __soap_fault value if you don't want it thrown again up the call stack
?>
psfere at hotmail dot com 21-Sep-2010 09:52
I was needing to add a blank soap header (<SOAP-ENV:Header /> and found no other place that has done this.  The only way I was able to support this was to extend SoapClient and re-define __doRequest.  Hope this helps someone or if there is support for this in the library, please point me in the right direction:

<?php
class MySoapCli extends SoapClient {
  function __doRequest($request, $location, $action, $version) {
    $dom = new DomDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($request);
    $hdr = $dom->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'SOAP-ENV:Header');
    $dom->documentElement->insertBefore($hdr, $dom->documentElement->firstChild);
    $request = $dom->saveXML();
    return parent::__doRequest($request, $location, $action, $version);
  }
}
?>
lepidosteus 19-Nov-2009 02:59
If you happen to get an error during your request which says "SOAP-ERROR: Encoding: Can't decode apache map, only Strings or Longs are allowd as keys", the reason seems to be the response xml using integer for keys and php failling to understand them

Here is something that worked for me (converts integer keys to strings):

<?php
class mySoap extends SoapClient
{
    public function __doRequest($request, $location, $action, $version)
    {
        $result = parent::__doRequest($request, $location, $action, $version);
        $result = str_replace('<key xsi:type="xsd:int">', '<key xsi:type="xsd:string">', $result);
        return $result;
    }
}

// $soap = new mySoap(...
?>
Artur Graniszewski 08-Nov-2009 04:35
Beware of PHP incosistent behaviour in __doRequest() method. It seems that some arguments passed to this method are passed by reference!

If you try to create your own __doRequest() method and store it's arguments as SoapClient properties you will find that after __soapCall all of them will be null or unknown.

<?php
    protected $__soapAction = '';

    public function __doRequest($request, $location, $action, $version, $oneWay = 0) {
        ob_start();
        $this->server->handle($request);
        $response = ob_get_contents();
        ob_end_clean();
        $this->__soapAction = $action;
        return $response;
    }
?>

In above example $this->__soapAction will be null after $obj->__soapCall()..

To store $action value, you must cast it to a string (so PHP will be forced to create a new variable with different memory pointer):

<?php
    public function __doRequest($request, $location, $action, $version, $oneWay = 0) {
        ob_start();
        $this->server->handle($request);
        $response = ob_get_contents();
        ob_end_clean();
        $this->__soapAction = (string)$action;
        return $response;
    }
?>
james dot ellis at gmail dot com 04-Feb-2008 04:12
If your application interacts with SOAP services and you wish to cache the responses for consumption later, then overriding SoapClient::__doRequest is the way to go.

For instance, if you know that the information presented doesn't change that often and you don't want to do a superfluous HTTP request, you can grab a response from a local cache and let SoapClient do the transformation to PHP data types.

<?php
class YourNamespace_SoapClient_Local extends SoapClient {
    protected $cacheDocument = "";
    public function __construct($wsdl, $options) {
        parent::__construct($wsdl, $options);
    }

    /**
     * SetCacheDocument() sets the previously cached document contents
     */
    public function SetCacheDocument($document) {
        $this->cacheDocument = $document;
    }

    /**
     * __doRequest() overrides the standard SoapClient to handle a local request
     */
    public function __doRequest() {
        return $this->cacheDocument;
    }
}

//---- code snippet showing usage within a class
//$document is a cached SOAP response document from a previous request, saved with SoapClient::__getLastResponse() to some cache somewhere
//for the purpose of this example, it is assumed that $this->wsdl, $this->options, $this->method and $this->params are set.

public function SoapRequest($document) {
    $method = $this->method;
    if($document == "") {
        //uncached
        try {
            //default options
            $client = new SoapClient($this->wsdl, $this->options);
            $result = $client->$method($this->params);
            //send the response to the cache
            $this->CacheResponse($client->__getLastResponse());
        } catch(SoapFault $fault) {
            //log something
            return FALSE;
        }
    } else {
        //cached document
        try {
            /**
             * the WSDL needs to be set to allow the method to be called on the client object
             * and to trigger SoapClient to decode the response to native data types
             */
            $client = new YourNamespace_SoapClient_Local($this->wsdl, $this->options);
            $client->SetCacheDocument($document);
            $result = $client->$method($this->params);
        } catch (SoapFault $fault) {
            //log something
            return FALSE;
        }
    }
    return $result;
}
?>

I'll leave you to work out the caching, plenty of options there.. ;)
albert at jool dot nl 26-Mar-2007 06:28
If you want to communicate with a default configured ASP.NET server with SOAP 1.1 support, override your __doRequest with the following code. Adjust the namespace parameter, and all is good to go.

<?php
class MSSoapClient extends SoapClient {

    function __doRequest($request, $location, $action, $version) {
        $namespace = "http://tempuri.com";

        $request = preg_replace('/<ns1:(\w+)/', '<$1 xmlns="'.$namespace.'"', $request, 1);
        $request = preg_replace('/<ns1:(\w+)/', '<$1', $request);
        $request = str_replace(array('/ns1:', 'xmlns:ns1="'.$namespace.'"'), array('/', ''), $request);

        // parent call
        return parent::__doRequest($request, $location, $action, $version);
    }
}

$client = new MSSoapClient(...);
?>

Hope this will save people endless hours of fiddling...
jfitz at spacelink dot com 05-Dec-2006 09:56
Note that __getLastRequest() data are buffered _before_ the call to __doRequest().  Thus any modifications you make to the XML while in __doRequest() will not be visible in the output of __getLastRequest().   This is so in at least v5.2.0
06-Jul-2006 01:17
Do you have problems with the PHP5 SoapClient when you need to send a request to a service with a ComplexType parameter?

Maybe because my service is build in Delphi with REMObjects SDK 3.0 I had the problems, maybe not. Anyway, this was my remedy:
<?php
$versie = new stdClass();//define a basic class object
$versie->versieID = $aVersie->versieID();//fill it with the exact attributes as your complextype Object in the wsdl is
$versie->versieNummer = $aVersie->versieNummer();
$versie->isActief = $aVersie->isActief();

$soapVersieType = new SoapVar($versie , SOAP_ENC_OBJECT, "Versie", "http://127.0.0.1:8999/SOAP?wsdl"); //create the complex soap type, Versie is the name of my complex type in the wsdl, the latter url beeing the location of my wsdl.

try{
  $result =  $soapClient->BewaarVersie($this->sessieId,$soapVersieType); //BewaarVersie is a function derived from my WSDL with two params.
}
catch(SoapFault $e){
  trigger_error('Something soapy went wrong: '.$e->faultstring,E_USER_WARNING);            }
?>
After some more testing i found out that the conversion to the StdClass() object was not required. My 'Versie' local object has the attributes for the 'Versie' wsdl complex type defined as private vars and give no pain when i create the SoapVar with an instance of the local 'Versie' Object.
metator at netcabo dot pt 20-Oct-2005 04:32
You can use this method to correct the SOAP request before sending it, if necessary. You can use the DOM API to accomplish that.

<?php

public ExtendedClient extends SoapClient {

   function __construct($wsdl, $options = null) {
      parent::__construct($wsdl, $options);
   }

   function __doRequest($request, $location, $action, $version) {
      $dom = new DOMDocument('1.0');

      try {

         //loads the SOAP request to the Document
         $dom->loadXML($request);

      } catch (DOMException $e) {
         die('Parse error with code ' . $e->code);
      }

      //create a XPath object to query the request
      $path = new DOMXPath($dom);

      //search for a node
      $nodesToFix = $path->query('//SOAP-ENV:Envelope/SOAP-ENV:Body/path/to/node');

      //check if nodes are ok
      $this->checkNodes($path, $nodesToFix);

      //save the modified SOAP request
      $request = $dom->saveXML();

      //doRequest
      return parent::__doRequest($request, $location, $action, $version);
   }

   function checkNodes(DOMXPath $path, DOMNodeList $nodes) {
      //iterate through the node list
      for ($i = 0; $ < $nodes->length; $i++) {
         $aNode = $nodes->item($i);

         //just an example
         if ($node->nodeValue == null) {
            //do something. For instance, let's remove it.
            $node->parentNode->removeChild($node);
         }
      }
   }
}
?>

This gives the developer the chance to solve interoperability problems with a web service.


Get list of cookies

  • ? SoapClient::__doRequest
  • SoapClient::__getFunctions ?
  • PHP Manual
  • SoapClient
  • Get list of cookies

SoapClient::__getCookies

(PHP 5 >= 5.4.30, PHP 7, PHP 8)

SoapClient::__getCookies — Get list of cookies

说明

public SoapClient::__getCookies ( ) : array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Returns list of available SOAP functions

  • ? SoapClient::__getCookies
  • SoapClient::__getLastRequest ?
  • PHP Manual
  • SoapClient
  • Returns list of available SOAP functions

SoapClient::__getFunctions

(PHP 5, PHP 7, PHP 8)

SoapClient::__getFunctions — Returns list of available SOAP functions

说明

public SoapClient::__getFunctions ( ) : array|null

Returns an array of functions described in the WSDL for the Web service.

Note:

此函数仅在 WSDL 模式下生效。

参数

此函数没有参数。

返回值

The array of SOAP function prototypes, detailing the return type, the function name and type-hinted parameters.

范例

Example #1 SoapClient::__getFunctions() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

以上例程会输出：

array(26) {
  [0]=>
  string(70) "ProductInfo KeywordSearchRequest(KeywordRequest $KeywordSearchRequest)"
  [1]=>
  string(79) "ProductInfo TextStreamSearchRequest(TextStreamRequest $TextStreamSearchRequest)"
  [2]=>
  string(64) "ProductInfo PowerSearchRequest(PowerRequest $PowerSearchRequest)"
...
  [23]=>
  string(107) "ShoppingCart RemoveShoppingCartItemsRequest(RemoveShoppingCartItemsRequest $RemoveShoppingCartItemsRequest)"
  [24]=>
  string(107) "ShoppingCart ModifyShoppingCartItemsRequest(ModifyShoppingCartItemsRequest $ModifyShoppingCartItemsRequest)"
  [25]=>
  string(118) "GetTransactionDetailsResponse GetTransactionDetailsRequest(GetTransactionDetailsRequest $GetTransactionDetailsRequest)"
}

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

jvanoort at simplexis dot nl 05-Jan-2016 03:32
_getFunctions can return null, not only array. This happens if the WSDL has not been parsed yet. This may be helpful to someone debugging, just like I was a few minutes ago when writing an extension to SoapClient.
Beebs 13-Nov-2013 02:26
The following code works for me while it appears soap.amazon.com has been deprecated and taken out of service. http://webservices.amazon.com has replaced Amazon's SOAP.

<?php
$client = new SoapClient('http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl');
var_dump($client->__getFunctions());
?>
hasegeli at arebt dot com 02-Jun-2009 12:19
This function did not work if schema is not in wsdl file.


Returns last SOAP request

  • ? SoapClient::__getFunctions
  • SoapClient::__getLastRequestHeaders ?
  • PHP Manual
  • SoapClient
  • Returns last SOAP request

SoapClient::__getLastRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequest — Returns last SOAP request

说明

public SoapClient::__getLastRequest ( ) : string|null

Returns the XML sent in the last SOAP request.

Note:

This method works only if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP request, as an XML string.

范例

Example #1 SoapClient::__getLastRequest() example

<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

参见

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse() - Returns last SOAP response
  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response

User Contributed Notes

hejdavladislav at gmail dot com 15-Sep-2016 10:20
Note that when you create SoapClient with option "trace" set to FALSE or omit it, than "__getLastRequest()" always returns NULL.
LZhang 11-Jul-2014 08:22
Creating an xml file and link to the file is my way.

$outputxml = '/output.xml';

file_put_contents($_SERVER['DOCUMENT_ROOT'] . $outputxml, $client->__getLastRequest());

echo '<a href="' . $outputxml . '">here</a>';
mayurvirkar at gmail dot com 09-Sep-2013 08:37
Just to make it a bit more readable

echo "REQUEST:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastRequest())) . "\n";
echo "Response:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastResponse())) . "\n";

PS: If you are using \n then you need to enclose above statements in <pre>. You can also use <br />, but it gets a bit messy.
Anonymous 26-Jan-2010 01:32
Adding htmlentities() can be helpful since it makes the XML visible in your browser without needing to view the source.

<?php

echo "REQUEST:\n" . htmlentities($client->__getLastRequest()) . "\n";

?>
Ersin DOGAN 12-Apr-2009 10:40
I guess many peoples calls getLastRequest and it returns nothing. "Heey where is the my last request". Now we will see our request,  when you created a SoapClient instance, you should give a option parameter as below :

<?php
// below $option=array('trace',1);
// correct one is below
$option=array('trace'=>1);

$client=new SoapClient('some.wsdl',$option);

try{
  $client->aMethodAtRemote();
}catch(SoapFault $fault){
  // <xmp> tag displays xml output in html
  echo 'Request : <br/><xmp>',
  $client->__getLastRequest(),
  '</xmp><br/><br/> Error Message : <br/>',
  $fault->getMessage();
}
?>

"trace" parameter enables output of request. Now, you should see SOAP request.
Omar Nabil 12-Nov-2008 06:14
the getLastResult function doesn't require that the server answers.
as my browser handled and hided the xml code I thought the function doesn't return the last request


Returns the SOAP headers from the last request

  • ? SoapClient::__getLastRequest
  • SoapClient::__getLastResponse ?
  • PHP Manual
  • SoapClient
  • Returns the SOAP headers from the last request

SoapClient::__getLastRequestHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request

说明

public SoapClient::__getLastRequestHeaders ( ) : string|null

Returns the SOAP headers from the last request.

Note:

This function only works if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP request headers.

范例

Example #1 SoapClient::__getLastRequestHeaders() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

参见

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response

User Contributed Notes

mischa molhoek 02-Jun-2015 08:48
it seems to me that is does not return the SOAP headers as it states in the explanation, but the request headers....


Returns last SOAP response

  • ? SoapClient::__getLastRequestHeaders
  • SoapClient::__getLastResponseHeaders ?
  • PHP Manual
  • SoapClient
  • Returns last SOAP response

SoapClient::__getLastResponse

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponse — Returns last SOAP response

说明

public SoapClient::__getLastResponse ( ) : string|null

Returns the XML received in the last SOAP response.

Note:

This method works only if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP response, as an XML string.

范例

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>

参见

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request

User Contributed Notes

mayurvirkar at gmail dot com 09-Sep-2013 08:38
Just to make it a bit more readable

echo "REQUEST:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastRequest())) . "\n";
echo "RESPONSE:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastResponse())) . "\n";

PS: If you are using \n then you need to enclose above statements in <pre>. You can also use <br />, but it gets a bit messy.
bshafs at gmail dot com 22-Jun-2011 12:45
You don't need to surround SoapClient in a try-catch block.  Just set the "exceptions" option to false, and the SoapFault instance will be returned instead of thrown.
ceo at l-i-e dot com 04-Jan-2006 01:31
D'oh!
That example needs:
$soapClient = new SoapClient($url, array('trace'=>1));
to turn ON tracing in the first place.
ceo at l-i-e dot com 04-Jan-2006 01:30
You almost for sure will need to wrap a try/catch block around your SOAP call in order to use these to debug something that's not working.

Otherwise, PHP throws a fatal error before you can execute this function.

For example:
<?php
    $soapClient = new SoapClient($url);
    echo htmlentities($soapClient->__getFunctions());
    //Assume that has output 'someFunction' (among others)
    try {
        $results = $soapClient->someFunction(...);
    }
    catch (SoapFault $soapFault) {
        var_dump($soapFault);
        echo "Request :<br>", htmlentities($soapClient->__getLastRequest()), "<br>";
        echo "Response :<br>", htmlentities($soapClient->__getLastResponse()), "<br>";
    }
?>

Without try/catch, your just get the Fatal Error and PHP commits suicide before you can call __getLastRequest/__getLastResponse


Returns the SOAP headers from the last response

  • ? SoapClient::__getLastResponse
  • SoapClient::__getTypes ?
  • PHP Manual
  • SoapClient
  • Returns the SOAP headers from the last response

SoapClient::__getLastResponseHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response

说明

public SoapClient::__getLastResponseHeaders ( ) : string|null

Returns the SOAP headers from the last response.

Note:

This function only works if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP response headers.

范例

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
?>

参见

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response

User Contributed Notes

noncey 30-Sep-2015 12:33
For long running scripts which may be set to a longer timeout in the PHP script, be aware that the IIS connection timeout settings do not restart when you initiate a SOAP call even though you are using a new web address than your current running script.

Because of this, we noted a SOAP call that seemed to not return headers from a Web Service. It was found to be related to IIS timing out. This was in IIS 7.5. The resolution was to increase the connection timeout for IIS at the website/domain level.

There were no faults or exceptions captured when this occurred so your only indicator is that you have no header information.
jeroen{at}asystance{dot}nl 17-Aug-2009 03:20
Note SoapClient does not wait for a response for one-way operations (i.e. <wsdl:operation>s that do not have a <wsdl:response>)! To see if a request failed, use
$sc = new SoapClient( 'some.wsdl', array('features'=>SOAP_WAIT_ONE_WAY_CALLS));

See http://bugs.php.net/bug.php?id=36083 and http://bugs.php.net/bug.php?id=49278


Returns a list of SOAP types

  • ? SoapClient::__getLastResponseHeaders
  • SoapClient::__setCookie ?
  • PHP Manual
  • SoapClient
  • Returns a list of SOAP types

SoapClient::__getTypes

(PHP 5, PHP 7, PHP 8)

SoapClient::__getTypes — Returns a list of SOAP types

说明

public SoapClient::__getTypes ( ) : array|null

Returns an array of types described in the WSDL for the Web service.

Note:

此函数仅在 WSDL 模式下生效。

参数

此函数没有参数。

返回值

The array of SOAP types, detailing all structures and types.

范例

Example #1 SoapClient::__getTypes() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getTypes());
?>

以上例程会输出：

array(88) {
  [0]=>
  string(30) "ProductLine ProductLineArray[]"
  [1]=>
  string(85) "struct ProductLine {
 string Mode;
 string RelevanceRank;
 ProductInfo ProductInfo;
}"
  [2]=>
  string(105) "struct ProductInfo {
 string TotalResults;
 string TotalPages;
 string ListName;
 DetailsArray Details;
}"
...
  [85]=>
  string(32) "ShortSummary ShortSummaryArray[]"
  [86]=>
  string(121) "struct GetTransactionDetailsRequest {
 string tag;
 string devtag;
 string key;
 OrderIdArray OrderIds;
 string locale;
}"
  [87]=>
  string(75) "struct GetTransactionDetailsResponse {
 ShortSummaryArray ShortSummaries;
}"
}

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

felipe dot cwb at hotmail dot com 21-Jul-2014 06:50
<?php
// to see formated types

$soap = new SoapClient('http://domain.com/ws.php?WSDL');

echo '<pre>';
echo '<h2>Types:</h2>';
$types = $soap->__getTypes();
foreach ($types as $type) {
    $type = preg_replace(
        array('/(\w+) ([a-zA-Z0-9]+)/', '/\n /'),
        array('<font color="green">${1}</font> <font color="blue">${2}</font>', "\n\t"),
        $type
    );
    echo $type;
    echo "\n\n";
}
echo '</pre>';


Defines a cookie for SOAP requests

  • ? SoapClient::__getTypes
  • SoapClient::__setLocation ?
  • PHP Manual
  • SoapClient
  • Defines a cookie for SOAP requests

SoapClient::__setCookie

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

SoapClient::__setCookie — Defines a cookie for SOAP requests

说明

public SoapClient::__setCookie ( string $name , string|null $value = null ) : void

Defines a cookie to be sent along with the SOAP requests.

Note:

Calling this method will affect all following calls to SoapClient methods.

参数

name

The name of the cookie.

value

The value of the cookie. If not specified, the cookie will be deleted.

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | value is now nullable.

User Contributed Notes

Jaygiri Goswami 17-Dec-2011 01:22
You can access the cookies sent by SOAP server using $client->_cookies

Most you need to send session cookies back to server.
lukasz at szostak dot biz 14-Aug-2006 10:53
On the server side you can access the cookie via $_COOKIE['cookie_name'].

Also remember that since HTTP is a stateless protocol, you have to send the cookie with every single SOAP call in order for it to be visible at server site.

It seems obvious but might save one a lot of time.


Sets the location of the Web service to use

  • ? SoapClient::__setCookie
  • SoapClient::__setSoapHeaders ?
  • PHP Manual
  • SoapClient
  • Sets the location of the Web service to use

SoapClient::__setLocation

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

SoapClient::__setLocation — Sets the location of the Web service to use

说明

public SoapClient::__setLocation ( string $location = "" ) : string|null

Sets the endpoint URL that will be touched by following SOAP requests. This is equivalent to specifying the location option when constructing the SoapClient.

Note:

Calling this method is optional. The SoapClient uses the endpoint from the WSDL file by default.

参数

location

The new endpoint URL.

返回值

The old endpoint URL.

范例

Example #1 SoapClient::__setLocation() example

<?php
$client = new SoapClient('http://example.com/webservice.php?wsdl');

$client->__setLocation('http://www.somethirdparty.com');

$old_location = $client->__setLocation(); // unsets the location option

echo $old_location;

?>

以上例程的输出类似于：

http://www.somethirdparty.com

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

maoneid at gmail dot com 24-May-2018 07:24
for some cases , ignoring location from initialization throw exception

PHP Fatal error:  Uncaught SoapFault exception: [HTTP] Could not connect to host

Better call and define the end point location manually.


Sets SOAP headers for subsequent calls

  • ? SoapClient::__setLocation
  • SoapClient::__soapCall ?
  • PHP Manual
  • SoapClient
  • Sets SOAP headers for subsequent calls

SoapClient::__setSoapHeaders

(PHP 5 >= 5.0.5, PHP 7, PHP 8)

SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls

说明

public SoapClient::__setSoapHeaders ( SoapHeader|array|null $headers = null ) : bool

Defines headers to be sent along with the SOAP requests.

Note:

Calling this method will replace any previous values.

参数

headers

The headers to be set. It could be SoapHeader object or array of SoapHeader objects. If not specified or set to null, the headers will be deleted.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 SoapClient::__setSoapHeaders() example

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$header = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$client->__setSoapHeaders($header);

$client->__soapCall("echoVoid", null);
?>

Example #2 Set Multiple Headers

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$headers = array();

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world again');

$client->__setSoapHeaders($headers);

$client->__soapCall("echoVoid", null);
?>

User Contributed Notes

mlconnor at yahoo dot com 11-Nov-2010 01:28
Does anyone know how to get the response headers?  The getLastResponseHeader returns a string response, not the complex object I was expecting...
peamik1953 at NOSPAM dot btinternet dot com 12-Jul-2010 11:06
You cannot add an additional header. If you want two headers, and one already exists, first delete it with $client->__setSoapHeaders(NULL). Then issue $client->__setSoapHeaders($headers) where $headers is an array of soapHeader() objects.
kedar dot purohit @ mavs dot uta dot edu 10-Sep-2009 12:58
To create complex SOAP Headers, you can do something like this:

Required SOAP Header:

<soap:Header>
    <RequestorCredentials xmlns="http://namespace.example.com/">
      <Token>string</Token>
      <Version>string</Version>
      <MerchantID>string</MerchantID>
      <UserCredentials>
        <UserID>string</UserID>
        <Password>string</Password>
      </UserCredentials>
    </RequestorCredentials>
</soap:Header>

Corresponding PHP code:

<?php

$ns = 'http://namespace.example.com/'; //Namespace of the WS.

//Body of the Soap Header.
$headerbody = array('Token' => $someToken,
                    'Version' => $someVersion,
                    'MerchantID'=>$someMerchantId,
                      'UserCredentials'=>array('UserID'=>$UserID,
                                             'Password'=>$Pwd));

//Create Soap Header.
$header = new SOAPHeader($ns, 'RequestorCredentials', $headerbody);

//set the Headers of Soap Client.
$soap_client->__setSoapHeaders($header);

?>
jayrajput at gmail dot com 30-Mar-2009 01:07
With multiple SOAP headers, when using SoapVar for creation of SoapHeader the PHP code just terminates (command terminated). I am not sure if that is a bug.

Without the SOAPVar the code worked fine for me

There are different way to creart SoapHeader I was using SoapVar and the code was not working. I am still a novice with this SOAP stuff.

Tried using normal strings and it worked fine. SoapHeader can take SoapVar or string as the third argument.

my code:

<?php
// first soap header.
$var = new SoapVar($header, XSD_ANYXML);
$soapHeader = new SoapHeader(NAME_SPACE, "Security", $var);
// second soap header.
$var2 = new SoapVar($header2, XSD_ANYXML);
$soapHeader2 = new SoapHeader(DIFF_NAME_SPACE, "ID", $var2);

$client = new SoapClient($wsdl, array("location" => $location));

$headers = array();
$headers[] = $soapHeader;
$headers[] = $soapHeader2;

// Here my code was just terminating.
$client->__setSoapHeaders($headers);
?>


Calls a SOAP function

  • ? SoapClient::__setSoapHeaders
  • SoapServer ?
  • PHP Manual
  • SoapClient
  • Calls a SOAP function

SoapClient::__soapCall

(PHP 5, PHP 7, PHP 8)

SoapClient::__soapCall — Calls a SOAP function

说明

public SoapClient::__soapCall ( string $name , array $args , array|null $options = null , SoapHeader|array|null $inputHeaders = null , array &$outputHeaders = null ) : mixed

This is a low level API function that is used to make a SOAP call. Usually, in WSDL mode, SOAP functions can be called as methods of the SoapClient object. This method is useful in non-WSDL mode when soapaction is unknown, uri differs from the default or when sending and/or receiving SOAP Headers.

On error, a call to a SOAP function can cause PHP to throw exceptions or return a SoapFault object if exceptions are disabled. To check if the function call failed to catch the SoapFault exceptions, check the result with is_soap_fault().

参数

name

The name of the SOAP function to call.

args

An array of the arguments to pass to the function. This can be either an ordered or an associative array. Note that most SOAP servers require parameter names to be provided, in which case this must be an associative array.

options

An associative array of options to pass to the client.

The location option is the URL of the remote Web service.

The uri option is the target namespace of the SOAP service.

The soapaction option is the action to call.

inputHeaders

An array of headers to be sent along with the SOAP request.

outputHeaders

If supplied, this array will be filled with the headers from the SOAP response.

返回值

SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value of __soapCall will be a simple value (e.g. an integer, a string, etc). If multiple values are returned, __soapCall will return an associative array of named output parameters.

On error, if the SoapClient object was constructed with the exceptions option set to false, a SoapFault object will be returned.

范例

Example #1 SoapClient::__soapCall() example

<?php

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);

$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c), NULL,
                    new SoapHeader(), $output_headers);

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->SomeFunction($a, $b, $c);
$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c),
                    array('soapaction' => 'some_action',
                          'uri'        => 'some_uri'));
?>

参见

  • SoapClient::__construct() - SoapClient constructor
  • SoapParam::__construct() - SoapParam constructor
  • SoapVar::__construct() - SoapVar constructor
  • SoapHeader::__construct() - SoapHeader constructor
  • SoapFault::__construct() - SoapFault constructor
  • is_soap_fault() - Checks if a SOAP call has failed

User Contributed Notes

arturklesun at gmail dot com 10-Aug-2016 06:16
Sharing my experience cuz i believe it is most important for you if you decide to use this Soap Client implementation.

At php 7.0.8 the stdClass generated by SoapClient from the response does not use "minOccurs" and "maxOccurs" WSDL modifiers to distinct properties in stdClass-es (aka keys in "associative arrays") and elements in arrays ("aka indexed arrays").

Instead, the implementation decides whether tag is _a key in associative array_ or _one of elements with same tag in indexed array_ by simply the fact whether there is just one element with such tag in the sequence or many.

Consider alive example from my case:
<?php
response xml:
...
<ValidatingCarrier>
    <Alternate>AA</Alternate>
</ValidatingCarrier>
...
<ValidatingCarrier>
    <Alternate>AA</Alternate>
    <Alternate>AY</Alternate>
</ValidatingCarrier>
...

response structure generated by SoapClient:
...
[ValidatingCarrier] => stdClass Object(
    [Alternate] => AA // here it is a string
)
...
[ValidatingCarrier] => stdClass Object (
    [Alternate] => Array ( // and here this is an array
        [0] => AA
        [1] => AY
    )
)
...

field XSD definition:
<xs:element name="Alternate" type="CarrierCode" minOccurs="0" maxOccurs="24">
?>

You see, the definition in XSD tells us this tag can be repeated up to 24 times, what means it would be an indexed array, but SoapClient does not take that into account and treats the first <Alternate> in example as a value instead of array containing this value.

Undoubtedly, a value should be a property in the stdClass (a key in associative array) _only_ when maxOccurs is 1 or less or not specified (default is 1, see https://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints). Hope this info will be useful for you when you will be implementing your own, correctly working, SoapClient.
ub at sturmundbraem dot ch 11-Jun-2016 12:51
To avoid the SOAP client returning sometimes objects and sometimes arrays of objects, there's a setting:

   $this->soapClient = new \SoapClient($wsdlUrl, array(
    'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
    'trace' => DEBUG_SOAP
   ));
pmeth at softersoftware dot com 12-May-2014 04:44
Note, when trying to overload the __soapCall function, you should not use type hints or STRICT_STANDARDS will complain.
The correct signature is as follows:

<?php
class MySoapClient extends \SoapClient
{
    ...
    public function __soapCall($function_name, $arguments, $options = null, $input_headers = null, &$output_headers = null)
     {
        ...
    }
    ....
}
?>
vb 17-Oct-2012 04:23
Note that calling __soapCall and calling the generated method from WSDL requires specifying parameters in two different ways.

For example, if you have a web service with method login that takes username and password, you can call it the following way:
<?php
$params = array('username'=>'name', 'password'=>'secret');
$client->login($params);
?>

If you want to call __soapCall, you must wrap the arguments in another array as follows:
<?php
$client->__soapCall('login', array($params));
?>
snuufix+nospam at gmail dot com 11-Feb-2011 03:23
I am using SOAP call response headers to sign request results.

After alot of hours, I finally got the best way to get SOAP response headers (other than parsing __getLastResponse() witch requires trace option enabled) is using __soapCall() wrapper.

You can extend SoapClient class and wrap some functions to make sure you get the headers.

<?php

class API extends SoapClient
{

    // ... Constructor, etc.

    // Get SOAP Server response headers
    public function __soapCall($function, $arguments, $options = array(), $input_headers = null, &$output_headers = null)
    {
        parent::__soapCall($function, $arguments, $options, $input_headers, $output_headers);

        print_r($output_headers); // Array of response headers
    }

    // If you are using WSDL you need this, so you still can call functions directly without calling __soapCall manualy
    public function __call($func, $args)
    {
        return $this->__soapCall($func, $args);
    }

?>
niko dot hujanen at gmail dot com 09-Nov-2010 11:06
I was integrating a local warehouse system with a SOAP to our system and noticed some things.

1) Service uses "dot-namespacing" (fe. Item.Price) I classmapped this to Item_Price and used magical __get() and __set() to strip off 'Item.' from variable names. Works like a charm.

Example:
<Item.Price>1.52</Item.Price>

<?php
class Item_Price {
    public $price;
    public function __get($field) { $field = str_replace('Item.', '', $field); return $this->$field; }
    public function __set($field, $value) { $field = str_replace('Item.', '', $field); $this->$field = $value; }
?>

2) I noticed that classmapping a segment with attributes and value is possible. Class uses variables as attributes and $_ is the value.

Example:
<?php
class Foo {
    public $item = 'Bar';
    public $_ = 'Value here';
}
?>
Turns to <Foo item="Bar">Value here</Foo>

Example of using classes with soapcalls:
<?php
    $client = ExtendSoapClient::getInstance();
    $foo = new Foo();
    $response = $client->sendFoo($foo);
?>

Posted these since I think the documentation is lacking and very obsolete. Hopefully someone's burden eases.
james dot ellis at gmail dot com 09-Jun-2010 07:12
If you are using this method, remember that the array of arguments need to be passed in with the ordering being the same order that the SOAP endpoint expects.

e.g
<?php
//server expects: Foo(string name, int age)

//won't work
$args = array(32, 'john');
$out = $client->__soapCall('Foo', $args);

//will work
$args = array('john', 32);
$out = $client->__soapCall('Foo', $args);
?>
lesley at casbah dot com dot au 21-Apr-2009 06:55
If you are calling a weblogic service with a certificate and you are getting this error on the soap method call statement:

[EJB:010160]Security Violation: User: '<anonymous>' has insufficient permission to access EJB: type=<ejb>, application=app2_0_52_3, module=appsejb.jar, ejb=AppMethod, method=AppMethod, methodInterface=Remote, signature={java.lang.String}.

then check the wsdl in the soap open call - it must be https.  Supplied with an http wsdl this took some time to figure out.

<?php
    $client = new SoapClient("https://example.com/AppWs/Service?WSDL",
                array('trace'=>true,
                      'exceptions'=>true,
                      'local_cert' => "/var/www/html/app/newcert.pem",
                      'passphrase' => "thepassphrase"));
    $response = $client->__soapCall("MyMethod", array("param1" => $value1));
?>

Thanks to the authors for their comments on enabling openssl and curl by uncommenting extension=php_opensll.dll and extension=php_curl.dll in php.ini.  Also for Olaf's instructions "append the content of the private key file and the certificate file to a single file". I did this using copy command on the DOS prompt:

copy mycert.pem+mykey.pem newcert.pem
Tim Williams 08-Apr-2009 06:55
One little gotcha when passing the parameters where you need to have attributes and a simpletype value:

To get the xml

<foo bar="moo">cheese</foo>

You'd pass in:

<?php
array("foo" => array("_" => "cheese", "bar"=>"moo"));
?>

See that "_" bit? It really wasn't obvious from the documentation.
deWarlock 02-Apr-2009 04:10
The most annoying thing is that you'll get no warning trying to pass object not matching wsdl e.g. if server expects smth like $Object->expName->... and you would pass $Object->otherName the client will send empty request without notifying you.
Also pay attention that names are key sensitive.

In my case I spent hours trying to pass $Post->Lead->... object instead of $Post->lead-> ...
Shto 03-Mar-2009 03:17
One thing to note.

This happened to me and it took a while until I discovered what the problem was.

I was trying to get .NET objects from a provided web service, however it always seemed to return empty objects. It did return the backbone, but nothing within the objects that made up the structure.

Anyhow, it seems that you have to be very precise with the arrays when calling these functions. Par example, do this:

<?php
$obj = $client->__soapCall($SOAPCall, array('parameters'=>$SoapCallParameters));
?>

meaning that you must put an array as the second argument with 'parameters' as the key and the soap call parameters as the value.

Also make sure that the parameter variable, in my case $SoapCallParameters is in the form of what is requested by the webservice.

So, don't just make an array of the form:
<?php

(
   [0] => 'Mary',
   [1] => 1983
)

?>

but if the webservice requests a 'muid' variable as 'Mary' and a 'birthyear' as 1983, then make your array like this:

<?php

(
   [muid] => 'Mary',
   [birthyear] => 1983
)

?>

The above arrays refer to the $SoapCallParameters variable.

Hope this helps somebody, not having to spend too much time figuring out the problems.
Alejandro Cavallo 19-Mar-2008 07:38
I get the same problem reported above by ryan:
"ryan at grunt dot tv
22-Sep-2005 01:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason."

When defined variable soapVar I assigned the type XSD_STRING rather than as XSD_ANYXML.
And when calls to the function you must pass the soapVar in an associative array.

For example if the function (called myFunc) expect a parameter called xmlInput you should do something like this:
$soapvar = new SoapVar($query, XSD_STRING);
$result = $client->myFunc(array('xmlInput'=>$soapvar));

This XML fragment are wrapped around xmlImput tags.-
stefan at datax dot biz 24-Oct-2007 07:28
The call to __soapCall returned an object to me either. This is the function which makes my life easier:

function obj2array($obj) {
  $out = array();
  foreach ($obj as $key => $val) {
    switch(true) {
        case is_object($val):
         $out[$key] = obj2array($val);
         break;
      case is_array($val):
         $out[$key] = obj2array($val);
         break;
      default:
        $out[$key] = $val;
    }
  }
  return $out;
}

Usage:
...
$response = $client ->__soapCall("track", array('parameters' => $request));
$response = obj2array($response);

Hope it helps.
temp at mailinator dot com 30-Jan-2007 04:43
The options in the third argument is documented in http://php.net/manual/en/function.soap-soapclient-construct.php
paulsjv at gmail dot com 11-Jan-2006 07:44
I was working with SOAP for the first time and I had to create a client that sent a date range to a WSDL (Web Services Description Language) to return some information I needed.  I didn't know how to pass the params and there really was no documentation about it.  The main thing you have to make sure to do is when you pass params to a method that is definied by the WSDL that you are calling is that you use the same param name for the key of the array or the object variable as shown below.  Also, if you don't know what the methods/functions that a WSDL has or the params that you need to pass it you can use the __getFunctions() and __getTypes() methods after you declare your new SoapClient.

<?php
// From and to are the two params that the execute function needs
// when called from the WSDL so make you to have them as the
// key to an array like below
$params["From"] = "06/01/2005"; // also can use $params->From = "date";
$params["to"] = "12/31/2005"; // also can use $params->to = "date";

$client = new SoapClient("some.wsdl");

try {
        print($client->execute($params));
} catch (SoapFault $exception) {
        echo $exception;
}
?>
ryan at grunt dot tv 21-Sep-2005 09:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason.

Therefore, to get this to work you must either register the XSD_ANYXML #define as a PHP constant, or use the integer value of the constant when creating the SoapVar, which is 147.

$soapvar = new SoapVar($xml_text, 147);

$params = array("ItemXml" => $soapvar, "PropertyView" => "blah");
$result = $this->soapclient->__soapCall("SaveItem", array("parameters"=>$params), null, $this->soapheaders);

However, this still doesnt give the correct result. For some reason, the ItemXml parameter node is not wrapped around the associated xml parameter in the soap request, and the following soap is produced (assumming '<item>blah</item>' is used as the $xml_text):

<SOAP-ENV:Envelope xmlns:SOAP-ENV="..." xmlns:ns1="...">
<SOAP-ENV:Header>...</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:SaveItem>
<item>blah</item>
<ns1:PropertyView>blah</ns1:PropertyView>
</ns1:SaveItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
DesmondJ 04-May-2005 03:36
Following OrionI's example:

<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "-1"
?>

Please note that the lines:

"$client->Sum($params);"

and

"$simpleresult = $objectresult->SumResult;"

are based off of each other. If your web service function is called "Sum", then add "Result" to the end of it to get the results of the call.

EG:

<?php
 $client = new SoapClient("http://server/mathservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Minus($params); // note the name of the function is "Minus"
 $simpleresult = $objectresult->MinusResult; // note the name of the result is referenced as "MinusResult"
 print($simpleresult); //produces "5"
?>
OrionI 18-Apr-2005 07:27
Correction on the previously submitted code snippet...the incoming parameter for .NET also has to be in object or array form for it to be correctly converted to the XML form that .NET expects (as already mentioned by Llu?s P?mies). The full example (when using WSDL) should be like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $params->param1 = $value1;
 $params->param2 = $value2;
 $objectresult = $client->MyMethod($params);
 $simpleresult = $objectresult->MyMethodResult;
?>
So if you have a C# function like this:
//sumservice.asmx
...
[WebMethod]
public int Sum(int a, int b)
{
  return a + b;
}
...
The PHP client would be this:
<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "5"
?>
OrionI 15-Apr-2005 11:46
When calling over SOAP to a .NET application, you may end up with an object as a result instead of a simple type, even if you're just grabbing a simple type (like a boolean result). Use a property accessor to get the actual result, like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $objectresult = $client->MyMethod($param1, $param2);
 $simpleresult = $objectresult->MyMethodResult;
?>
Note that .NET seems to name the result MethodNameResult for method MethodName.
17-Feb-2005 03:19
If your service is a .NET doc/lit, which means the input message has a single part named 'parameters' that is a structure that wraps the parameters.  Your call should look like this:

<?php

$params = array('param_name_1'=>$val_1,'param_name_2'=>$val_2);
$client->call('MethodName', array('parameters' => $params));

?>


The SoapServer class

(PHP 5, PHP 7, PHP 8)

简介

The SoapServer class provides a server for the » SOAP 1.1 and » SOAP 1.2 protocols. It can be used with or without a WSDL service description.

类摘要

SoapServer {
/* 方法 */
public __construct ( string|null $wsdl , array $options = [] )
public addFunction ( mixed $functions ) : void
public addSoapHeader ( SoapHeader $header ) : void
public fault ( string $code , string $string , string $actor = "" , mixed $details = null , string $name = "" ) : void
public getFunctions ( ) : array
public handle ( string|null $request = null ) : void
public setClass ( string $class , mixed ...$args ) : void
public setObject ( object $object ) : void
public setPersistence ( int $mode ) : void
}

Table of Contents

  • SoapServer::addFunction — 添加一个或多个函数来处理SOAP请求
  • SoapServer::addSoapHeader — Add a SOAP header to the response
  • SoapServer::__construct — SoapServer constructor
  • SoapServer::fault — Issue SoapServer fault indicating an error
  • SoapServer::getFunctions — Returns list of defined functions
  • SoapServer::handle — Handles a SOAP request
  • SoapServer::setClass — Sets the class which handles SOAP requests
  • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
  • SoapServer::setPersistence — Sets SoapServer persistence mode

User Contributed Notes

mail at borisd dot ru 08-Feb-2019 12:43
If you want to run dummy SoapServer as a daemon for tests on linux, you need to:

1. Set up location "localhost:12312/soapServer.php" in your wsdl like:

<wsdl:service name="ServiceName">
        <wsdl:port name="ServiceNamePort" binding="tns:ServiceNameBinding">
            <soap:address location="http://localhost:12312/soapServer.php" />
        </wsdl:port>
</wsdl:service>

2. Write your test server like:

<?php
/*
  * Server
  */
class TestSoapServer
{
    public function getMessage()
    {
        return 'Hello, World!';
    }
}
$options = ['uri' => 'http://localhost:12312/'];
$server = new SoapServer(null, $options);
$server->setClass('TestSoapServer');
$server->handle();

?>

3. Run it with `php -S localhost:12312` (in the same folder)

Whenever you make a request according to your wsdl, it will end up at your "server".
softontherocks at gmail dot com 29-Oct-2014 06:20
I posted in this URL http://softontherocks.blogspot.com/2014/02/web-service-soap-con-php.html a full example of a nusoap web service.

There is defined the server and the cliente who calls the web service.

I hope it would be useful for you.
s at dumdeedum dot com 12-Sep-2013 05:32
I was running PHP 5.3.2 and couldn't for the life of me get SOAP headers to work, no matter how carefully I built my class/wsdl/client.  What finally fixed it was updating to the latest PHP.  No idea if there was a bug somewhere or what, but it's never a bad idea to stay current and it might save you weeks of frustration!
phpman dot fulter47 at recursor dot net 04-Jul-2012 05:36
For those (like me) coming from other SOAP frameworks and getting confused:

- A PHP SOAP server application created using the SoapServer class can not be used as a standalone SOAP server.
It needs an HTTP server to receive SOAP requests, which must run a PHP engine to execute the PHP SOAP server script as a CGI.

- For this reason, there are no settings in PHP that control the Interface/Port under which the SOAP server will wait for requests - it is the HTTP server who is responsible for that.

- The "uri" parameter is an "id value", used as the namespace for the SOAP response. It is only required if no WSDL file is used (that contains this setting), i.e. "wsdl" is set to NULL. It does _not_ control the Hostname/Port under which the HTTP server will be reachable for requests.
php1221 at klox dot net 18-Aug-2011 01:39
While there are plenty of mentions online that SoapServer doesn't support SOAP Headers, this isn't true.

In your class, if you declare a function with the name of the header, the function will be called when that header is received.

<?php
class MySoapService {
  private $user_is_valid;

  function MyHeader($header) {
    if ((isset($header->Username)) && (isset($header->Password))) {
      if (ValidateUser($header->Username, $header->Password)) {
        $user_is_valid = true;
      }
    }
  }

  function MySoapRequest($request) {
    if ($user_is_valid) {
      // process request
    }
    else {
      throw new MyFault("MySoapRequest", "User not valid.");
    }
  }
}
?>
hawky83 at googlemail dot com 21-Jan-2011 02:46
Another simple example for SOAP_SERVER with errorhandling an params and wsdl:

SERVER (soap_all_srv.php):

<?php
// PEAR::SOAP einbinden
require_once "SOAP/Server.php";
$skiptrace =& PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
$skiptrace = true;

// Service-Class
class mytimeserv {

  // __dispatch_map
  public $__dispatch_map = array ();

  // In/Out param -> __dispatch_map
  public function __construct() {
    $this->__dispatch_map["now"] =
      array ("in" => array("format" => "string"),
             "out" => array("time" => "string"));
  }

  // get back __dispatch_map in __dispatch
  public function __dispatch($methodname) {

    if (isset($this->__dispatch_map[$methodname])) {
      return $this->__dispatch_map[$methodname];
    }

    return NULL;
  }

  // servicemthod with parameters
  function now ($format) {

    // formaterror?
    if (($format == null) || (trim($format) == "")) {

      // send errormessage
      return new SOAP_Fault("Kein Parameter angegeben","0815", "Client");
    }

    date_default_timezone_set('Europe/Berlin');

    $time = date ($format);

    // return SOAP-Obj.
    return (new SOAP_Value('time','string', $time));
  }
}

// service-class
$service = new mytimeserv();

// server
$ss = new SOAP_Server();

// add service with name
$ss->addObjectMap (&$service,"urn:mytimeserv");

// service or wsdl
if (isset($_SERVER["REQUEST_METHOD"])&& $_SERVER["REQUEST_METHOD"] == "POST") {

    // postdata -> service
    $ss->service ($HTTP_RAW_POST_DATA);

} else {

  // wsdl-param in url
  if (isset($_SERVER['QUERY_STRING']) && strcasecmp($_SERVER['QUERY_STRING'],'wsdl') == 0) {

    // DISCO_Server for WSDL
    require_once "SOAP/Disco.php";
    $disco = new SOAP_DISCO_Server ($ss,"mytimeserv","My Time Service");

    // set HTML-Header
    header("Content-type: text/xml");

    // return wsdl
    print $disco->getWSDL ();
  }
}

?>

CLIENT (soap_all_client.php) (for wsdl: http://example.com/soap_all_srv.php?wsdl):
<?php

require_once "SOAP/Client.php";

// SOAP/WSDL
$sw = new SOAP_WSDL ("http://example.com/soap_all_srv.php?wsdl");

// Proxy-Obj.
$proxy = $sw->getProxy ();

// servicemthod
$erg = $proxy->now ("H:i:s");

// return
print $erg."\n";

?>
mikkel at nsales dot dk 02-Jun-2010 03:15
If you want to return a custom object array from a nusoap webservice, you have to cast the objects to arrays like so:

<?php
$users = array();
while($res = $db_obj->fetch_row())
{
  $user = new user();
  $user->Id = $res['id'];
  $user->Username = $res['username'];
  $user->Email = $res['email'];

  $users[] = (array) $user;
}

return ($users);
?>
junk2cm at gmx dot de 25-May-2010 12:54
As the SoapServer class lacks the possibility of dealing with SOAP-Headers, my following workaround is suitable to my needs when I had to do authentication via the SOAP-Headers:
1. Use a class which handles SOAP requests and let the constructor of this class take the sent headers.
2. Before invoking the SoapServer extract the SOAP-Header from the incoming raw data.
3. When using setClass pass the extracted header to the handling class.

In Your Server-Skript do things like this
<?php
$hdr = file_get_contents("php://input");
if (strpos($hdr,'<s:Header>')===false) {
    $hdr = null;
} else {
    $hdr = explode('<s:Header>',$hdr);
    $hdr = explode('</s:Header>',$hdr[1]);
    $hdr = $hdr[0];
}
$srv = new SoapServer('Your_wsdl');
$srv->setClass("ServiceClass",$hdr);
$srv->handle();
?>

And the service class is like this:
<?php
class ServiceClass {
    var $IsAuthenticated;

    function __construct($hdr) {
        $this->IsAuthenticated = false;
        if ($hdr!=null) {
            $this->header = simplexml_load_string($hdr);
            //Your authentication stuff goes here...
        }
    }

    function SomeFunctionOfTheService($a) {
        if ($this->IsAuthenticated) {
            //here Your function...
        }
    }

}
?>
carlos dot vini at gmail dot com 20-May-2010 01:55
SoapServer does not support WSDL with literal/document. I have a class:

<?php
class My_Soap {
    /**
     * Returns Hello World.
     *
     * @param string $world
     * @return string
     */
    public function getInterAdmins($world) {
        return 'hello' . $world;
    }
}
?>

To fix this I had to create proxy class:
<?php
class My_Soap_LiteralDocumentProxy {
   public function __call($methodName, $args) {
       $soapClass = new My_Soap();
       $result = call_user_func_array(array($soapClass, $methodName),  $args[0]);
       return array($methodName . 'Result' => $result);
   }
}
?>

Now make sure that the WSDL is created using My_Soap. And that the Server is created using My_Soap_LiteralDocumentProxy:

<?php

if (isset($_GET['wsdl'])) {
    $wsdl = new Zend_Soap_AutoDiscover(); // It generates the WSDL
    $wsdl->setOperationBodyStyle(array(
        'use' => 'literal'
    ));
    $wsdl->setBindingStyle(array(
        'style' => 'document'
    ));
    $wsdl->setClass('My_Soap');
    $wsdl->handle();
} else {
    $server = new Zend_Soap_Server('http://localhost/something/webservice.php?wsdl');
    $server->setClass('My_Soap_LiteralDocumentProxy');
    $server->handle();
}

?>
dsubar at interna dot com 25-Dec-2009 09:49
Do not put a SoapServer and a SoapClient in the same PHP file. This seems to cause arbitrary behavior. On the PHP interpreter in Eclipse, everything worked fine. Under MAMP, I got an undocumented error. In moving the client from the same file as the server, everything worked fine.


添加一个或多个函数来处理SOAP请求

  • ? SoapServer
  • SoapServer::addSoapHeader ?
  • PHP Manual
  • SoapServer
  • 添加一个或多个函数来处理SOAP请求

SoapServer::addFunction

(PHP 5, PHP 7, PHP 8)

SoapServer::addFunction — 添加一个或多个函数来处理SOAP请求

说明

public SoapServer::addFunction ( mixed $functions ) : void

为远程客户端导出一个或多个函数

参数

functions

导出一个函数，将函数名作为字符串传递给这个参数。

导出多个函数，将一组函数名作为数组传递。

导出所有函数，传递特殊常量 SOAP_FUNCTIONS_ALL.

Note:

functions 接收的所有输入参数必须同时和WSDL文件中定义的 顺序一样（它们不应该接收任何输出变量作为参数）并且返回一个或多个值。如果要返回多个 值，它们必须返回一组被命名的输出参数作为数组。

返回值

没有返回值。

范例

Example #1 SoapServer::addFunction() example

<?php

function echoString($inputString)
{
    return $inputString;
}

$server->addFunction("echoString");

function echoTwoStrings($inputString1, $inputString2)
{
    return array("outputString1" => $inputString1,
                 "outputString2" => $inputString2);
}
$server->addFunction(array("echoString", "echoTwoStrings"));

$server->addFunction(SOAP_FUNCTIONS_ALL);

?>

参见

  • SoapServer::SoapServer()
  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

dotpointer at gmail dot com 26-Oct-2007 06:52
Be careful with SOAP_FUNCTIONS_ALL, as it adds ALL availiable PHP functions to your server.

This can be a potential security threat, imagine clients doing this:

echo $client->file_get_contents("c:\\my files\\my_passwords.doc");

And voila, they have the contents of your file my_passwords.doc.
Evan Borgstrom 23-Aug-2006 03:42
In response to comment by Nathan O'Sullivan about returning (or passing) a complex type, you can also use the stdClass() object.

Assume you define a complex type like so:

<xsd:complexType name="TestType">
        <xsd:all>
                <xsd:element name="A" type="xsd:string" />
                <xsd:element name="B" type="xsd:int" />
                <xsd:element name="C" type="xsd:boolean" />
        </xsd:all>
</xsd:complexType>

To use an object in place of an array you can do:

$test = new stdClass();
$test->A = "test string";
$test->B = 45;
$test->C = false;

$result = $client->Test($test);
Nathan O'Sullivan 28-Apr-2005 11:36
You may be left wondering, as I was, how to return a complex type - consider the following WSDL snippets, for a method called Login:

 <xs:element name="Login">
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="1" name="username" type="xs:string" />
            <xs:element minOccurs="0" maxOccurs="1" name="password" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

   <xs:complexType name="UserInfo">
        <xs:sequence>
          <xs:element minOccurs="0" maxOccurs="1" name="Id" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Nickname" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Email" type="xs:string" />
        </xs:sequence>
      </xs:complexType>

   <xs:element name="LoginResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="1" name="LoginResult" type="s0:UserInfo" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

Here's a working Login function  that I've added with add SoapServer::addFunction

function Login($username, $password)
{
  return array("LoginResult", array("Id"=>1, "Name"=>"Nathan", "Nickname"=>"Nathan", "Email"=>"email address") );
}

The UserInfo complextype is represented by the inner array.  The outer array has just one element, "LoginResult".  The LogineResponse element  seems to be treated as a one-member array by PHP.


Add a SOAP header to the response

  • ? SoapServer::addFunction
  • SoapServer::__construct ?
  • PHP Manual
  • SoapServer
  • Add a SOAP header to the response

SoapServer::addSoapHeader

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SoapServer::addSoapHeader — Add a SOAP header to the response

说明

public SoapServer::addSoapHeader ( SoapHeader $header ) : void

Adds a SOAP header to be returned with the response to the current request.

参数

header

The header to be returned.

返回值

没有返回值。

User Contributed Notes

vladimir at bashkirtsev dot com 21-Nov-2016 09:30
Notably addSoapHeaders() must be called within handling class/object.

If you call addSoapHeaders() like this:

$server = new SoapServer("some.wsdl");
$server->setObject(new Service());
$server->addSoapHeaders(new SoapHeader("ns", "Header", "value"));
$server->handle();

Your SOAP header will not be added to the server response as it will be overwritten by result of handle() function.

If you want to add SOAP headers to the resulting response you should make $server global/static variable and then call addSoapHeaders() from within of the method of Service class which will handle the request.


SoapServer constructor

  • ? SoapServer::addSoapHeader
  • SoapServer::fault ?
  • PHP Manual
  • SoapServer
  • SoapServer constructor

SoapServer::__construct

(PHP 5, PHP 7, PHP 8)

SoapServer::__construct — SoapServer constructor

说明

public SoapServer::__construct ( string|null $wsdl , array $options = [] )

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

参数

wsdl

To use the SoapServer in WSDL mode, pass the URI of a WSDL file. Otherwise, pass null and set the uri option to the target namespace for the server.

options

Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor).

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

There is also a features option which can be set to SOAP_WAIT_ONE_WAY_CALLS, SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE.

The send_errors option can be set to false to sent a generic error message ("Internal error") instead of the specific error message sent otherwise.

范例

Example #1 SoapServer::__construct() example

<?php

$server = new SoapServer("some.wsdl");

$server = new SoapServer("some.wsdl", array('soap_version' => SOAP_1_2));

$server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C"));

$server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1'));

$server = new SoapServer(null, array('uri' => "http://test-uri/"));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

Anonymous 10-Jun-2012 02:35
// Workin Server with Client for localhost

// server.php

<?php
class MyClass {
  public function helloWorld() {

    return 'Hallo Welt '. print_r(func_get_args(), true);
  }
}

try {
  $server = new SOAPServer(
    NULL,
    array(
     'uri' => 'http://localhost/soap/server.php'
    )
  );

  $server->setClass('MyClass');
  $server->handle();
}

catch (SOAPFault $f) {
  print $f->faultstring;
}

?>

// client.php:

<?php
$client = new SoapClient(null, array(
      'location' => "http://localhost/soap/server.php",
      'uri'      => "http://localhost/soap/server.php",
      'trace'    => 1 ));

echo $return = $client->__soapCall("helloWorld",array("world"));
?>

// Hope you like it


Issue SoapServer fault indicating an error

  • ? SoapServer::__construct
  • SoapServer::getFunctions ?
  • PHP Manual
  • SoapServer
  • Issue SoapServer fault indicating an error

SoapServer::fault

(PHP 5, PHP 7, PHP 8)

SoapServer::fault — Issue SoapServer fault indicating an error

说明

public SoapServer::fault ( string $code , string $string , string $actor = "" , mixed $details = null , string $name = "" ) : void

Sends a response to the client of the current request indicating an error.

Note:

This can only be called when handling a request.

参数

code

The error code to return

string

A brief description of the error

actor

A string identifying the actor that caused the fault.

details

More details of the fault

name

The name of the fault. This can be used to select a name from a WSDL file.

返回值

没有返回值。

参见

  • SoapFault::__construct() - SoapFault constructor

User Contributed Notes

christian at cmjdesign dot dk 06-Jun-2013 10:41
hi,
to control the fault output one may do the following

/**
 * mySoapServer class
 */
class mySoapServer extends SoapServer {
    public function __construct($wsdl, array $options = null) {
        parent::SoapServer($wsdl, $options);
    }
    public function fault ($code, $string, $actor = null, $details = null, $name = null) {
        throw new SoapFault($code, $string, $actor, $details, $name);
    }
}

Use:
try {
    $server = new mySoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
    $server->setClass('mySoapAPI');
    $server->handle();
} catch (SoapFault $exc) {
    echo $exc->getTraceAsString();
}

that how i did this,
hope iot can help some one.
brian dot reynolds at risaris dot com 21-Feb-2012 09:44
Example Usage:

return new SoapFault( "Client", "foo or bar must be supplied");

SOAP Fault Codes

VersionMismatch: Found an invalid namespace for the SOAP Envelope element
MustUnderstand    : An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood
Client: The message was incorrectly formed or contained incorrect information
Server: There was a problem with the server so the message could not proceed
dub357 at gmail dot com 08-Feb-2012 08:01
This function also sends a 500 response code back to the client with the request.
This was causing issues with an Apache Axis 1.2 client I had so I instead implemented by own fault handling:

<?php
header("Content-Type: text/xml");
header("Status: 200");
die("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\\"http://schemas.xmlsoap.org/soap/envelope/\\">
  <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
      <faultcode>500</faultcode>
      <faultstring>".$ex->getMessage())."</faultstring>
    </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>");
?>
Amr Mostafa 09-Sep-2009 06:16
This function currently terminates execution as well, which may be undesirable. See: http://bugs.php.net/bug.php?id=49513
Anonymous 16-Jul-2008 12:12
If you use Adobe Flex, Flash or AIR as SOAP client and are unable to get the error message in case of a soap fault, upgrade to PHP 5.2.6.

Details in:
http://bugs.php.net/bug.php?id=43507


Returns list of defined functions

  • ? SoapServer::fault
  • SoapServer::handle ?
  • PHP Manual
  • SoapServer
  • Returns list of defined functions

SoapServer::getFunctions

(PHP 5, PHP 7, PHP 8)

SoapServer::getFunctions — Returns list of defined functions

说明

public SoapServer::getFunctions ( ) : array

Returns a list of the defined functions in the SoapServer object. This method returns the list of all functions added by SoapServer::addFunction() or SoapServer::setClass().

参数

此函数没有参数。

返回值

An array of the defined functions.

范例

Example #1 SoapServer::getFunctions() example

<?php
$server = new SoapServer(NULL, array("uri" => "http://test-uri"));
$server->addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $server->handle();
} else {
  echo "This SOAP server can handle following functions: ";
  $functions = $server->getFunctions();
  foreach($functions as $func) {
    echo $func . "\n";
  }
}
?>

参见

  • SoapServer::__construct() - SoapServer constructor
  • SoapServer::addFunction() - 添加一个或多个函数来处理SOAP请求
  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

There are no user contributed notes for this page.


Handles a SOAP request

  • ? SoapServer::getFunctions
  • SoapServer::setClass ?
  • PHP Manual
  • SoapServer
  • Handles a SOAP request

SoapServer::handle

(PHP 5, PHP 7, PHP 8)

SoapServer::handle — Handles a SOAP request

说明

public SoapServer::handle ( string|null $request = null ) : void

Processes a SOAP request, calls necessary functions, and sends a response back.

参数

request

The SOAP request. If this argument is omitted, the request is assumed to be in the raw POST data of the HTTP request.

返回值

没有返回值。

范例

Example #1 SoapServer::handle() example

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

更新日志

版本 | 说明
8.0.0 | request is now nullable.

参见

  • SoapServer::__construct() - SoapServer constructor

User Contributed Notes

Bas van Dorst 19-Feb-2014 02:58
Additional information to the comment of "Joeri Thissen" (http://www.php.net/manual/en/soapserver.handle.php#113866)

In some cases the replacements generates a timeout (looks like it is in combination with Nginx). The problem is that PHP has already sent a content-length, and the webserver is still waiting for new content.

To fix this you have to reset the HTTP Content-Length with the right value:

<?php
ob_start();
$soapServer->handle();
$result = ob_get_contents();
ob_end_clean();

$result = str_replace("abcdef", "abc", $result);
$length = strlen($result);

header("Content-Length: ".$length);
echo $result;
Joeri Thissen 11-Dec-2013 10:59
Sometimes returned data can contain characters which are not valid in xml 1.0. This causes the xml being output by SoapServer::handle to be invalid. Although it's probably better to sanitize the data ealier, a combination of output buffering and a simple regular expression can be used as a quick fix to make sure the output is indeed valid xml.

For example:

<?php
    ob_start();
    $soapServer->handle();
    $soapXml = ob_get_contents();
    ob_end_clean();
    $soapXml = preg_replace ('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $soapXml);
    echo $soapXml;
?>
dub357 at gmail dot com 08-Feb-2012 10:54
After much headache and looking through PHP source code, I finally found out why the handle() function would immediately send back a fault with the string "Bad Request".
Turns out that my client was sending valid XML, but the first line of the XML was the actual XML declaration:

<?xml version="1.0" encoding="UTF-8"?>

When the "handle" function in the SoapServer class is called, it first tries to parse the XML.  When the XML document can't be parsed, a "Bad Request" fault is returned and execution of the script immediately stops.  I assume that the XML parser built into PHP (libxml2) already assumes the document to be XML and when it finds the declaration, it thinks it isn't valid.

I added some XML parsing calls to my service before the handle() function is called to check for valid XML and avoid the "Bad Request" fault.  This also allows me to send back a more suitable error message:

<?php
$parser = xml_parser_create("UTF-8");
if (!xml_parse($parser,$HTTP_RAW_POST_DATA,true)){
   $webService->fault("500", "Cannot parse XML: ".
      xml_error_string(xml_get_error_code($parser)).
       " at line: ".xml_get_current_line_number($parser).
       ", column: ".xml_get_current_column_number($parser));
}
?>
prenaud at profideo dot com 09-Jan-2012 02:23
Please note that when defining several services in one wsdl file, and calling one of those services, you may always get the response for your first service.

This is a known bug. You will find its description and some workarounds here  : https://bugs.php.net/bug.php?id=49169
Artur Graniszewski 15-Nov-2009 10:19
Be aware that SoapServer::handle(); method sends additional HTTP headers to the browser. One of them is "Content-Type: application/soap+xml". If you want to execute SOAP methods locally as a part of SoapClient::__doRequest() (see example at http://pl2.php.net/manual/en/soapclient.dorequest.php ) you may need to reset (override) this header back to "Content-Type: text/html" like so:

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));

header("Content-Type: text/html");

var_dump($x->Add(3,4));

?>
tom at backslashinteractive dot com 03-Oct-2008 10:54
In response to Blizzke:

Sometimes this problem can be hidden by an Apache segmentation fault along with an HTTP headers error SoapFault thrown to the client.

If you get either of those 2, try checking to make sure that style="rpc" in your WSDL file's soap:operation's.

-T
Blizzke at gmail dot com 12-Mar-2008 04:39
Seems pretty logical once you find the solution, but it took me quite a while to figure this one out:
If you are using WSDL based SOAP requests and you have more than one operation in your binding (with the same parameters), make sure the <soap:operation> style is set to rpc, NOT body!

When you specify 'body' here, all that will be transmitted in the request is the parameters for the function call, and SoapServer->handle() will use the first function it finds with the same parameter-makeup to handle the call.

ie If you have 2 functions:
<?php
function One ( string $blah );
function Two ( string $blah );
?>
Making a client call with SoapClient -> Two ( 'test' ); will result in One ( ) being called when your 'type' is set to 'body'

The actual method to call will only be included in the request when your type is set to 'rpc', resulting in the expected behavior
king dot maxemilian at noos dot fr 21-Aug-2007 09:23
Sometime, it happens that PHP does not detect anything in $HTTP_RAW_POST_DATA.

To solve this problem and make it work in any case:

function soaputils_autoFindSoapRequest()    {
    global $HTTP_RAW_POST_DATA;

    if($HTTP_RAW_POST_DATA)
        return $HTTP_RAW_POST_DATA;

    $f = file("php://input");
    return implode(" ", $f);
}

$server = new SoapServer($wsdl);
$server->setClass($MyClass);

$server->handle(soaputils_autoFindSoapRequest());


Sets the class which handles SOAP requests

  • ? SoapServer::handle
  • SoapServer::setObject ?
  • PHP Manual
  • SoapServer
  • Sets the class which handles SOAP requests

SoapServer::setClass

(PHP 5, PHP 7, PHP 8)

SoapServer::setClass — Sets the class which handles SOAP requests

说明

public SoapServer::setClass ( string $class , mixed ...$args ) : void

Exports all methods from specified class.

The object can be made persistent across request for a given PHP session with the SoapServer::setPersistence() method.

参数

class

The name of the exported class.

args

These optional parameters will be passed to the default class constructor during object creation.

返回值

没有返回值。

参见

  • SoapServer::__construct() - SoapServer constructor
  • SoapServer::addFunction() - 添加一个或多个函数来处理SOAP请求
  • SoapServer::setPersistence() - Sets SoapServer persistence mode

User Contributed Notes

funky2step at gmail dot com 25-Nov-2011 01:54
When passing arguments to the default class constructor, make sure that you don't try and use the magic __construct method because that won't work.

<?php

class MyClass
{
  function MyClass($arg1, $arg2)
  {

  }
}

// Not:

class MyClass
{
  function __construct($arg1, $arg2)
  {

  }
}

?>
christiaan at oakfox dot net 04-May-2009 04:21
You can also retrieve object properties the following way while using __autoload($class_name).

<?php

# Start Session
session_start();

# Auto Load Class as Required
function __autoload($class_name)
{
    require_once "/var/www/example/class/". $class_name. ".php";
}

//service

$_SESSION[_bogus_session_name] = unserialize($_SESSION[_bogus_session_name]);
$server = new SoapServer('service.wsdl');
$server->setClass("MyClass");
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
$_SESSION[_bogus_session_name] = serialize($_SESSION[_bogus_session_name])

?>
Ariz Jacinto 04-Dec-2008 04:38
If you want your SOAP client to be able to save and then retrieve the object properties, you need to set the SOAP server to be persistent by setting session.auto_start=0, invoking session_start(), and SoapServer->setPersistence(SOAP_PERSISTENCE_SESSION) in the following manner:

<?php
  //set ini
  ini_set("soap.wsdl_cache_enabled", 0);
  ini_set("session.auto_start", 0);

  //class file
  require_once('MyClass.php');

  //for persistent session
  session_start();

  //service
  $server = new SoapServer('service.wsdl');
  $server->setClass("MyClass");
  $server->setPersistence(SOAP_PERSISTENCE_SESSION);
  $server->handle();
?>


Sets the object which will be used to handle SOAP requests

  • ? SoapServer::setClass
  • SoapServer::setPersistence ?
  • PHP Manual
  • SoapServer
  • Sets the object which will be used to handle SOAP requests

SoapServer::setObject

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SoapServer::setObject — Sets the object which will be used to handle SOAP requests

说明

public SoapServer::setObject ( object $object ) : void

This sets a specific object as the handler for SOAP requests, rather than just a class as in SoapServer::setClass().

参数

object

The object to handle the requests.

返回值

没有返回值。

参见

  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

There are no user contributed notes for this page.


Sets SoapServer persistence mode

  • ? SoapServer::setObject
  • SoapFault ?
  • PHP Manual
  • SoapServer
  • Sets SoapServer persistence mode

SoapServer::setPersistence

(PHP 5, PHP 7, PHP 8)

SoapServer::setPersistence — Sets SoapServer persistence mode

说明

public SoapServer::setPersistence ( int $mode ) : void

This function allows changing the persistence state of a SoapServer object between requests. This function allows saving data between requests utilizing PHP sessions. This method only has an affect on a SoapServer after it has exported functions utilizing SoapServer::setClass().

Note:

The persistence of SOAP_PERSISTENCE_SESSION makes only objects of the given class persistent, but not the class static data. In this case, use $this->bar instead of self::$bar.

Note:

SOAP_PERSISTENCE_SESSION serializes data on the class object between requests. In order to properly utilize resources (e.g. PDO), __wakeup() and __sleep() magic methods should be utilized.

参数

mode

One of the SOAP_PERSISTENCE_XXX constants.

SOAP_PERSISTENCE_REQUEST - SoapServer data does not persist between requests. This is the default behavior of any SoapServer object after setClass is called.

SOAP_PERSISTENCE_SESSION - SoapServer data persists between requests. This is accomplished by serializing the SoapServer class data into $_SESSION['_bogus_session_name'], because of this session_start() must be called before this persistence mode is set.

返回值

没有返回值。

范例

Example #1 SoapServer::setPersistence() example

<?php
 class MyFirstPersistentSoapServer {
     private $resource; // (Such as PDO, mysqli, etc..)
     public $myvar1;
     public $myvar2;

     public function __construct() {
         $this->__wakeup(); // We're calling our wakeup to handle starting our resource
     }

     public function __wakeup() {
         $this->resource = CodeToStartOurResourceUp();
     }

     public function __sleep() {
         // We make sure to leave out $resource here, so our session data remains persistent
         // Failure to do so will result in the failure during the unserialization of data
         // on the next request; thus, our SoapObject would not be persistent across requests.
         return array('myvar1','myvar2');
     }
 }

 try {
     session_start();
     $server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
     $server->setClass('MyFirstPersistentSoapServer');
     // setPersistence MUST be called after setClass, because setClass's
     // behavior sets SESSION_PERSISTENCE_REQUEST upon enacting the method.
     $server->setPersistence(SOAP_PERSISTENCE_SESSION);
     $server->handle();
 } catch(SoapFault $e) {
     error_log("SOAP ERROR: ". $e->getMessage());
 }
?>

参见

  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

csnaitsirch at web dot de 01-Apr-2010 05:25
I want to give one example for the order of commands if you want to use a class in persistence mode.

<?php
// 1. class definition or include
class UserService
{
    public function __construct() { }
}

// 2. start the session after defining or including the class!!
session_start();

// 3. instanciate the server
$server = new SoapServer(null, array("something"));

// 4. set the class to use
$server->setClass('UserService');

// 5. set persistance mode
$server->setPersistence(SOAP_PERSISTENCE_SESSION);

// 6. handle the request
$server->handle();
?>
doug dot manley at gmail dot com 30-May-2008 12:54
When using "SoapServer::setPersistence( SOAP_PERSISTENCE_SESSION )", you apparently MUST include the class that was used in "SoapServer::setClass()" BEFORE any "session_*" commands.

I found this out using "__autoload()" and a whole lot of "syslog()"; it kept failing to include the class that I was using for my soap server, but that class is ONLY ever referenced by the page itself, and even then only for the purposes of setting the class for the soap server; none of my code would ever cause it to autoload.  The problem was that I was including my session-handling code first.

If the session gets started BEFORE the page defines the class definition, then persistence CANNOT happen.

The order should be:
1. Include the class for use with the soap server.
2. Start up your session.
3. Set up your soap server.
4. Handle your soap request.
boogiebug at gmail dot com 25-Mar-2008 07:40
setPersistence works only for a single instance of service class.

To use multiple instance of services objects, you need to instantiate the classes into objects and use an undocumented SoapServer's method - setObject() to add the service object into the SoapServer object, and handle the service object persistence with $_SESSION instead.

For example:

$ServiceObjects = array()
$ServiceObjects[0] = new ServiceClass1();
$ServiceObjects[1] = new ServiceClass2();
$ServiceObjects[2] = new ServiceClass3();

$_SESSION['ServiceClass1'] = $ServiceObjects[0];
$_SESSION['ServiceClass2'] = $ServiceObjects[1];
$_SESSION['ServiceClass3'] = $ServiceObjects[2];

...

$Servers = array()
for ( $i = 0; $i < count($ServiceObjects); i++)
{
  $s = new SoapServer($wsdl);
  $s->setObject($ServiceObject[$i]);
  $Servers[] = $s;
}

...

$Server[$i]->handle()

...
jan at pinna dot nl 26-Jan-2008 03:28
I found that using both modes (SOAP_PERSISTENCE_SESSION and SOAP_PERSISTENCE_REQUEST) cannot be used simultaniously. Because it didn't work at once, I started experimenting by using different settings and as stated below in the comments, "...also use SOAP_PERSISTENCE_REQUEST to save objects between requests" led me to think it was nessecary to use both modes. Well, it might for others, be but for me it turned out a day of freaking out ;) (trying all kinds of session stuff, etc etc).
Also, if persistence doesn't work, please check if session_start() is called somewhere in the script and try not to call it twice or whatsoever: it won't work...
jared at ws-db dot com 28-Aug-2005 12:07
I had some issues getting session persistence (SOAP_PERSISTENCE_SESSION) to work. I finally got it working after setting session.auto_start=0, and then only calling session_start() in the script containing the SoapServer. Maybe this is obvious, but took me a bit to figure it out.

I only tried it with session.use_cookies=1, so if the settings above don't work for you, make sure cookies are enabled, though it may work without the need for cookies.
cperez1000 at hotmail dot com 28-May-2005 08:54
Always remember to place the "setPersistence" method before the handle method, otherwise it won't work.  It sounds obvious, but it's still a very common mistake, since no errors are shown.


The SoapFault class

(PHP 5, PHP 7, PHP 8)

简介

Represents a SOAP fault.

类摘要

SoapFault extends Exception {
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 方法 */
public __construct ( array|string|null $code , string $string , string|null $actor = null , mixed $details = null , string|null $name = null , mixed $headerFault = null )
public __toString ( ) : string
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

Table of Contents

  • SoapFault::__construct — SoapFault constructor
  • SoapFault::__toString — Obtain a string representation of a SoapFault

User Contributed Notes

fbernoldi at gmail dot com 03-Oct-2012 05:46
Hi all,

I've decided to post this since it may be helpful, I've spend a couple of days trying to do this.

In order to use wsdl's specified faults with complex types, i.e:

WSDL definitions:

(xsd:schema namespace, ns1 = target namespace)

<xsd:element name="doubleFault">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="detail1" type="xsd:string"/>
      <xsd:element name="detail2" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>

WSDL messages:

<message name="fault_specified">
    <part name="relevant_name" element="ns1:doubleFault"/>
</message>

WSDL port type:

<portType name="test">
  <operation name="operationTest">
  <input message="ns1:not_relevant_request"/>
  <output message="ns1:not_relevant_response"/>
  <fault name="FaultSpecified" message="ns1:fault_specified"/>
  ....
</portType>

You have to specify the response in the detail parameter as an array corresponding the tag names.

PHP Code:

<?php

function operationTest($request_param ...) {

    // ...
    $array_details = array("detail1" => "Explanation 1", "detail2" => "Explanation 2");

    return new SoapFault("Server", "example fault string", null, $array_details, "FaultSpecified");

}

$server = new SOAPServer("handmade.wsdl");
$server->addFunction("operationTest");
$server->handle();

?>

that should respond something like this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://mynamespace">
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>SOAP-ENV:Server</faultcode>
         <faultstring>example fault string</faultstring>
         <detail>
            <ns1:doubleFault>
               <detail1>Explanation 1</detail1>
               <detail2>Explanation 2</detail2>
            </ns1:doubleFault>
         </detail>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I Hope it helps,
Federico.
chris AT cmbuckley DOT co DOT uk 13-May-2010 03:53
A bit more digging in ext/soap/soap.c and the set_soap_fault function reveals the other undocumented properties from the constructor:

<?php
try {
    throw new SoapFault('code', 'string', 'actor', 'detail', 'name', 'header');
} catch (Exception $ex) {
    var_dump($ex->faultcode, $ex->faultstring, $ex->faultactor, $ex->detail, $ex->_name, $ex->headerfault);
}
?>
dmitry dot koterov at gmail dot com 29-Oct-2009 02:21
You may use undocumented and invisible property $e->faultcode to access string version of $code. Because standard $e->getCode() does not work:

<?php
$e = new SoapFault("test", "msg");
var_dump($e->getCode()); // prints "0"
var_dump($e->faultcode); // prints "test"
?>

Also you may use namespaced fault codes:

<?php
$e = new SoapFault(array("namespace", "test"), "msg");
?>

- see ext/soap/soap.php, PHP_METHOD(SoapFault, SoapFault). To access the namespace, use $e->faultcodens


SoapFault constructor

  • ? SoapFault
  • SoapFault::__toString ?
  • PHP Manual
  • SoapFault
  • SoapFault constructor

SoapFault::__construct

(PHP 5, PHP 7, PHP 8)

SoapFault::__construct — SoapFault constructor

说明

public SoapFault::__construct ( array|string|null $code , string $string , string|null $actor = null , mixed $details = null , string|null $name = null , mixed $headerFault = null )

This class is used to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and detail are standard elements of a SOAP Fault.

参数

faultcode

The error code of the SoapFault.

faultstring

The error message of the SoapFault.

faultactor

A string identifying the actor that caused the error.

detail

More details about the cause of the error.

faultname

Can be used to select the proper fault encoding from WSDL.

headerfault

Can be used during SOAP header handling to report an error in the response header.

范例

Example #1 Some examples

<?php
function test($x)
{
    return new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

It is possible to use PHP exception mechanism to throw SOAP Fault.

Example #2 Some examples

<?php
function test($x)
{
    throw new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

参见

  • SoapServer::fault() - Issue SoapServer fault indicating an error
  • is_soap_fault() - Checks if a SOAP call has failed

User Contributed Notes

csnaitsirch at web dot de 01-Apr-2010 05:04
The first Parameter of the constructor, the faultcode, of SoapFault must be a string. Otherwise it will lead to an error.

<?php
throw new SoapFault(1, "Error message!"); // wrong
throw new SoapFault("1", "Error message!"); // right
?>


Obtain a string representation of a SoapFault

  • ? SoapFault::__construct
  • SoapHeader ?
  • PHP Manual
  • SoapFault
  • Obtain a string representation of a SoapFault

SoapFault::__toString

(PHP 5, PHP 7, PHP 8)

SoapFault::__toString — Obtain a string representation of a SoapFault

说明

public SoapFault::__toString ( ) : string

Returns a string representation of the SoapFault.

参数

此函数没有参数。

返回值

A string describing the SoapFault.

User Contributed Notes

There are no user contributed notes for this page.


The SoapHeader class

(PHP 5, PHP 7, PHP 8)

简介

Represents a SOAP header.

类摘要

SoapHeader {
/* 方法 */
__construct ( string $namespace , string $name , mixed $data = ? , bool $mustunderstand = ? , string $actor = ? )
}

Table of Contents

  • SoapHeader::__construct — SoapHeader constructor

User Contributed Notes

ericvaneldik at gmail dot com 08-Apr-2019 07:16
If you want to create an soap header wihtout namespace and without an item key value setup, you can use SoapVar

To get this:
<SOAP-ENV:Header>
    <IdentityHeader>
      <SessionID>123456789</SessionID>
    </IdentityHeader>
  </SOAP-ENV:Header>

you can use this php code:
<?php
$headerVar = new SoapVar('<IdentityHeader><SessionID>123456789</SessionID></IdentityHeader>',
      XSD_ANYXML);
$header = new SoapHeader('http://tempuri.org/','RequestParams',
      $headerVar);
?>
abdul dot rashid at paytabs dot co 13-Mar-2016 10:06
Just to add some note regarding his john at jtresponse dot co dot uk

In PHP you can try following code to avoid the <item><key/>

$Auth = new stdClass();
$Auth->SystemId = "DATA";
$Auth->UserName = "USERNAME";
$Auth->Password = "PASSWORD";

$header = new SoapHeader('NAMESPACE','Auth',$Auth,false);
$soapClient->__setSoapHeaders($header);

  <SOAP-ENV:Header>
    <ns1:Auth>
      <ns1:SystemId>DATA</ns1:SystemId>
      <ns1:UserName>USERNAME</ns1:UserName>
      <ns1:Password>PASSWORD</ns1:Password>
    </ns1:Auth>
  </SOAP-ENV:Header>
voroks at logics dot net dot au 03-Jul-2015 12:43
Example by john at jtresponse dot co dot uk does miss one important point: to be able to add attributes they must be mentioned in WSDL. If they not exist in WSDL they WILL NOT appear as attributes but rather <item><key/><value/></item> elements.
john at jtresponse dot co dot uk 13-Mar-2012 01:30
None of the examples really do it for me.
Note: you should NOT need to hard-code any XML.

Here is an example of creating a nested header and including a parameter.

$client = new SoapClient(WSDL,array());

$auth = array(
        'UserName'=>'USERNAME',
        'Password'=>'PASSWORD',
        'SystemId'=> array('_'=>'DATA','Param'=>'PARAM'),
        );
  $header = new SoapHeader('NAMESPACE','Auth',$auth,false);
  $client->__setSoapHeaders($header);

Gives the following header XML:

  <SOAP-ENV:Header>
    <ns1:Auth>
      <ns1:SystemId Param="PARAM">DATA</ns1:SystemId>
      <ns1:UserName>USERNAME</ns1:UserName>
      <ns1:Password>PASSWORD</ns1:Password>
    </ns1:Auth>
  </SOAP-ENV:Header>


SoapHeader constructor

  • ? SoapHeader
  • SoapParam ?
  • PHP Manual
  • SoapHeader
  • SoapHeader constructor

SoapHeader::__construct

(PHP 5, PHP 7, PHP 8)

SoapHeader::__construct — SoapHeader constructor

说明

SoapHeader::__construct ( string $namespace , string $name , mixed $data = ? , bool $mustunderstand = ? , string $actor = ? )

Constructs a new SoapHeader object.

参数

namespace

The namespace of the SOAP header element.

name

The name of the SoapHeader object.

data

A SOAP header's content. It can be a PHP value or a SoapVar object.

mustUnderstand

Value of the mustUnderstand attribute of the SOAP header element.

actor

Value of the actor attribute of the SOAP header element.

范例

Example #1 SoapHeader::__construct() example

<?php
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->__soapCall("echoVoid", null, null,
                new SoapHeader('http://soapinterop.org/echoheader/',
                               'echoMeStringRequest',
                               'hello world'));
?>

参见

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::__construct() - SoapVar constructor
  • SoapParam::__construct() - SoapParam constructor
  • SoapServer::addSoapHeader() - Add a SOAP header to the response

User Contributed Notes

There are no user contributed notes for this page.


The SoapParam class

(PHP 5, PHP 7, PHP 8)

简介

Represents parameter to a SOAP call.

类摘要

SoapParam {
/* 方法 */
public __construct ( mixed $data , string $name )
}

Table of Contents

  • SoapParam::__construct — SoapParam constructor

User Contributed Notes

There are no user contributed notes for this page.


SoapParam constructor

  • ? SoapParam
  • SoapVar ?
  • PHP Manual
  • SoapParam
  • SoapParam constructor

SoapParam::__construct

(PHP 5, PHP 7, PHP 8)

SoapParam::__construct — SoapParam constructor

说明

public SoapParam::__construct ( mixed $data , string $name )

Constructs a new SoapParam object.

参数

data

The data to pass or return. This parameter can be passed directly as PHP value, but in this case it will be named as paramN and the SOAP service may not understand it.

name

The parameter name.

范例

Example #1 SoapParam::__construct() example

<?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
                                    'uri'      => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?>

参见

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::__construct() - SoapVar constructor

User Contributed Notes

There are no user contributed notes for this page.


The SoapVar class

(PHP 5, PHP 7, PHP 8)

简介

A class representing a variable or object for use with SOAP services.

类摘要

SoapVar {
/* 方法 */
public __construct ( mixed $data , int|null $encoding , string $typeName = "" , string $typeNamespace = "" , string $nodeName = "" , string $nodeNamespace = "" )
}

Table of Contents

  • SoapVar::__construct — SoapVar constructor

User Contributed Notes

seth dot johnson at gmail dot com 25-Feb-2015 12:09
It is not documented and thus may be subject to change but if you need to inspect the constructed SoapVar it sets everything you pass it on public variables:

<?php
$foo = new \stdClass();
$foosoap = new \SoapVar($foo, SOAP_ENC_OBJECT, 'Foo');
var_dump($foosoap);
echo $foosoap->enc_stype;
echo get_class($foosoap->enc_value);
?>

Will output (tested in PHP 5.3.3 cli):

object(SoapVar)#2 (3) {
  ["enc_type"]=>
  int(301)
  ["enc_value"]=>
  object(stdClass)#1 (0) {
  }
  ["enc_stype"]=>
  string(3) "Foo"
}

Foo
stdClass


SoapVar constructor

  • ? SoapVar
  • Yar ?
  • PHP Manual
  • SoapVar
  • SoapVar constructor

SoapVar::__construct

(PHP 5, PHP 7, PHP 8)

SoapVar::__construct — SoapVar constructor

说明

public SoapVar::__construct
 ( mixed $data
, int|null $encoding
, string $typeName = ""
, string $typeNamespace = ""
, string $nodeName = ""
, string $nodeNamespace = ""
)

Constructs a new SoapVar object.

参数

data

The data to pass or return.

encoding

The encoding ID, one of the XSD_... constants.

type_name

The type name.

type_namespace

The type namespace.

node_name

The XML node name.

node_namespace

The XML node namespace.

范例

Example #1 SoapVar::__construct() example

<?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f)
    {
        $this->varString = $s;
        $this->varInt = $i;
        $this->varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>

参见

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapParam::__construct() - SoapParam constructor

User Contributed Notes

There are no user contributed notes for this page.


Yet Another RPC Framework

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
  • Yar_Server — The Yar_Server class
    • Yar_Server::__construct — 创建一个HTTP RPC Server
    • Yar_Server::handle — 启动HTTP RPC Server
  • Yar_Client — The Yar_Client class
    • Yar_Client::__call — 调用远程服务
    • Yar_Client::__construct — 创建一个客户端实例
    • Yar_Client::setOpt — 设置调用的配置
  • Yar_Concurrent_Client — The Yar_Concurrent_Client class
    • Yar_Concurrent_Client::call — 注册一个并行的服务调用
    • Yar_Concurrent_Client::loop — 发送所有注册的并行调用
  • Yar_Server_Exception — The Yar_Server_Exception class
    • Yar_Server_Exception::getType — 获取异常的原始类型
  • Yar_Client_Exception — The Yar_Client_Exception class
    • Yar_Client_Exception::getType — The getType purpose

User Contributed Notes

There are no user contributed notes for this page.


简介

Yar 是一个轻量级, 高效的RPC框架, 它提供了一种简单方法来让PHP项目之间可以互相远程调用对方的本地方法. 并且Yar也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法.

User Contributed Notes

There are no user contributed notes for this page.


需求

如果需要使用Msgpack作为打包协议, 则需要在configure的时候加上--enable-msgpack, 并且要保证Msgpack扩展也安装到PHP内.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/yar.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

liubinn_208391 at qq dot com 08-Dec-2013 05:35
Yar Concurrent Client doesn't work on Mac OS.  It is because the cURL shipped with Mac has some difference.

you can resolve that by install a new cURL, like (brew install curl).

then use :
"export DYLD_LIBRARY_PATH=/path-to-new-curl/lib:$DYLD_LIBRARY_PATH"

make the PHP use the new cURL.

of course you can also re-compile your PHP with --with-curl=/path-to-new-curl/


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Yar 配置选项
名字 | 默认 | 可修改范围 | 更新日志
yar.packager | php | PHP_INI_SYSTEM |
yar.debug | Off | PHP_INI_ALL |
yar.connect_timeout | 1000 | PHP_INI_ALL |
yar.timeout | 5000 | PHP_INI_ALL |
yar.expose_info | On | PHP_INI_SYS |

这是配置指令的简短说明。

yar.packager string

设置Yar的打包工具, 可以是PHP(serialize), JSON, Msgpack(这个需要编译的时候指定--enable-msgpack).

yar.debug string

打开的时候, Yar会把请求过程的日志都打印出来(到stderr).

yar.connect_timeout integer

连接超时(毫秒为单位)

yar.timeout integer

处理超时(毫秒为单位)

yar.expose_info bool

如果关闭, 则当通过浏览器访问Server的时候, 不会出现Server Info信息.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

YAR_VERSION (string)
YAR_CLIENT_PROTOCOL_HTTP (integer)
YAR_CLIENT_OPT_PACKAGER (integer)
YAR_CLIENT_OPT_TIMEOUT (integer)
YAR_CLIENT_OPT_CONNECT_TIMEOUT (integer)
YAR_PACKAGER_PHP (string)
YAR_PACKAGER_JSON (string)
YAR_ERR_OKEY (integer)
YAR_ERR_OUTPUT (integer)
YAR_ERR_TRANSPORT (integer)
YAR_ERR_REQUEST (integer)
YAR_ERR_PROTOCOL (integer)
YAR_ERR_PACKAGER (integer)
YAR_ERR_EXCEPTION (integer)

User Contributed Notes

There are no user contributed notes for this page.


范例

Example #1 Yar Server示例

<?php

/* 假设这个页面的访问路径是: http://example.com/operator.php */

class Operator {

    /**
     * Add two operands
     * @param interge
     * @return interge
     */
    public function add($a, $b) {
        return $this->_add($a, $b);
    }

    /**
     * Sub
     */
    public function sub($a, $b) {
        return $a - $b;
    }

    /**
     * Mul
     */
    public function mul($a, $b) {
        return $a * $b;
    }

    /**
     * Protected methods will not be exposed
     * @param interge
     * @return interge
     */
    protected function _add($a, $b) {
        return $a + $b;
    }
}

$server = new Yar_Server(new Operator());
$server->handle();
?>

Example #2 通过浏览器访问(GET请求)

以上例程的输出类似于：

Yar Server Info

Example #3 Yar Client示例

<?php
$client = new yar_client("http://example.com/operator.php");

/* call directly */
var_dump($client->add(1, 2));

/* call via call */
var_dump($client->call("add", array(3, 2)));

/* __add can not be called */
var_dump($client->_add(1, 2));
?>

以上例程的输出类似于：

int(3)
int(5)
PHP Fatal error:  Uncaught exception 'Yar_Server_Exception' with message 'call to api Operator::_add() failed' in *

Example #4 Yar Concurrent Client示例

<?php
function callback($ret, $callinfo) {
    echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* 注册一个异步调用 */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "mul", array(2, 2), "callback");

/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */
Yar_Concurrent_Client::loop();
?>

以上例程的输出类似于：

mul result: 4
sub result: 1
add result: 3

User Contributed Notes

124960772 at qq dot com 10-Nov-2015 11:03
<?php
function callback($ret, $callinfo) {
    echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* 注册一个异步调用 */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */
Yar_Concurrent_Client::loop();
/* 重置call ,否则上面的call会调用*/
Yar_Concurrent_Client::reset();
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::loop();

?>


The Yar_Server class

(No version information available, might only be in Git)

简介

类摘要

Yar_Server {
/* 属性 */
protected $_executor ;
/* 方法 */
final public __construct ( Object $obj )
public handle ( ) : boolean
}

属性

_executor

Table of Contents

  • Yar_Server::__construct — 创建一个HTTP RPC Server
  • Yar_Server::handle — 启动HTTP RPC Server

User Contributed Notes

There are no user contributed notes for this page.


创建一个HTTP RPC Server

  • ? Yar_Server
  • Yar_Server::handle ?
  • PHP Manual
  • Yar_Server
  • 创建一个HTTP RPC Server

Yar_Server::__construct

(PECL yar >= 1.0.0)

Yar_Server::__construct — 创建一个HTTP RPC Server

说明

final public Yar_Server::__construct ( Object $obj )

创建一个Yar的HTTP RPC服务，参数 $obj 对象的所有公开方法都会被注册为服务函数， 可以被RPC调用。

参数

obj

一个对象实例, 这个对象的所有公开方法都会被注册为服务函数.

返回值

返回一个Yar_Server的实例。

范例

Example #1 Yar_Server::__construct()示例

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
         return "some_method";
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

以上例程的输出类似于：

参见

  • Yar_Server::handle() - 启动HTTP RPC Server
    •

User Contributed Notes

There are no user contributed notes for this page.


启动HTTP RPC Server

  • ? Yar_Server::__construct
  • Yar_Client ?
  • PHP Manual
  • Yar_Server
  • 启动HTTP RPC Server

Yar_Server::handle

(PECL yar >= 1.0.0)

Yar_Server::handle — 启动HTTP RPC Server

说明

public Yar_Server::handle ( ) : boolean

启动服务, 开始接受客户端的调用请求.

Note:

来自客户端的调用, 都是通过POST请求发送过来的. 如果一个GET请求访问到这个Server, 那在yar.expose_info开启的情况下, 这个服务的Server Info信息会被展现.

参数

此函数没有参数。

返回值

boolean

范例

Example #1 Yar_Server::handle()示例

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

以上例程的输出类似于：

参见

  • Yar_Server::__construct() - 创建一个HTTP RPC Server
    •

User Contributed Notes

There are no user contributed notes for this page.


The Yar_Client class

(No version information available, might only be in Git)

简介

类摘要

Yar_Client {
/* 属性 */
protected $_protocol ;
protected $_uri ;
protected $_options ;
protected $_running ;
/* 方法 */
public __call ( string $method , array $parameters ) : void
final public __construct ( string $url )
public setOpt ( number $name , mixed $value ) : boolean
}

属性

_protocol

_uri

_options

_running

Table of Contents

  • Yar_Client::__call — 调用远程服务
  • Yar_Client::__construct — 创建一个客户端实例
  • Yar_Client::setOpt — 设置调用的配置

User Contributed Notes

porschegt23 at foxmail dot com 05-Jul-2016 11:07
A simple example on here:

server.php
<?php
class API {

    public function api($parameter = "", $option = "foo") {
          return $this->client_can_not_see($parameter);
    }

    public function doAdd($a = 0, $b = 0) {
          return $a+$b;
    }

    protected function client_can_not_see( $name ) {
      return "你好$name~";
    }
}

$service = new Yar_Server ( new API () );
$service->handle ();
?>
client.php
<?php
  $client = new Yar_Client("http://host/server.php");
  $result = $client->api("parameter");
  echo $result.'<hr>';
  echo $client->doAdd(10, 20);
?>


调用远程服务

  • ? Yar_Client
  • Yar_Client::__construct ?
  • PHP Manual
  • Yar_Client
  • 调用远程服务

Yar_Client::__call

(PECL yar >= 1.0.0)

Yar_Client::__call — 调用远程服务

说明

public Yar_Client::__call ( string $method , array $parameters ) : void

发起一个RPC调用, 并且得到返回值. 如果服务端的远程调用抛出异常, 那么本地也会相应的抛出一个Yar_Server_Exception异常.

参数

method

远程服务的名字.

parameters

调用参数.

返回值

范例

Example #1 Yar_Client::__call() example

<?php

$client = new Yar_Client("http://host/api/");

/* 调用远程服务的some_method服务 */
$result = $client->some_method("parameter");

?>

以上例程的输出类似于：

参见

  • Yar_Client::setOpt() - 设置调用的配置
    •

User Contributed Notes

There are no user contributed notes for this page.


创建一个客户端实例

  • ? Yar_Client::__call
  • Yar_Client::setOpt ?
  • PHP Manual
  • Yar_Client
  • 创建一个客户端实例

Yar_Client::__construct

(PECL yar >= 1.0.0)

Yar_Client::__construct — 创建一个客户端实例

说明

final public Yar_Client::__construct ( string $url )

创建一个Yar_Client 到一个 Yar_Server的实例.

参数

url

服务端的HTTP URL路径.

返回值

Yar_Client实例.

范例

Example #1 Yar_Client::__construct()示例

<?php
$client = new Yar_Client("http://host/api/");
?>

以上例程的输出类似于：

参见

  • Yar_Client::__call() - 调用远程服务
    •

  • Yar_Client::setOpt() - 设置调用的配置
    •

User Contributed Notes

There are no user contributed notes for this page.


设置调用的配置

  • ? Yar_Client::__construct
  • Yar_Concurrent_Client ?
  • PHP Manual
  • Yar_Client
  • 设置调用的配置

Yar_Client::setOpt

(PECL yar >= 1.0.0)

Yar_Client::setOpt — 设置调用的配置

说明

public Yar_Client::setOpt ( number $name , mixed $value ) : boolean

设置调用远程服务的一些配置, 比如超时值, 打包类型等.

参数

name

可以是: YAR_OPT_PACKAGER, YAR_OPT_PERSISTENT (需要服务端支持keepalive), YAR_OPT_TIMEOUT, YAR_OPT_CONNECT_TIMEOUT

value

返回值

范例

Example #1 Yar_Client::setOpt()示例

<?php

$cient = new Yar_Client("http://host/api/");

//Set timeout to 1s
$client->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);

//Set packager to JSON
$client->SetOpt(YAR_OPT_PACKAGER, "json");

/* call remote service */
$result = $client->some_method("parameter");
?>

以上例程的输出类似于：

参见

  • Yar_Client::__call() - 调用远程服务
    •

User Contributed Notes

There are no user contributed notes for this page.


The Yar_Concurrent_Client class

(No version information available, might only be in Git)

简介

类摘要

Yar_Concurrent_Client {
/* 属性 */
static $_callstack ;
static $_callback ;
static $_error_callback ;
/* 方法 */
public static call ( string $uri , string $method , array $parameters = ? , callable $callback = ? , callable $error_callback = ? , array $options = ? ) : int
public static loop ( callable $callback = ? , callable $error_callback = ? ) : boolean
}

属性

_callstack

_callback

_error_callback

Table of Contents

  • Yar_Concurrent_Client::call — 注册一个并行的服务调用
  • Yar_Concurrent_Client::loop — 发送所有注册的并行调用

User Contributed Notes

There are no user contributed notes for this page.


注册一个并行的服务调用

  • ? Yar_Concurrent_Client
  • Yar_Concurrent_Client::loop ?
  • PHP Manual
  • Yar_Concurrent_Client
  • 注册一个并行的服务调用

Yar_Concurrent_Client::call

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::call — 注册一个并行的服务调用

说明

public static Yar_Concurrent_Client::call ( string $uri , string $method , array $parameters = ? , callable $callback = ? , callable $error_callback = ? , array $options = ? ) : int

注册一个并行的(异步的)远程服务调用, 不过这个调用请求不会被立即发出, 而是会在接下来调用 Yar_Concurrent_Client::loop()的时候才真正的发送出去.

参数

uri

RPC 服务的 URI(http 或 tcp).

method

调用的服务名字(也就是服务方法名).

parameters

调用的参数.

callback

回调函数, 在远程服务的返回到达的时候被Yar调用, 从而可以处理返回内容.

返回值

唯一 ID， 可用于区分到底是那个调用的返回.

范例

Example #1 Yar_Concurrent_Client::call()示例

<?php
function callback($retval, $callinfo) {
     var_dump($retval);
}

function error_callback($type, $error, $callinfo) {
    error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"));   // if the callback is not specificed,
                                                                               // callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //custom timeout

// 这个时候请求都还没有发出
?>

以上例程的输出类似于：

参见

  • Yar_Concurrent_Client::loop() - 发送所有注册的并行调用
    •

  • Yar_Concurrent_Client::reset()
    •

  • Yar_Server::__construct() - 创建一个HTTP RPC Server
    •

  • Yar_Server::handle() - 启动HTTP RPC Server
    •

User Contributed Notes

There are no user contributed notes for this page.


发送所有注册的并行调用

  • ? Yar_Concurrent_Client::call
  • Yar_Server_Exception ?
  • PHP Manual
  • Yar_Concurrent_Client
  • 发送所有注册的并行调用

Yar_Concurrent_Client::loop

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::loop — 发送所有注册的并行调用

说明

public static Yar_Concurrent_Client::loop ( callable $callback = ? , callable $error_callback = ? ) : boolean

发送所有的已经通过 Yar_Concurrent_Client::call()注册的并行调用, 并且等待返回.

参数

callback

如果这个回掉函数被设置, 那么Yar在发送出所有的请求之后立即调用一次这个回掉函数(此时还没有任何请求返回), 调用的时候$callinfo参数是NULL.

如果在注册并行调用的时候制定了callback, 那么那个callback有更高的优先级.

error_callback

错误回掉函数, 如果设置了, 那么Yar在出错的时候会调用这个回掉函数.

返回值

范例

Example #1 Yar_Concurrent_Client::loop() example

<?php
function callback($retval, $callinfo) {
     if ($callinfo == NULL) {
        echo "现在, 所有的请求都发出去了, 还没有任何请求返回\n";
     } else {
              echo "这是一个远程调用的返回, 调用的服务名是", $callinfo["method"],
                      ". 调用的sequence是 " , $callinfo["sequence"] , "\n";
        var_dump($retval);
     }
}

function error_callback($type, $error, $callinfo) {
    error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"));   // if the callback is not specificed,
                                                                               // callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //custom timeout

Yar_Concurrent_Client::loop("callback", "error_callback"); //send the requests,
                                                           //the error_callback is optional
?>

以上例程的输出类似于：

现在, 所有的请求都发出去了, 还没有任何请求返回
这是一个远程调用的返回, 调用的服务名是some_method, 调用的sequence是 4
string(11) "some_method"
这是一个远程调用的返回, 调用的服务名是some_method, 调用的sequence是 1
string(11) "some_method"
这是一个远程调用的返回, 调用的服务名是some_method, 调用的sequence是 2
string(11) "some_method"
这是一个远程调用的返回, 调用的服务名是some_method, 调用的sequence是 3
string(11) "some_method"

参见

  • Yar_Concurrent_Client::call() - 注册一个并行的服务调用
  • Yar_Server::__construct() - 创建一个HTTP RPC Server
  • Yar_Server::handle() - 启动HTTP RPC Server

User Contributed Notes

There are no user contributed notes for this page.


The Yar_Server_Exception class

(No version information available, might only be in Git)

简介

If service threw exceptions, A Yar_Server_Exception will be threw in client side.

类摘要

Yar_Server_Exception extends Exception {
/* 属性 */
protected $_type ;
/* 方法 */
public getType ( ) : string
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

属性

message

code

file

line

_type

Table of Contents

  • Yar_Server_Exception::getType — 获取异常的原始类型

User Contributed Notes

There are no user contributed notes for this page.


获取异常的原始类型

  • ? Yar_Server_Exception
  • Yar_Client_Exception ?
  • PHP Manual
  • Yar_Server_Exception
  • 获取异常的原始类型

Yar_Server_Exception::getType

(PECL yar >= 1.0.0)

Yar_Server_Exception::getType — 获取异常的原始类型

说明

public Yar_Server_Exception::getType ( ) : string

当服务端的服务函数抛出异常的时候, 客户端本地会响应的抛出一个Yar_Server_Exception异常. 有一个属性, 标明了服务端异常的类型. 这个方法就是获取这个异常类型.

参数

此函数没有参数。

返回值

string

范例

Example #1 Yar_Server_Exception::getType()示例

//Server.php
<?php
class Custom_Exception extends Exception {};

class API {
    public function throw_exception($name) {
        throw new Custom_Exception($name);
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

//Client.php
<?php
$client = new Yar_Client("http://host/api.php");

try {
    $client->throw_exception("client");
} catch (Yar_Server_Exception $e) {
    var_dump($e->getType());
    var_dump($e->getMessage());
}

以上例程的输出类似于：

string(16) "Custom_Exception"
string(6) "client"

参见

User Contributed Notes

There are no user contributed notes for this page.


The Yar_Client_Exception class

(No version information available, might only be in Git)

简介

类摘要

Yar_Client_Exception extends Exception {
/* 属性 */
/* 方法 */
public getType ( ) : void
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

属性

message

code

file

line

Table of Contents

  • Yar_Client_Exception::getType — The getType purpose

User Contributed Notes

There are no user contributed notes for this page.


The getType purpose

  • ? Yar_Client_Exception
  • XML-RPC ?
  • PHP Manual
  • Yar_Client_Exception
  • The getType purpose

Yar_Client_Exception::getType

(PECL yar >= 1.0.0)

Yar_Client_Exception::getType — The getType purpose

说明

public Yar_Client_Exception::getType ( ) : void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

范例

Example #1 Yar_Client_Exception::getType() example

<?php

/* ... */

?>

以上例程的输出类似于：

...

参见

User Contributed Notes

There are no user contributed notes for this page.


XML-RPC

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • XML-RPC 函数
    • xmlrpc_decode_request — 将 XML 译码为 PHP 本身的类型
    • xmlrpc_decode — 将 XML 译码为 PHP 本身的类型
    • xmlrpc_encode_request — 为 PHP 的值生成 XML
    • xmlrpc_encode — 为 PHP 的值生成 XML
    • xmlrpc_get_type — 为 PHP 的值获取 xmlrpc 的类型
    • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions — 将 XML 译码成方法描述的列表
    • xmlrpc_server_add_introspection_data — 添加自我描述的文档
    • xmlrpc_server_call_method — 解析 XML 请求同时调用方法
    • xmlrpc_server_create — 创建一个 xmlrpc 服务端
    • xmlrpc_server_destroy — 销毁服务端资源
    • xmlrpc_server_register_introspection_callback — 注册一个 PHP 函数用于生成文档
    • xmlrpc_server_register_method — 注册一个 PHP 函数用于匹配 xmlrpc 方法名
    • xmlrpc_set_type — 为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间

User Contributed Notes

There are no user contributed notes for this page.


简介

These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at » http://www.xmlrpc.com/, and more documentation on this extension and its functions at » http://xmlrpc-epi.sourceforge.net/.

Warning

此扩展是实验性 的。 此扩展的表象，包括其函数名称以及其他此扩展的相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本扩展风险自担。

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 01:21
If you have troubles installing the php extension, there is an alternative package which tries to implement the same API  as pure-php library and can be installed via Composer: phpxmlrpc/polyfill-xmlrpc


安装

默认情况下在 PHP 中是不能使用 XML-RPC 支持的。你需要使用 --with-xmlrpc[=DIR] 配置选项编译 PHP 才能够使用 XML-RPC 支持。从 PHP 4.1.0 开始附带了此扩展。

User Contributed Notes

pitje 31-Jan-2021 07:40
according to php(dot)watch/versions/8.0/xmlrpc ,
PHP 8.0: XMLRPC extension is moved to PECL

checked, xmlrpc-1.0.0RC2 works for me
giunta dot gaetano at gmail dot com 29-Dec-2020 01:18
Here's what I had to do in order to install the xmlrpc extension on php 8 (from sury repos) on Ubuntu 16, as there is no package available via pecl or apt:

# build
git clone https://git.php.net/repository/pecl/networking/xmlrpc.git
export CPPFLAGS=-I/usr/include/libxml2/
cd xmlrpc && phpize && ./configure --with-expat && make && make install

# enable - this varies depending on your configuration; apache/nginx/fpm will also need to be restarted
echo "extension=xmlrpc.so" > /etc/php/8.0/mods-available/xmlrpc.ini
ln -s /etc/php/8.0/mods-available/xmlrpc.ini /etc/php/8.0/cli/conf.d/20-xmlrpc.ini
ln -s /etc/php/8.0/mods-available/xmlrpc.ini /etc/php/8.0/fpm/conf.d/20-xmlrpc.ini
Anonymous 15-Dec-2020 02:11
for centos try:
yum install php-xmlrpc
cnunez at cyberargsistemas dot com dot ar 17-Oct-2019 08:07
sudo apt-get install php7.2-xmlrpc


资源类型

This extension defines a XML-RPC server resource returned by xmlrpc_server_create().

User Contributed Notes

There are no user contributed notes for this page.


XML-RPC 函数

Table of Contents

  • xmlrpc_decode_request — 将 XML 译码为 PHP 本身的类型
  • xmlrpc_decode — 将 XML 译码为 PHP 本身的类型
  • xmlrpc_encode_request — 为 PHP 的值生成 XML
  • xmlrpc_encode — 为 PHP 的值生成 XML
  • xmlrpc_get_type — 为 PHP 的值获取 xmlrpc 的类型
  • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
  • xmlrpc_parse_method_descriptions — 将 XML 译码成方法描述的列表
  • xmlrpc_server_add_introspection_data — 添加自我描述的文档
  • xmlrpc_server_call_method — 解析 XML 请求同时调用方法
  • xmlrpc_server_create — 创建一个 xmlrpc 服务端
  • xmlrpc_server_destroy — 销毁服务端资源
  • xmlrpc_server_register_introspection_callback — 注册一个 PHP 函数用于生成文档
  • xmlrpc_server_register_method — 注册一个 PHP 函数用于匹配 xmlrpc 方法名
  • xmlrpc_set_type — 为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间

User Contributed Notes

digibrisk at gmail dot NOSPAM dot SPAMNO dot com 05-Oct-2007 03:24
Adding to what giunta dot gaetano at sea-aeroportimilano dot it and astrolox at lawyersonline dot co dot uk said about the Sourceforge PHP XML-RPC project: You can probably use function_exists() to determine whether the extension is installed so you don't have to incur performance costs. If it's not installed, then the function won't exist, and function_exists() returns false. You can then fall back on the alternative library if that's the case. For example:

<?php

if(!function_exists("xmlrpc_server_create")) {
    // include necessary files.
}

?>
handco at gmail dot com 20-Feb-2007 08:19
Hi,

A little snippet to implement OO XML RPC Server.

File RPCPlugin.php :

class RPCPlugins {

    private $plugins;

    function __construct ($pathname, $rpcServer) {
        $d = dir($pathname);
        while (($file = $d->read()) !== false) {
            if (ereg('(.*)\.php$', $file, $regs)) {
                include_once ($pathname . '/' . $file);
                $class=$regs[1];
                $this->plugins = new $class($rpcServer);
            }
        }
    }

}

class RPCPlugin {

    private $_rpcServer;

    function __construct($rpcServer) {
        $this->_rpcServer = $rpcServer;

        $methods = get_class_methods($this);

        foreach ($methods as $method) {
            if (substr($method, 0,1) != '_') {
                xmlrpc_server_register_method($rpcServer,get_class($this) . "." . $method,array(&$this,$method));
            }
        }

    }

}

An example of plugin in plugins/Test.php  :

 class Test extends RPCPlugin {

     function HelloWorld ($method, $params) {
         return "Hello World --->>" . $params[0];
     }

 }

Now the real server :

require_once 'RPCPlugin.php';

 $rpcServer = xmlrpc_server_create();

$plugins = new RPCPlugins(realpath('plugins/'), $rpcServer);

 $resp = xmlrpc_server_call_method($rpcServer,$HTTP_RAW_POST_DATA,null);
 if ($resp) {
     header ('Content-Type: text/xml');
     echo $resp;
 }
 xmlrpc_server_destroy($rpcServer)

Then you can call ethod by classname.method.
For this sample Test.HelloWorld

Hn'Co
giunta dot gaetano at sea-aeroportimilano dot it 13-Sep-2006 06:40
If you need to use this extension but are stuck on a server where it can not be installed, the php-xmlrpc library found at http://phpxmlrpc.sourceforge.net includes an emulation layer that aims to be 100% compatible with the API of the native extension (as part of the "extras" package since version 0.2).
This means your code should be able to run unmodified on top of the php-xmlrpc library. Of course performance will be at least an order of magnitude worse...
keithNO dot SPAMthornhill at gmail dot com 17-May-2006 02:16
for others attempting the same thing, here is what a function would look like if you wanted to send a base64 encoded file from a client and then save it onto the server. the other code necessary to call this function via an RPC is available in other comments so i won't repeat it.

parameters:
1 - name of file
2 - base64 encoded data of file

note the use of $file_data->scalar

<?
    function sendFile($method_name, $params, $user_data) {
        $file = "/somedir/" . $params[0];
        $file_data = $params[1];

        $fh = @fopen($file, "wb");
        if ($fh) {
            if (@fwrite($fh, $file_data->scalar)) {
                $msg = "success msg";
            } else {
                $msg = "couldn't write to file";
            }
            fclose($fh);
            return $msg;
        } else {
            return "couldn't open file";
        }
    }
?>
09-Mar-2006 12:47
This XML-RPC Service makes the use XML-RPC very esay.

<?php

/**
* function myfun() returns
*@return array
*/
function myfunc(){
    return $some_array;
}

$ws = new XML_RPC_Server();
$ws->registerFunction('myfunc');
$ws->run();

?>

http://www.pure-php.de/node/31

It creates also a simple docu.
http://www.pure-php.com/php/service.php?doc
john # curioussymbols com 19-Oct-2005 04:37
I couldn't make the 'xmlrpc_errors' php.ini setting do anything
noticeable (PHP 4.3.11), so I used the following code to report errors
from my XMLRPC server. Hope it's helpful for someone.

<?php
function return_xmlrpc_error($errno,$errstr,$errfile=NULL,$errline=NULL
       ,$errcontext=NULL){
    global $xmlrpc_server;
    if(!$xmlrpc_server)die("Error: $errstr in '$errfile', line '$errline'");

    header("Content-type: text/xml; CHARSET=gb2312");
    print(xmlrpc_encode(array(
        'faultCode'=>$errno
        ,'faultString'=>"Remote XMLRPC Error from
          ".$_SERVER['HTTP_HOST'].": $errstr in at $errfile:$errline"
    )));
    die();
}
set_error_handler('return_xmlrpc_error');
?>

In my server function, I just trigger_error("message",E_USER_ERROR)]
 if something can't be completed.

Then on the client side,
<?php
        $data =& xmlrpc_decode($response['body']);

        if(xmlrpc_is_fault($data)){
            trigger_error($data['faultString'],E_USER_ERROR);
        }
?>
martin dot rode at programmfabrik dot de 04-Aug-2005 05:28
To connect to a python xmlrpc server I use:

function do_call($host, $port, $request) {

    $url = "http://$host:$port/";
    $header[] = "Content-type: text/xml";
    $header[] = "Content-length: ".strlen($request);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
        return $data;
    }
}

$request = xmlrpc_encode_request('add', array(3, 4));
$response = do_call($host, $port, $request);
astrolox at lawyersonline dot co dot uk 22-Mar-2005 04:20
The PHP XML-RPC project at SourceForge makes life a hell of a lot easier. However, the project uses some function names which are identical to thoses provided by the XML-RPC extention.

If you are on a server with XML-RPC extension compiled in but wish to use the PHP based version then you will have to rename some of the functions.

I notice that sourceforce says there is activity on the project in 2005 but the last release was January 12, 2003.

I recommend that you use this not so friendly PHP extention if available. However this sourceforce project is still a good idea if you don't control which extenions are be available on the server.

http://phpxmlrpc.sourceforge.net/
Jerome Delamarche 14-Oct-2004 02:58
The documentation lacks an example that shows how to send a fault in a response. Here is how to do it:

$args = array("faultCode" => $errcode, "faultString" => $errmsg);
$resp = xmlrpc_encode_request(NULL,$args);
//echo $resp;
php at hendrik-krauss dot de 13-Aug-2004 12:38
On "datetime" values:

If you implement an XML-RPC server with these functions and a client calls a method on your server, sending a datetime as parameter (in ISO 8601 format, as specified at http://www.xmlrpc.com/spec), the PHP XML-RPC will pass your registered server method an object as parameter. That object, for example, looks like:
obj->type="datetime"
obj->scalar="20040420T13:32:40"
obj->timestamp=1082460760

If you do xmlrpc_get_type(obj), it will return "datetime", so presumably that function just returns the value of 'type'. 'scalar' seems to be the on-the-wire representation of the datetime (ISO 8601, exactly as received). 'timestamp' appears to be the ISO value in 'scalar' converted into a normal PHP timestamp (i.e. Unix time_t).

Note on 'scalar': Using a MySQL DB, we did something like  "select blah where start_time >= $obj->scalar ;". That actually worked and returned expected results, so MySQL appears to handle that ISO 8601 format correctly.
swunderlin at REMOVE-telemedia dot ch 09-Jun-2004 03:20
pear hs an XML_RPC package, if you can't recompile your php:
http://pear.php.net/package/XML_RPC
steph at zend dot com 08-Jun-2004 04:04
It took me a while to get a client together without external libraries.  This very basic client/server pair works on my home set-up - hopefully it will save the next xml-rpc virgin some grief.

/* clienttest.php */
<?php
function do_call($host, $port, $request) {

    $fp = fsockopen($host, $port, $errno, $errstr);
    $query = "POST /home/servertest.php HTTP/1.0\nUser_Agent: My Egg Client\nHost: ".$host."\nContent-Type: text/xml\nContent-Length: ".strlen($request)."\n\n".$request."\n";

    if (!fputs($fp, $query, strlen($query))) {
        $errstr = "Write error";
        return 0;
    }

    $contents = '';
    while (!feof($fp)) {
        $contents .= fgets($fp);
    }

    fclose($fp);
    return $contents;
}

$host = 'localhost';
$port = 80;
$request = xmlrpc_encode_request('cycle', 'egg');
$response = do_call($host, $port, $request);
/* do something with $response, e.g. print it */
?>

/* servertest.php */
<?php
function lifecycle($method, $params) {
/* $method = 'cycle', $params = (array of) request parameter(s); $data is also passed from xmlrpc_server_call_method, if we had any data to pass */
    switch($params[0]) {
        case 'egg':
            $reply = 'All eggs will be birds one day.';
        break;
        default:
            $reply = 'That must have been an otheregg';
    }
    return $reply;
}

$server = xmlrpc_server_create();

/* register the 'external' name and then the 'internal' name */
xmlrpc_server_register_method($server, "cycle", "lifecycle");

$request = $HTTP_RAW_POST_DATA; // no you don't need 'always on', and no $_POST doesn't work.

/* the parameters here are 'server, xml-string and user data'.  There's supposed to be an optional 'output options' array too, but I can't get it working :( hence header() call */
$response = xmlrpc_server_call_method($server, $request, null);
header('Content-Type: text/xml');
print $response;

xmlrpc_server_destroy($server);
?>
mboeren at php dot net 25-Feb-2004 04:34
Just a quick addition to my previous xmlrpc_client class: since you cannot use remote methods containing capital letters or methods from subhandlers (like 'system.listMethods()'), I added a 'call(...)' method to the class.

<?php
    // this method should be copy/pasted in the
    // xmlrpc_client class

    function call($function)
    {
        $return = NULL;
        $argv = func_get_args();
        array_shift($argv); // remove function argument
        $this->__call($function, $argv, &$return);
        return $return;
    }

    // now, you can also do
    $result = $client->call('system.listMethods');
    $sum = client->call('add', '1', '2');
?>
mboeren at php dot net 24-Feb-2004 07:01
I use the following code (requires the overload extension) to make developing clients easier:

<?php
include("utils/utils.php"); // from xmlrpc-epi utils

/*
Usage:
    $client = new xmlrpc_client("http://localhost:7080");
    print $client->echo('x')."\n";
    print $client->add(1, 3)."\n";

*/
class xmlrpc_client
{
    var $url;
    var $urlparts;

    function xmlrpc_client($url)
    {
        $this->url = $url;
        $this->urlparts = parse_url($this->url);
        foreach(array('scheme', 'host', 'user', 'pass', 'path',
                      'query', 'fragment')
                as $part) {
            if (!isset($this->urlparts[$part])) {
                $this->urlparts[$part] = NULL;
                }
            }
    }

    function __call($function, $arguments, &$return)
    {
        $requestprms['host'] = $this->urlparts['host'];
        $requestprms['port'] = $this->urlparts['port'];
        $requestprms['uri'] = $this->urlparts['path'];
        $requestprms['method'] = $function;
        $requestprms['args'] = $arguments;
        $requestprms['debug'] = 0;
        $requestprms['timeout'] = 0;
        $requestprms['user'] = NULL;
        $requestprms['pass'] = NULL;
        $requestprms['secure'] = 0;

        $result = xu_rpc_http_concise($requestprms);
        if (is_array($result) && isset($result['faultCode'])) {
            print('Error in xmlrpc call \''.$function.'\''."\n");
            print('  code   : '.$result['faultCode']."\n");
            print('  message: '.$result['faultString']."\n");
            return false;
            }
        $return = $result;
        return true;
    }

}
overload('xmlrpc_client');

?>
bmichael at goldparrot dot com 08-Feb-2003 09:52
If anyone is interested in making XMLRPC requests directly from the client, I have been able to get xmlrpc to
work with vcXMLRPC javascript backend.

After about 1 week of scanning the market, I found this solution to be the best on Javascript back end.  It uses the Microsoft.HTTP activeX control for IE, or HTTPRequest Object for Mozilla.

You include vc(Virtual Cowboys) vcXMLRPC.js file into your pages and make the rpc calls from with javascript to create the requests.

It works both ways.

Two Notes:

I have tested it on IE 6.02 and you need to change lines in ProcessRequest :
function to read:

  dom = this.getObject("XMLDOM",http.responseText);

and change the getObject function to use the latest ActiveX Control:

 MSXML2.XMLHTTP.3.0  (or 4.0)
 MSXML2.DOMDocument.3.0  (or 4.0)

The controls are found on MSDN in the Web Services -> XML area.

As another note, you DO NOT NEED the rpcproxy.cgi script to use this.  That is a proxy script to get around JS Security.  You can use PHP to build the proxy.  But, I was able to get the CGI working with GCC compiler on Solaris (change the -KPCI, depend and -x03 optimizer settings in the Makefile )
steve at orangeNOSPAMimagineering dot com 24-Aug-2002 01:32
There's a handy library by Keith Devens (version 2.2.1) at
http://www.keithdevens.com/software/xmlrpc/

Here is a sample client. It remotely calls sample.sumAndDifference
with two parameters (3 and 5).
It returns:

sum => 8
difference => -2

<?php
include ("kd_xmlrpc.php");
// define("XMLRPC_DEBUG", 0);    // Set to 1 for handy debugging

$method = "sample.sumAndDifference";
$params = XMLRPC_prepare(array(3,5));

$site = "xmlrpc-c.sourceforge.net";
$location = "/api/sample.php";

list($success, $result) = XMLRPC_request( $site, $location, $method, $params );

// XMLRPC_debug_print();    // uncomment for debugging

foreach ( $result as $key => $value ) {
          echo(" $key => $value \n");
}

?>
hfuecks at pinkgoblin dot com 15-Aug-2002 08:32
This extension does not handle the process of making making XML-RPC client requests via HTTP; it only prepares the XML-RPC request payload.

This differs from many other XML-RPC implementations but offers greater flexibility, allowing SSL connections, authentication headers and XML-RPC via other transports like SMTP.
ivanr at webkreator dot com 21-Jun-2002 11:50
For a really easy way to use this XML-RPC extension take a look at

XML-RPC Class Server (http://www.webkreator.com/php/xcs/)

It automatically creates servers out of PHP classes. Creating clients is almost as easy, especially with the recent addition of the overload extension to PHP (see http://www.php.net/manual/en/ref.overload.php).
nic at uklinux dot NOSPAM dot net 24-Apr-2002 09:05
An alternative XML-RPC implementation is available at http://xmlrpc.usefulinc.com - it's written in PHP so you can use it on servers for which you don't have the luxury of rebuilding PHP on.

nic


将 XML 译码为 PHP 本身的类型

  • ? XML-RPC 函数
  • xmlrpc_decode ?
  • PHP Manual
  • XML-RPC 函数
  • 将 XML 译码为 PHP 本身的类型

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode_request — 将 XML 译码为 PHP 本身的类型

说明

xmlrpc_decode_request ( string $xml , string &$method , string $encoding = ? ) : mixed
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

e dot sand at elisand dot com 22-Jun-2009 08:20
This function works exactly the same as xmlrpc_decode() except it gives you access to the method being called as well (xmlrpc_decode() only outputs the params from the XML-RPC call).

To use this function, simply create an empty variable to store the method string in, and then pass by reference like so:

<?php
$method = null;
$params = xmlrpc_decode_request('<xml rpc request>', &$method);
?>

What you will get back are the params stored in $params, and $method will have the method being requested.


将 XML 译码为 PHP 本身的类型

  • ? xmlrpc_decode_request
  • xmlrpc_encode_request ?
  • PHP Manual
  • XML-RPC 函数
  • 将 XML 译码为 PHP 本身的类型

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode — 将 XML 译码为 PHP 本身的类型

说明

xmlrpc_decode ( string $xml , string $encoding = "iso-8859-1" ) : mixed
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

xml

XML response returned by XMLRPC method.

encoding

Input encoding supported by iconv.

返回值

Returns either an array, or an integer, or a string, or a boolean according to the response returned by the XMLRPC method.

范例

See example by xmlrpc_encode_request().

参见

  • xmlrpc_encode_request() - 为 PHP 的值生成 XML
  • xmlrpc_is_fault() - Determines if an array value represents an XMLRPC fault

User Contributed Notes

Alwin 18-May-2016 02:24
Note that from libxml 2.7.9+ there is a limit of 10MB for the XML-RPC response.

If the response is larger, xmlrpc_decode will simply return NULL.

There is currently no way to override this limit like we can with the other xml functions (LIBXML_PARSEHUGE)
carmageddon at gmail dot com 03-Jun-2013 07:42
Apparently there is a slight problem with xmlrpc_decode (or php) which re-formats this input: <value><double>0.000000</double></value>

As the double number 0.

To get around it, use: number_format($val, 2);
Output would be 0.00
phil dot berry at elise-international dot net 05-Sep-2011 08:09
Make sure the server isn't returning a string with a space for the first character, this fails in version 5.3.3 and the function returns null (though seems to be ok in 5.2).

Easily sorted by  trimming the response data:

<?php xmlrpc_decode( trim($response) ); ?>
ryon dot sherman at gmail dot com 21-Aug-2009 04:18
64 bit (i8) integers are not parsed by xmlrpc_decode().
Use a string replacement to work around this:

<?php

$xml = str_replace('i8>', 'i4>', $xml);

$decoded_xml = xmlrpc_decode($xml);

?>
david dot bachelart at polytechnique dot org 18-Jul-2004 08:18
Be careful with encodings, the xmlrpc-decode function is rather strict. For example, the following response parse returns NULL :

<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>a & b</string></value>
         </param>
      </params>
   </methodResponse>

You should use entities :
<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>a &amp; b</string></value>
         </param>
      </params>
   </methodResponse>

If your server does not encode responses properly, you may have to process responses before parse.
hfuecks at pinkgoblin dot com 16-Aug-2002 03:57
Use this with an XML-RPC client to decode a server response into native PHP variables. It will automatically translate the response XML-RPC data types into their PHP equivalents.

This function will return only false is there is any problem with format of the XML it receives.

The HTTP response header will need to be stripped off with something like;

<?php
$xml=(substr($response, strpos($response, "\r\n\r\n")+4));

$phpvars = xmlrpc_decode ($xml);
?>


为 PHP 的值生成 XML

  • ? xmlrpc_decode
  • xmlrpc_encode ?
  • PHP Manual
  • XML-RPC 函数
  • 为 PHP 的值生成 XML

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode_request — 为 PHP 的值生成 XML

说明

xmlrpc_encode_request ( string $method , mixed $params , array $output_options = ? ) : string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

method

Name of the method to call.

params

Method parameters compatible with method signature.

output_options

Array specifying output options may contain (default values are emphasised):

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (may be a string with one value or an array with multiple values)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, other character set supported by iconv

返回值

Returns a string containing the XML representation of the request.

范例

Example #1 XMLRPC client functions example

<?php
$request = xmlrpc_encode_request("method", array(1, 2, 3));
$context = stream_context_create(array('http' => array(
    'method' => "POST",
    'header' => "Content-Type: text/xml",
    'content' => $request
)));
$file = file_get_contents("http://www.example.com/xmlrpc", false, $context);
$response = xmlrpc_decode($file);
if ($response && xmlrpc_is_fault($response)) {
    trigger_error("xmlrpc: $response[faultString] ($response[faultCode])");
} else {
    print_r($response);
}
?>

参见

  • stream_context_create() - 创建资源流上下文
  • file_get_contents() - 将整个文件读入一个字符串
  • xmlrpc_decode() - 将 XML 译码为 PHP 本身的类型

User Contributed Notes

Anonymous 27-Aug-2009 12:33
ever tried transmitting an array like the following with xmlrpc?
$var1=array(7=>14,9=>18);

The output array looks quite different! It will look like that:
$var2=array(14,18);

The only solution i found is to prepend a space to the index:
$var3=array(' 7'=>14,' 9'=>18);

Using that method you'll get the right result. ($var1)
cometfish at hotmail dot com 01-Sep-2008 12:47
The example above is incorrect - the header needs to be an array, see post by "chris dot vigelius at gmx dot net": http://au.php.net/manual/en/function.stream-context-create.php#74431
His post also shows how to do browser authentication, as below:
<?php
   $request = xmlrpc_encode_request("methodName", array("methodParam"));
   $auth = base64_encode($username.":".$password);
   $header = (version_compare(phpversion(), '5.2.8'))
     ? array("Content-Type: text/xml","Authorization: Basic $auth")
     : "Content-Type: text/xml\r\nAuthorization: Basic $auth" ; //[1]
   $context = stream_context_create(array('http' => array(
      'method' => "POST",
      'header' => $header,
      'content' => $request
   )));
   $webservice="http://www.example.com/rpc";
   $file = file_get_contents($webservice, false, $context);
   $response = xmlrpc_decode($file);
   if (xmlrpc_is_fault($response)) {
      return "xmlrpc: $response[faultString] ($response[faultCode])";
   } else {
      return $response;
   }
?>

1 - EDITOR NOTE: THIS IS A FIX FROM "SandersWang dt php at gmail dot com"
fredrik at it dot cdon dot com 06-Feb-2008 05:05
It should be noted that encoding does not seem to encode anything, just specify what goes into the XML header.

We had problems with double-encoded UTF strings being saved to database when using this function, sending it of to a apache xml-rpc servlet and storing it in mysql database. It was solved by setting 'escaping' to just 'markup' and 'encoding' to 'UTF-8' (don't forget to set 'utf-8' in xmlrpc_decode too).

It seems that UTF-8 encoded strings gets escaped with their bytes as entities instead of their characters as entites.
handco at gmail dot com 12-Mar-2007 08:39
Simple OO client with function Overload :

the php metho test_helloworld is translated to xmlrpc method test.helloworld.

class RpcClient {

    private $_methods;
    private $_context;
    private $_url;

    function __construct ($url, $user, $passwd) {
        $auth = base64_encode(sprintf('%s:%s', $user,$passwd));
        $this->_context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => "Content-Type: text/xml\r\n".
                            "Authorization: Basic $auth" ,

            )
        ));
        $this->_url = $url;

        $this->registerMethod ("Test_HelloWorld");

    }

    function __call($methodName, $params) {
        if (array_key_exists($methodName,$this->_methods)) {
            // on appelle la fonction RPC
            $m = str_replace('_', '.', $methodName);
            $r = xmlrpc_encode_request($m, $params,array('verbosity'=>'newlines_only'));
            $c = $this->_context;
            stream_context_set_option($c,'http','content',$r);
            $f = file_get_contents($this->_url,false,$c);
            $resp = xmlrpc_decode($f);
            return $resp;
        } else {
            // on appelle la fonction de l'objet
            call_user_method_array($methodName, $this,$params);
        }
    }

    private function registerMethod ($method) {
        $this->_methods[$method] = true;
    }

}
giunta dot gaetano at sea-aeroportimilano dot it 21-Aug-2006 03:54
Take care that this function will generate invalid xmlrpc content when invoked with certain parameters (said content will be happily parsed by the lib itself, but not by other implementations).

xmlrpc_encode_request(null, null)
will generate a response without a value

xmlrpc_encode_request('myfunc', array('faultCode' => 666, 'faultString' => 'hello world')
will generated a request containing a <fault> member instead of <params>
php at hendrik dash krauss dot de 28-May-2005 02:29
For examples / documentation of the array output_options, see http://xmlrpc-epi.sourceforge.net/main.php?t=php_api#output_options

In short, output_options lets you send compact xmlrpc (without all the "pretty whitespace" xmlrpc_encode adds normally), apply an own escaping table prior to sending, set the encoding, and a couple of other things (the page even says something about soap 1.1 ... I don't know details).
<URL:http://www.dlitz.net/go/contact/> 03-May-2004 11:28
Note that as far as I can tell, the &#10; characters generated by PHP in the base64 fields don't appear to violate the XML-RPC standard at all.  XML-RPC messages *are* in XML format, and as such, the XML entities should be getting decoded before being passed to a base64 decoder.  So, the previously-mentioned Jakarta-based XML-RPC server appears to violate the XML spec.  i.e. There's nothing here that needs to be "fixed" in PHP.
kelly at seankelly dot biz 28-Dec-2002 04:02
Binary strings (set with xmlrpc_set_type) go into a <base64>...</base64> block like you'd expect. But after every 80th character, this function inserts the XML entity "&#10;", which is a Unicode newline, as if to cause a line-wrap, which is admittedly silly.

Silly though it may be, it causes real problems for some XML-RPC servers, such as http://jakarta.apache.org/xmlrpc/ (nee Helma). Stripping out those entities with something like

$req = preg_replace('/&#10;/', '', xmlrpc_encode_request("my.method", $args));

works around the problem.
hfuecks at pinkgoblin dot com 15-Aug-2002 09:06
This function should be used by an XML-RPC client to create an XML payload for an XML-RPC request;

<?php
$params = "system.methodSignature";
$method = "system.methodHelp";
$request = xmlrpc_encode_request($method,$params);
echo ( $request );
?>

Produces;

<?xml version='1.0' encoding="iso-8859-1" ?>
<methodCall>
<methodName>system.methodHelp</methodName>
<params>
 <param>
  <value>
   <string>system.methodSignature</string>
  </value>
 </param>
</params>
</methodCall>

The second argument recognises the type of variable and generates the correct XML-RPC structure. See xmlrpc_encode() for more details.


为 PHP 的值生成 XML

  • ? xmlrpc_encode_request
  • xmlrpc_get_type ?
  • PHP Manual
  • XML-RPC 函数
  • 为 PHP 的值生成 XML

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode — 为 PHP 的值生成 XML

说明

xmlrpc_encode ( mixed $value ) : string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

remi 13-May-2009 01:56
This xmlrpc_encode function doesn't generate the "methodResponse" tag required by some clients.

Using xmlrpc_encode_request seems better:

<?php
$xmlresponse = xmlrpc_encode_request(NULL, $phpresponse);

xmlrpc_encode(1) generate
<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <int>1</int>
 </value>
</param>
</params>

xmlrpc_encode_request(NULL,1) generate
<?xml version="1.0" encoding="iso-8859-1"?>
<methodResponse>
<params>
 <param>
  <value>
   <int>1</int>
  </value>
 </param>
</params>
</methodResponse>
?>
dave dot wilcock at gmail dot com 21-Sep-2007 07:05
Worth noting, you can use this function to generate fault response xml.

If you pass a pre-determined array into this function, as follows

<?
$myArray = array ("faultCode"=>1,"faultString"=>"Too many params");
$xml = xmlrpc_encode($myArray);
?>

... you will get output much like the following:

<?xml version="1.0" encoding="utf-8"?>
<fault>
<value>
 <struct>
  <member>
   <name>faultCode</name>
   <value>
    <int>4</int>
   </value>
  </member>
  <member>
   <name>faultString</name>
   <value>
    <string>Too many params</string>
   </value>
  </member>
 </struct>
</value>
</fault>

All that is needed to do here to make it valid XML-RPC is inject some of your own methodResponse tags.

Check the XML-RPC specification at http://www.xmlrpc.com/spec
08-Jun-2006 07:32
Another quirk (more of a bug i think) is the automatic encoding of hashes where all keys that begin with a digit between 1 and 9 are lost:
http://bugs.php.net/bug.php?id=37746

Luckily I found a quick workaround. Just append chr(0x00) to your keys and the xmlrpc response will be correct. Maybe this will apply to encoding of hashes for requests too.
Amir.LaherATcomplinetDOTcom 26-Aug-2005 01:54
Beware this quirk: when you xmlrpc_encode a hash into xmlrpc, numeric keys will not be kept. Even strings containing numbers-only will be lost.

i.e.: xmlrpc_decode(xmlrpc_encode(array('123'=>456)));
returns: array(0=>456);

Apparently this is intentional functionality (see http://bugs.php.net/bug.php?id=21949)

2 workarounds:
1. prepend/append a string (even whitespace) to all keys, and strip them out at the other end. eg array('key_123'=>456);
2. create an array of hashes. array(array('key'=>123,'value'=>456));

I favour the second option because it's more deliberate.

... this also applies to xmlrpc_encode_request()
hfuecks at pinkgoblin dot com 15-Aug-2002 08:16
This function would be used by an XML-RPC server to convert PHP variables into an XML-RPC response.

It would be used within the PHP functions defined using xmlrpc_server_register_method()

Uses PHP variable reflection to assign the correct data types for the XML-RPC response. For example;

<?php
$params = array ( "one"=>"red","two"=>"blue","three"=>"green" );

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

Produces;

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <struct>
   <member>
    <name>one</name>
    <value>
     <string>red</string>
    </value>
   </member>
   <member>
    <name>two</name>
    <value>
     <string>blue</string>
    </value>
   </member>
   <member>
    <name>three</name>
    <value>
     <string>green</string>
    </value>
   </member>
  </struct>
 </value>
</param>
</params>

While
<?php
$params = array ( "red", "blue", "green" );

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

produces;

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <array>
   <data>
    <value>
     <string>red</string>
    </value>
    <value>
     <string>blue</string>
    </value>
    <value>
     <string>green</string>
    </value>
   </data>
  </array>
 </value>
</param>
</params>

And

<?php
$params = 1;

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

produces

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <int>1</int>
 </value>
</param>
</params>

It's useful to be aware of the settype() function (http://www.php.net/settype).

For binary base64 data and XML-RPC iso8601 date times the xmlrpc_set_type() function should be used on a PHP variable before using xmlrpc_encode()


为 PHP 的值获取 xmlrpc 的类型

  • ? xmlrpc_encode
  • xmlrpc_is_fault ?
  • PHP Manual
  • XML-RPC 函数
  • 为 PHP 的值获取 xmlrpc 的类型

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_get_type — 为 PHP 的值获取 xmlrpc 的类型

说明

xmlrpc_get_type ( mixed $value ) : string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

该函数对于 base64 与日期时间字符串特别有用。

参数

value

PHP value

返回值

Returns the XML-RPC type.

范例

Example #1 XML-RPC type example

<?php
echo xmlrpc_get_type(null) . "\n"; // base64
echo xmlrpc_get_type(false) . "\n"; // boolean
echo xmlrpc_get_type(1) . "\n"; // int
echo xmlrpc_get_type(1.0) . "\n"; // double
echo xmlrpc_get_type("") . "\n"; // string
echo xmlrpc_get_type(array()) . "\n"; // array
echo xmlrpc_get_type(new stdClass) . "\n"; // array
echo xmlrpc_get_type(STDIN) . "\n"; // int
?>

参见

  • xmlrpc_set_type() - 为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间

User Contributed Notes

hfuecks at pinkgoblin dot com 16-Aug-2002 10:41
This function returns the type of a PHP variable in XML-RPC terms. It won't "spot" base64 or iso8601 types unless they have been defined using xmlrpc_set_type().

For iso8601 type it returns "datetime".

Otherwise it returns strings corresponding directly the XML-RPC data types e.g. "struct","int","string","base64" etc.


Determines if an array value represents an XMLRPC fault

  • ? xmlrpc_get_type
  • xmlrpc_parse_method_descriptions ?
  • PHP Manual
  • XML-RPC 函数
  • Determines if an array value represents an XMLRPC fault

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault

说明

xmlrpc_is_fault ( array $arg ) : bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

arg

Array returned by xmlrpc_decode().

返回值

Returns true if the argument means fault, false otherwise. Fault description is available in $arg["faultString"], fault code is in $arg["faultCode"].

范例

See example by xmlrpc_encode_request().

参见

  • xmlrpc_decode() - 将 XML 译码为 PHP 本身的类型

User Contributed Notes

angelo at at dot com 25-Jan-2011 12:31
A note, response from xmlrpc_decode is not always an array. Whenever the XMLRPC server returns a string, xmlrpc_is_fault will complain about not being an array.

Best way to detect errors is

<?php

    $response = xmlrpc_decode($file);

    if (is_array($response) && xmlrpc_is_fault($response)) {
        throw new Exception($response['faultString'], $response['faultCode']);
    }

?>


将 XML 译码成方法描述的列表

  • ? xmlrpc_is_fault
  • xmlrpc_server_add_introspection_data ?
  • PHP Manual
  • XML-RPC 函数
  • 将 XML 译码成方法描述的列表

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_parse_method_descriptions — 将 XML 译码成方法描述的列表

说明

xmlrpc_parse_method_descriptions ( string $xml ) : array
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 05:05
The format for the xml string is the same that has to be returned by functions registered via calls to `xmlrpc_server_register_introspection_callback`.

It is documented at http://xmlrpc-epi.sourceforge.net/specs/rfc.system.describeMethods.php


添加自我描述的文档

  • ? xmlrpc_parse_method_descriptions
  • xmlrpc_server_call_method ?
  • PHP Manual
  • XML-RPC 函数
  • 添加自我描述的文档

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_add_introspection_data — 添加自我描述的文档

说明

xmlrpc_server_add_introspection_data ( resource $server , array $desc ) : int
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 05:03
The format to be used for data in the $desc array is the same as returned by calls to function `xmlrpc_parse_method_descriptions`


解析 XML 请求同时调用方法

  • ? xmlrpc_server_add_introspection_data
  • xmlrpc_server_create ?
  • PHP Manual
  • XML-RPC 函数
  • 解析 XML 请求同时调用方法

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_call_method — 解析 XML 请求同时调用方法

说明

xmlrpc_server_call_method ( resource $server , string $xml , mixed $user_data , array $output_options = ? ) : string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

marco.buratto at tiscali punto it 28-Dec-2006 08:15
xmlrpc_server_call_method() with class methods

<?php
require_once ('Connections/adodb_mysql_connection.php');

// Instantiating my own class
$my_report = new external_report($db_connection);

// Setting up the XML-RPC "server"
$xmlrpc_server_handler = xmlrpc_server_create();
xmlrpc_server_register_method($xmlrpc_server_handler, "external_method", array(&$my_report, "export"));

// Creating XML return data
if ($response = xmlrpc_server_call_method($xmlrpc_server_handler, $HTTP_RAW_POST_DATA, null))
    {
    header('Content-Type: text/xml');
    echo $response;
    }

// **************** class definition ****************

class external_report
    {
    protected $db_connection;

    public function __construct($db_connection_pointer)
        {
        if (method_exists($db_connection_pointer, "Execute")) $this->db_connection = $db_connection_pointer;
        else die("...");
        }

    public function export($method_name, $params_array)
        {
        $id_dir = (int)$params_array[0];
        $id_usr = (int)$params_array[1]; // not used, just an example
        // We have to add arguments' validating code here and NOT inside the constructor (as usual)
        // because arguments are passed directly by xmlrpc_server_call_method (?!!)

        $myexport = array();

        $dirs_query = "SELECT documento_id FROM tabella_cartelle WHERE cartella_id = ".$id_dir;
        $dirs_result = $this->db_connection->Execute($dirs_query) or die("...");

        $index = 0;
        while(!$dirs_result->EOF)
            {
            $docs_query = "SELECT codice, titolo FROM tabella_documenti WHERE id_documento = ".$dirs_result->Fields('documento_id');
            $docs_result = $this->db_connection->Execute($docs_query) or die("...");

            $myexport[$index]['codice'] = $docs_result->Fields('codice');
            $myexport[$index]['titolo'] = $docs_result->Fields('titolo');

            $index++;
            $dirs_result->MoveNext();
            }

        return $myexport;
        }
    }
?>
nyvsld at gmail dot com 27-Nov-2005 05:08
<?php
/* method implementation */
function impl($method_name,$params,$user_data){
  var_dump(func_get_args('impl'));
  return array_sum($params);
}

/* create server */
$s=xmlrpc_server_create();
xmlrpc_server_register_method($s,'add','impl');

/* calling server method */
$req=xmlrpc_encode_request('add',array(1,2,3));
$resp=xmlrpc_server_call_method($s,$req,array(3,4));

/* process result */
$decoded=xmlrpc_decode($resp);
if(xmlrpc_is_fault($decoded)){
    echo 'fault!';
}

var_dump($decoded);
?>


创建一个 xmlrpc 服务端

  • ? xmlrpc_server_call_method
  • xmlrpc_server_destroy ?
  • PHP Manual
  • XML-RPC 函数
  • 创建一个 xmlrpc 服务端

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_create — 创建一个 xmlrpc 服务端

说明

xmlrpc_server_create ( ) : resource
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


销毁服务端资源

  • ? xmlrpc_server_create
  • xmlrpc_server_register_introspection_callback ?
  • PHP Manual
  • XML-RPC 函数
  • 销毁服务端资源

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_destroy — 销毁服务端资源

说明

xmlrpc_server_destroy ( resource $server ) : int
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

nospam at bigbadweb dot co dot uk 22-Nov-2005 02:26
This function returns true (1) if successful and false (0) if resource is invalid or could not be destroyed.


注册一个 PHP 函数用于生成文档

  • ? xmlrpc_server_destroy
  • xmlrpc_server_register_method ?
  • PHP Manual
  • XML-RPC 函数
  • 注册一个 PHP 函数用于生成文档

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_introspection_callback — 注册一个 PHP 函数用于生成文档

说明

xmlrpc_server_register_introspection_callback ( resource $server , string $function ) : bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 01:58
The introspection callback function should return an XML string with the following format:

<?xml version='1.0'?>
<introspection version='1.0'>
 <methodList>
  <methodDescription name='introspection.hello'>
   <author>Dan Libby</author>
   <purpose>greets the caller and demonstrates use of introspection mechanism</purpose>
   <signatures>
    <signature>
     <params>
      <value type='string' name='name'>name of the caller</value>
     </params>
     <returns>
      <value type='string'>a greeting to the caller</value>
     </returns>
    </signature>
   </signatures>
   <see><item>system.listMethods</item></see>
   <examples/>
   <errors>
      <item>returns fault code 1 if the caller's name is not specified</item>
   </errors>
   <notes>
    <item>this is a lame example</item>
    <item>example of multiple notes</item>
   </notes>
   <bugs/>
   <todo/>
  </methodDescription>
 </methodList>
</introspection>


注册一个 PHP 函数用于匹配 xmlrpc 方法名

  • ? xmlrpc_server_register_introspection_callback
  • xmlrpc_set_type ?
  • PHP Manual
  • XML-RPC 函数
  • 注册一个 PHP 函数用于匹配 xmlrpc 方法名

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_method — 注册一个 PHP 函数用于匹配 xmlrpc 方法名

说明

xmlrpc_server_register_method ( resource $server , string $method_name , string $function ) : bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

giunta dot gaetano at gmail dot com 30-Dec-2020 09:02
Note 1: even if you add introspection data via calls to `xmlrpc_server_register_introspection_callback` or `xmlrpc_server_add_introspection_data`, the server will not validate for you the number or type of received parameters.
This means that you have to implement all required validation of the received parameters in your php function.

Note 2: take care about dealing with base64 and datetime values in the received parameters: those are not automatically transformed into php scalar values, but into stdClass objects with members `xmlrpc_type` and `scalar`
giunta dot gaetano at sea-aeroportimilano dot it 11-Aug-2006 06:55
To have an xmlrpc fault response programatically generated by the server, the php function registered as method handler must return an array containing a FaultCode and a FaultString members.

function $myfunc($methodname, $vals, $extra_data)
{
...
return array('faultCode' => 666, 'faultString' => 'DOH!');
}
nyvsld at gmail dot com 27-Nov-2005 05:03
prototype of registered function:

function method_impl(string $method_name, array $params, array $user_data);

$method_name
    the public method name, known by calling client
$params
    parameters specified by calling client
$user_data
    any local data, passed by `xmlrpc_server_call_method'
dante at lorenso dot com 11-Aug-2005 12:46
To register a callback to a 'static' function within the same class, consider a syntax like the following:
<code>
$callback = array (__CLASS__, "my_function_name");
xmlrpc_server_register_method($xmlrpc_server, "my_function", $callback);
</code>
Doing it this way makes it easier to rename your class later.
eiriks at hollowmatrix dot com 28-Mar-2005 03:08
Remember that you can't do like Chrigu and Nate said if you want to add methods from a static class (Hence you can't create any instances of it).
A workaround is to create lambda functions calling the
methods:

// Our static handler class
static class MyHandler
{
    public function getPrice($item)
    {
        $prices = array("apple" => 4, "orange" => 5);
        return $prices[$item];
    }
    public function buy($item, $number)
    {
        $price = self::getPrice($item) * $number;
        do_thing_to_sell_the_item();
        return $price;
    }
}

// Use reflection to get method names and parameters
$mirror = new ReflectionClass("MyHandler");
foreach ($mirror->getMethods() as $method)
{
    // Create new "lambda" function for each method

    // Generate argument list
    $args = array();
    foreach ($method->getParameters() as $param)
    {
        $args[] = '$'.$param->getName();
    }
    $args = implode(',', $args);

    // Generate code
    $methodname = $method->getName();
    $code = "return {$real_class}::{$methodname}({$args});";

    // Create function, retrieve function name
    $function_name = create_function($args, $code);

    // Register the function
    xmlrpc_server_register_method($myserver, $methodname, $function_name);
}
Nate Parsons 29-Apr-2003 03:12
In case its not completely obvious what Chrigu meant,

You can register a method inside your class by doing the following:

xml_rpc_server_register_methode($xmlrpc_server, "myClientCall", array(&$this, "handleClientCallFunc"));

where $this == the magic class $this. =)
18-Nov-2002 10:40
Here is an example how to register a class methode:

xml_rpc_server_register_methode($xmlrpc_server, "foo", array(&$bar, "foo_func"));

where $bar is the instance of your class and foo_func a methode of this class. Don't forget the '&'!

hope this may be useful...

Chrigu


为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间

  • ? xmlrpc_server_register_method
  • Windows 专用扩展 ?
  • PHP Manual
  • XML-RPC 函数
  • 为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_set_type — 为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间

说明

xmlrpc_set_type ( string &$value , string $type ) : bool

为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

value

Value to set the type

type

'base64' or 'datetime'

返回值

成功时返回 true， 或者在失败时返回 false。 If successful, value is converted to an object.

范例

Example #1 A xmlrpc_set_type() example

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

以上例程的输出类似于：

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

错误／异常

Issues E_WARNING with type unsupported by XMLRPC.

User Contributed Notes

bmatheny at mobocracy dot net 24-Mar-2006 03:08
The following code segfaults some older (pre 5.1.2) versions of PHP:

$foo = date('c', time());
xmlrpc_set_type($foo, 'datetime');

Please upgrade before reporting as a bug.
shem((at))etkDOTca [aka.Przemyslaw Szot] 30-Oct-2004 02:23
Once you use the xmlrpc_set_type function, the data is encoded into a PHP object.  In your XMLRPC server, in order to access the data you must be able to access the necessary part of the object.

So.. to expend on the example above:

<---------- CLIENT ---------->
$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

In order to retrieve the binary file data you would need to get the scalar portion of the object:

<---------- SERVER ------------>
$string=$params[0];
$date_obj=$params[1];
$binary_obj=$params[2];

$date=$date_obj->scalar;
$binary_data=$binary_obj->scalar;

// Then you can proceed to write the binary
fwrite($handle,$binary_data);
kelly at seankelly dot biz 28-Dec-2002 07:53
The problem is that PHP has a string type which is also used to hold binary data and dates.  But XML-RPC defines three separate types for strings, binary data, and dates.  How do you tell how you want strings encoded?  That's where this function comes in.

Suppose the XML-RPC method "log.data" took a string, a date, and a binary object.  To tell XML-RPC that the date (which is a PHP string) is a really a date and that the binary data (which is also a PHP string) is really binary data, try:

$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

Note the reference passing in the calls to xmlrpc_set_type; that enables the function to change the values from strings into what xmlrpc_encode/_request expects (which are objects that include a bonus field that tells the desired XML-RPC type).


Windows 专用扩展

  • COM — COM and .Net (Windows)
    • 简介
    • 安装／配置
    • 预定义常量
    • Errors and error handling
    • 范例
    • com — The com class
    • dotnet — The dotnet class
    • variant — variant class
    • COMPersistHelper — The COMPersistHelper class
    • com_exception — The com_exception class
    • COM 函数
  • win32service
    • 简介
    • 安装／配置
    • 预定义常量
    • Win32ServiceException — The Win32ServiceException class
    • 范例
    • win32service 函数

User Contributed Notes

There are no user contributed notes for this page.


COM and .Net (Windows)

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Errors and error handling
  • 范例
    • For Each
    • Arrays and Array-style COM properties
  • com — The com class
    • com::__construct — com class constructor
  • dotnet — The dotnet class
    • dotnet::__construct — dotnet class constructor
  • variant — variant class
    • variant::__construct — variant class constructor
  • COMPersistHelper — The COMPersistHelper class
    • COMPersistHelper::__construct — Construct a COMPersistHelper object
    • COMPersistHelper::GetCurFileName — Get current filename
    • COMPersistHelper::GetMaxStreamSize — Get maximum stream size
    • COMPersistHelper::InitNew — Initialize object to default state
    • COMPersistHelper::LoadFromFile — Load object from file
    • COMPersistHelper::LoadFromStream — Load object from stream
    • COMPersistHelper::SaveToFile — Save object to file
    • COMPersistHelper::SaveToStream — Save object to stream
  • com_exception — The com_exception class
  • COM 函数
    • com_create_guid — Generate a globally unique identifier (GUID)
    • com_event_sink — Connect events from a COM object to a PHP object
    • com_get_active_object — Returns a handle to an already running instance of a COM object
    • com_load_typelib — 装载一个 Typelib
    • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
    • variant_abs — Returns the absolute value of a variant
    • variant_add — "Adds" two variant values together and returns the result
    • variant_and — Performs a bitwise AND operation between two variants
    • variant_cast — Convert a variant into a new variant object of another type
    • variant_cat — Concatenates two variant values together and returns the result
    • variant_cmp — Compares two variants
    • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
    • variant_div — Returns the result from dividing two variants
    • variant_eqv — Performs a bitwise equivalence on two variants
    • variant_fix — Returns the integer portion of a variant
    • variant_get_type — Returns the type of a variant object
    • variant_idiv — Converts variants to integers and then returns the result from dividing them
    • variant_imp — Performs a bitwise implication on two variants
    • variant_int — Returns the integer portion of a variant
    • variant_mod — Divides two variants and returns only the remainder
    • variant_mul — Multiplies the values of the two variants
    • variant_neg — Performs logical negation on a variant
    • variant_not — Performs bitwise not negation on a variant
    • variant_or — Performs a logical disjunction on two variants
    • variant_pow — Returns the result of performing the power function with two variants
    • variant_round — Rounds a variant to the specified number of decimal places
    • variant_set_type — Convert a variant into another type "in-place"
    • variant_set — Assigns a new value for a variant object
    • variant_sub — Subtracts the value of the right variant from the left variant value
    • variant_xor — Performs a logical exclusion on two variants

User Contributed Notes

robert dot johnson at icap dot com 24-Jul-2012 09:30
(From?) PHP 5.4.5 for Windows:

If you are seeing this in your error log:

Fatal error:  Class 'COM' not found

You require this in php.ini:

[PHP_COM_DOTNET]
extension=php_com_dotnet.dll

Previously it was compiled as built-in on the Windows build.  I assume this has happened because the com extension can now be built as a shared component.
Anonymous 23-Sep-2009 05:00
Add hyperlink at a Word Document's bookmark

<?php
// Create COM instance to word
       function clsMSWord($Visible = false)
       {
           $this->handle = new COM("word.application") or die("Unable to instanciate Word");
           $this->handle->Visible = $Visible;
       }

function WriteHyperlink($Bookmark,$Path,$Text)
       {
               $objBookmark = $this->handle->ActiveDocument->Bookmarks($Bookmark);
               $range = $objBookmark->Range;
               $objHyperlink = $this->handle->ActiveDocument->Hyperlinks;
               $objHyperlink->add($range,$Path,"","",$Text);

       }
?>
Dave Bachtel 27-May-2009 02:20
Hello everybody!

Here is some helpful advice for people attempting to use COM with Microsoft MapPoint 2006 or 2009 with PHP.

If you are using apache, it MUST be running under the same credentials as a desktop user that has already installed/run mappoint or modifiy the service and select the "Allow Service to Interact with Desktop" option.  Otherwise, it won't work due to the EULA popup having to be accepted.  Mappoint 2004 works just fine, this only applies to 2006 and 2009.

For troubleshooting, the error that appears in the System event viewer is:
The server {31851F82-AFE6-11D2-A3C9-00C04F72F340} did not register with DCOM within the required timeout.

The error generated by PHP, if you happen to get lucky and let the COM() function timeout by cranking up set_time_limit() timeout is:
<?php

set_time_limit(1000) ;

$mapoint =  new COM("MapPoint.Application") or die("Unable to instantiate Mappoint COM object");

?>
Generates:
Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `MapPoint.Application': Server execution failed ' in [somefile.php]:9 Stack trace: #0 [somefile.php](9): com->com('MapPoint.Applic...') #1 {main} thrown in [somefile.php] on line 9

Also, if you have multiple versions of MapPoint installed, you will need to run:
c:\path\to\mappoint\MapPoint.exe /registerserver

(using the correct folder path) to select the right version of the com object to use.  Gooood luck!
acsandeep at gmail dot com 04-Apr-2009 09:40
If you are trying to get the properties of a Word document opened via COM object, you may need to define some constants in your script like so.

<?php
define('wdPropertyTitle', 1);
define('wdPropertySubject', 2);
define('wdPropertyAuthor', 3);
define('wdPropertyKeywords', 4);
define('wdPropertyComments', 5);
define('wdPropertyTemplate', 6);
define('wdPropertyLastAuthor', 7);

$word = new COM("word.application") or die ("Could not initialise MS Word object.");
$word->Documents->Open(realpath("Sample.doc"));
$Author = $word->ActiveDocument->BuiltInDocumentProperties(wdPropertyAuthor);

echo $Author;
?>
long2hu3 ATT yahoo DOTT com 18-Mar-2009 04:38
When you work with MS Excel, Word, ... and other applications, never forget that COM doesn't know their predefined constants, thus if you want to do sth. that would look like this in VB:

With myRange.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

you should either use numbers or define constants above, like this:

<?php

define('xlEdgeBottom', 9);
define('xlContinuous', 1);
define('xlThin', 2);
define('xlAutomatic', -4105);

$ex = new COM("Excel.Application", NULL, CP_UTF8) or Die ("Did not instantiate Excel");
$wb = $ex->Application->Workbooks->Add();
$ws = $wb->Worksheets(1);

$xra = $ws->Range("A1:A6");

$bs = $xra->Borders(xlEdgeBottom);
$bs->LineStyle = xlContinuous;
$bs->Weight = xlThin;
$bs->ColorIndex = xlAutomatic;

?>

It is pointless to try to use text strings, i.e.

<?php

$bs = $xra->Borders('xlEdgeBottom');
$bs->Weight = 'xlThin';

?>

this will cause an error: Unable to set property Weight of class Border ...
ilayansmano at gmail dot com 26-Aug-2008 01:39
Extracting text from Word Documents via PHP and COM

<?php
$word = new COM("word.application") or die ("Could not initialise MS Word object.");
$word->Documents->Open(realpath("Sample.doc"));

// Extract content.
$content = (string) $word->ActiveDocument->Content;

echo $content;

$word->ActiveDocument->Close(false);

$word->Quit();
$word = null;
unset($word);
?>


简介

COM is an acronym for Component Object Model; it is an object orientated layer (and associated services) on top of DCE RPC (an open standard) and defines a common calling convention that enables code written in any language to call and interoperate with code written in any other language (provided those languages are COM aware). Not only can the code be written in any language, but it need not even be part of the same executable; the code can be loaded from a DLL, be found in another process running on the same machine, or, with DCOM (Distributed COM), be found in another process on a remote machine, all without your code even needing to know where a component resides.

There is a subset of COM known as OLE Automation which comprises a set of COM interfaces that allow loose binding to COM objects, so that they can be introspected and called at run-time without compile-time knowledge of how the object works. The PHP COM extension utilizes the OLE Automation interfaces to allow you to create and call compatible objects from your scripts. Technically speaking, this should really be called the "OLE Automation Extension for PHP", since not all COM objects are OLE compatible.

Now, why would or should you use COM? COM is one of the main ways to glue applications and components together on the Windows platform; using COM you can launch Microsoft Word, fill in a document template and save the result as a Word document and send it to a visitor of your web site. You can also use COM to perform administrative tasks for your network and to configure your IIS; these are just the most common uses; you can do much more with COM.

Additionally, we support the instantiation and creation of .Net assemblies using the COM interoperability layer provided by Microsoft.

User Contributed Notes

There are no user contributed notes for this page.


需求

COM functions are only available for the Windows version of PHP.

.Net support requires the .Net runtime.

User Contributed Notes

There are no user contributed notes for this page.


安装

As of PHP 5.3.15 / 5.4.5, this extension requires php_com_dotnet.dll to be enabled inside of php.ini in order to use these functions. Previous versions of PHP enabled these extensions by default.

You are responsible for installing support for the various COM objects that you intend to use (such as MS Word); we don't and can't bundle all of those with PHP.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

COM 配置选项
名字 | 默认 | 可修改范围 | 更新日志
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.dotnet_version | "" | PHP_INI_SYSTEM | As of PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

com.allow_dcom

如果打开此选项，PHP 将被允许以一个 D-COM（Distributed COM）客户方式操作并允许 PHP 脚本在远程服务器上实例化 COM 对象。

com.autoregister_typelib

When this is turned on, PHP will attempt to register constants from the typelibrary of COM objects that it instantiates, if those objects implement the interfaces required to obtain that information. The case sensitivity of the constants it registers is controlled by the configuration directive.

com.autoregister_verbose

When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.

com.autoregister_casesensitive

When this is turned on (the default), constants found in auto-loaded type libraries when instatiating COM objects will be registered case sensitively. See com_load_typelib() for more details.

com.code_page

It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.

If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the com class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.

com.dotnet_version

The version of the .NET framework to use for dotnet objects. The value of the setting is the first three parts of the framework's version number, separated by dots, and prefixed with v, e.g. v4.0.30319.

com.typelib_file

When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

CLSCTX_INPROC_SERVER (integer)
CLSCTX_INPROC_HANDLER (integer)
CLSCTX_LOCAL_SERVER (integer)
CLSCTX_REMOTE_SERVER (integer)
CLSCTX_SERVER (integer)
CLSCTX_ALL (integer)
VT_NULL (integer)
VT_EMPTY (integer)
VT_UI1 (integer)
VT_I2 (integer)
VT_I4 (integer)
VT_R4 (integer)
VT_R8 (integer)
VT_BOOL (integer)
VT_ERROR (integer)
VT_CY (integer)
VT_DATE (integer)
VT_BSTR (integer)
VT_DECIMAL (integer)
VT_UNKNOWN (integer)
VT_DISPATCH (integer)
VT_VARIANT (integer)
VT_I1 (integer)
VT_UI2 (integer)
VT_UI4 (integer)
VT_INT (integer)
VT_UINT (integer)
VT_ARRAY (integer)
VT_BYREF (integer)
CP_ACP (integer)
CP_MACCP (integer)
CP_OEMCP (integer)
CP_UTF7 (integer)
CP_UTF8 (integer)
CP_SYMBOL (integer)
CP_THREAD_ACP (integer)
VARCMP_LT (integer)
VARCMP_EQ (integer)
VARCMP_GT (integer)
VARCMP_NULL (integer)
NORM_IGNORECASE (integer)
NORM_IGNORENONSPACE (integer)
NORM_IGNORESYMBOLS (integer)
NORM_IGNOREWIDTH (integer)
NORM_IGNOREKANATYPE (integer)
NORM_IGNOREKASHIDA (integer)
DISP_E_DIVBYZERO (integer)
DISP_E_OVERFLOW (integer)
MK_E_UNAVAILABLE (integer)

User Contributed Notes

There are no user contributed notes for this page.


Errors and error handling

This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.

User Contributed Notes

There are no user contributed notes for this page.


范例

Table of Contents

  • For Each
  • Arrays and Array-style COM properties

User Contributed Notes

There are no user contributed notes for this page.


For Each

You may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In layman's terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

Example #1 For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Example #2 foreach in PHP

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj->Name . "<br />";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Arrays and Array-style COM properties

Many COM objects expose their properties as arrays, or using array-style access.

You can:

  • Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.

  • Iterate SafeArrays ("true" arrays) using the foreach control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at For Each for more information on this topic.

User Contributed Notes

There are no user contributed notes for this page.


The com class

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

简介

The com class allows you to instantiate an OLE compatible COM object and call its methods and access its properties.

类摘要

com extends variant {
/* 方法 */
public __construct ( string $module_name , array|string|null $server_name = null , int $codepage = CP_ACP , string $typelib = "" )
}

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM.

PHP will automatically detect methods that accept parameters by reference, and will automatically convert regular PHP variables to a form that can be passed by reference. This means that you can call the method very naturally; you needn't go to any extra effort in your code.

com examples

Example #1 com example (1)

<?php
// starting word
$word = new com("word.application") or die("Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}\n";

//bring it to front
$word->Visible = 1;

//open an empty document
$word->Documents->Add();

//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//closing word
$word->Quit();

//free the object
$word = null;
?>

Example #2 com example (2)

<?php

$conn = new com("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Recordset

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++) {
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF) {
    for ($i=0; $i < $num_columns; $i++) {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs = null;
$conn = null;

?>

Table of Contents

  • com::__construct — com class constructor

User Contributed Notes

info at ensostudio dot ru 26-Jul-2020 09:52
Complete example of using WScript.Shell:
<?php
/**
  * Methods & properties
  * @link https://msdn.microsoft.com/en-us/library/2f38xsxe(v=vs.84).aspx
  */
$shell = new com('WScript.Shell', null, CP_UTF8);
var_dump($shell->CurrentDirectory);
foreach ($shell->Environment as $value) {
    var_dump($value);
}
// check file 'Test.php'
$process = $shell->Exec('.../php.exe --syntax-check --file=".../src/Test.php"');
// wait complete: 1 - done
while (! $process->Status) {
    usleep(5000);
}
// results: -1 - syntax error, 0 - no error
var_dump($process->ExitCode);
// show responce
var_dump($process->StdOut->ReadAll());
// show errors
var_dump($process->StdErr->ReadAll());
?>
Danil_lll 14-Aug-2018 10:14
Hello. There is a code c# which works with the COM-library (written on C++) - hybrid.dll.
I need to rewrite this code from C# to PHP (that is connect the COM-library to the PHP code)

Here is the function that is called inside C#:
Gr = HybridLib.Hybrid_Color.GREEN;

And here is the list of "Hybrid_Color"which in the library:
enum Hybrid_Color
{
    GREEN = 0x00000001,
    BLACK = 0x00000002,
    BLUE = 0x00000004,
};

The library itself was launched in PHP:
$PHP_Lib = new COM("HybridLib.Hybrid");

Can not assign value:
$gr = $PHP_Lib -> ..... ?????

What I write next, I don't know...
Tell me, please, who knows...
IceNV 13-Dec-2016 02:17
Under PHP7(.x) 64-bit, there is a documentation error (on the MSDN side, already reported) causing problems if you try to manipulate the registry (StdRegProv) through COM.

Indeed, MSDN reports that the registry hive/root must be reported as a uint32, which means that, in PHP 64-bit, one would create a new Variant($root,VT_UI4).

This would throw a type mismatch error.
It seems internally and contrary to what MSDN says (as of now, 2016-12-13), the root parameter must actually be passed as an int32.

So you have to :
1. convert your root number to a negative int to avoid out-of-bounds exceptions when creating the variant below (basically the integer being >= 2^31, you have to wrap it around the 32-bit signed integer maximum yourself) ;
2. create a new Variant($root,VT_I4) ;
3. pass that Variant to your COM API call.

This did not happen before PHP 7.0 as it always used VT_I4 internally before (see https://bugs.php.net/bug.php?id=73605), but now it respects (and is right to do so) the real integer length, so without an explicit conversion, PHP7 would now output a VT_I8 on x64, versus VT_I4 for PHP5.
juan156_elias at gmail dot com 08-Nov-2015 03:22
This is an example of using .Net using the NetPhp library that is based on the COM/DOTNET classes.

You can use any .dll file,  wether it is or not COM decorated and any of the .Net framework types out of the box. You can also target any version of the .Net framework.

<?php

$runtime = new \NetPhp\Core\NetPhpRuntime('COM', 'netutilities.NetPhpRuntime');

// Add both SpreadsheetLight and the OpenXML it depends on.
$runtime->RegisterAssemblyFromFile('/binaries/SpreadsheetLight.dll', 'SpreadsheetLight');
$runtime->RegisterAssemblyFromFile('/binaries/DocumentFormat.OpenXml.dll', 'DocumentFormat.OpenXml');
$runtime->RegisterAssemblyFromFile('/binaries/AjaxMin.dll', 'AjaxMin');

// Using the FullName of a type that belongs to an assembly that has already been registered.
$datetime = $runtime->TypeFromName("System.DateTime");

// Using the FullName of a type that has not been registered yet (from a file)
$minifier = $runtime->TypeFromFile("Microsoft.Ajax.Utilities.Minifier", APPLICATION_ROOT . '/binaries/AjaxMin.dll');

// Using the FullName of a type that has not been registered yet (autodiscoverable)
$datetime2 = $runtime->TypeFromAssembly("System.DateTime", "mscorlib, ....");

$datetime->Instantiate();
echo $datetime->ToShortDateString()->Val(); // Outputs 01/01/0001

// We can only use Int32 from native PHP, so parse
// an Int64 that is equivalent to (long) in the DateTime constructor.
$ticks = $runtime->TypeFromName("System.Int64")->Parse('98566569856565656');

$datetime->Instantiate($ticks);
echo $datetime->ToShortDateString()->Val(); // Outputs 07/05/0313

// We can only use Int32 from native PHP, so parse
// an Int64 that is equivalent to (long) in the DateTime constructor.
$ticks = $runtime->TypeFromName("System.Int64")->Parse('98566569856565656');

// Dump a .Net System.Timers.Timer object!
$data = $timer->GetPhpFromJson();

var_dump($data);

    // Outputs:
    //  object(stdClass)[38]
    //     public 'AutoReset' => boolean true
    //     public 'Enabled' => boolean false
    //     public 'Interval' => int 100
    //     public 'Site' => null
    //     public 'SynchronizingObject' => null
    //     public 'Container' => null

// Check if today is monday
$IsMonday = $runtime->TypeFromName("System.DateTime")->Now->DayOfWeek->
Equals($runtime->TypeFromName("System.DayOfWeek")->Enum('Monday'));

?>
Eion Robb 12-Feb-2014 09:59
All the examples here show
<?php $var = new COM('Whatever.Something') or die(); ?>
however the 'or die()' bit is redundant as a fatal 'com_exception' exception will be thrown, killing your script.  If you want to handle the 'or' condition you need to catch the exception, eg
<?php
try {
$var = new COM('Whatever.Something');
} catch (com_exception $e) {
 //couldn't load, do something else like register
exec('regsvr32 /s whatever.dll');
}
?>
rogier 28-Oct-2011 10:09
Took me a while to figure this out by trial and error:

If your frustrated when getting a com-exception like "Error [0x80004002] ..." (with a message nagging you about an unsupported interface), and you're calling a class method through COM that expects a char as an argument, you should NOT call the method with a single-character string.

The correct way of calling a method like this is to use a VARIANT with a type of VT_UI1.

COM enabled method definition:

public bool DoSomething(char arg);

<?php

$com = new COM('Some.Class.Name');

// This will fail
$var = 'a';
$com->DoSomething($var);

// This works correctly
$var = new VARIANT(ord('a'), VT_UI1);
$com->DoSomething($var);

?>

I hope this helps some people
sparrowstail at googlemail dot com 12-Nov-2010 11:35
This script reports all Windows drives, drive type, status (if not available), free space and total drive size:

<?php

    $fso = new COM('Scripting.FileSystemObject');
    $D = $fso->Drives;
    $type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk");
    foreach($D as $d ){
       $dO = $fso->GetDrive($d);
       $s = "";
       if($dO->DriveType == 3){
           $n = $dO->Sharename;
       }else if($dO->IsReady){
           $n = $dO->VolumeName;
           $s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize);
       }else{
           $n = "[Drive not ready]";
       }
   echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>";

    }

      function file_size($size)
      {
      $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
      }

?>

There are a number of other properties of the drive object which can be called this way - see:

http://msdn.microsoft.com/en-us/library/ts2t8ybh%28VS.85%29.aspx
z3n at overflow dot biz 24-Sep-2009 08:35
On a query reply using ADODB.Connection object, all my $rs->Fields['field_name']->Value returned `variable Object` when inserted into a array, like this:

<?php
for ($rl[$v]=array(),_qm($_query);!$res->EOF;$res->MoveNext()) {
    $rl[$v][]=$res->Fields['x']->Value;
}
?>

I figured out that converting the value into a INT fixed the issue:

<?php $rl[$v][]=intval($res->Fields['x']->Value); ?>
pavanphp Gudipati 17-Jun-2009 06:49
Here I Am describing a Program from which you can connect any exe(software) using COM component.
pdf2swf is a software for converting PDf to SWF files.

This is best example for  WScript.Shell

<?php
#code for pdf to swf using pdf2swf software
#this codeworks in windows environment.

## Important Parameters
$software_path  ="C:\\SWFTools\\pdf2swf" ;
$pdf_path       ="C:\\SWFTools\\abcd.pdf" ;
$argument       = "-o";
$swf_output     ="C:\\SWFTools\\abcd.swf" ;

#actual code
$cmd        =" $software_path $pdf_path  $argument $swf_output";

$WshShell   = new COM("WScript.Shell");
$oExec      = $WshShell->Run("cmd /C $cmd ", 0, true);

# 0 for command prompt invisible mode
# 3 for visible

?>
tsintra at humansoft dot pt 11-May-2009 08:18
After one week of trying to understand what was wrong with my PHP communication with MS Word, i finally got it working...
It seems that if you're running IIS, the COM object are invoked with restricted privileges.
If you're having permission problems like not being able to opening or saving a document and you're getting errors like:

 - This command is not available because no document is open
or
 - Command failed

try this (if you're running IIS):

- Execute "dcomcnfg"
- Open Component Services > Computers > My Computer > DCOM Config
- Search for Microsoft Office Word 97-2003 Document (it will be something like this translated to your language, so take a while and search for it)
- Right-Click on it and open the properties
- Choose "Identity" tab
- Normally this is set to "the launching user". You have to change this to "the interactive user" or a admin user of your choice.
- Apply these new settings and test your COM application. It should work fine now.

I hope I save lots and lots of hours of headaches to some of you :)
dpchiesa at hotmail dot com 27-Mar-2009 09:35
Here's a way to create an AES-Encrypted ZIP file in PHP, using DotNetZip via the COM class.

<?php
try
{
  $fname = "zip-generated-from-php-" . date('Y-m-d-His') . ".zip";
  $zipOutput = "c:\\temp\\" . $fname;
  $zip = new COM("Ionic.Zip.ZipFile");
  $zip->Name = $zipOutput;
  $dirToZip= "c:\\temp\\psh";
  #$dirToZip= "c:\\dinoch\\webs\\php";
  $zip->Encryption = 3;
  $zip->Password = "AES-Encryption-Is-Secure";
  $zip->AddDirectory($dirToZip);
  $zip->Save();
  $zip->Dispose();

  if (file_exists($zipOutput))
  {
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-Type: application/x-zip');
    header('Content-Disposition: attachment; filename=' . $fname);
    header('Content-Length: ' . filesize($zipOutput));
    readfile($zipOutput);
    unlink($zipOutput);
  }
  else
  {
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '</body>';
    echo '</html>';
  }
}
catch (Exception $e)
{
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '<p>Caught exception: ',  $e->getMessage(), '</p>', "\n";
    echo '<pre>';
    echo $e->getTraceAsString(), "\n";
    echo '</pre>';
    echo '</body>';
    echo '</html>';
}

?>
james dot m dot love at gmail dot com 07-Jan-2009 03:27
If you're using COM to create a DSN Less connection to an MS Access 2007 database, you'll find through Googling that you need to use an updated version of Jet, so the connection string I've found looks like this:

<?php
$databaselocation = "C:\Path\to\db.accdb";
$conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
$conn->Open("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=$databaselocation") or die('Cannot start with Jet');
?>

However, on my setup (WinVista, Access 2007, PHP526) I found that it always 'dies' with "Cannot start with Jet", even if the connection was successful ($conn->State reads "1").

I figured to just drop the die() command on $conn->Open(). If something catastrophic happens with the ADO connection then it's own error handling engine passes stack traces, etc back to the console/standard output.

Therefore, my Open() command looks like this:

<?php
$conn->Open("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=$databaselocation");
?>
casanoteva at yahoo dot com 26-Dec-2008 01:19
Hi, just wanna share to everyone after tried and tested many many times to create report in PDF format from Crystal Report.
Finally I can do it without any error.
 Here is my system; PHP 5.1.6, MSSQL2005 and Crystal Report Server XI RL2

<?php

//- Variables - for your RPT and PDF
echo "Print Report Test";
$my_report = "D:\\Folder1\\SubFolder1\\Report.rpt"; //
rpt source file
$my_pdf = "D:\\Folder1\\SubFolder1\\Report.pdf"; // RPT export to pdf file
//-Create new COM object-depends on your Crystal Report version
$ObjectFactory= new COM("CrystalReports115.ObjectFactory.1") or die ("Error on load"); // call COM port
$crapp = $ObjectFactory-> CreateObject("CrystalDesignRunTime.Application"); // create an instance for Crystal
$creport = $crapp->OpenReport($my_report, 1); // call rpt report

// to refresh data before

//- Set database logon info - must have
$creport->Database->Tables(1)->SetLogOnInfo("servername", "DBname", "user", "password");

//- field prompt or else report will hang - to get through
$creport->EnableParameterPrompting = 0;

//- DiscardSavedData - to refresh then read records
$creport->DiscardSavedData;
$creport->ReadRecords();

//export to PDF process
$creport->ExportOptions->DiskFileName=$my_pdf; //export to pdf
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // export to file
$creport->ExportOptions->FormatType=31; // PDF type
$creport->Export(false);

//------ Release the variables ------
$creport = null;
$crapp = null;
$ObjectFactory = null;

//------ Embed the report in the webpage ------
print "<embed src=\"D:\\Folder1\\SubFolder1\\Report.pdf\" width=\"100%\" height=\"100%\">"

?>

 That's all for me, anyway in Crystal Report I have to check DisCardSavedData, Save data with report and AutoSave (1 min) in Option Tab and also in Report Options I have to check save dat with report, too.

Hope this should be help to anybody

Casanoteva
johnno1985 at gmail dot com 21-Aug-2008 11:34
I couldn't find an example anywhere on what I was trying to do.  After taking bits from everyone I ended up with something that worked.

Im using Crystal Reports 10, MS SQL Server 2005, Apache2, and PHP5.

My report uses an SQL Store Procedure and passes some parameter to get the report data, so our PHP must set the database logon info and pass the parameters.

Below is the solution I came up with:

<?php

//------  Variables ------
$my_report = "C:\\Apache2\htdocs\\test\\MyReport.rpt";  //This must be the full path to the file
$my_pdf = "C:\\Apache2\htdocs\\test\\MyReport.pdf";

//------ Create a new COM Object of Crytal Reports 10 ------
$ObjectFactory= new COM("CrystalReports10.ObjectFactory.1");

//------ Create a instance of library Application -------
$crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application.10");

//------ Open your rpt file ------
$creport = $crapp->OpenReport($my_report, 1);

//------ Set database logon info ------
$creport->Database->Tables(1)->SetLogOnInfo("MYSERVER", "Database", "user", "password");

//------ Suppress the Parameter field prompt or else report will hang ------
$creport->EnableParameterPrompting = 0;

//------ DiscardSavedData make a Refresh in your data -------
$creport->DiscardSavedData;
$creport->ReadRecords();

//------ Pass formula fields --------
$creport->FormulaFields->Item(1)->Text = ("'My Report Title'");
$creport->ParameterFields(1)->AddCurrentValue ("FirstParameter");
$creport->ParameterFields(2)->AddCurrentValue (2000);

//------ Export to PDF -------
$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->FormatType=31;
$creport->ExportOptions->DestinationType=1;
$creport->Export(false);

//------ Release the variables ------
$creport = null;
$crapp = null;
$ObjectFactory = null;

//------ Embed the report in the webpage ------
print "<embed src=\"MyReport.pdf\" width=\"100%\" height=\"100%\">"

?>

Obviously there's plenty of room for refinement in there, but it works and should get you going on the right track.  I also found that during testing, the script was hanging before supressing the parameter prompt. Once this had happened, some exports that had been working earlier stopped completely and wouldn't work again untill I restarted Apache.  This might be something worth doing if you keep having issues after a script has hung.
mastrboy.servebeer.com 13-Jun-2008 05:03
quick wmi query example:

<?php
    $obj = new COM ( 'winmgmts://localhost/root/CIMV2' );
    $wmi_computersystem =     $obj->ExecQuery("Select * from Win32_ComputerSystem");
    $wmi_bios             =    $obj->ExecQuery("Select * from Win32_BIOS");
    foreach ( $wmi_computersystem as $wmi_call )
    {
        $model = $wmi_call->Model;
    }

    foreach ( $wmi_bios as $wmi_call )
    {
        $serial = $wmi_call->SerialNumber;
        $bios_version = $wmi_call->SMBIOSBIOSVersion;
    }
    echo "Bios version   : $bios_version\n".
         "Serial number  : $serial\n".
         "Hardware Model : $model\n";
?>
mbirth at webwriters dot de 08-Jun-2008 03:19
Using the DynamicWrapper from http://freenet-homepage.de/gborn/WSHBazaar/WSHDynaCall.htm and after registering it via "regsvr32 dynwrap.dll", you can easily set output colors to make colorful CLI scripts even on Windows.

<?php

$dw = new COM('DynamicWrapper');  // needs dynwrap.dll (regsvr32 dynwrap.dll)

// register needed features
$dw->Register('kernel32.dll', 'GetStdHandle', 'i=h', 'f=s', 'r=l');
$dw->Register('kernel32.dll', 'SetConsoleTextAttribute', 'i=hl', 'f=s', 'r=t');
$dw->Register('kernel32.dll', 'SetConsoleTitle', 'i=s', 'f=s', 'r=l');

// get console handle
$ch = self::$dw->GetStdHandle(-11);  // -11 = STD_OUTPUT_HANDLE

?>

After these initialization steps, you can set the console output color using:

<?php
$dw->SetConsoleTextAttribute($ch, 14);
echo 'This is yellow text!';
$dw->SetConsoleTextAttribute($ch, 7);
echo 'Back to normal gray!';
?>

Using SetConsoleTitle you can even set the title displayed in the console window.

Color values are 0..7 for dark colors and 8..15 for light colors. Sequence is (black/silver, blue, green, cyan, red, magenta, yellow/brown, white/gray). I also found that if you add 16384 to the value, it should be inverse. 32768 added should get underlined text. But these latter two didn't work for me.
amenthes at NOSPAM dot gmail dot com 03-Mar-2008 10:13
If you ever want to save an Excel(.xls) file into the Office Excel 2003 XML format, just use

$excel->Workbooks[1]->SaveAs('new_file_name.xml', 46);

That's the number you need, 46.
halfer 21-Jun-2007 05:03
Thanks to paul at completewebservices who added a note earlier; I have used his code to solve a particularly difficult issue with the Crystal 9 runtime component. For some reason, VBA/VBS can pass a native Date type as a parameter to a Crystal Report requiring a date, but in PHP I've tried all manner of strings, unix timestamps, COM variant dates etc and all of these resulted in a com_exception.

My solution was to employ VBScript to borrow the CDate function, which works correctly. Not the most elegant of solutions, but this parameterised approach is to be preferred to search-n-replacing the RecordSelectionFormula string. Of course if anyone here has an even better approach, do post it here - I am sure it would be of use.

<?php
// $rptParam is a report parameter object having a type of date
$oScript = new COM("MSScriptControl.ScriptControl");
$oScript->Language = "VBScript";
$oScript->AllowUI = false;
$oScript->AddObject('rptParam', $rptParam, true);
$oScript->AddCode('Function SetDateParameter(strDate)
rptParam.AddCurrentValue(CDate(strDate))
End Function');
$oScript->Run("SetDateParameter", "25 April 2006");
?>
hwcshirley at gmail dot com 21-May-2006 10:59
Reply to: djogopatrao at gmail dot com
I have change little bit your code. Its work.

$COM_Object = "CrystalDesignRunTime.Application";
$my_report = "C:\\appserv\\www\\mc\\test.rpt";
$my_pdf = "C:\\appserv\www\\mc\\test.pdf";

$crapp= New COM($COM_Object) or die("Unable to Create Object");
$creport = $crapp->OpenReport($my_report, 1);
$creport->ReadRecords(); // attention!

$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // Export to File
$creport->ExportOptions->FormatType=31; // Type: PDF
$creport->Export(false);
djogopatrao at gmail dot com 05-Apr-2006 12:25
My previous notes about Crystal Reports have vanished away, but anyway I was up to correct them.

The code above connects to COM (beware of the version number! search on the Registry Editor for the correct name to put in $COM_Object), opens a report from a file ($my_report), reload records from database and then exports it to a PDF file ($my_pdf).

* IMPORTANT * this code, when invoked from the browser (I'm using Apache) AND with a report that connects to a ODBC database, does not work (the problem is specificly the line ReadRecords(), but may arise without it too when data is not saved into the report file).

But when you run this code by PHP-CLI (that is, by the command line), it works ok! I bug-reported this, but have no answer till now ( give it a vote, if you thing it's important: http://bugs.php.net/bug.php?id=36959 ).

Also, exceptions may arise, so put it on a try_catch block.

--------------------------

// by dfcp '06 (djogopatrao@gmail.com)

$COM_Object = "CrystalReports11.ObjectFactory.1";
$my_report = "C:\\report.rpt";
$my_pdf = "C:\\report.pdf";

$ObjectFactory= New COM($COM_Object);
$crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
$creport = $crapp->OpenReport($my_report, 1);
$creport->ReadRecords(); // attention!

$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // Export to File
$creport->ExportOptions->FormatType=31; // Type: PDF
$creport->Export(false);
djogopatrao at gmail dot com 04-Mar-2006 07:27
I found somewhere (http://www.recrystallize.com/merchant/supportfaq/supportfaq0003.htm) a list relating each version of Crystal Reports to its respective progID - it may help some fellows out there.

7          Crystal.CRPE.Application

8.0        CrystalRuntime.Application or CrystalRuntime.Application.8

8.5        CrystalRuntime.Application or CrystalRuntime.Application.8.5

9 (RDC)    CrystalRuntime.Application.9
9 (RAS)    CrystalReports.ObjectFactory.2
10 (RDC)   CrystalRuntime.Application.11
10 (CEE)   CrystalReports10.ObjectFactory.1

XI (RDC)   CrystalRuntime.Application.11
XI (RAS)   CrystalReports11.ObjectFactory.1
paul at completewebservices dot com dot au 28-Jan-2006 03:49
It seems that PHP does not support setting of properties with arguments.  This is how I got around the problem:

        // Object with method I want to set
        $auth = new COM("AUTHXOCX.AuthXOCXCtrl.1");

        // ScriptControl
        $oScript = new COM("MSScriptControl.ScriptControl");
        $oScript->Language = "VBScript";
        $oScript->AllowUI = TRUE;

        // Add out object to the control
        $oScript->AddObject('auth', $auth, true);

        // Create a VBScript function that allow me to set them
       $oScript->AddCode(
'Function fixAccess(accessname)
    auth.AuthDataReferrerEnabled(accessname) = 1
    auth.AuthDataAuthentiXDBEnabled(accessname) = 0
End Function');

        // Execute function
        $oScript->Run("fixAccess", $dir);
volker at kybs dot de 07-Oct-2005 12:51
To use the windows speech system install the "Speech SDK 5.1 for Windows? applications" from the Microsoft homepage (free download).
Then you can do Text2Speech like this:

$voice = new COM("SAPI.SpVoice");
$voice->Speak("Hello, lets have a conversation");
sadi at unicornsoftbd dot com 06-Oct-2005 01:56
If your PHP is configured as ISAPI module then the COM object you create in ur php page will use the same memory space as the web server. If your COM object takes too much memory then this may force some COM error as PHP does not handle the memory usage of COM itself. And also Web server doesnt know what do to free COM memory. But if you use PHP as CGI then PHP itself handle the memory usage of COM. Once in a script where i used COM and PHP as ISAPI module i got unknown COM error.But when i used PHP as CGI there was no error. So those who want to use COM object in your application please be careful about it.
deletethis@bjoern(at)syltonline(doot)de 15-Sep-2005 07:36
If you can get the old "TaskScheduler.dll" and register it, it is quite simple to handle and start Windows tasks from PHP.
This is extremely useful when you got things to do which must be run in a different user context. Prepare a task with the user and use PHP & Com to build a webinterface for it.

Here is an example how to start a Windows task:

  function start_task ($taskname) {
    $SchedObj = new COM("Scheduler.SchedulingAgent.1");
    foreach ($SchedObj->Tasks as $task) {
      if (strtolower( (string) $task) == strtolower( $taskname.".job" )) {
         $task->Run();
      }
    }
  }

I'm also working on a class to handle infos, adding and removing of tasks via PHP. If you are interested drop me a line.
csaba at alum dot mit dot edu 03-Mar-2005 05:21
Getting IE to the foreground
If you are using a command line (CLI) version of PHP on a Win32 platform (e.g. XP Pro, SP2), you might want to have output directed to IE (perhaps you'll want to work with the output there) when Popup does not suffice (see my earlier post, below).

It's easy enough to get an instance of IE using $ie = new COM("InternetExplorer.Application");.  The problem is, you don't necessarily see it in the foreground (especially if you already have one open) and who wants to waste keystrokes getting to it?  The code below has been working for me (If you want to do other adjustments (e.g. $ie->Document->ParentWindow->resizeTo(800,500); or $ie->Document->Body->bgColor = "yellow";), doing them before the $ie->Visible = true; line will avoid screen distractions):

<?php
function newIEtoForeground($title, $evtPrefix="") {
    // brings new instance of IE to foreground with title $title
    if (!$extPrefix) $ie = new COM("InternetExplorer.Application");
    else $ie = new COM("InternetExplorer.Application", $evtPrefix);
    $ie->Navigate2("about:blank");
    $oWSH = new COM("WScript.Shell");
    while ($ie->ReadyState!=4) usleep(10000);

    $ie->Document->Title = ($tmpTitle = mt_rand());  //unique title
    $ie->Visible = true;
    while (!$oWSH->AppActivate("$tmpTitle - M")) usleep(10000);

    $ie->Document->Title = $title;
    $ie->Document->ParentWindow->opener="me";  // allows self.close()
    return $ie;
}
?>

Csaba Gabor from Vienna
csaba at alum dot mit dot edu 14-Feb-2005 12:22
Basic Windows IO
If you are using a command line (CLI) version of PHP on a Win32 platform, you might like to have a simple graphical interface to get input and output.  The following gives an illustration for both.

<?php
    // first we get some input
    $oScript = new COM("MSScriptControl.ScriptControl");
    $oScript->Language = "VBScript";
    $title = "I/O Demo: Input half";
    $initial = "Change this value";
    $prompt = "Please enter a value";

    $code = <<<EOF
Function getInput()
    inVal = InputBox("$prompt", "$title", "$initial")
    getInput = inVal         'how return values are assigned in VB
End Function
EOF;

    $oScript->AddCode($code);
    $input = $oScript->Eval("getInput()");
    if (gettype($input)=="NULL") $input = "Input box was cancelled";

    // now we show some output
    $oWSH = new COM("WScript.Shell");
    $title = "I/O Demo: Output half";
    $timeout = 2;        // 0 for no timeout
    $style = 0 + 48;    // buttons to show + alert symbol
    $oWSH->Popup($input, $timeout, $title, $style);
?>

This is example is overblown for illustrative purposes.  The whole input part collapses if the amount of code used is a single statement.  So, this would have sufficed:
$code = "InputBox(\"$prompt\", \"$title\", \"$initial\")";
$input = $oScript->Eval($code);

This technique exposes quite a bit of scripting power tied into the Windows operating system and VBScript.  However, you should have a really specific reason for using it since VBScript tends to be dog slow when compared to PHP in my tests.  Simple IO like this is good, however, and the popup size can be quite large.  Furthermore, this could be a viable route to go for accessing WinAPI's.

http://www.ss64.com/wsh/popup.html shows some documentation for $oWSH->Popup

Csaba Gabor from Vienna
phpguy _from_ toshpro _dot_ com 12-Nov-2004 05:55
if you ever need to connect to an access database (on the server, using the IIS or APACHE user account), here is code below that can help to ease the process.  It is written like this because we have a MySQL as well as an Access database and need to be able to switch back and forth.  The runQuery function will return a 2 dimensional array and can use column names or numbers for the index of the internal arrays.  External arrays are always integer-indexed.  We also have found issues with Access staying open and growing from 7MB to 2.5GB within two hours, so we open and close it each time we run a query.  If it is not a select query it will return TRUE.  if it fails with errors, it will return false.

There is a showErr flag that we mostly only use for MySQL, since you can output MySQL errors without PHP errors.  Access doesn't appear to be that friendly.

<?php

function runQuery(&$conn,
                    $strSQL,
                    $associative=true,
                    $debug=false,
                    $showSQL=false,
                    $showErr=false) {
    return runMSQuery($conn,$strSQL,$associative,$debug,$showSQL,$showErr);
    //return runMyQuery($conn,$strSQL,$associative,$debug,$showSQL,$showErr);
}

function openMSDB($dbfile="c:/path/and/filename.mdb") {
    if (!@$conn = new COM("ADODB.Connection"))
        exit("Unable to create an ADODB connection<br>");
    $strConn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$dbfile;
    @$conn->open($strConn);
    if($conn->State == 0) return false;
    return $conn;
}

function closeMSDB(&$conn) {
    @$conn->Close();
    $conn = null;
    return true;
}

function runMSQuery(&$conn,
                    $strSQL,
                    $associative=true,
                    $debug=false,
                    $showSQL=false,
                    $showErr=false) {
    if(!is_object($conn)) if(!$conn=openMSDB()) return false;
    if( $showSQL || $debug ) echo $strSQL."\n<br>\n";
    $rtn = false;
    if($debug) $rs = $conn->execute($strSQL);
    else $rs = @$conn->execute($strSQL);

    if(!$rs) {
        if($showErr) echo "Error running SQL.<br>\n";
        closeMSDB($conn);
        return false;
    }
    if ($rs->State == 0) {
        closeMSDB($conn);
        return true;
    } else {
        $rows=0;
        while(!$rs->EOF) {
            for($i=0;$i<$rs->Fields->count;$i++) {
                $rsf = $rs->Fields($i);
                if($associative) $rtn[$rows][$rsf->Name] = $rsf->value;
                else $rtn[$rows][$i] = $rsf->value;
            }
            $rows++;
            $rs->MoveNext();
        }
        if($rs->State != 0) $rs->Close();
        $rs = null;
    }
    if($debug) var_dump($rtn);
    closeMSDB($conn);
    return $rtn;
}
?>
sodeh at dana dot ir 30-Oct-2004 03:11
for connection to sql server and know the utf-8 code
use this method to connect the database

$db = new COM("ADODB.Connection",NULL, 65001 );
jon at jonroig dot com 03-Dec-2003 12:28
Here's a simple example of printing formatted templates with MS Word.

To begin with, I've already built my invoice in Word and saved it as an RTF file.
In this case, I'm using "sampleInvoice.php"

Fields that will be replaced have been marked as ||CUSTOMER ID|| and so on.

<?php
$dataText = "";

// open the file
if(!($fp= fopen ("C:\wordTest\sampleInvoice.rtf", "r"))) die ("Can't open");
$dataText = fread($fp, 2000000);
fclose ($fp);

// replace the template fields
$dataText = str_replace ("||CUSTOMER ID||",$customerIDValue, $dataText);

// save the file as an rtf
$timeStamp = time();
$saveFile = "C:/wordTemp/".$timeStamp."-invoice-".$customerIDValue.".rtf";
if(!($fq= fopen ($saveFile, "w+"))) die ("Can't open");
fwrite ($fq, $dataText);
fclose ($fq);

// initialize the word components
$word = new COM("word.application") or die("Unable to instantiate Word");

print "Loaded word version ($word->Version)\n";
$word->visible = true;
$word->Documents->Add();

// open the file
$word->Documents->Open("$saveFile");

// output the file to the default printer
$word->ActiveDocument->PrintOut(1);

// shutdown word
$word->Quit();
?>
drich at nea-online dot net 18-Nov-2003 02:47
Changing Fields (Not FORMFIELDS) In MS Word....

Searched most of the afternoon for this, as it is something needed here for our projects.  Maybe this can help someone else as well.

<?php
$input = "x:\\path\\to\\test.doc";
$word = @new COM("word.application") or die("Unable to instantiate Word");
print "Loaded Word, version {$word->Version}\n<br>";
$word->Visible = 1;
print "Set Word To Visible<br>";
$word->Documents->Open($input);
print "Opened $input<br>";
$word->Activate;
print "Activated Word<br>";

print "Editing Fields<br>";
$Field = $word->ActiveDocument->Fields(1);
$fieldData = $Field->Result;
$fieldData->Text = "Testing";

// Print the document.
$word->Printout();

// closing word
$word->Quit();

// free the object
$word->Release();
$word = null;

?>
admin at CdnDomainRegistry dot ca 20-Sep-2003 03:57
Here's an example/comparison of VBScript vs PHP's COM component to connect to an IIS Webserver.
The examples backup the IIS MetaBase (your server's website(s) configuration) in IIS.

VBScript:
  Dim obj, iFlags
  Set obj = GetObject("IIS://LocalHost")
  ' Backup to next available version number.
  ' Set flags to save the metabase first and
  ' force the backup even if save fails.
  iFlags = (MD_BACKUP_SAVE_FIRST or MD_BACKUP_FORCE_BACKUP)
  obj.Backup "MyBackups", MD_BACKUP_NEXT_VERSION, iFlags
  ' Note: The above was copied from Microbucks.
  ' This is how you would have to do it.
  ' i.e. use the actual constant's value.
  iFlags = (2 or 4)
  obj.Backup "MyBackups", &HFFFFFFFF, iFlags

PHP:
  <?php
  $obj = new COM("IIS://LocalHost")or die("Unable to instantiate IIS");
  $err = com_invoke ($obj, "Backup", "MyBackups", "&HFFFFFFFF", 2|4 );
  $obj = null;
  print "err=".$err; // returns 0 on success
  ?>

Glen
rickardsjoquist at hotmail dot com 09-Jul-2003 10:33
If you want to use a DSN-less connection to a database (access for example) and return the results of a query as a multidimensional array with the fieldnames as identifier try this. Hope it helps someone :-)
--------------------------------------------------------

<?php
function db($sql) {
    $c = new COM("ADODB.Connection");
    $c->open('DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=' . realpath("relative_path/db.mdb"));
    $r = $c->execute($sql);
    $i = 0;
    $num_fields = $r->fields->count();
    while (!$r->EOF)
        {
            for($j = 0;$j<$num_fields;$j++) {
            $key = $r->Fields($j);
            $r_items[$i][$key->name] = $key->value;
        }
        $i++;
        $r->MoveNext();
    }
    $r->close();
    $c->close();
    $r = null;
    $c = null;
    return $r_items;
}
?>

--------------------------------------------------------
use it like this:
--------------------------------------------------------
<?php
$results = db("SELECT field_a, field_b FROM table");
foreach($result as $i => $item) {
    echo $item['field_a'];
    echo $item['field_b'];
}
?>
--------------------------------------------------------
You can also use: print_r($result); if you want the structure of the array to be printed.
info at sharedprojects dot nl 16-Jun-2003 09:41
<?php
// An other way to connect
// this connect to a ODBC-datasourced added in the
// ODBC Data Source Administrator under System DSN

$odbcname = "northwind";
$conn->Open("DSN=$odbcname");
?>
eguan1ao_at_yahoo_dot_com 20-Nov-2002 01:35
An example of connecting to a Microsoft Access database, executing an SQL query, and displaying the results in HTML.

<?php

$db = 'C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb';

$conn = new COM('ADODB.Connection');

// Two ways to connect. Choose one.
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$db");
//$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");

$sql = 'SELECT   ProductName, QuantityPerUnit, UnitPrice
         FROM     Products
          ORDER BY ProductName';
$rs = $conn->Execute($sql);

?>

<table>
<tr>
          <th>Product Name</th>
         <th>Quantity Per Unit</th>
         <th>Unit Price</th>
</tr>
<?php while (!$rs->EOF): ?>
         <tr>
                  <td><?= $rs->Fields['ProductName']->Value ?></td>
                   <td><?= $rs->Fields['QuantityPerUnit']->Value ?></td>
                  <td><?= $rs->Fields['UnitPrice']->Value ?></td>
          </tr>
         <?php $rs->MoveNext() ?>
<?php endwhile ?>
</table>

<?php

$rs->Close();
$conn->Close();

?>
yinon at xacct dot com 06-Apr-2002 12:33
In order to get the Word exaple running, do the following on the server side.
Worked for me...
1. Click START-->RUN and enter "dcomcnfg"
2. In the "Applications" tab, go down to "Microsoft Word Document"
3. Click PROPERTIES button
4. Go to the "Security" Tab
5. Click "Use custom access permissions", and then click EDIT
6. Click ADD and then click SHOW USERS
7. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD
8. Go back to the "Security" tab by hitting OK
9. Click "Use custom launch permissions", and the click EDIT
10. Click ADD and then click SHOW USERS
11. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD
12. Hit OK, and then hit APPLY.

Also, you should look at the "Identity" tab in the Microsoft Word Document PROPERTIES and see that it is set to "Interactive User"

ALSO, log into the machine AS the IUSR_<machinename> account, start word, and make sure to click through the dialog boxes that Word shows the first time it is run for a certain user.  In other words, make sure Word opens cleanly for the IUSR_ user.

More useful information could be found here:
http://www.email-screen.com/support-doc2txt.html
mstaiger at informatik dot uni-siegen dot de 23-Jan-2002 06:17
The example above (MS Word) is quiet unsatisfying, as I find. Especially since I couldn't find anybody who actually got it running, including myself.

You might therefore give this Powerpoint-example a chance:
----------------------------------
#Instantiate a PowerPoint object.
$ppoint = new COM("PowerPoint.application") or die("Unable to instantiate PowerPoint");

<?php
#Create a new presentation
$ppoint->Presentations->Add() or die ("Could not create presentation");

//Add a slide
$slide=$ppoint->Presentations[1]->Slides->Add(1,1);

//Get the name of this slide
$slidename = $slide->Name();
echo"<br>slidename : $slidename";

//Change the name of this new slide
$slide->Name = "New Slidename";
$slidename = $slide->Name();
echo"<br>NEW slidename : $slidename";

//Save the presentation
$ppoint->Presentations[1]->SaveAs("c:/InetPub/www/test.ppt");
$ppoint->Presentations[1]->Close();

//closing powerpoint
$ppoint->Quit();

//free the object
$ppoint->Release();
$ppoint = null;
-----------------------
?>

the config is :
w2k-server/office2k/iis5/php 4.1.1 isapi

If you happen to run into a working word2k-example, please let me know.

Marc


com class constructor

  • ? com
  • dotnet ?
  • PHP Manual
  • com
  • com class constructor

com::__construct

(PHP 4 > 4.1.0, PHP 5, PHP 7, PHP 8)

com::__construct — com class constructor

说明

public com::__construct ( string $module_name , array|string|null $server_name = null , int $codepage = CP_ACP , string $typelib = "" )

Constructs a new com object.

参数

module_name
Can be a ProgID, Class ID or Moniker that names the component to load. A ProgID is typically the application or DLL name, followed by a period, followed by the object name. e.g: Word.Application. A Class ID is the UUID that uniquely identifies a given class. A Moniker is a special form of naming, similar in concept to a URL scheme, that identifies a resource and specifies how it should be loaded. As an example, you could load up Word and get an object representing a word document by specifying the full path to the word document as the module name, or you can use LDAP: as a moniker to use the ADSI interface to LDAP.
server_name
The name of the DCOM server on which the component should be loaded and run. If null, the object is run using the default for the application. The default is typically to run it on the local machine, although the administrator might have configured the application to launch on a different machine. If you specify a non-null value for server, PHP will refuse to load the object unless the configuration option is set to true.

If server_name is an array, it should contain the following elements (case sensitive!). Note that they are all optional (although you need to specify both Username and Password together); if you omit the Server setting, the default server will be used (as mentioned above), and the instantiation of the object will not be affected by the directive.

DCOM server name
key | type | description
Server | string | The name of the server.
Username | string | The username to connect as.
Password | string | The password for Username.
Domain | string | The domain of server.
Flags | integer | One or more of the following constants, logically OR'd together: CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER and CLSCTX_ALL. The default value if not specified here is CLSCTX_SERVER if you also omit Server, or CLSCTX_REMOTE_SERVER if you do specify a server. You should consult the Microsoft documentation for CoCreateInstance for more information on the meaning of these constants; you will typically never have to use them.

codepage
Specifies the codepage that is used to convert strings to unicode-strings and vice versa. The conversion is applied whenever a PHP string is passed as a parameter or returned from a method of this COM object. The code page is sticky, which means that it will propagate to objects and variants returned from the object. Possible values are CP_ACP (use system default ANSI code page - the default if this parameter is omitted), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (use codepage/locale set for the current executing thread), CP_UTF7 and CP_UTF8. You may also use the number for a given codepage; consult the Microsoft documentation for more details on codepages and their numeric values.

User Contributed Notes

There are no user contributed notes for this page.


The dotnet class

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

简介

The dotnet class allows you to instantiate a class from a .Net assembly and call its methods and access its properties, if the class and the methods and properties are » visible to COM.

Neither instantiating static classes nor calling static methods is supported.

Some .Net classes do not implement IDispatch, so while they can be instantiated, calling methods or accessing properties on these classes is not supported.

Note:

You need to install the .Net runtime on your web server to take advantage of this feature.

Note:

.Net framework 4.0 and later are not supported by the dotnet class. If assemblies have been registered with regasm.exe, the classes can be instantiated as com objects, though.

类摘要

dotnet extends variant {
/* 方法 */
public __construct ( string $assembly_name , string $datatype_name , int $codepage = CP_ACP )
}

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.

Once you have created a dotnet object, PHP treats it identically to any other COM object; all the same rules apply.

dotnet examples

Example #1 dotnet example

<?php
$stack = new dotnet("mscorlib", "System.Collections.Stack");
$stack->Push(".Net");
$stack->Push("Hello ");
echo $stack->Pop() . $stack->Pop();
?>

Table of Contents

  • dotnet::__construct — dotnet class constructor

User Contributed Notes

Bitterblue 30-Jul-2018 02:54
I worked with this the last few days and figured it out.
On stack overflow: https://stackoverflow.com/a/51541801/1442225
jcastromail at yahoo dot es 18-Nov-2016 09:04
using dotnet with visual studio 2015 (and net framework 4.6.1 but its the same with others).

1) In visual studio 2015, created a library project (in this case a C#)
2) Double click in the project -> build events -> post build

"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\gacutil.exe"  /i "$(TargetPath)"

When the project its compiled, it adds to the GAC automatically. Please changes the bin folder according your installation.

3) in tools -> External tools, add the next external tool
Title: Get Qualified Assembly Name
Command: Powershell.exe
Arguments: -command "[System.Reflection.AssemblyName]::GetAssemblyName(\"$(TargetPath)\").FullName"
User Output Windows : checks

4) run tools -> Get qualified Assembly Name and checks the output windows

5) Creates the next class (Class1 may be its already creates)

namespace ClassLibrary2 // <-- changes it.
{
    public class Class1
    {
        public string Ping(string t1,string t2)
        {
            return "pong "+t1+t2;
        }
    }
}

6) in php

$full="ClassLibrary2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=746927f9726d7222"; // its from the output windows
$class = 'ClassLibrary2.Class1'; // its the namespace and the class.

 $stack = new DOTNET($full,$class);
 $r1="hello";
 $r2="world";
 echo $stack->Ping($r1,$r2);

IMPORTANT NOTE: PHP "caches" the dll library, so every time that the dll library is compiled, the php service should be restarted (restart the apache service).
IMPORTANT NOTE 2: May be you should run Visual Studio as an Administrator.
juan156_elias at gmail dot com 04-Jun-2015 08:00
Using COM and DOTNET directly is quite a nightmare. DOTNET only allows you to target .Net 3.5 and below, and all the binaries need to be COM  Visible. This basically means that you will need to write your own .Net binaries for everything, at least wrappers.

There is a library out there (NetPhp) built on top of the COM class that will solve all these issues, so you can get code like this:

$manager = new \NetPhp\Core\NetManager();
$manager->RegisterAssembly('mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', 'mscorlib');
$manager->RegisterClass('mscorlib', 'System.IO.File', 'File');
$manager->RegisterClass('mscorlib', 'System.IO.FileOptions', 'FileOptions');
$file = $manager->Create('mscorlib', 'File');
$fileoptions = $manager->Create('mscorlib', 'System.IO.FileOptions')->Enum('Encrypted');

$file->Create("C:\\www\\prueba.tres", 2048, $fileoptions);
m dot atifmajeed at gmail dot com 11-Feb-2015 04:29
How to use donet class for creating object of parameterized constructor

http://php.net/manual/en/class.dotnet.php

private SGF ingerPrintManager m_FPM; //member variable
SGFPMDeviceName device_name = SGFPMDeviceName.DEV_ FDU02 ;
m_FPM = new SGF ingerPrintManager (device_name);
ricardopsj at gmail dot com 14-Apr-2014 01:30
Create an Excel Workbook using DOTNET.

<?php

$full_assembly_string = 'Microsoft.Office.Interop.Excel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c';
$full_class_name = 'Microsoft.Office.Interop.Excel.ApplicationClass';

$e = new DOTNET($full_assembly_string, $full_class_name);
$wb = $e->workbooks->add();
$Precios = $wb->Worksheets(1);
$Precios->Name = 'Precios';
$Venta = $wb->Worksheets(2);
$Venta->Name = 'Venta';
$Tons = $wb->Worksheets(3);
$Tons->Name = 'Tons';

$Meses = Array('2014-01', '2014-02', '2014-03', '2014-04', '2014-05', '2014-06', '2014-07', '2014-08', '2014-09', '2014-10', '2014-11', '2014-12');
foreach ($Meses as $Numero => $Mes) {
   $Precios->Range("A" . ($Numero+1))->Value = $Mes;
}

$wb->SaveAs('c:\temp\Meta.2014.05.xlsx');
$wb->Close();

?>

Go to c:\windows\assembly to know what value to put in $full_assembly_string.

If you don't know the assembly, use http://www.red-gate.com/products/dotnet-development/reflector/ to browse it, use what you learn there to fill $full_class_name.

Enjoy,

Ricardo.
jan dot zahradnik at data3s dot com 06-Jan-2014 09:17
PHP searches only GAC for .NET 2.0 runtime, so your DLL has to be targeted 2.0 - 3.5 framework.

Also it recognize only classes, not stucts, so you can't instantiate DateTime for example.
sandips (yardi) 29-Jun-2011 02:57
exercise to try different type of method signature and calling them in php.

VB.net Code
Public Class Class1
    Public Function SayHello(ByVal input As String) As String
        Return "Php input: " & input & "</BR>Dot net library said- 'Hello'"
    End Function
    Public Function ConcatArray(ByVal Values As Object()) As String
        Dim ret As String = String.Empty
        For Each sval As Object In Values
            ret = ret & sval.ToString & " "
        Next
        Return ret.Substring(1, ret.Length - 1)
    End Function
    Public Function ReturnObject(ByVal FirstName As String, ByVal LastName As String) As Name
        Dim obj As New Name
        obj.FirstName = FirstName
        obj.LastName = LastName
        Return obj
    End Function
'To explain Byref doesn't work with php
    Public Function CallByRef(ByRef value As String) As String
        value = "Value to ByRef parameter set in dot net."
        Return "ByRef CallByRef() method called."
    End Function
End Class

Public Class Name
    Public FirstName As String = String.Empty
    Public LastName As String = String.Empty
End Class

Php code to test .net library
<?php
  $class1 = new DOTNET("DotNetTest,"
              ."Version=1.0.0.0,"
                          ."Culture=neutral,"
                      ."PublicKeyToken=6675daefc27eafc4"
              ,"DotNetTest.Class1");
 echo $class1->SayHello("Hi PHP!!!!");
 echo "</P>";

 $parameter[0] = 12345;
 $parameter[1] = "MyString";
 $parameter[2] = false;
 $ret = $class1 -> ConcatArray($parameter);
 echo $ret;
 echo "</P>";

 $Obj = $class1 -> ReturnObject("Sandip","Shimpi");
 echo $Obj->FirstName." ".$Obj->LastName;

 echo "</P>";
 $myByRef = "";
 echo "Value of ByRef Variable before calling .net CallByRef() method: ".$myByRef;
 echo "</BR>";
 echo $class1 -> CallByRef($myByRef);
 echo "</BR>";
 echo "Now value of ByRef Variable: ".$myByRef;
 echo $myByRef;
?>
Anonymous 04-Jul-2010 05:17
As suggested before, you'll likely have to use a full assembly string including the assembly name, the assembly version (not the dll file version), the culture, and the public key token.  Otherwise, you'll get a 'file not found' catchable error.  To quickly find this on your own system to get the ball rolling, open C:\Windows\assembly in explorer (not in cmd as that shows a different view), scroll down the list until you find the assembly you want to work with, hover the mouse over it, and the tooltip shows the exact string to use (though processcorArchitecture if shown is optional).  You'll have to use .net utilities or other methods to automate collecting this info on other machines.

You'll also have to use the fully-qualified class name.  In other words, if you want to use the 'Form' class within 'System.Windows.Forms', you have to use the full class hierarchy 'System.Windows.Forms.Form'.  Otherwise you'll get an unhelpful 'Failed to instantiate .Net object' catchable error.

The following example shows the correct syntax to use the 'Form' class to pop up a blank form from php-cli, which can be used in leu of many Windows GUI PHP extensions out there.  Replace Version with your local version, and PublicKeyToken with your own local key token.

<?php

$full_assembly_string = 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a8425bc35256e463';
$full_class_name = 'System.Windows.Forms.Form';
$form = new DOTNET($full_assembly_string, $full_class_name);

// code to add buttons, menus, text, etc

$form->Show();

$form_event = '';
while($form_event !== 'close') {

  // handle form functions and events

  }
?>
murat at muratyaman dot co dot uk 11-Feb-2010 05:46
First, I hit the same mine:

"... Failed to instantiate .Net object [Unwrapped, QI for IDispatch] [0x80004002] No such interface supported ..."

In order to load the assembly and class in it successfully, I had to change my AssemblyInfo.cs file regarding the visibility of the types in it.

// some code above

// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(true)]

// some code below
m holmes at windowlogic dot com dot au 21-Sep-2009 09:31
For strongly-named NET assemblies that are registered in the GAC, you can just use the assembly name
e.g: $x = new DOTNET ("myAssembly", "myClass");

For strongly-named NET assemblies that aren't registered in the GAC, you need to use the full assembly string
e.g. $x = new DOTNET('myAssembly, Version=X.X.X.X, Culture=neutral, PublicKeyToken=ZZZZZZZZZZZZ', 'myClass');

You can't instantiate assemblies that haven't been strongly named.

"Strongly named" means that the assembly has a public key. To strongly name your own classes in Visual Studio, go to the Signing tab in the project properties and click the 'sign the assembly' box and choose a key file name.

To register an assembly in the GAC, there are various tools around to do that, but the easiest method is to drag-and-drop the compiled assembly into c:\windows\assembly using windows explorer (a shell extension is installed by default that handles registering dragged files).
kschroeder at mirageworks dot com 08-Apr-2009 11:55
In order to find out what the PublicKeyToken value is, open up Explorer and go to c:\windows\assembly.  In that directory you will see all of the registered assemblies along with their PublicKeyToken value.
sam at bitopia dot co dot uk 02-May-2008 08:54
If you want to load any other assembly apart from mscorlib, you'll need to include it like the following

$x = new DOTNET('The.Assembly.Name, Version=X.X.X.X, Culture=neutral, PublicKeyToken=ZZZZZZZZZZZZ', 'The.Class.Name');

Replace all relevant details.


dotnet class constructor

  • ? dotnet
  • variant ?
  • PHP Manual
  • dotnet
  • dotnet class constructor

dotnet::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

dotnet::__construct — dotnet class constructor

说明

public dotnet::__construct ( string $assembly_name , string $datatype_name , int $codepage = CP_ACP )

Constructs a new dotnet object.

参数

assembly_name
Specifies which assembly should be loaded.
datatype_name
Specifices which class in that assembly to instantiate.
codepage
Codepage to use for unicode string transformations; see the com class for more details on code pages.

User Contributed Notes

There are no user contributed notes for this page.


variant class

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

简介

The VARIANT is COM's equivalent of the PHP zval; it is a structure that can contain a value with a range of different possible types. The variant class provided by the COM extension allows you to have more control over the way that PHP passes values to and from COM.

类摘要

variant {
/* 方法 */
public __construct ( mixed $value = null , int $type = VT_EMPTY , int $codepage = CP_ACP )
}

variant examples

Example #1 variant example

<?php
$v = new variant(42);
print "The type is " . variant_get_type($v) . "<br/>";
print "The value is " . $v . "<br/>";
?>

Note:

When returning a value or fetching a variant property, the variant is converted to a PHP value only when there is a direct mapping between the types that would not result in a loss of information. In all other cases, the result is returned as an instance of the variant class. You can force PHP to convert or evaluate the variant as a PHP native type by using a casting operator explicitly, or implicitly casting to a string by printing it. You may use the wide range of variant functions to perform arithmetic operations on variants without forcing a conversion or risking a loss of data.

See also variant_get_type().

Table of Contents

  • variant::__construct — variant class constructor

User Contributed Notes

darren at dcook dot org 17-Jul-2007 05:59
If you are frustrated that print_r($obj) (where $obj is something returned from a call to a function on a COM object) does not return anything helpful, and that variant_get_type($obj) just returns a number, the function you are actually after is:
  com_print_typeinfo($obj);

It lists all functions, variables, their types in a human-readable (well, programmer-readable) format. Lovely!
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:50
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.


variant class constructor

  • ? variant
  • COMPersistHelper ?
  • PHP Manual
  • variant
  • variant class constructor

variant::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

variant::__construct — variant class constructor

说明

public variant::__construct ( mixed $value = null , int $type = VT_EMPTY , int $codepage = CP_ACP )

Constructs a new variant object.

参数

value
Initial value. If omitted, or set to null an VT_EMPTY object is created.
type
Specifies the content type of the variant object. Possible values are one of the VT_XXX 预定义常量. PHP can detect parameters passed by reference automatically; they do not even need to be passed as variant objects. Consult the MSDN library for additional information on the VARIANT type.
codepage
Specifies the codepage that is used to convert strings to unicode. See the parameter of the same name in the com class for more information.

User Contributed Notes

There are no user contributed notes for this page.


The COMPersistHelper class

(PHP 5, PHP 7, PHP 8)

简介

COMPersistHelper improves the interoperability of COM and PHP with regard to the php.ini directive open_basedir, and stream 资源(resource)s.

类摘要

final COMPersistHelper {
/* 方法 */
public __construct ( variant|null $variant = null )
public GetCurFileName ( ) : string|false
public GetMaxStreamSize ( ) : int
public InitNew ( ) : bool
public LoadFromFile ( string $filename , int $flags = 0 ) : bool
public LoadFromStream ( resource $stream ) : bool
public SaveToFile ( string|null $filename , bool $remember = true ) : bool
public SaveToStream ( resource $stream ) : bool
}

Table of Contents

  • COMPersistHelper::__construct — Construct a COMPersistHelper object
  • COMPersistHelper::GetCurFileName — Get current filename
  • COMPersistHelper::GetMaxStreamSize — Get maximum stream size
  • COMPersistHelper::InitNew — Initialize object to default state
  • COMPersistHelper::LoadFromFile — Load object from file
  • COMPersistHelper::LoadFromStream — Load object from stream
  • COMPersistHelper::SaveToFile — Save object to file
  • COMPersistHelper::SaveToStream — Save object to stream

User Contributed Notes

There are no user contributed notes for this page.


Construct a COMPersistHelper object

  • ? COMPersistHelper
  • COMPersistHelper::GetCurFileName ?
  • PHP Manual
  • COMPersistHelper
  • Construct a COMPersistHelper object

COMPersistHelper::__construct

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::__construct — Construct a COMPersistHelper object

说明

public COMPersistHelper::__construct ( variant|null $variant = null )

Constructs a persistence helper object, usually associated with a variant.

参数

variant
A COM object which implements IDispatch. To be able to successfully call any of COMPersistHelper's methods, the object has to implement IPersistFile, IPersistStream and/or IPersistStreamInit. Passing null as variant is only useful if the object is to be loaded from a stream by calling COMPersistHelper::LoadFromStream().

User Contributed Notes

There are no user contributed notes for this page.


Get current filename

  • ? COMPersistHelper::__construct
  • COMPersistHelper::GetMaxStreamSize ?
  • PHP Manual
  • COMPersistHelper
  • Get current filename

COMPersistHelper::GetCurFileName

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::GetCurFileName — Get current filename

说明

public COMPersistHelper::GetCurFileName ( ) : string|false

Retrieves the current name of the file associated with the object.

参数

此函数没有参数。

返回值

Returns the current name of the file associated with the object.

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::GetCurFile() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Get maximum stream size

  • ? COMPersistHelper::GetCurFileName
  • COMPersistHelper::InitNew ?
  • PHP Manual
  • COMPersistHelper
  • Get maximum stream size

COMPersistHelper::GetMaxStreamSize

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::GetMaxStreamSize — Get maximum stream size

说明

public COMPersistHelper::GetMaxStreamSize ( ) : int

Retrieves the size of the stream (in bytes) needed to save the object.

参数

此函数没有参数。

返回值

Returns the size of the stream (in bytes) needed to save the object.

错误／异常

A com_exception is thrown if the associated object does neither implement the COM interface IPersistStream nor IPersistStreamInit, or when calling the IPersistStream::GetSizeMax() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Initialize object to default state

  • ? COMPersistHelper::GetMaxStreamSize
  • COMPersistHelper::LoadFromFile ?
  • PHP Manual
  • COMPersistHelper
  • Initialize object to default state

COMPersistHelper::InitNew

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::InitNew — Initialize object to default state

说明

public COMPersistHelper::InitNew ( ) : bool

Initializes an object to a default state.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistStreamInit, or when calling its IPersistStreamInit::Init() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Load object from file

  • ? COMPersistHelper::InitNew
  • COMPersistHelper::LoadFromStream ?
  • PHP Manual
  • COMPersistHelper
  • Load object from file

COMPersistHelper::LoadFromFile

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::LoadFromFile — Load object from file

说明

public COMPersistHelper::LoadFromFile ( string $filename , int $flags = 0 ) : bool

Opens the specified file and initializes an object from the file contents.

参数

filename
The name of the file from which to load the object.
flags
The access mode to be used when opening the file. Possible values are taken from the » STGM enumeration. The method can treat this value as a suggestion, adding more restrictive permissions if necessary. If flags is 0, the implementation is supposed to open the file using whatever default permissions are used when a user opens the file.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Load() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Load object from stream

  • ? COMPersistHelper::LoadFromFile
  • COMPersistHelper::SaveToFile ?
  • PHP Manual
  • COMPersistHelper
  • Load object from stream

COMPersistHelper::LoadFromStream

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::LoadFromStream — Load object from stream

说明

public COMPersistHelper::LoadFromStream ( resource $stream ) : bool

Initializes an object from the stream where it was saved previously.

参数

stream
The stream 资源(resource) from which to load the object.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistStream, or when calling the IPersistStream::Load() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Save object to file

  • ? COMPersistHelper::LoadFromStream
  • COMPersistHelper::SaveToStream ?
  • PHP Manual
  • COMPersistHelper
  • Save object to file

COMPersistHelper::SaveToFile

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::SaveToFile — Save object to file

说明

public COMPersistHelper::SaveToFile ( string|null $filename , bool $remember = true ) : bool

Saves a copy of the object to the specified file.

参数

filename
The name of the file to which to save the object.
remember
Indicates whether the filename parameter is to be used as the current working file. If true, filename becomes the current file and the object is supposed to clear its dirty flag after the save. If false, this save operation is a "Save A Copy As ..." operation. In this case, the current file is unchanged and the object is not supposed to clear its dirty flag.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Save() method failed.

范例

Example #1 Basic COMPersistHelper::saveToFile() Usage

<?php
$word = new COM('Word.Application');
$doc = $word->Documents->Add();
$ph = new COMPersistHelper($doc);
$ph->SaveToFile('C:\\Users\\cmb\\Documents\\my.docx');
$word->Quit();
?>

User Contributed Notes

There are no user contributed notes for this page.


Save object to stream

  • ? COMPersistHelper::SaveToFile
  • com_exception ?
  • PHP Manual
  • COMPersistHelper
  • Save object to stream

COMPersistHelper::SaveToStream

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::SaveToStream — Save object to stream

说明

public COMPersistHelper::SaveToStream ( resource $stream ) : bool

Saves an object to the specified stream.

参数

stream
The stream 资源(resource) to which to save the object.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does neither implement the COM interface IPersistStream nor IPersistStreamInit, or when calling the IPersistStream::Save() method failed.

User Contributed Notes

There are no user contributed notes for this page.


The com_exception class

(PHP 5, PHP 7, PHP 8)

简介

类摘要

com_exception extends Exception implements Throwable {
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

There are no user contributed notes for this page.


COM 函数

参见

For further information on COM read the » COM specification. You might find some additional useful information in our FAQ for PHP 和 COM. If you're thinking of using MS Office applications on the server side, you should read the information here: » Considerations for Server-Side Automation of Office.

Table of Contents

  • com_create_guid — Generate a globally unique identifier (GUID)
  • com_event_sink — Connect events from a COM object to a PHP object
  • com_get_active_object — Returns a handle to an already running instance of a COM object
  • com_load_typelib — 装载一个 Typelib
  • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
  • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
  • variant_abs — Returns the absolute value of a variant
  • variant_add — "Adds" two variant values together and returns the result
  • variant_and — Performs a bitwise AND operation between two variants
  • variant_cast — Convert a variant into a new variant object of another type
  • variant_cat — Concatenates two variant values together and returns the result
  • variant_cmp — Compares two variants
  • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
  • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
  • variant_div — Returns the result from dividing two variants
  • variant_eqv — Performs a bitwise equivalence on two variants
  • variant_fix — Returns the integer portion of a variant
  • variant_get_type — Returns the type of a variant object
  • variant_idiv — Converts variants to integers and then returns the result from dividing them
  • variant_imp — Performs a bitwise implication on two variants
  • variant_int — Returns the integer portion of a variant
  • variant_mod — Divides two variants and returns only the remainder
  • variant_mul — Multiplies the values of the two variants
  • variant_neg — Performs logical negation on a variant
  • variant_not — Performs bitwise not negation on a variant
  • variant_or — Performs a logical disjunction on two variants
  • variant_pow — Returns the result of performing the power function with two variants
  • variant_round — Rounds a variant to the specified number of decimal places
  • variant_set_type — Convert a variant into another type "in-place"
  • variant_set — Assigns a new value for a variant object
  • variant_sub — Subtracts the value of the right variant from the left variant value
  • variant_xor — Performs a logical exclusion on two variants

User Contributed Notes

Sorin Negulescu 05-Nov-2016 10:49
I have spent a lot of hours trying to make word.application work on a Windows Server using Apache as a service.
The application was working if Apache was started from command line (not as a service).

In the hope that this will help others not to lose hours of trying to solve this problem here is what I found out:

- In php.ini make sure you have the following key under the [COM_DOT_NET]: extension=php_com_dotnet.dll
- Apache shall run under a normal user account (not SYSTEM account). Run services.msc and fill-in the info of the user under the Apache service's Properties tab.
- Make sure you are able to start MS Word normally under that user account and dismiss all the dialogs that may appear (license, your info with initials, etc.). Start Word once again and make sure no dialogs appear.
- Launch dcomcnfg.exe->Console Root->Component Services->Computers->My Computer->DCOM Config->Microsoft Office Word 97 - 2003->Right Click(Properties)->Identity Tab and fill in the same user account information as for Apache service.
- If you cannot find the Microsoft Office Word 97 - 2003, make sure you are launching the correct DCOM Config (64 bit vs 32 bit) depending on what version of Office you have installed. To launch the 32 bit version run: mmc comexp.msc /32

Before following the steps described above, the winword.exe app appears in task manager but, if you look at the memory consumption you can notice two things:
- it increases slowly
- it stops usually at about 7-8 MB.

Keywords: COM, word.application, Apache, service, winword, timeout, no error
larrywalker at at chelseagroton dot com 02-Sep-2008 08:53
To run a php script in a background process and pass it you var use

<?php

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("c:\\xampp\\php\\php.exe

c:\\xampp\\Not_on_Web\\ftptestback.php --user=$username", 7, false);

?>

Works for me.
monica at digitaldesignservices dot com 27-Dec-2007 02:41
Working with Word 2003 COM object.

Have you been trying to work with the Word.Application COM and the Word Document would crash and the PHP script would hang?

Turns out that there is an issue within the Office COM object that doesn't let the web application (IIS, Apache) scripting engine release the object after instancing the COM.  The Service Pack 3 office update claims to remedy this.  Will test and post findings.
tomfmason at nospam-gmail dot com 08-Oct-2007 07:26
To get the cpu load percentage you can do something like this.

<?php
$wmi = new COM('winmgmts://');
$processor = $wmi->ExecQuery("SELECT * FROM Win32_Processor");
foreach($processor as $obj){
    $cpu_load_time = $obj->LoadPercentage;
}
echo $cpu_load_time;
?>

reference http://msdn2.microsoft.com/en-us/library/aa394373.aspx

To list current apache instances

<?php
$wmi = new COM('winmgmts://');
$processes = $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'httpd.exe'");
foreach($processes as $process){
    echo $process->CommandLine . "<br />";
    echo $process->ProcessId . "<br />";
}
?>

reference http://msdn2.microsoft.com/en-us/library/aa394372.aspx

To run a php script in a background process

<?php
$dir = "C:\\path\\to\\dir";
$php_path = "C:\\path\\to\\php.exe";
$file = "somescript.php";
//send time current timestamp
$cmd_options = "-t " . time();
$wscript = new COM('WScript.Shell');
$wscript->Run("cmd /K CD $php_path $dir\\$file  &  ", 0, false);
?>

Enjoy

Tom
naveed at php dot net 10-Mar-2007 05:24
Here is a spell check implementation that displays the suggestion list for each misspelled word.

<?php
function SpellCheck($input)
{
    $word=new COM("word.application") or die("Cannot create Word object");
    $word->Visible=false;
    $word->WindowState=2;
    $word->DisplayAlerts=false;
    $doc=$word->Documents->Add();
    $doc->Content=$input;
    $doc->CheckSpelling();
    $result= $doc->SpellingErrors->Count;
    if($result!=0)
    {
        echo "Input text contains misspelled words.\n\n";
        for($i=1; $i <= $result; $i++)
        {
            echo "Original Word: " .$doc->SpellingErrors[$i]->Text."\n";
            $list=$doc->SpellingErrors[$i]->GetSpellingSuggestions();
            echo "Suggestions: ";
            for($j=1; $j <= $list->Count; $j++)
            {
                $correct=$list->Item($j);
                echo $correct->Name.",";
            }
            echo "\n\n";
        }
    }
    else
    {
        echo "No spelling mistakes found.";
    }
    $word->ActiveDocument->Close(false);
    $word->Quit();
    $word->Release();
    $word=null;
}

$str="Hellu world. There is a spellling error in this sentence.";
SpellCheck($str);
?>
Francois-R dot Boyer at PolyMtl dot ca 13-Feb-2007 08:32
I had the problem when trying to call Access VBA scripts from PHP; the call was working but Access would never quit.  The problem was that the Apache server is running as SYSTEM, and not a user we normally use to run Office.  And as the first time a user runs Office, it asked the SYSTEM user to enter its name and initials! ;-)

To correct this problem: Stop Apache, go to Services, Apache, Properties, "Log On" tab, and check "Allow service to interact with desktop.  Restart Apache, then open your office application, in a page loaded by the Apache server, with a small PHP code like this, :

<?php
$app = new COM("Access.Application"); // or Word.Application or Excel.Application ...
$app->Visible = true; // so that we see the window on screen
?>

Put the name you want and quit the application.  Now your Office application should terminate correctly the next time you load it with a COM object in PHP.  You can stop Apache uncheck the "Allow service to interact with desktop", and restart Apache if you like.  I don't even require a Quit or anything to be sent to Access, it quits automatically when PHP terminates.

And for those who wish to know how I'm calling Access VBA scripts, instead of using ODBC or any other way to send SQL requests, which does not seem to work to call VBA scripts, I open the database as a COM object and it works fine:

<?php
$db_com = new COM("pathname of the file.mdb");
$result = $db_com->Application->Run("function_name", 'param1', 'param2', '...');
?>
03-Oct-2006 04:11
If someone want to get a COM object out of a DCOM object can do something like that:

<?php
  $dcom_obj = new COM('dacom.object','remotehost') or die("Unable to get DCOM object!");
  $com_obj = new Variant(NULL);
  $dcom_obj->Get_Module($com_obj); //user function which returns a custom IDispatch (casted as variant*)
?>

Hopefully this will help someone, because it took me quite long to figure this out.
kiotech at hotmail dot com 18-Jul-2006 06:35
For use parameters with PHP this is a Code Example

<?php
$ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport("//report1.rpt", 1);

      $z= $creport->ParameterFields(1)->SetCurrentValue("Mango");
      $z= $creport->ParameterFields(2)->SetCurrentValue(5000);

  $creport->ExportOptions->DiskFileName="reportin.pdf";
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=31;
  $creport->Export(false);

$len = filesize("reportin.pdf");
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=reportin.pdf");
readfile("reportin.pdf");
?>
a dot kulikov at pool4tool dot com 13-Mar-2006 09:36
In case you are wondering how to group rows or columns in the freshly created EXCEL files, then this may help you

<?php
   /***
    * Grouping Rows optically in Excel Using a COM Object
    *
    * That was not easy, I have spent several hours of trial and error to get
    * this thing to work!!!
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @since  13.03.2006
    *
    * @see    Open Excel, Hit Alt+F11, thne Hit F2 -- this is your COM bible
    ***/

   //starting excel
   $excel = new COM("excel.application") or die("Unable to instanciate excel");
   print "Loaded excel, version {$excel->Version}\n";

   //bring it to front
   #$excel->Visible = 1;//NOT

   //dont want alerts ... run silent
   $excel->DisplayAlerts = 0;

   //create a new workbook
   $wkb = $excel->Workbooks->Add();

   //select the default sheet
   $sheet=$wkb->Worksheets(1);

   //make it the active sheet
   $sheet->activate;

   //fill it with some bogus data
   for($row=1;$row<=7;$row++){
       for ($col=1;$col<=5;$col++){

          $sheet->activate;
          $cell=$sheet->Cells($row,$col);
          $cell->Activate;
          $cell->value = 'pool4tool 4eva ' . $row . ' ' . $col . ' ak';
       }//end of colcount for loop
   }

   ///////////
   // Select Rows 2 to 5
   $r = $sheet->Range("2:5")->Rows;

   // group them baby, yeah
   $r->Cells->Group;

   // save the new file
   $strPath = 'tfile.xls';
   if (file_exists($strPath)) {unlink($strPath);}
   $wkb->SaveAs($strPath);

   //close the book
   $wkb->Close(false);
   $excel->Workbooks->Close();

   //free up the RAM
   unset($sheet);

   //closing excel
   $excel->Quit();

   //free the object
   $excel = null;
?>
Pedro Heliodoro 05-Mar-2006 02:38
Using the Windows Media Player OCX and the latest snap of PHP 5.1 i was able to eject a CD-ROM drive

<?php
//create an instance of Windows Media Player
$mp = new COM("WMPlayer.OCX");
//ejects the first cd-rom on the drive list
$mp->cdromcollection->item(0)->eject();

?>
allan666 at gmail dot com 29-Sep-2005 03:37
If you are using a COM object that opens windows or dialogs (like Office applications), those windows or dialogs will not appear and will stay invisible even if you use codes like

$word->visible = true;

To solve this problem, go to the web service properties (Administrative Tools) and click (in the Logon TAB) "Allow the Service to Iterate with desktop".

This explain lots of problems to close applications. When you try to close, the dialos asking to save the file must appear, but only in the option to iterate with desktop is on.

Hope it helps.
bruce at yourweb dot com dot au 23-Apr-2005 05:47
Simple convert xls to csv
<?php
// starting excel
$excel = new COM("excel.application") or die("Unable to instanciate excel");
print "Loaded excel, version {$excel->Version}\n";

//bring it to front
#$excel->Visible = 1;//NOT
//dont want alerts ... run silent
$excel->DisplayAlerts = 0;

//open  document
$excel->Workbooks->Open("C:\\mydir\\myfile.xls");
//XlFileFormat.xlcsv file format is 6
//saveas command (file,format ......)
$excel->Workbooks[1]->SaveAs("c:\\mydir\\myfile.csv",6);

//closing excel
$excel->Quit();

//free the object
$excel->Release();
$excel = null;
?>
michael at example dot com 23-Feb-2005 12:42
After alot of trouble with IIS 6/Windows 2003 and PHP 5.0.2 I figured out how to use Imagemagick COM+/OLE interface. Seems you have to recreate the COM object after each convert() otherwise it will sometimes fail with very strange errors, since the PHP COM interface is not as stable as the old ASP one apparently is.
06-Jan-2005 09:11
if you want to add a new hyperlink with excel :

<?php
$cell=$sheet->Range('O'.$j);
$cell->Hyperlinks->Add($cell ,'here_your_file');
?>

I write this note because is very difficult to find
the good method to do that .

Merci beaucoup
sorin dot andrei at mymail dot ro 25-Sep-2004 02:24
[Editor's Note:
Serializing the object, storing it and then (on the next page) unserializing it WILL work.
End Note]

the big problem for PHP is it can't save in session an COM object

an samples code is here. This works just first time, then give the error:
Call to undefined method com::Refresh() on line  $mMap->Refresh();
the reson is he can't save the object $mMap in session

<?php
    session_start();
      if (isset($_SESSION['map'])) {
            $mMap = $_SESSION['map'];
        }
        else
        {
        $ArcIMSConnector = new COM ("aims.ArcIMSConnector")  or die("can not create AIMS message object");
            echo "Loaded ArcIMSConnector, <br>";
            $ArcIMSConnector->ServerName = "map.sdsu.edu";
            $ArcIMSConnector->ServerPort = 5300;

            $mMap = new COM ("aims.Map")  or die("can not create aims.Map message object");
            echo "Loaded aims.Map, <br>";
            print "AIMS-ServerName= $ArcIMSConnector->ServerName <br>";

            $resultInit= $mMap->InitMap($ArcIMSConnector,"Worldgeography");

            $mMap->Width    = 400;            //                                'Width of the map in pixels
            $mMap->Height   = 300;            //                                'Height of the map in pixels
            $mMap->BackColor = 15130848;
            $_SESSION['map'] = $mMap;
        }

    $resultRefresh = $mMap->Refresh();                                //Refresh the map
    $urlImage      = $mMap->GetImageAsUrl();
    print "<br>urlImage=$urlImage<br>";

    print "<br><IMG SRC='$urlImage'>";

/*
    $ArcIMSConnector->Release();
    $ArcIMSConnector = null;

    $mMap->Release();
    $mMap = null;
*/

?>
ferozzahid [at] usa [dot] com 24-Aug-2004 12:06
To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it.

As an example, calling a function that retrieves the name of a person will look like:

<?php
$Name = new VARIANT;

$comobj = new COM("MyCOMOBj.Component") or die("Couldn't create the COM Component");

if(!$comobj->GetName($Name)) {
    echo("Could not retrieve name");
}
else {
    echo("The name retrieved is : " . $Name->value);
}
?>

$Name->type will contain the type of the value stored in the VARIANT e.g. VT_BSTR.

Note For PHP 5:

Insted of '$Name->value', we can use only '$Name' for getting the value stored in the VARIANT. To get the type of the value stored in the VARIANT, use 'variant_get_type($Name)'.

Feroz Zahid
Shawn Coppock 11-Aug-2004 01:15
For those of us that are not experts with object models, if you have Microsoft Excel or Microsoft Word available, go into the Visual Basic Editor (Alt+F11). Now you can open the object browser window (F2) and see what you find.

If you select "Word" in the object browser, then the classes and members of that class are displayed below. For example, if you click on "Selection" in the classes column, and then "Font" in the members column, you will then see "Property Font As Font Member of Word.Selection" displayed at the bottom. Click on the "Font" link there.

Click on Word "Selection" again in the classes column, and then "PageSetup" in the members column, you will then see "Property PageSetup As PageSetup Member of word.Selection" displayed at the bottom. Click on the "PageSetup" link there.

Using the above examples, you can now formulate your Word Document from php. Here is a simple example that creates a 1 & 1/2" space for text based on the margin settings & with dark red text and an 8pt Helvetica font face:

<?php
$content = "Insert Sample Text Here\n\nThis starts a new paragraph line.";
$word= new COM("word.application") or die("Unable to create Word document");
print "Loaded Word, version {$word->Version}\n";
$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '3"';
$word->Selection->PageSetup->RightMargin = '4"';
$word->Selection->Font->Name = 'Helvetica';
$word->Selection->Font->Size = 8;
$word->Selection->Font->ColorIndex= 13; //wdDarkRed = 13
$word->Selection->TypeText("$content");
$word->Documents[1]->SaveAs("some_tst.doc");
$word->quit();
echo "done";
?>

This example (and others) worked for me with Microsoft Word 10.0 Object Library (MS Word 2002), Apache & PHP on Windows XP. Experimenting using the Visual Basic editor will yield some amazing documents from PHP as it will help you see the relationships of the objects used and give you an idea as to how to construct your code. But be prepared for an occaisional PHP.exe crash if your code is way off base.

Hope this helps!
angelo [at] mandato <dot> com 18-May-2004 04:30
Useful PHP functions I created (similar to other standard PHP database functions) for working with an ADO datasource:
<?php
    // ado.inc.php

    $ADO_NUM = 1;
    $ADO_ASSOC = 2;
    $ADO_BOTH = 3;

    function ado_connect( $dsn )
    {
        $link = new COM("ADODB.Connection");
        $link->Open($dsn);
        return $link;
    }

    function ado_close( $link )
    {
        $link->Close();
    }

    function ado_num_fields( $rs )
    {
        return $rs->Fields->Count;
    }

    function ado_error($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Number;
    }

    function ado_errormsg($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Description;
    }

    function ado_fetch_array( $rs, $result_type,  $row_number = -1 )
    {
        global $ADO_NUM, $ADO_ASSOC, $ADO_BOTH;
        if( $row_number > -1 ) // Defined in adoint.h - adBookmarkFirst    = 1
            $rs->Move( $row_number, 1 );

        if( $rs->EOF )
            return false;

        $ToReturn = array();
        for( $x = 0; $x < ado_num_fields($rs); $x++ )
        {
            if( $result_type == $ADO_NUM || $result_type == $ADO_BOTH )
                $ToReturn[ $x ] = $rs->Fields[$x]->Value;
            if( $result_type == $ADO_ASSOC || $result_type == $ADO_BOTH )
                $ToReturn[ $rs->Fields[$x]->Name ] = $rs->Fields[$x]->Value;
        }
        $rs->MoveNext();
        return $ToReturn;
    }

    function ado_num_rows( $rs )
    {
        return $rs->RecordCount;
    }

    function ado_free_result( $rs )
    {
        $rs->Close();
    }

    function ado_query( $link, $query )
    {
        return $link->Execute($query);
    }

    function ado_fetch_assoc( $rs,  $row_number = -1 )
    {
        global $ADO_ASSOC;
        return  ado_fetch_array( $rs, $ADO_ASSOC, $row_number);
    }

    function ado_fetch_row( $rs,  $row_number = -1 )
    {
        global $ADO_NUM;
        return ado_fetch_array( $rs, $ADO_NUM, $row_number);
    }

    // Extra functions:
    function ado_field_len( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Precision;
    }

    function ado_field_name( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Name;
    }

    function ado_field_scale( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->NumericScale;
    }

    function ado_field_type( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Type;
    }

?>

The aod version was a typo.
mark dickens at mindspring dot com 29-Feb-2004 08:03
Just a note to those wanting to use COM to interface to printers under Windows 2000/XP.  If it doesn't work or seems to hang, try changing the logon identity under which the Apache (assuming you're using Apache) service is running from the System account to another account.  By default most services will install to run under the System account and although the System account has total authority on the computer it is running on, it has no authority outside of that realm as I understand it.  Apparently accessing printers is considered "outside the realm".  I used this technique to interface a Dymo thermal label printer to my server and it works now.
alanraycom at el hogar dot net com 03-Dec-2003 03:50
XSLT transformations using MSXML can be done with this code

<?php
function xsltransform1($xslpath,$xmlstring)
 {
  $xml= new COM("Microsoft.XMLDOM");
  $xml->async=false;
  // $xmlstring is an xml string
  $xml->load($xmlstring);
  $xsl = new COM("Microsoft.XMLDOM");
  $xsl->async=false;
  // $xslpath is path to an xsl file
  $xsl->load($xslpath);
  $response=$xml->transformNode($xsl);
  unset($xml);
  unset($xsl);
  return $response;
 }
?>

enjoy
Alan Young
chris at hitcatcher dot com 01-Dec-2003 04:19
Many COM objects don't do well when passing long (win32) filenames as function parameters.  You can get the 8.3 name of the folder or file on *most* (some win platforms don't support it, and it can be toggled off in the registry for performance reasons) servers using the following:

<?php
//create FSO instance
$exFSO = new COM("Scripting.FileSystemObject") or die ("Could not create Scripting.FileSystemObject");

//set vars
$myDir = "C:\\Program Files\\";
$myFile = "a long file name.txt";

//get folder & file objects
$exDir = $exFSO->GetFolder($myDir);
$exFile = $exFSO->GetFile($myDir . $myFile);
echo $exDir->ShortPath;
echo $exFile->ShortPath;
?>
23-Nov-2003 09:57
Here is an example of reading the custom properties like Author, Keywords, etc. which are stored in MS Office and other Windows files. You must install and register dsofile as described at http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224351. The .frm file in that distribution lists most of the available properties.

<?php
// the file you wish to access
$fn = '/docs/MFA.xls';

$oFilePropReader = new COM('DSOleFile.PropertyReader');
$props = $oFilePropReader->GetDocumentProperties($fn);

// one syntax
$au = com_get($props, 'Author');
print "au: $au \n";

//another syntax
$str = 'LastEditedBy';
$lsb = $props->$str;
var_dump($lsb);

// set a property if you wish
if (!$props->IsReadOnly()) {
  $props->Subject = 'tlc';
}
?>
brana 17-Nov-2003 05:17
How to send email via MAPI (works with Windows NT4, apache launched as a service)

<?php
#New MAPI session...
$session = new COM("MAPI.Session");

#Login
$strProfileInfo = "exchange_server" . chr(10) . "exchange_user";
$session->Logon("", "", 0, 1, 0, 1, $strProfileInfo);

# New message...
$msg = $session->Outbox->Messages->Add();
$msg->Subject = "Subject";
$msg->Text = "body";

#set recipients...
$rcpts = $msg->Recipients;
$rcpts->AddMultiple("toto@toto.com", 1);   #To...
$rcpts->AddMultiple("titi@titi.com", 2);   #Cc...
$rcpts->AddMultiple("tutu@tutu.com", 3);   #Bcc...

# Resolve senders
$rcpts->Resolve();

#Send message
$msg->Send();

#Logoff
$session->Logoff();

#Cleanup
if($msg!=null) {
    $msg->Release();
    $msg = null;
}
if($session!=null) {
    $session->Release();
    $session = null;
}
?>

ps : NT account launching the service and exchange user must match !
php at dictim dot com 06-Sep-2003 01:17
This took me days to work out how to do so I gotta share it:

How to get the word count from a MS Word Document:

<?php
#Instantiate the Word component.

$word = new COM("word.application") or die("Unable to instantiate Word");

$word->Visible = 1;

$word->Documents->Open("c:/anydocument.doc");
$temp = $word->Dialogs->Item(228);
$temp->Execute();
$numwords = $temp->Words();

echo $numwords;

$word->Quit();
?>

Note that this is the only way to get the word count accurately:
$word->ActiveDocument->Words->Count;
Will see all carriage returns and punctuation as words so is wildy innaccurate.
tomas dot pacl at atlas dot cz 16-Jun-2003 06:07
Passing parameters by reference in PHP 4.3.2 (and in a future releases of PHP )

In PHP 4.3.2 allow_call_time_pass_reference option is set to "Off" by default and future versions may not support this option any longer.
Some COM functions has by-reference parameters. VARIANT object must be used to call this functions, but it would be passed without an '&' before variable name.

Example:

<?php
$myStringVariant = new VARIANT("over-write me", VT_BSTR);

/* works */
$result = $comobj->DoSomethingTo($myStringVariant );

/* works only with allow_call_time_pass_reference option set to "On" and may not work in a future release of PHP */
$result = $comobj->DoSomethingTo(&$myStringVariant );

/* The value in the variant can be retrieved by: */
$theActualValue = $myStringVariant->value;
?>
php at racinghippo dot co dot uk 22-Mar-2003 05:47
PASSING/RETURNING PARAMETERS BY REFERENCE
=========================================

Some COM functions not only return values through the return value, but also act upon a variable passed to it as a parameter *By Reference*:

RetVal = DoSomethingTo (myVariable)

Simply sticking an '&' in front of myVariable doesn't work - you need to pass it a variant of the correct type, as follows:

  $myStringVariant = new VARIANT("over-write me", VT_BSTR);
  $result = $comobj->DoSomethingTo( &$myStringVariant );

The value in the variant can then be retrieved by:

  $theActualValue = $myStringVariant->value;

Other types of variant can be created as your needs demand - see the preceding section on the VARIANT type.
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:51
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.
pchason at juno dot com 11-Dec-2002 11:23
Searched for days on how to set up a multi-column html output grid that didn't use an array when creating an ADODB connection. Couldn't find one so I figured it out myself. Pretty simple. Wish I would have tried it myself sooner. Commented code with database connection is below...

<html>
<body>
<table>
<?php
//create the database connection
$conn = new COM("ADODB.Connection");
$dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
$conn->Open($dsn);
//pull the data through SQL string
$rs = $conn->Execute("select clients from web");
$clients = $rs->Fields(1);
//start the multicolumn data output
$i = 0;
$columns = 5;
while (!$rs->EOF){
//if $i equals 0, start a row
if($i == 0){
echo "<tr>";
}
//then start writing the cells in the row, increase $i by one, and move to the next record
echo "<td>" . $clients->value . "</td>";
$i++;
$rs->movenext();
//once $i increments to equal $columns, end the row,
//and start the process over by setting $i to 0
if($i == $columns || $rs->EOF) {
echo "</tr>";
$i = 0;
    }
}
//end multicolumn data output

//close the ADO connections and release resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null; ?>
</table>
</body>
</html>
tedknightusa at hotmail dot com 26-Sep-2002 09:29
A Notes example:

<?php
$session = new COM "Lotus.NotesSession" );
$session->Initialize($password);

$someDB = "C:\Lotus\Notes\Data\somedb.nsf";
$db = $session->GetDatabase("", $someDB) or die("Cannot get someDB.nsf");
$view = $db->GetView("some_view") or die("Some View not found");

$doc = $view->GetFirstDocument() or die("Unable to get Initial Some Document");

// loop through
while($doc){
  $col_vals = $doc->ColumnValues();
  echo $col_vals[0];
  $doc = $view->GetNextDocument($doc);
}
?>
dwt at myrealbox dot com 27-Aug-2002 03:31
When first writing applications instancing COM objects I always faced the problem of the instanced program not terminating correctly although everything else worked fine. In fact the process had to be killed manually by using the task manager. When experimenting a bit I was able to isolate the cause for this peculiar behaviour to be illustrated by the sample code below:

<?php

//Accessing arrays by retrieving elements via function ArrayName(Index) works, but certainly is neither efficient nor good style
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$book=$excel->Workbooks(1);
$sheet=$book->Worksheets(1);

$sheet->Name="Debug-Test";
$book->saveas("C:\\debug.xls");

$book->Close(false);
unset($sheet);
unset($book);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

//Accessing arrays as usual (using the [] operator) works, buts leads to the application not being able to terminate by itself
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$excel->Workbooks[1]->Worksheets[1]->Name="Debug-Test";
$excel->Workbooks[1]->saveas("C:\\debug.xls");

$excel->Workbooks[1]->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

?>

The sample code performs the same action twice and each time the file is properly created. Yet for some mysterious reason the instanced excel process won't terminate once you've accessed an array the way most programmers (especially those who do a lot of oop in c++) do! Therefore until the PHP developers become aware of this problem we'll have to use the inefficient coding style illustrated in the first example.
madon at cma-it dot com 07-Mar-2002 12:59
I thought this excel chart example could be useful.

Note the use of Excel.application vs Excel.sheet.

<pre>
<?php
    print "Hi";
#Instantiate the spreadsheet component.
#    $ex = new COM("Excel.sheet") or Die ("Did not connect");
$exapp = new COM("Excel.application") or Die ("Did not connect");

#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";

$wkb=$exapp->Workbooks->add();
#$wkb = $ex->Application->ActiveWorkbook or Die ("Did not open workbook");
print "we opened workbook<BR>";

$ex->Application->Visible = 1; #Make Excel visible.
print "we made excell visible<BR>";

$sheets = $wkb->Worksheets(1); #Select the sheet
print "selected a sheet<BR>";
$sheets->activate; #Activate it
print "activated sheet<BR>";

#This is a new sheet
$sheets2 = $wkb->Worksheets->add(); #Add a sheet
print "added a new sheet<BR>";
$sheets2->activate; #Activate it
print "activated sheet<BR>";

$sheets2->name="Report Second page";

$sheets->name="Report First page";
print "We set a name to the sheet: $sheets->name<BR>";

# fills a columns
$maxi=20;
for ($i=1;$i<$maxi;$i++) {
    $cell = $sheets->Cells($i,5) ; #Select the cell (Row Column number)
    $cell->activate; #Activate the cell
    $cell->value = $i*$i; #Change it to 15000
}

$ch = $sheets->chartobjects->add(50, 40, 400, 100); # make a chartobject

$chartje = $ch->chart; # place a chart in the chart object
$chartje->activate; #activate chartobject
$chartje->ChartType=63;
$selected = $sheets->range("E1:E$maxi"); # set the data the chart uses
$chartje->setsourcedata($selected); # set the data the chart uses
print "set the data the chart uses <BR>";

$file_name="D:/apache/Apache/htdocs/alm/tmp/final14.xls";
if (file_exists($file_name)) {unlink($file_name);}
#$ex->Application->ActiveWorkbook->SaveAs($file_name); # saves sheet as final.xls
$wkb->SaveAs($file_name); # saves sheet as final.xls
print "saved<BR>";

#$ex->Application->ActiveWorkbook->Close("False");
$exapp->Quit();
unset($exapp);
?>

</pre>

Alex Madon


Generate a globally unique identifier (GUID)

  • ? COM 函数
  • com_event_sink ?
  • PHP Manual
  • COM 函数
  • Generate a globally unique identifier (GUID)

com_create_guid

(PHP 5, PHP 7, PHP 8)

com_create_guid — Generate a globally unique identifier (GUID)

说明

com_create_guid ( ) : string|false

Generates a Globally Unique Identifier (GUID).

A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

返回值

Returns the GUID as a string, 或者在失败时返回 false.

参见

  • uuid_create() in the PECL uuid extension

User Contributed Notes

internmail (at the google mail).com 22-Jan-2020 02:26
function create_guid() { // Create GUID (Globally Unique Identifier)
        $guid = '';
        $namespace = rand(11111, 99999);
        $uid = uniqid('', true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
        $guid = substr($hash,  0,  8) . '-' .
                substr($hash,  8,  4) . '-' .
                substr($hash, 12,  4) . '-' .
                substr($hash, 16,  4) . '-' .
                substr($hash, 20, 12);
        return $guid;
    }
rogervila dot es 10-Sep-2019 02:16
I implemented a com_create_guid implementation for systems that do not support it as a Composer package in order to keep it separated from my applications

https://github.com/rogervila/com_create_guid
Dave Pearson (dave at pds-uk dot com) 14-Apr-2016 10:07
Here's my final version of a GUIDv4 function (based on others work here) that should work on all platforms and gracefully fallback to less cryptographically secure version if others are not supported...

<?php
/**
 * Returns a GUIDv4 string
 *
 * Uses the best cryptographically secure method
 * for all supported pltforms with fallback to an older,
 * less secure version.
 *
 * @param bool $trim
 * @return string
 */
function GUIDv4 ($trim = true)
{
    // Windows
    if (function_exists('com_create_guid') === true) {
        if ($trim === true)
            return trim(com_create_guid(), '{}');
        else
            return com_create_guid();
    }

    // OSX/Linux
    if (function_exists('openssl_random_pseudo_bytes') === true) {
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    // Fallback (PHP 4.2+)
    mt_srand((double)microtime() * 10000);
    $charid = strtolower(md5(uniqid(rand(), true)));
    $hyphen = chr(45);                  // "-"
    $lbrace = $trim ? "" : chr(123);    // "{"
    $rbrace = $trim ? "" : chr(125);    // "}"
    $guidv4 = $lbrace.
              substr($charid,  0,  8).$hyphen.
              substr($charid,  8,  4).$hyphen.
              substr($charid, 12,  4).$hyphen.
              substr($charid, 16,  4).$hyphen.
              substr($charid, 20, 12).
              $rbrace;
    return $guidv4;
}
?>
indrora 08-Nov-2015 07:09
If you're going to generate random UUIDs, at least make them conform:

* The uppermost byte of the third stanza must be 4
* the uppermost byte of the fourth stanza may be any of (8 9 a b)

see also: The wikipedia page for UUIDs: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
pavel.volyntsev(at)gmail 27-Aug-2015 12:37
Use more cryptographically strong algorithm to generate pseudo-random bytes and format it as GUID v4 string

function guidv4()
{
    if (function_exists('com_create_guid') === true)
        return trim(com_create_guid(), '{}');

    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
Alix Axel 16-Aug-2010 03:59
The phunction PHP framework (http://sourceforge.net/projects/phunction/) uses the following function to generate valid version 4 UUIDs:

<?php

function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

?>

The output generated by the sprintf() and mt_rand() calls is identical to com_create_guid() results.


Connect events from a COM object to a PHP object

  • ? com_create_guid
  • com_get_active_object ?
  • PHP Manual
  • COM 函数
  • Connect events from a COM object to a PHP object

com_event_sink

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_event_sink — Connect events from a COM object to a PHP object

说明

com_event_sink ( variant $variant , object $sink_object , array|string|null $sink_interface = null ) : bool

Instructs COM to sink events generated by variant into the PHP object sink_object.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

参数

variant

sink_object

sink_object should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

sink_interface

PHP will attempt to use the default dispinterface type specified by the typelibrary associated with variant, but you may override this choice by setting sink_interface to the name of the dispinterface that you want to use.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | sink_interface is nullable now.

范例

Example #1 COM event sink example

<?php
class IEEventSinker {
    var $terminated = false;

   function ProgressChange($progress, $progressmax) {
      echo "Download progress: $progress / $progressmax\n";
    }

    function DocumentComplete(&$dom, $url) {
      echo "Document $url complete\n";
    }

    function OnQuit() {
      echo "Quit!\n";
      $this->terminated = true;
    }
}
$ie = new COM("InternetExplorer.Application");
$sink = new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.example.org");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

注释

Caution

Prior to PHP 8.0.0, calling exit() from any of the event handlers is not supported, and may cause PHP to hang. This can be worked around by throwing an exception from the event handler, catching the exception in the main code, and calling exit() from there.

参见

  • com_print_typeinfo() - Print out a PHP class definition for a dispatchable interface
  • com_message_pump() - Process COM messages, sleeping for up to timeoutms milliseconds

User Contributed Notes

veggie 25-Dec-2016 10:23
I got voice recognition working. I'm not sure why the way I called the sink function made it work but I'm more about results right now. This small example had me rolling on the floor laughing.

<?php
/*
 * Search this for more info on the voice stuff:
 * Automation Interfaces and Objects (SAPI 5.4)
 */

//directions:
//php friend.php
//then fire up windows voice recognition and turn it on and say stuff

$voice = new COM("SAPI.SpVoice");

print "Hit control+c to end.\n";
print "Friend: Hello friend!\n";

$voice->Speak("Hello friend!");

class listen
{

    function Recognition($StreamNumber, $StreamPosition, $RecognitionType, $ISpeechRecoResult)
    {

        $phrase = $ISpeechRecoResult->PhraseInfo;
        $text = $phrase->GetText();

        print "\nYou:$text\n";

        global $voice;
        $say = array('oh', 'nice', 'humm', 'interesting', 'you dont say', 'uh huh', 'right', 'what', 'ha ha', 'you have got to be joking', 'right back at you buddy');
        $idx = rand(0, count($say)-1);

        print "Friend: " . $say[$idx] . "\n";
        $voice->Speak($say[$idx]);

    }

}

$recog = new COM("SAPI.SpSharedRecognizer");

$context = $recog->CreateRecoContext();

//SRERecognition = 16 (default)
//SREAllEvents = 393215
//$context->EventInterests = 393215;

//try to listen to events on context
$listen = new listen(); //event handler
if (!com_event_sink($context, $listen, "RecognizerStateChange"))
{
    print "Unable to sink events\n";
    exit;
}

$grammar = $context->CreateGrammar();

$i = $grammar->DictationLoad();

$s = $grammar->DictationSetState(1); //1=on, 0=off

while(true)
{

    if(!com_message_pump(1000))
    {
        print ".";
    }

}

?>
fjortiz 14-Jul-2005 12:33
In case someone needs a skeleton sink for ADODB.Connection events:

class ADOConnectionEventSink    {

    function BeginTransComplete( $translevel, $objerror, $status, $objconn )    {
        return 0;
    }

    function CommitTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function RolbackTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function WillConnect ( $ConnectionString, $userid, $psword, $options, $status, $objconn )    {
        return 0;
    }

    function ConnectComplete ( $objerror, $status, $objconn)    {
        return 0;
    }

    function Disconnect( $status, $objConn )    {
        return 0;
    }

    function WillExecute ( $src, $cursortyp, $locktyp, $options, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function ExecuteComplete ( $recaffected, $objerror, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function InfoMessage ( $objerror, $status, $objconn)    {
        return 0;
    }
}

// later on...
$db = new COM("ADODB.Connection", NULL, $charPage);
$sink = new ADOConnectionEventSink();
com_event_sink($db, $sink, "ConnectionEvents");
//...


Returns a handle to an already running instance of a COM object

  • ? com_event_sink
  • com_load_typelib ?
  • PHP Manual
  • COM 函数
  • Returns a handle to an already running instance of a COM object

com_get_active_object

(PHP 5, PHP 7, PHP 8)

com_get_active_object — Returns a handle to an already running instance of a COM object

说明

com_get_active_object ( string $prog_id , int|null $codepage = null ) : variant

com_get_active_object() is similar to creating a new instance of a com object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the "Running Object Table" to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

参数

prog_id

prog_id must be either the ProgID or CLSID for the object that you want to access (for example Word.Application).

codepage

Acts in precisely the same way that it does for the com class.

返回值

If the requested object is running, it will be returned to your script just like any other COM object.

错误／异常

There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

更新日志

版本 | 说明
8.0.0 | codepage is nullable now.

注释

Warning

Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read » Considerations for Server-Side Automation of Office for more information on the general issues involved.

User Contributed Notes

gerrit at timingteam dot nl 04-Jan-2009 09:25
Please note the next behavior (Apache 2.2.8, W2K, WXP)

If Apache runs as a service, com_get_active_object() always returns MK_E_UNAVAILABLE, even when it is definitely sure that the Running Object Table contains a reference to the required object.

If Apache runs in a console, com_get_active_object()  returns the object handle as required.

This apparently is a Windows issue.


装载一个 Typelib

  • ? com_get_active_object
  • com_message_pump ?
  • PHP Manual
  • COM 函数
  • 装载一个 Typelib

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

com_load_typelib — 装载一个 Typelib

说明

com_load_typelib ( string $typelib_name , bool $case_insensitive = true ) : bool

Loads a type-library and registers its constants in the engine, as though they were defined using define().

Note that it is much more efficient to use the configuration setting to pre-load and register the constants, although not so flexible.

If you have turned on , then PHP will attempt to automatically register the constants associated with a COM object when you instantiate it. This depends on the interfaces provided by the COM object itself, and may not always be possible.

参数

typelib_name

typelib_name can be one of the following:

  • The filename of a .tlb file or the executable module that contains the type library.

  • The type library GUID, followed by its version number, for example {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • The type library name, e.g. Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP will attempt to resolve the type library in this order, as the process gets more and more expensive as you progress down the list; searching for the type library by name is handled by physically enumerating the registry until we find a match.

case_insensitive

The case_insensitive behaves in the same way as the parameter with the same name in the define() function.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

tomas dot burba at softneta dot lt 12-Mar-2012 11:38
I had some problems with a third-party Word-controlling code that is somewhat similar to Richard's example. (Word 2007 SP1, XP SP2.) Rewrote some parts according to that example, no luck. Error messages from Word were crazy:

"Bad parameter" -- it didn't like wdGoToBookmark but was ok with its numeric equivalent -1;

"Call to undefined method variant::SaveAs()" -- the same with Save() that was suitable in my case, so no options were remaining.

But then I ran the example via php.exe in the command line, and it worked! Eventually it turned out that Apache service must be run as some real user instead of SYSTEM.
RQuadling at GMail dot com 17-Jun-2008 03:40
Some libraries load other libraries as part of their functionality. For example Crystal Reports Object Factory uses the CreateObject() method to create an instance of a Crystal Design RunTime Application. If you want to use constants defined in the newly loaded library, you will need to manually register the library - even with com.autoregister_typelib set to true.

<?php
echo 'com.autoregister_typelib = ', ini_get('com.autoregister_typelib'), PHP_EOL;

$o_CrObjectFactory = New COM('CrystalReports11.ObjectFactory.1');

$o_CrApplication = $o_CrObjectFactory->CreateObject("CrystalDesignRunTime.Application");

echo 'Will not be defined : ', crOpenReportByDefault, PHP_EOL;

com_load_typelib('CrystalDesignRunTime.Application');

echo 'Will now be defined : ', crOpenReportByDefault, PHP_EOL;
?>

outputs ...

com.autoregister_typelib = 1
Will not be defined :
Notice: Use of undefined constant crOpenReportByDefault - assumed 'crOpenReportByDefault' in C:\refl.php on line 8
crOpenReportByDefault
Will now be defined : 0
03-May-2004 07:18
In case any of you were wondering what com_load_typelib actually DOES, I have found that it loads constants\enums that the COM obeject has defined.  The example below is using the Nero COM object (from Nero Burning rom, version 6+).  The Nero object defines a bunch of constants, but they can not be used as PHP constants unless you use the mentioned function.  So the example below will work just fine:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
com_load_typelib("Nero.Nero");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

But this one will not, since PHP will return a message saying that the constant is undefined:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

This one took me a while to figure out, hope it helps.

Also, check out http://www.php.net/manual/en/faq.com.php to find out how to get COM events working in PHP.
ojpp at webdevfm dot com 30-Jan-2004 06:33
Hello PHP community, I want to help in a problem I found in this COM built-in function: com_load_typelib(), when I executed it in order to open a COM Server process (for example: Word, Excel, etc.) I was in trouble to release the object from memory, I figured it out, this is the solution:

Change a configuration in the php.ini:

; autoregister constants of a components typlib on com_load()
com.autoregister_typelib = true

When com.autoregister_typelib directive is true, PHP parser manage the COM server type library, I hope it helps.
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:55
<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.


Process COM messages, sleeping for up to timeoutms milliseconds

  • ? com_load_typelib
  • com_print_typeinfo ?
  • PHP Manual
  • COM 函数
  • Process COM messages, sleeping for up to timeoutms milliseconds

com_message_pump

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds

说明

com_message_pump ( int $timeout_milliseconds = 0 ) : bool

This function will sleep for up to timeout_milliseconds milliseconds, or until a message arrives in the queue.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

参数

timeout_milliseconds

The timeout, in milliseconds.

If you do not specify a value for timeout_milliseconds, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return false immediately without sleeping.

返回值

If a message or messages arrives before the timeout, they will be dispatched, and the function will return true. If the timeout occurs and no messages were processed, the return value will be false.

User Contributed Notes

There are no user contributed notes for this page.


Print out a PHP class definition for a dispatchable interface

  • ? com_message_pump
  • variant_abs ?
  • PHP Manual
  • COM 函数
  • Print out a PHP class definition for a dispatchable interface

com_print_typeinfo

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_print_typeinfo — Print out a PHP class definition for a dispatchable interface

说明

com_print_typeinfo ( variant|string $variant , string|null $dispatch_interface = null , bool $display_sink = false ) : bool

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

参数

variant

variant should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()).

dispatch_interface

The name of an IDispatch descendant interface that you want to display.

display_sink

If set to true, the corresponding sink interface will be displayed instead.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • com_event_sink() - Connect events from a COM object to a PHP object
  • com_load_typelib() - 装载一个 Typelib

User Contributed Notes

Richard Lynch 03-Oct-2006 04:51
In my particular version of PHP, the second and third arguments are not, in fact, optional.

Passing in '' for both, however, yielded a bucketful of information.

YMMV
csaba at alum dot mit dot edu 14-Feb-2005 12:49
com_print_typeinfo is really useful if you're trying to figure out what properties and methods you have access to.  For example, I might do:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer);
?>

The first line shows me the class of the object (what VBScript calls 'typename'), in my case IShellDispatch4.  It's frequently the case that if you plunk that in as the second argument to com_print_typeinfo, you get way more methods/properties coming back.  Thus:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer, "IShellDispatch4");
?>

Furthermore, you might get additional functions listed if you try lower number suffixes (or not).  At any rate, it would be useful for PHP to have a typename function like VBScript does.  For example, if you iterate through the Windows of $oExplorer you get both IE and Explorer windows and typename is the easy way to differentiate between them.  Here's what I'm using:

<?php
    function typeName($objCOM) {
    if (empty($objCOM)) return "no COM object";
    if (gettype($objCOM)!="object") return "not a COM object";
    ob_start();
    com_print_typeinfo($objCOM);
    $typeInfo = ob_get_contents();
    ob_end_clean();
    $pattern = "/^\\s*class (.*) \\{/";
    if (!($matchCnt = preg_match($pattern, $typeInfo, $aMatch))) return "Not found";
    return $aMatch[1];
}
?>

Csaba Gabor from Vienna


Returns the absolute value of a variant

  • ? com_print_typeinfo
  • variant_add ?
  • PHP Manual
  • COM 函数
  • Returns the absolute value of a variant

variant_abs

(PHP 5, PHP 7, PHP 8)

variant_abs — Returns the absolute value of a variant

说明

variant_abs ( mixed $value ) : variant

Returns the absolute value of a variant.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the absolute value of value.

错误／异常

Throws a com_exception on failure.

参见

  • abs() - 绝对值

User Contributed Notes

There are no user contributed notes for this page.


"Adds" two variant values together and returns the result

  • ? variant_abs
  • variant_and ?
  • PHP Manual
  • COM 函数
  • "Adds" two variant values together and returns the result

variant_add

(PHP 5, PHP 7, PHP 8)

variant_add — "Adds" two variant values together and returns the result

说明

variant_add ( mixed $left , mixed $right ) : variant

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

Variant Addition Rules
If | Then
Both expressions are of the string type | Concatenation
One expression is a string type and the other a character | Addition
One expression is numeric and the other is a string | Addition
Both expressions are numeric | Addition
Either expression is NULL | NULL is returned
Both expressions are empty | Integer subtype is returned

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result.

错误／异常

Throws a com_exception on failure.

参见

  • variant_sub() - Subtracts the value of the right variant from the left variant value

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise AND operation between two variants

  • ? variant_add
  • variant_cast ?
  • PHP Manual
  • COM 函数
  • Performs a bitwise AND operation between two variants

variant_and

(PHP 5, PHP 7, PHP 8)

variant_and — Performs a bitwise AND operation between two variants

说明

variant_and ( mixed $left , mixed $right ) : variant

Performs a bitwise AND operation. Note that this is slightly different from a regular AND operation.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant AND Rules
If left is | If right is | then the result is
true | true | true
true | false | false
true | null | null
false | true | false
false | false | false
false | null | false
null | true | null
null | false | false
null | null | null

错误／异常

Throws a com_exception on failure.

参见

  • variant_or() - Performs a logical disjunction on two variants

User Contributed Notes

There are no user contributed notes for this page.


Convert a variant into a new variant object of another type

  • ? variant_and
  • variant_cat ?
  • PHP Manual
  • COM 函数
  • Convert a variant into a new variant object of another type

variant_cast

(PHP 5, PHP 7, PHP 8)

variant_cast — Convert a variant into a new variant object of another type

说明

variant_cast ( variant $variant , int $type ) : variant

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

参数

variant

The variant.

type

type should be one of the VT_XXX constants.

返回值

Returns a variant of given type.

参见

  • variant_set_type() - Convert a variant into another type "in-place"

User Contributed Notes

There are no user contributed notes for this page.


Concatenates two variant values together and returns the result

  • ? variant_cast
  • variant_cmp ?
  • PHP Manual
  • COM 函数
  • Concatenates two variant values together and returns the result

variant_cat

(PHP 5, PHP 7, PHP 8)

variant_cat — Concatenates two variant values together and returns the result

说明

variant_cat ( mixed $left , mixed $right ) : variant

Concatenates left with right and returns the result.

This function is notionally equivalent to $left . $right.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result of the concatenation.

错误／异常

Throws a com_exception on failure.

参见

  • 字符串运算符 for the string concatenation operator

User Contributed Notes

There are no user contributed notes for this page.


Compares two variants

  • ? variant_cat
  • variant_date_from_timestamp ?
  • PHP Manual
  • COM 函数
  • Compares two variants

variant_cmp

(PHP 5, PHP 7, PHP 8)

variant_cmp — Compares two variants

说明

variant_cmp ( mixed $left , mixed $right , int $locale_id = LOCALE_SYSTEM_DEFAULT , int $flags = 0 ) : int

Compares left with right.

This function will only compare scalar values, not arrays or variant records.

参数

left

The left operand.

right

The right operand.

locale_id

A valid Locale Identifier to use when comparing strings (this affects string collation).

flags

flags can be one or more of the following values OR'd together, and affects string comparisons:

Variant Comparision Flags
value | meaning
NORM_IGNORECASE | Compare case insensitively
NORM_IGNORENONSPACE | Ignore nonspacing characters
NORM_IGNORESYMBOLS | Ignore symbols
NORM_IGNOREWIDTH | Ignore string width
NORM_IGNOREKANATYPE | Ignore Kana type
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns one of the following:

Variant Comparision Results
value | meaning
VARCMP_LT | left is less than right
VARCMP_EQ | left is equal to right
VARCMP_GT | left is greater than right
VARCMP_NULL | Either left, right or both are null

User Contributed Notes

There are no user contributed notes for this page.


Returns a variant date representation of a Unix timestamp

  • ? variant_cmp
  • variant_date_to_timestamp ?
  • PHP Manual
  • COM 函数
  • Returns a variant date representation of a Unix timestamp

variant_date_from_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp

说明

variant_date_from_timestamp ( int $timestamp ) : variant

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

参数

timestamp

A unix timestamp.

返回值

Returns a VT_DATE variant.

参见

  • variant_date_to_timestamp() - Converts a variant date/time value to Unix timestamp
  • mktime() - 取得一个日期的 Unix 时间戳
  • time() - 返回当前的 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


Converts a variant date/time value to Unix timestamp

  • ? variant_date_from_timestamp
  • variant_div ?
  • PHP Manual
  • COM 函数
  • Converts a variant date/time value to Unix timestamp

variant_date_to_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp

说明

variant_date_to_timestamp ( variant $variant ) : int|null

Converts variant from a VT_DATE (or similar) value into a Unix timestamp. This allows easier interopability between the Unix-ish parts of PHP and COM.

参数

variant

The variant.

返回值

Returns a unix timestamp, or null on failure.

参见

  • variant_date_from_timestamp() - Returns a variant date representation of a Unix timestamp
  • date() - 格式化一个本地时间／日期
  • strftime() - 根据区域设置格式化本地时间／日期

User Contributed Notes

radek at tetik dot cz 25-Dec-2015 03:21
variant_date_to_timestamp() assumes the COM date in the current Windows time zone and converts it to the current PHP time zone


Returns the result from dividing two variants

  • ? variant_date_to_timestamp
  • variant_eqv ?
  • PHP Manual
  • COM 函数
  • Returns the result from dividing two variants

variant_div

(PHP 5, PHP 7, PHP 8)

variant_div — Returns the result from dividing two variants

说明

variant_div ( mixed $left , mixed $right ) : variant

Divides left by right and returns the result.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Double is returned
One expression is a string type and the other a character | Division and a double is returned
One expression is numeric and the other is a string | Division and a double is returned.
Both expressions are numeric | Division and a double is returned
Either expression is NULL | NULL is returned
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty. | 0 as type double is returned
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown

错误／异常

Throws a com_exception on failure.

参见

  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise equivalence on two variants

  • ? variant_div
  • variant_fix ?
  • PHP Manual
  • COM 函数
  • Performs a bitwise equivalence on two variants

variant_eqv

(PHP 5, PHP 7, PHP 8)

variant_eqv — Performs a bitwise equivalence on two variants

说明

variant_eqv ( mixed $left , mixed $right ) : variant

Performs a bitwise equivalence on two variants.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

If each bit in left is equal to the corresponding bit in right then true is returned, otherwise false is returned.

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the integer portion of a variant

  • ? variant_eqv
  • variant_get_type ?
  • PHP Manual
  • COM 函数
  • Returns the integer portion of a variant

variant_fix

(PHP 5, PHP 7, PHP 8)

variant_fix — Returns the integer portion of a variant

说明

variant_fix ( mixed $value ) : variant

Gets the integer portion of a variant.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

If value is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of value.

错误／异常

Throws a com_exception on failure.

注释

Warning

This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation.

参见

  • variant_int() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - 舍去法取整
  • ceil() - 进一法取整
  • round() - 对浮点数进行四舍五入

User Contributed Notes

There are no user contributed notes for this page.


Returns the type of a variant object

  • ? variant_fix
  • variant_idiv ?
  • PHP Manual
  • COM 函数
  • Returns the type of a variant object

variant_get_type

(PHP 5, PHP 7, PHP 8)

variant_get_type — Returns the type of a variant object

说明

variant_get_type ( variant $variant ) : int

Returns the type of a variant object.

参数

variant

The variant object.

返回值

This function returns an integer value that indicates the type of variant, which can be an instance of com, dotnet or variant classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

参见

  • variant_set_type() - Convert a variant into another type "in-place"

User Contributed Notes

There are no user contributed notes for this page.


Converts variants to integers and then returns the result from dividing them

  • ? variant_get_type
  • variant_imp ?
  • PHP Manual
  • COM 函数
  • Converts variants to integers and then returns the result from dividing them

variant_idiv

(PHP 5, PHP 7, PHP 8)

variant_idiv — Converts variants to integers and then returns the result from dividing them

说明

variant_idiv ( mixed $left , mixed $right ) : variant

Converts left and right to integer values, and then performs integer division.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Integer Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Division and integer is returned
One expression is a string type and the other a character | Division
One expression is numeric and the other is a string | Division
Both expressions are numeric | Division
Either expression is NULL | NULL is returned
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown

错误／异常

Throws a com_exception on failure.

参见

  • variant_div() - Returns the result from dividing two variants

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise implication on two variants

  • ? variant_idiv
  • variant_int ?
  • PHP Manual
  • COM 函数
  • Performs a bitwise implication on two variants

variant_imp

(PHP 5, PHP 7, PHP 8)

variant_imp — Performs a bitwise implication on two variants

说明

variant_imp ( mixed $left , mixed $right ) : variant

Performs a bitwise implication operation.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Implication Table
If left is | If right is | then the result is
true | true | true
true | false | false
true | null | true
false | true | true
false | false | true
false | null | true
null | true | true
null | false | null
null | null | null

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the integer portion of a variant

  • ? variant_imp
  • variant_mod ?
  • PHP Manual
  • COM 函数
  • Returns the integer portion of a variant

variant_int

(PHP 5, PHP 7, PHP 8)

variant_int — Returns the integer portion of a variant

说明

variant_int ( mixed $value ) : variant

Gets the integer portion of a variant.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

If value is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of value.

错误／异常

Throws a com_exception on failure.

参见

  • variant_fix() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - 舍去法取整
  • ceil() - 进一法取整
  • round() - 对浮点数进行四舍五入

User Contributed Notes

There are no user contributed notes for this page.


Divides two variants and returns only the remainder

  • ? variant_int
  • variant_mul ?
  • PHP Manual
  • COM 函数
  • Divides two variants and returns only the remainder

variant_mod

(PHP 5, PHP 7, PHP 8)

variant_mod — Divides two variants and returns only the remainder

说明

variant_mod ( mixed $left , mixed $right ) : variant

Divides left by right and returns the remainder.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the remainder of the division.

错误／异常

Throws a com_exception on failure.

参见

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Multiplies the values of the two variants

  • ? variant_mod
  • variant_neg ?
  • PHP Manual
  • COM 函数
  • Multiplies the values of the two variants

variant_mul

(PHP 5, PHP 7, PHP 8)

variant_mul — Multiplies the values of the two variants

说明

variant_mul ( mixed $left , mixed $right ) : variant

Multiplies left by right.

参数

left

The left operand.

right

The right operand.

Boolean values are converted to -1 for false and 0 for true.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Multiplication Rules
If | Then
Both expressions are of the string, date, character, boolean type | Multiplication
One expression is a string type and the other a character | Multiplication
One expression is numeric and the other is a string | Multiplication
Both expressions are numeric | Multiplication
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

错误／异常

Throws a com_exception on failure.

参见

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Performs logical negation on a variant

  • ? variant_mul
  • variant_not ?
  • PHP Manual
  • COM 函数
  • Performs logical negation on a variant

variant_neg

(PHP 5, PHP 7, PHP 8)

variant_neg — Performs logical negation on a variant

说明

variant_neg ( mixed $value ) : variant

Performs logical negation of value.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result of the logical negation.

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Performs bitwise not negation on a variant

  • ? variant_neg
  • variant_or ?
  • PHP Manual
  • COM 函数
  • Performs bitwise not negation on a variant

variant_not

(PHP 5, PHP 7, PHP 8)

variant_not — Performs bitwise not negation on a variant

说明

variant_not ( mixed $value ) : variant

Performs bitwise not negation on value and returns the result.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the bitwise not negation. If value is null, the result will also be null.

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Performs a logical disjunction on two variants

  • ? variant_not
  • variant_pow ?
  • PHP Manual
  • COM 函数
  • Performs a logical disjunction on two variants

variant_or

(PHP 5, PHP 7, PHP 8)

variant_or — Performs a logical disjunction on two variants

说明

variant_or ( mixed $left , mixed $right ) : variant

Performs a bitwise OR operation. Note that this is slightly different from a regular OR operation.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant OR Rules
If left is | If right is | then the result is
true | true | true
true | false | true
true | null | true
false | true | true
false | false | false
false | null | null
null | true | true
null | false | null
null | null | null

错误／异常

Throws a com_exception on failure.

参见

  • variant_and() - Performs a bitwise AND operation between two variants
  • variant_xor() - Performs a logical exclusion on two variants

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of performing the power function with two variants

  • ? variant_or
  • variant_round ?
  • PHP Manual
  • COM 函数
  • Returns the result of performing the power function with two variants

variant_pow

(PHP 5, PHP 7, PHP 8)

variant_pow — Returns the result of performing the power function with two variants

说明

variant_pow ( mixed $left , mixed $right ) : variant

Returns the result of left to the power of right.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result of left to the power of right.

错误／异常

Throws a com_exception on failure.

参见

  • pow() - 指数表达式

User Contributed Notes

There are no user contributed notes for this page.


Rounds a variant to the specified number of decimal places

  • ? variant_pow
  • variant_set_type ?
  • PHP Manual
  • COM 函数
  • Rounds a variant to the specified number of decimal places

variant_round

(PHP 5, PHP 7, PHP 8)

variant_round — Rounds a variant to the specified number of decimal places

说明

variant_round ( mixed $value , int $decimals ) : variant|null

Returns the value of value rounded to decimals decimal places.

参数

value

The variant.

decimals

Number of decimal places.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the rounded value, or null on failure.

参见

  • round() - 对浮点数进行四舍五入

User Contributed Notes

There are no user contributed notes for this page.


Convert a variant into another type "in-place"

  • ? variant_round
  • variant_set ?
  • PHP Manual
  • COM 函数
  • Convert a variant into another type "in-place"

variant_set_type

(PHP 5, PHP 7, PHP 8)

variant_set_type — Convert a variant into another type "in-place"

说明

variant_set_type ( variant $variant , int $type ) : void

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

参数

variant

The variant.

type

返回值

没有返回值。

参见

  • variant_cast() - Convert a variant into a new variant object of another type
  • variant_get_type() - Returns the type of a variant object

User Contributed Notes

martin at itmission dot com 22-May-2009 10:55
In my application I was using ADODB to retrieve data from Microsoft Access.  During queries, fields defined as "Date/Time" in Access were being returned to PHP as instances of the Variant class.

For some reason, the variant_date_to_timestamp function returned incorrect timestamps.  As a workaround, I used variant_set_type($variant, VT_BSTR) to get a string representation of the date.  This can be used for most variant types PHP doesn't handle.


Assigns a new value for a variant object

  • ? variant_set_type
  • variant_sub ?
  • PHP Manual
  • COM 函数
  • Assigns a new value for a variant object

variant_set

(PHP 5, PHP 7, PHP 8)

variant_set — Assigns a new value for a variant object

说明

variant_set ( variant $variant , mixed $value ) : void

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

参数

variant

The variant.

value

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Subtracts the value of the right variant from the left variant value

  • ? variant_set
  • variant_xor ?
  • PHP Manual
  • COM 函数
  • Subtracts the value of the right variant from the left variant value

variant_sub

(PHP 5, PHP 7, PHP 8)

variant_sub — Subtracts the value of the right variant from the left variant value

说明

variant_sub ( mixed $left , mixed $right ) : variant

Subtracts right from left.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Subtraction Rules
If | Then
Both expressions are of the string type | Subtraction
One expression is a string type and the other a character | Subtraction
One expression is numeric and the other is a string | Subtraction.
Both expressions are numeric | Subtraction
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

错误／异常

Throws a com_exception on failure.

参见

  • variant_add() - "Adds" two variant values together and returns the result

User Contributed Notes

There are no user contributed notes for this page.


Performs a logical exclusion on two variants

  • ? variant_sub
  • win32service ?
  • PHP Manual
  • COM 函数
  • Performs a logical exclusion on two variants

variant_xor

(PHP 5, PHP 7, PHP 8)

variant_xor — Performs a logical exclusion on two variants

说明

variant_xor ( mixed $left , mixed $right ) : variant

Performs a logical exclusion.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant XOR Rules
If left is | If right is | then the result is
true | true | false
true | false | true
false | true | true
false | false | false
null | null | null

错误／异常

Throws a com_exception on failure.

参见

  • variant_or() - Performs a logical disjunction on two variants
  • variant_and() - Performs a bitwise AND operation between two variants

User Contributed Notes

tinelbarb at yahoo dot com 30-Aug-2010 12:21
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com dot RE-MO-VE dot ME 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)


win32service

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
    • Security consideration
  • 预定义常量
    • Win32Service Service Type Bitmasks
    • Win32Service Service Status Constants
    • Win32Service Service Control Message Constants
    • Win32Service Service Control Message Accepted Bitmasks
    • Win32Service Service Start Type Constants
    • Win32Service Service Error Control Constants
    • Win32Service Service Flag Constants
    • Win32 Error Codes
    • Win32 Base Priority Classes
    • Win32 Recovery action
    • Win32 Service informations
  • Win32ServiceException — The Win32ServiceException class
  • 范例
  • win32service 函数
    • win32_continue_service — Resumes a paused service
    • win32_create_service — Creates a new service entry in the SCM database
    • win32_delete_service — Deletes a service entry from the SCM database
    • win32_get_last_control_message — Returns the last control message that was sent to this service
    • win32_pause_service — Pauses a service
    • win32_query_service_status — Queries the status of a service
    • win32_send_custom_control — Send a custom control to the service
    • win32_set_service_exit_code — Define or return the exit code for the current running service
    • win32_set_service_exit_mode — Define or return the exit mode for the current running service
    • win32_set_service_status — Update the service status
    • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
    • win32_start_service — Starts a service
    • win32_stop_service — Stops a service

User Contributed Notes

jbnahan at php dot net 12-Jun-2019 11:45
The version 0.4 allow now to send and receive a custom control code.
gospodin dot p dot zh at gmail dot com 04-Oct-2012 06:49
win32service extension does not realize very important (as for me) method of ServiceBase::OnCustomCommand
----
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.oncustomcommand.aspx
"OnCustomCommand lets you specify additional functionality beyond starting, stopping, pausing and continuing services."


简介

The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.

User Contributed Notes

There are no user contributed notes for this page.


安装／配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型
  • Security consideration

User Contributed Notes

There are no user contributed notes for this page.


需求

The versions of Windows supported are the same as the Visual C++ redistributable package used to build PHP.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/win32service

User Contributed Notes

alphp 10-Jan-2017 03:08
Para actualizar esta extensión a PHP-7 se está trabajando en https://github.com/win32service/win32service
Ya ha disponibles algunos binarios para poder probar.

To update this extension to PHP-7 is working at https://github.com/win32service/win32service
Some binaries have already been available for testing.


Security consideration

This extension needs administrator privileges for some actions such as create, delete, start, stop, pause and continue. This requirement can cause an elevation of privileges if the service control is available from the web interface or remote control.

You can set the ACL on the service after adding it into SCM to delegate the current administration tasks to an non administrator account or service account. For further instructions, see the » Microsoft Knowledge Base.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

Table of Contents

  • Win32Service Service Type Bitmasks
  • Win32Service Service Status Constants
  • Win32Service Service Control Message Constants
  • Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Start Type Constants
  • Win32Service Service Error Control Constants
  • Win32Service Service Flag Constants
  • Win32 Error Codes
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Service informations

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Type Bitmasks

  • ? 预定义常量
  • Win32Service Service Status Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Type Bitmasks
Win32Service Service Type Bitmasks
Constant | Value | Description
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | The service runs in its own process.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | The service can interact with the desktop. This option is not available on Windows Vista or later.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | The service runs in its own process and can interact with the desktop. This option is not available on Windows Vista or later.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Status Constants

  • ? Win32Service Service Type Bitmasks
  • Win32Service Service Control Message Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Status Constants
Win32Service Service Status Constants
Constant | Value | Description
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | The service continue is pending.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | The service pause is pending.
WIN32_SERVICE_PAUSED | 0x00000007 | The service is paused.
WIN32_SERVICE_RUNNING | 0x00000004 | The service is running.
WIN32_SERVICE_START_PENDING | 0x00000002 | The service is starting.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | The service is stopping.
WIN32_SERVICE_STOPPED | 0x00000001 | The service is not running.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Control Message Constants

  • ? Win32Service Service Status Constants
  • Win32Service Service Control Message Accepted Bitmasks ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Control Message Constants
Win32Service Service Control Message Constants
Constant | Value | Description
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Notifies a paused service that it should resume.
WIN32_SERVICE_CONTROL_DEVICEEVENT | 0x0000000B |
WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE | 0x0000000C |
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Notifies a service that it should report its current status information to the service control manager.
WIN32_SERVICE_CONTROL_NETBINDADD | 0x00000007 | Notifies a network service that there is a new component for binding.
WIN32_SERVICE_CONTROL_NETBINDDISABLE | 0x0000000A | Notifies a network service that one of its bindings has been disabled.
WIN32_SERVICE_CONTROL_NETBINDENABLE | 0x00000009 | Notifies a network service that a disabled binding has been enabled.
WIN32_SERVICE_CONTROL_NETBINDREMOVE | 0x00000008 | Notifies a network service that a component for binding has been removed.
WIN32_SERVICE_CONTROL_PARAMCHANGE | 0x00000006 | Notifies a service that its startup parameters have changed.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Notifies a service that it should pause.
WIN32_SERVICE_CONTROL_POWEREVENT | 0x0000000D |
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Notifies a service that the system will be shutting down. A service that handles this notification blocks system shutdown until the service stops or the preshutdown time-out interval expires. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_CONTROL_SESSIONCHANGE | 0x0000000E |
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Notifies a service that the system is shutting down so the service can perform cleanup tasks. If a service accepts this control code, it must stop after it performs its cleanup tasks. After the SCM sends this control code, it will not send other control codes to the service.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Notifies a service that it should stop.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Control Message Accepted Bitmasks

  • ? Win32Service Service Control Message Constants
  • Win32Service Service Start Type Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Control Message Accepted Bitmasks
Constant | Value | Description
WIN32_SERVICE_ACCEPT_HARDWAREPROFILECHANGE | 0x00000020 | The service is notified when the computer's hardware profile has changed. This enables the system to send WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE notifications to the service.
WIN32_SERVICE_ACCEPT_NETBINDCHANGE | 0x00000010 | The service is a network component that can accept changes in its binding without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_NETBINDENABLE, and WIN32_SERVICE_CONTROL_NETBINDDISABLE notifications.
WIN32_SERVICE_ACCEPT_PARAMCHANGE | 0x00000008 | The service can reread its startup parameters without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_PARAMCHANGE notifications.
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | The service can be paused and continued. This control code allows the service to receive WIN32_SERVICE_CONTROL_PAUSE and WIN32_SERVICE_CONTROL_CONTINUE notifications.
WIN32_SERVICE_ACCEPT_POWEREVENT | 0x00000040 | The service is notified when the computer's power status has changed. This enables the system to send WIN32_SERVICE_CONTROL_POWEREVENT notifications to the service.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | The service can perform preshutdown tasks. This control code enables the service to receive WIN32_SERVICE_CONTROL_PRESHUTDOWN notifications. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_ACCEPT_SESSIONCHANGE | 0x00000080 | The service is notified when the computer's session status has changed. This enables the system to send WIN32_SERVICE_CONTROL_SESSIONCHANGE notifications to the service. Windows 2000: This value is not supported
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | The service is notified when system shutdown occurs. This control code allows the service to receive WIN32_SERVICE_CONTROL_SHUTDOWN notifications.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | The service can be stopped. This control code allows the service to receive WIN32_SERVICE_CONTROL_STOP notifications.
WIN32_SERVICE_ACCEPT_TIMECHANGE | 0x00000200 | The service is notified when the system time has changed. This enables the system to send WIN32_SERVICE_CONTROL_TIMECHANGE notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.
WIN32_SERVICE_ACCEPT_TRIGGEREVENT | 0x00000400 | The service is notified when an event for which the service has registered occurs. This enables the system to send WIN32_SERVICE_CONTROL_TRIGGEREVENT notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Start Type Constants

  • ? Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Error Control Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Start Type Constants
Win32Service Service Start Type Constants
Constant | Value | Description
WIN32_SERVICE_BOOT_START | 0x00000000 | A device driver started by the system loader. This value is valid only for driver services.
WIN32_SERVICE_SYSTEM_START | 0x00000001 | A device driver started by the IoInitSystem function. This value is valid only for driver services.
WIN32_SERVICE_AUTO_START | 0x00000002 | A service started automatically by the service control manager during system startup.
WIN32_SERVICE_DEMAND_START | 0x00000003 | A service started by the service control manager when a process calls the StartService function.
WIN32_SERVICE_DISABLED | 0x00000004 | A service that cannot be started. Attempts to start the service result in the error code WIN32_ERROR_SERVICE_DISABLED.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Error Control Constants

  • ? Win32Service Service Start Type Constants
  • Win32Service Service Flag Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Error Control Constants
Win32Service Service Error Control Constants
Constant | Value | Description
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | The startup program ignores the error and continues the startup operation.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | The startup program logs the error in the event log but continues the startup operation.
WIN32_SERVICE_ERROR_SEVERE | 0x00000002 | The startup program logs the error in the event log. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
WIN32_SERVICE_ERROR_CRITICAL | 0x00000003 | The startup program logs the error in the event log, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Flag Constants

  • ? Win32Service Service Error Control Constants
  • Win32 Error Codes ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Flag Constants
Win32Service Service Flag Constants
Constant | Value | Description
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | The service runs in a system process that must always be running.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Error Codes

  • ? Win32Service Service Flag Constants
  • Win32 Base Priority Classes ?
  • PHP Manual
  • 预定义常量
  • Win32 Error Codes

Note:

These constants are no longer in use as of Win32Service 1.0.0.

Win32 Error Codes
Constant | Value | Description
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | The handle to the SCM database does not have the appropriate access rights.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | A circular service dependency was specified.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | The specified database does not exist.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | The service cannot be stopped because other running services are dependent on it.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | The display name already exists in the service control manager database either as a service name or as another display name.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | This error is returned if the program is being run as a console application rather than as a service. If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | The buffer is too small for the service status structure. Nothing was written to the structure.
WIN32_ERROR_INVALID_DATA | 0x0000000D | The specified service status structure is invalid.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | The handle to the specified service control manager database is invalid.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | The InfoLevel parameter contains an unsupported value.
WIN32_ERROR_INVALID_NAME | 0x0000007B | The specified service name is invalid.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | A parameter that was specified is invalid.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | The user account name specified in the user parameter does not exist. See win32_create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | The requested control code is not valid, or it is unacceptable to the service.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | The service binary file could not be found.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | An instance of the service is already running.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | The requested control code cannot be sent to the service because the state of the service is WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING, or WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | The database is locked.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | The service depends on a service that does not exist or has been marked for deletion.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | The service depends on another service that has failed to start.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | The service has been disabled.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | The specified service does not exist as an installed service.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | The specified service already exists in this database.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | The service did not start due to a logon failure. This error occurs if the service is configured to run under an account that does not have the "Log on as a service" right.
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | The specified service has already been marked for deletion.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | A thread could not be created for the service.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | The service has not been started.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | The system is shutting down; this function cannot be called.
WIN32_ERROR_SERVICE_SPECIFIC_ERROR | 0x0000042A | The service has returned a service-specific error code.
WIN32_NO_ERROR | 0x00000000 | No error.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Base Priority Classes

  • ? Win32 Error Codes
  • Win32 Recovery action ?
  • PHP Manual
  • 预定义常量
  • Win32 Base Priority Classes
Win32 Base Priority Classes
Constant | Value | Description
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Process that has priority above WIN32_NORMAL_PRIORITY_CLASS but below WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Process that has priority above WIN32_IDLE_PRIORITY_CLASS but below WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Process that performs time-critical tasks that must be executed immediately. The threads of the process preempt the threads of normal or idle priority class processes. An example is the Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class application can use nearly all available CPU time.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Process whose threads run only when the system is idle. The threads of the process are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle-priority class is inherited by child processes.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Process with no special scheduling needs.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Process that has the highest possible priority. The threads of the process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Recovery action

  • ? Win32 Base Priority Classes
  • Win32 Service informations ?
  • PHP Manual
  • 预定义常量
  • Win32 Recovery action
Win32 Recovery action
Constant | Value | Description
WIN32_SC_ACTION_NONE | 0x00000000 | No action.
WIN32_SC_ACTION_REBOOT | 0x00000001 | Restart the server.
WIN32_SC_ACTION_RESTART | 0x00000002 | Restart the service.
WIN32_SC_ACTION_RUN_COMMAND | 0x00000003 | Run a command.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Service informations

  • ? Win32 Recovery action
  • Win32ServiceException ?
  • PHP Manual
  • 预定义常量
  • Win32 Service informations
Win32 Service informations
Constant | Value | Description
WIN32_INFO_SERVICE | "service" |
WIN32_INFO_DISPLAY | "display" |
WIN32_INFO_USER | "user" |
WIN32_INFO_PASSWORD | "password" |
WIN32_INFO_PATH | "path" |
WIN32_INFO_PARAMS | "params" |
WIN32_INFO_DESCRIPTION | "description" |
WIN32_INFO_START_TYPE | "start_type" |
INFO_LOAD_ORDER | "load_order" |
INFO_SVC_TYPE | "svc_type" |
INFO_ERROR_CONTROL | "error_control" |
INFO_DELAYED_START | "delayed_start" |
INFO_BASE_PRIORITY | "base_priority" |
INFO_DEPENDENCIES | "dependencies" |
INFO_RECOVERY_DELAY | "recovery_delay" |
INFO_RECOVERY_ACTION_1 | "recovery_action_1" |
INFO_RECOVERY_ACTION_2 | "recovery_action_2" |
INFO_RECOVERY_ACTION_3 | "recovery_action_3" |
INFO_RECOVERY_RESET_PERIOD | "recovery_reset_period" |
INFO_RECOVERY_ENABLED | "recovery_enabled" |
INFO_RECOVERY_REBOOT_MSG | "recovery_reboot_msg" |
INFO_RECOVERY_COMMAND | "recovery_command" |

User Contributed Notes

There are no user contributed notes for this page.


The Win32ServiceException class

(PECL win32service >=1.0.0)

简介

The exception replaces the old mechanism where the error value needed to be compared to constants to detect which error was emitted. The Exception code is equal to the value of the error value and the exception message is based on the corresponding constant name.

类摘要

Win32ServiceException extends Exception {
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

There are no user contributed notes for this page.


范例

Example #1 Registering a PHP script to run as a service

<?php
win32_create_service(array(
    'service'     => 'dummyphp',                                           # the name of your service
    'display'     => 'sample dummy PHP service',                           # short description
    'description' => 'This is a dummy Windows service created using PHP.', # long description
    'params'      => '"' . __FILE__ . '"  run',                            # path to the script and parameters
));
?>

Example #2 Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Example #3 Running as a service

<?php
if ($argv[1] == 'run') {
  win32_start_service_ctrl_dispatcher('dummyphp');

  while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
    # do your work here.
    # try not to take up more than 30 seconds before going around the loop
    # again
  }
}
?>

User Contributed Notes

There are no user contributed notes for this page.


win32service 函数

Table of Contents

  • win32_continue_service — Resumes a paused service
  • win32_create_service — Creates a new service entry in the SCM database
  • win32_delete_service — Deletes a service entry from the SCM database
  • win32_get_last_control_message — Returns the last control message that was sent to this service
  • win32_pause_service — Pauses a service
  • win32_query_service_status — Queries the status of a service
  • win32_send_custom_control — Send a custom control to the service
  • win32_set_service_exit_code — Define or return the exit code for the current running service
  • win32_set_service_exit_mode — Define or return the exit mode for the current running service
  • win32_set_service_status — Update the service status
  • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
  • win32_start_service — Starts a service
  • win32_stop_service — Stops a service

User Contributed Notes

brian dot ngure at gmail dot com 30-Apr-2010 03:03
An example of how it should be done:

<?php

class TestClass {
    private $args;

    function __construct($arg) {
        $this->args = $arg;
        $this->run();
    }

    private function run() {
        if ($this->args == 'run') {
            win32_start_service_ctrl_dispatcher('test_service');

            while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
                # do your work here.
                # try not to take up more than 30 seconds before going around the loop
                # again
            }
        }
    }
}

$object = new TestClass($argv[1]);

?>


Resumes a paused service

  • ? win32service 函数
  • win32_create_service ?
  • PHP Manual
  • win32service 函数
  • Resumes a paused service

win32_continue_service

(PECL win32service >=0.1.0)

win32_continue_service — Resumes a paused service

说明

win32_continue_service ( string $servicename , string $machine = ? ) : void

Resumes a paused, named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Creates a new service entry in the SCM database

  • ? win32_continue_service
  • win32_delete_service ?
  • PHP Manual
  • win32service 函数
  • Creates a new service entry in the SCM database

win32_create_service

(PECL win32service >=0.1.0)

win32_create_service — Creates a new service entry in the SCM database

说明

win32_create_service ( array $details , string $machine = ? ) : void

Attempts to add a service into the SCM database. Administrative privileges are required for this to succeed.

参数

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

description

The long description of the service. This is the description that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run. If the script name or path contains spaces, then wrap the full path to the PHP script with ".

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

delayed_start

If delayed_start is set to true, then this will inform the SCM that this service should be started after other auto-start services are started plus a short delay.

Any service can be marked as a delayed auto-start service; however, this setting has no effect unless the service's start_type is WIN32_SERVICE_AUTO_START.

This setting is only applicable on Windows Vista and Windows Server 2008 or greater.

base_priority

To reduce the impact on processor utilisation, it may be necessary to set a base priority lower than normal.

The base_priority can be set to one of the constants define in Win32 Base Priority Classes.

dependencies

To define the dependencies for your service, it may be necessary to set this parameter to the list of the services names in an array.

recovery_delay

This parameter defines the delay between the fail and the execution of recovery action. The value is in milliseconds.

The default value is 60000.

recovery_action_1

The action will be executed on first failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_1 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_2

The action will be executed on second failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_2 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_3

The action will be executed on next failures. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_3 can be set to one of the constants defined in Win32 Recovery action.

recovery_reset_period

The failure count will be reset after the delay defined in the parameter. The delay is expirement in seconds.

The default value is 86400.

recovery_enabled

Set this parameter at true to enable the recovery settings, false to disable.

The default value is false

recovery_reboot_msg

Set this parameter to define the message saved into the Windows Event Log before the reboot. Used only if one action is set to WIN32_SC_ACTION_REBOOT.

recovery_command

Set this parameter to define the command executed when one action is defined on WIN32_SC_ACTION_RUN_COMMAND.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the; value of service parameter is empty.

A ValueError is thrown if the; value of path parameter is missing or empty.

A ValueError is thrown if the; value of svc_type parameter is wrong.

A ValueError is thrown if the; value of start_type parameter is wrong.

A ValueError is thrown if the; value of error_control parameter is wrong.

A ValueError is thrown if the; value of base_priority parameter is wrong.

A ValueError is thrown if the; value of recovery_delay parameter is not between 0 and PHP_INT_MAX.

A ValueError is thrown if the; value of recovery_action_1 parameter is wrong.

A ValueError is thrown if the; value of recovery_action_2 parameter is wrong.

A ValueError is thrown if the; value of recovery_action_3 parameter is wrong.

A ValueError is thrown if the; value of recovery_reset_period parameter is not between 0 and PHP_INT_MAX.

A Win32ServiceException is thrown on error.

范例

Example #1 A win32_create_service() example

Create a service with the short name 'dummyphp'.

<?php
$x = win32_create_service(array(
    'service'     => 'dummyphp',                                           // the name of your service
    'display'     => 'sample dummy PHP service',                           // short description
    'description' => 'This is a dummy Windows service created using PHP.', // long description
    'params'      => '"' . __FILE__ . '"  run',                            // path to the script and parameters
));
debug_zval_dump($x);
?>

Example #2 A win32_create_service() example with dependencies

Create a service with the short name 'dummyphp' and dependencies.

<?php
$x = win32_create_service(array(
    'service'      => 'dummyphp',                                           // the name of your service
    'display'      => 'sample dummy PHP service',                           // short description
    'description'  => 'This is a dummy Windows service created using PHP.', // long description
    'params'       => '"' . __FILE__ . '"  run',                            // path to the script and parameters
    'dependencies' => array("Netman"),                                      // The list of the dependencies
));
debug_zval_dump($x);
?>

Example #3 A win32_create_service() example with recovery

Create a service with the short name 'dummyphp' and recovery settings.

<?php
$x = win32_create_service(array(
    'service'               => 'dummyphp',                                           // the name of your service
    'display'               => 'sample dummy PHP service',                           // short description
    'description'           => 'This is a dummy Windows service created using PHP.', // long description
    'params'                => '"' . __FILE__ . '"  run',                            // path to the script and parameters
    'recovery_delay'        => 120000,                                               // Recovery action is executed after 2 minutes
    'recovery_action_1'     => WIN32_SC_ACTION_RESTART,                              // On first failure, restart the service
    'recovery_action_2'     => WIN32_SC_ACTION_RUN_COMMAND,                          // On second failure, execute the commmand
    'recovery_action_3'     => WIN32_SC_ACTION_NONE,                                 // On other failure, do nothing
    'recovery_reset_period' => 86400,                                                // Reset the fail counter after 1 day
    'recovery_enabled'      => true,                                                 // Enable the recovery parameter
    'recovery_reboot_msg'   => null,                                                 // Do not define a reboot message, it's not needed here
    'recovery_command'      => "c:\clean-service.bat",                               // When the action is WIN32_SC_ACTION_RUN_COMMAND, execute this command
));
debug_zval_dump($x);
?>

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.4.0 | The dependencies, recovery_delay, recovery_action_1, recovery_action_2, recovery_action_3, recovery_reset_period, recovery_enabled, recovery_reboot_msg and recovery_command parameters have been added.

参见

  • win32_delete_service() - Deletes a service entry from the SCM database
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Error Codes

User Contributed Notes

Anonymous 08-Oct-2010 10:05
[An example of how to create a Windows service.  Evaluate code first and use at your own risk!]

<?php

//No timeouts, Flush Content immediatly
    set_time_limit(0);
    ob_implicit_flush();

//Service Settings
    $phpPath = "D:\\php\\php5.2.9";
    $ServiceName = 'phpServiceName';
    $ServiceDisplay = 'phpDisplayName';

//Windows Service Control
    $ServiceAction = "status";
    //$ServiceAction = "debug";
    if ( isset($_GET['ServiceAction']) and strlen($_GET['ServiceAction']) ) {
        $ServiceAction = addslashes($_GET['ServiceAction']);
    } else if ( isset($argv) and isset($argv[1]) and strlen($argv[1]) ) {
        $ServiceAction = $argv[1];
    }
    if( $ServiceAction == "status" ) {
        $ServiceStatus = win32_query_service_status($ServiceName);
        if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOPPED ) {
            echo "Service Stopped\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_START_PENDING ) {
            echo "Service Start Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOP_PENDING ) {
            echo "Service Stop Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_RUNNING ) {
            echo "Service Running\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_CONTINUE_PENDING ) {
            echo "Service Continue Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSE_PENDING ) {
            echo "Service Pause Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSED ) {
            echo "Service Paused\n\n";
        } else{
            echo "Service Unknown\n\n";
        }
      exit;
    } else if ( $ServiceAction == "install" ) {
    //Install Windows Service
        win32_create_service( Array(
            'service' => $ServiceName,
            'display' => $ServiceDisplay,
            'params' => __FILE__ . " run",
            'path' => $phpPath."\\php.exe",
        ));
        echo "Service Installed\n\n";
        exit;
    } else if ( $ServiceAction == "uninstall" ) {
    //Remove Windows Service
        win32_delete_service($ServiceName);
        echo "Service Removed\n\n";
        exit;
    } else if( $ServiceAction == "start") {
    //Start Windows Service
      win32_start_service($ServiceName);
      echo "Service Started\n\n";
      exit;
    } else if( $ServiceAction == "stop" ) {
    //Stop Windows Service
      win32_stop_service($ServiceName);
      echo "Service Stopped\n\n";
      exit;
    } else if ( $ServiceAction == "run" ) {
    //Run Windows Service
        win32_start_service_ctrl_dispatcher($ServiceName);
        win32_set_service_status(WIN32_SERVICE_RUNNING);
    } else if ( $ServiceAction == "debug" ) {
    //Debug Windows Service
        set_time_limit(10);
    } else {
        exit();
    }

//Server Loop
    while (1) {
    //Handle Windows Service Request
        usleep(100*1000);
        if ( $ServiceAction == "run" ) {
            switch ( win32_get_last_control_message() ) {
                case WIN32_SERVICE_CONTROL_CONTINUE:
                    break;
                case WIN32_SERVICE_CONTROL_INTERROGATE:
                    win32_set_service_status(WIN32_NO_ERROR);
                break;
                case WIN32_SERVICE_CONTROL_STOP:
                    win32_set_service_status(WIN32_SERVICE_STOPPED);
                    exit;
                default:
                    win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED);
            }
        }
    //User Loop
        sleep(1);
        echo "\n<BR>YOUR CODE HERE";
    }

//Exit
    if ( $ServiceAction == "run" ) {
        win32_set_service_status(WIN32_SERVICE_STOPPED);
    }
    exit();
?>
pauljamesthomson at gmail dot com 22-Jan-2007 04:54
Other start_type values:

0x00000002: A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services.

0x00000000: A device driver started by the system loader. This value is valid only for driver services.

0x00000003: A service started by the service control manager when a process calls the win32_start_service() function.

0x00000004: A service that cannot be started. Attempts to start the service result in the error code

0x00000001: A device driver started by the IoInitSystem function. This value is valid only for driver services.

I can confirm that 0x00000003 works as expected (service is created, but must be started manually).

More here:

http://msdn2.microsoft.com/en-us/library/ms682450.aspx


Deletes a service entry from the SCM database

  • ? win32_create_service
  • win32_get_last_control_message ?
  • PHP Manual
  • win32service 函数
  • Deletes a service entry from the SCM database

win32_delete_service

(PECL win32service >=0.1.0)

win32_delete_service — Deletes a service entry from the SCM database

说明

win32_delete_service ( string $servicename , string $machine = ? ) : void

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

参数

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the; value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

范例

Example #1 A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.

参见

  • win32_create_service() - Creates a new service entry in the SCM database
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Returns the last control message that was sent to this service

  • ? win32_delete_service
  • win32_pause_service ?
  • PHP Manual
  • win32service 函数
  • Returns the last control message that was sent to this service

win32_get_last_control_message

(PECL win32service >=0.1.0)

win32_get_last_control_message — Returns the last control message that was sent to this service

说明

win32_get_last_control_message ( ) : int

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

返回值

Returns a control constant which will be one of the Win32Service Service Control Message Constants: WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_DEVICEEVENT, WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDDISABLE, WIN32_SERVICE_CONTROL_NETBINDENABLE, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_PARAMCHANGE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_POWEREVENT, WIN32_SERVICE_CONTROL_PRESHUTDOWN, WIN32_SERVICE_CONTROL_SESSIONCHANGE, WIN32_SERVICE_CONTROL_SHUTDOWN, WIN32_SERVICE_CONTROL_STOP.

If the value is between 128 and 255, the control code is custom.

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Control Message Constants

User Contributed Notes

There are no user contributed notes for this page.


Pauses a service

  • ? win32_get_last_control_message
  • win32_query_service_status ?
  • PHP Manual
  • win32service 函数
  • Pauses a service

win32_pause_service

(PECL win32service >=0.1.0)

win32_pause_service — Pauses a service

说明

win32_pause_service ( string $servicename , string $machine = ? ) : void

Pauses a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the; value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Queries the status of a service

  • ? win32_pause_service
  • win32_send_custom_control ?
  • PHP Manual
  • win32service 函数
  • Queries the status of a service

win32_query_service_status

(PECL win32service >=0.1.0)

win32_query_service_status — Queries the status of a service

说明

win32_query_service_status ( string $servicename , string $machine = ? ) : array

Queries the current status for a service, returning an array of information.

参数

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

返回值

Returns an array consisting of the following information on success

Prior version 1.0.0，参数错误时返回 false，或失败时返回一个 Win32 错误码。

ServiceType

The dwServiceType. See Win32Service Service Type Bitmasks.

CurrentState

The dwCurrentState. See Win32Service Service Status Constants.

ControlsAccepted

Which service controls are accepted by the service. See Win32Service Service Control Message Accepted Bitmasks.

Win32ExitCode

If the service exited, the return code from the process. This value is equal to WIN32_ERROR_SERVICE_SPECIFIC_ERROR if the exit mode is not gracefuly. See Win32Service error codes and win32_set_service_exit_mode()

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here. This value is equal to the value defined by win32_set_service_exit_code()

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The Windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags. See Win32Service Service Service Flag Constants.

错误／异常

A ValueError is thrown if the; value of servicename parameter is empty.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now array, previously it was mixed.

参见

  • Win32Service Predefined Constants

User Contributed Notes

demers dot alex at gmail dot com 21-Jul-2009 08:39
This function will return an array containing the above information as a return value, but if this fails it will return an integer which is a System Error Code. All the System Error Codes can be found here:

http://msdn.microsoft.com/en-us/library/ms681381%28VS.85%29.aspx

In my case, it returned 5, in which I immediately knew why and fixed the issue right away.

In the case of mnemotronic at netscape dot net, here in the documentation notes, it returned 1060 which is:

ERROR_SERVICE_DOES_NOT_EXIST
1060 (0x424)
The specified service does not exist as an installed service.

Again, it should not return FALSE, instead an System Error Code for Windows.


Send a custom control to the service

  • ? win32_query_service_status
  • win32_set_service_exit_code ?
  • PHP Manual
  • win32service 函数
  • Send a custom control to the service

win32_send_custom_control

(PECL win32service >=0.4.0)

win32_send_custom_control — Send a custom control to the service

说明

win32_send_custom_control ( string $servicename , int $control , string $machine = ? ) : void

See » Microsoft ControlService function for more details

参数

servicename

The short name of the service.

control

The custom contole value between 128 and 255.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

Prior to version 1.0.0, if the control value is not between 128 and 255, this function emits an E_ERROR level error.

A ValueError is thrown if the; value of servicename parameter is empty.

A ValueError is thrown if the; value of control parameter is not between 128 and 255.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.

参见

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Define or return the exit code for the current running service

  • ? win32_send_custom_control
  • win32_set_service_exit_mode ?
  • PHP Manual
  • win32service 函数
  • Define or return the exit code for the current running service

win32_set_service_exit_code

(PECL win32service >=0.4.0)

win32_set_service_exit_code — Define or return the exit code for the current running service

说明

win32_set_service_exit_code ( int $exitCode = 1 ) : int

Change or return the exit code. The exit code is used only if the exit mode is not graceful. If the value is not zero, the recovery configuration can be used after service fail. See » Microsoft system error codes for more details

Caution

This function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

exitCode

The return code used on exit.

返回值

Return the current or old exit code.

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service

User Contributed Notes

There are no user contributed notes for this page.


Define or return the exit mode for the current running service

  • ? win32_set_service_exit_code
  • win32_set_service_status ?
  • PHP Manual
  • win32service 函数
  • Define or return the exit mode for the current running service

win32_set_service_exit_mode

(PECL win32service >=0.4.0)

win32_set_service_exit_mode — Define or return the exit mode for the current running service

说明

win32_set_service_exit_mode ( bool $gracefulMode = true ) : bool

If gracefulMode parameter is provided, the exit mode is changed. When the exit mode is not gracefuly, the exit code used can be set with the win32_set_service_exit_code() function.

Caution

This function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

gracefulMode

true for exit graceful. false for exit with error.

返回值

Return the current or old exit mode.

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_code() - Define or return the exit code for the current running service

User Contributed Notes

There are no user contributed notes for this page.


Update the service status

  • ? win32_set_service_exit_mode
  • win32_start_service_ctrl_dispatcher ?
  • PHP Manual
  • win32service 函数
  • Update the service status

win32_set_service_status

(PECL win32service >=0.1.0)

win32_set_service_status — Update the service status

说明

win32_set_service_status ( int $status , int $checkpoint = 0 ) : void

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

checkpoint

The checkpoint value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up.

The checkpoint is only valid when the status is one of WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING or WIN32_SERVICE_PAUSE_PENDING.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Status Constants

User Contributed Notes

paul_nelson57071 at yahoo dot com 13-May-2010 11:04
So after much searching I finally found all the peices to make a working windows service & server including:
- Installing & Uninstalling the service
- Starting & Stopping the Service
- Actually running a basic Server
- Responding to windows Service to Stop/Start/Restart

I hope you find this useful! I did this using PHP 5.2 and the PECL library for 5.2 (PHP 5.3 at the time does not have a PECL Library compiled for it)

<?php
    //Service Settings
    $Service = 'MyServiceFinal';
    $Display = 'My PHP Service';

    //Server Settings
    $host = '127.0.0.1';        //Bind to IP #
    $port = 23;                            //On port #
    $max = 20;                            //Maximum Clients

    //Exit if no start-up argument is passed
    if (!isset($argv[1])){ShowHelp(); exit;}

    //Create Windows Service
    if ($argv[1] == 'install') {
    $x = win32_create_service(array(
        'service' => $Service,
        'display' => $Service,
        'params' => __file__ . ' run',
        'path' => 'c:\\php\\php.exe',
    ));
    debug_zval_dump($x);
    echo "Service Installed\n\n";
    exit;

  //Remove Windows Service
    } else if ($argv[1] == 'uninstall') {
        $x = win32_delete_service($Service);
        debug_zval_dump($x);
        echo "Service Removed\n\n";
        exit;

  //Start Windows Service
    } elseif($argv[1] == "start") {
      $x = win32_start_service($Service);
      debug_zval_dump($x);
      echo "Service Started\n\n";
      exit;

    //Stop Windows Service
    } elseif($argv[1] == "stop") {
      $x = win32_stop_service($Service);
      debug_zval_dump($x);
      echo "Service Stopped\n\n";
      exit;

    //Unkown Command
    } else if ($argv[1] != 'run') {
        ShowHelp(); exit();
    }

//Tell windows the service has started...
if (!win32_start_service_ctrl_dispatcher($Service)) die("Could not connect to service : $Service");
win32_set_service_status(WIN32_SERVICE_RUNNING);

// No timeouts, flush content immediatly
set_time_limit(0);
ob_implicit_flush();

//Server Loop
while (1) {
    usleep(500);

    //Handle Windows Service Request
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }
    //Acutal Server Code

}

//Clean up and Exit
win32_set_service_status(WIN32_SERVICE_STOPPED);
exit;

//*************** FUNCTIONS ***************
function ShowHelp(){
    echo "Usage:
    install:\t installs servce
    uninstall:\t deletes service
    start:\t\t Start the windows service
    stop:\t\t Stops the windows service
    run:\t\t called by CMS to run the service

For information on code numbers type 'net helpmsg xxxx'
EXAMPEL: 'net helpmsg 1072'

    ";
}
?>
m dot hald at surfto dot ch 12-May-2008 04:16
On my Machine (Win XP SP2) the function "win32_get_last_control_message" never returns 4 so i will have to reply to 0 also.

finally after mixing several examples i now have a version working woithout filling my event log with errors:

<?php

/*
 * PHP SAMPLE TEMPLATE
 */

/*
 * APP MAIN FUNCTION
 * Called each second after the function last time finished
 * Should not take longer than max 20 seconds to execute
 * ELSE you should call NTServiceResponder(); at least each 20 secs
 * WARNING: NTServiceResponder will exit; if there was a STOP request
 */
function Service_Main()
{
    // YOU APPLICATION CODE HERE !!!
    sleep(1); // dummy something
}

/********************************************************************
 *
 * SERVICE CONTROLLING
 *
 ********************************************************************/

$SERVICE_NAME = "phptestservice";
$SERVICE_DISPLAY = "Test Service with PHP";

// so u can get: $SERVICE_PATH_PARTS["dirname"] $SERVICE_PATH_PARTS["basename"]  $SERVICE_PATH_PARTS["extension"]
$SERVICE_PATH_PARTS = pathinfo(__FILE__);

$SERVICE_PARAMS = " run";

    if (!isset($argv[1]))
    {
        die("this application need to be installed as a service.\n run with param install");
    }

    if ($argv[1] == 'install')
    {
        $x = win32_create_service(array(
                                        'service' => $SERVICE_NAME,
                                        'display' => $SERVICE_DISPLAY,
                                        'params' =>  __FILE__ . $SERVICE_PARAMS,
                                        //'path' =>  $SERVICE_PATH_PARTS["dirname"] . '\php.exe'
                                        ));
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] == 'uninstall')
    {
        $x = win32_delete_service('dummyphp');
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] != 'run')
    {
        die("bogus args, needs to run as service");
    }

    // Connect to service dispatcher and notify that startup was successful
    if (!win32_start_service_ctrl_dispatcher($SERVICE_NAME)) die('Could not connect to service :'.$SERVICE_NAME);
    win32_set_service_status(WIN32_SERVICE_RUNNING);

    // Main Server Loop
    while (1)
    {
        NTServiceResponder();

        // Main script goes here
        Service_Main();

        sleep(1); // at least 1 sec delay per loop
    }
    win32_set_service_status(WIN32_SERVICE_STOPPED);

/*
 * Response to NTServiceRequests
 */
function NTServiceResponder()
{

    switch (win32_get_last_control_message())
    {
    case 0: // PATCH for: seems never to go to 4 (WIN32_SERVICE_CONTROL_INTERROGATE)
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE;
        break;
    case WIN32_SERVICE_CONTROL_CONTINUE:
        return TRUE; // "Continue"
    case WIN32_SERVICE_CONTROL_INTERROGATE:
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE; // Respond with status
    case WIN32_SERVICE_CONTROL_STOP:
        win32_set_service_status(WIN32_SERVICE_STOPPED);
        exit; // Terminate script
    default:
        win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    return FALSE;
}

?>


Registers the script with the SCM, so that it can act as the service with the given name

  • ? win32_set_service_status
  • win32_start_service ?
  • PHP Manual
  • win32service 函数
  • Registers the script with the SCM, so that it can act as the service with the given name

win32_start_service_ctrl_dispatcher

(PECL win32service >=0.1.0)

win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name

说明

win32_start_service_ctrl_dispatcher ( string $name , bool $gracefulMode = true ) : void

When launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.

Once started, the service process should do 2 things. The first is to tell the Service Control Manager that the service is running. This is achieved by calling win32_set_service_status() with the WIN32_SERVICE_RUNNING constant. If you need to perform some lengthy process before the service is actually running, then you can use the WIN32_SERVICE_START_PENDING constant. The second is to continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

name

The short-name of the service, as registered by win32_create_service().

gracefulMode

true for exit graceful. false for exit with error. See win32_set_service_exit_mode() for more details.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

范例

Example #1 A win32_start_service_ctrl_dispatcher() example

Check if the service is runnig under the SCM.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
  die("I'm probably not running under the service control manager");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Some lengthy process to get this service up and running.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
  # do some work here, trying not to take more than around 30 seconds
  # before coming back into the loop again
}
?>

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.4.0 | The parameter gracefulMode has been added.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

参见

  • win32_set_service_status() - Update the service status
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32 Error Codes

User Contributed Notes

andrea 09-Oct-2009 03:07
Insert value of params between " if the string have a space:

<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => '"c:\\my folder\myphpservice.php"',
    'path' => 'c:\\PHP\\php.exe'));
*/
?>
dylan at nopower dot org 14-Jul-2007 07:59
<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => 'c:\\myphpservice.php',
    'path' => 'c:\\PHP\\php.exe'));
*/

$myservicename = 'myphpservice';

// Connect to service dispatcher and notify that startup was successful
if (!win32_start_service_ctrl_dispatcher($myservicename)) die('Could not connect to service :'.$myservicename);
win32_set_service_status(WIN32_SERVICE_RUNNING);

// Main Server Loop
while (1) {
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    // Main script goes here

    sleep(10); // Run every 10 seconds
}
win32_set_service_status(WIN32_SERVICE_STOPPED);
?>
Guibod 10-Jul-2007 05:41
Don't try to call "win32_start_service_ctrl_dispatcher" too late in your code. You'd trigger a #2186 error : "The service is not responding to the control function." (from commande line) or a #1053 error : "The service did not respond to the start or control request in a timely fashion." (from services GUI).

Try not to load a bunch of PEAR classes before to register php script as Service like I did.

Another good hint, to get a verbose version of the return code, you can call "NET HELPMSG ###" from command line where ### is your error code.


Starts a service

  • ? win32_start_service_ctrl_dispatcher
  • win32_stop_service ?
  • PHP Manual
  • win32service 函数
  • Starts a service

win32_start_service

(PECL win32service >=0.1.0)

win32_start_service — Starts a service

说明

win32_start_service ( string $servicename , string $machine = ? ) : void

Attempts to start the named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Stops a service

  • ? win32_start_service
  • XML 操作 ?
  • PHP Manual
  • win32service 函数
  • Stops a service

win32_stop_service

(PECL win32service >=0.1.0)

win32_stop_service — Stops a service

说明

win32_stop_service ( string $servicename , string $machine = ? ) : void

Stops a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_start_service() - Starts a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


XML 操作

  • DOM — Document Object Model
    • 简介
    • 安装／配置
    • 预定义常量
    • 范例
    • DOMAttr — The DOMAttr class
    • DOMCdataSection — The DOMCdataSection class
    • DOMCharacterData — The DOMCharacterData class
    • DOMComment — The DOMComment class
    • DOMDocument — The DOMDocument class
    • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentType — The DOMDocumentType class
    • DOMElement — The DOMElement class
    • DOMEntity — The DOMEntity class
    • DOMEntityReference — The DOMEntityReference class
    • DOMException — The DOMException class
    • DOMImplementation — The DOMImplementation class
    • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNode — The DOMNode class
    • DOMNodeList — The DOMNodeList class
    • DOMNotation — The DOMNotation class
    • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMText — The DOMText class
    • DOMXPath — The DOMXPath class
    • DOM 函数
  • libxml
    • 简介
    • 安装／配置
    • 预定义常量
    • libXMLError — The libXMLError class
    • libxml 函数
  • SimpleXML
    • 简介
    • 安装／配置
    • 预定义常量
    • 范例
    • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLIterator — The SimpleXMLIterator class
    • SimpleXML 函数
  • WDDX
    • 简介
    • 安装／配置
    • 预定义常量
    • 范例
    • WDDX 函数
  • XMLDiff — XML diff and merge
    • 简介
    • 安装／配置
    • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\File — The XMLDiff\File class
  • XML 解析器
    • 简介
    • 安装／配置
    • 预定义常量
    • 事件处理器
    • Case Folding(大写转换)
    • 错误代码
    • 字符编码
    • 范例
    • XML 解析器函数
  • XMLReader
    • 简介
    • 安装／配置
    • XMLReader — The XMLReader class
  • XMLWriter
    • 简介
    • 安装／配置
    • 预定义常量
    • 范例
    • XMLWriter — The XMLWriter class
  • XSL
    • 简介
    • 安装／配置
    • 预定义常量
    • 范例
    • XSLTProcessor — The XSLTProcessor class

User Contributed Notes

There are no user contributed notes for this page.


Document Object Model

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
  • DOMAttr — The DOMAttr class
    • DOMAttr::__construct — Creates a new DOMAttr object
    • DOMAttr::isId — Checks if attribute is a defined ID
  • DOMCdataSection — The DOMCdataSection class
    • DOMCdataSection::__construct — Constructs a new DOMCdataSection object
  • DOMCharacterData — The DOMCharacterData class
    • DOMCharacterData::appendData — Append the string to the end of the character data of the node
    • DOMCharacterData::deleteData — Remove a range of characters from the node
    • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
    • DOMCharacterData::substringData — Extracts a range of data from the node
  • DOMComment — The DOMComment class
    • DOMComment::__construct — Creates a new DOMComment object
  • DOMDocument — The DOMDocument class
    • DOMDocument::__construct — Creates a new DOMDocument object
    • DOMDocument::createAttribute — Create new attribute
    • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection — Create new cdata node
    • DOMDocument::createComment — Create new comment node
    • DOMDocument::createDocumentFragment — Create new document fragment
    • DOMDocument::createElement — Create new element node
    • DOMDocument::createElementNS — Create new element node with an associated namespace
    • DOMDocument::createEntityReference — Create new entity reference node
    • DOMDocument::createProcessingInstruction — Creates new PI node
    • DOMDocument::createTextNode — Create new text node
    • DOMDocument::getElementById — Searches for an element with a certain id
    • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode — Import node into current document
    • DOMDocument::load — Load XML from a file
    • DOMDocument::loadHTML — Load HTML from a string
    • DOMDocument::loadHTMLFile — Load HTML from a file
    • DOMDocument::loadXML — Load XML from a string
    • DOMDocument::normalizeDocument — Normalizes the document
    • DOMDocument::registerNodeClass — Register extended class used to create base node type
    • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
    • DOMDocument::save — Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML — Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.
    • DOMDocument::schemaValidateSource — Validates a document based on a schema
    • DOMDocument::validate — Validates the document based on its DTD
    • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object
  • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentFragment::appendXML — Append raw XML data
  • DOMDocumentType — The DOMDocumentType class
  • DOMElement — The DOMElement class
    • DOMElement::__construct — Creates a new DOMElement object
    • DOMElement::getAttribute — Returns value of attribute
    • DOMElement::getAttributeNode — Returns attribute node
    • DOMElement::getAttributeNodeNS — Returns attribute node
    • DOMElement::getAttributeNS — Returns value of attribute
    • DOMElement::getElementsByTagName — Gets elements by tagname
    • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
    • DOMElement::hasAttribute — Checks to see if attribute exists
    • DOMElement::hasAttributeNS — Checks to see if attribute exists
    • DOMElement::removeAttribute — Removes attribute
    • DOMElement::removeAttributeNode — Removes attribute
    • DOMElement::removeAttributeNS — Removes attribute
    • DOMElement::setAttribute — Adds new attribute
    • DOMElement::setAttributeNode — Adds new attribute node to element
    • DOMElement::setAttributeNodeNS — Adds new attribute node to element
    • DOMElement::setAttributeNS — Adds new attribute
    • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
  • DOMEntity — The DOMEntity class
  • DOMEntityReference — The DOMEntityReference class
    • DOMEntityReference::__construct — Creates a new DOMEntityReference object
  • DOMException — The DOMException class
  • DOMImplementation — The DOMImplementation class
    • DOMImplementation::__construct — Creates a new DOMImplementation object
    • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature
  • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNamedNodeMap::count — Get number of nodes in the map
    • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item — Retrieves a node specified by index
  • DOMNode — The DOMNode class
    • DOMNode::appendChild — Adds new child at the end of the children
    • DOMNode::C14N — Canonicalize nodes to a string
    • DOMNode::C14NFile — Canonicalize nodes to a file
    • DOMNode::cloneNode — Clones a node
    • DOMNode::getLineNo — Get line number for a node
    • DOMNode::getNodePath — Get an XPath for a node
    • DOMNode::hasAttributes — Checks if node has attributes
    • DOMNode::hasChildNodes — Checks if node has children
    • DOMNode::insertBefore — Adds a new child before a reference node
    • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isSameNode — Indicates if two nodes are the same node
    • DOMNode::isSupported — Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceUri — Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize — Normalizes the node
    • DOMNode::removeChild — Removes child from list of children
    • DOMNode::replaceChild — Replaces a child
  • DOMNodeList — The DOMNodeList class
    • DOMNodeList::count — Get number of nodes in the list
    • DOMNodeList::item — Retrieves a node specified by index
  • DOMNotation — The DOMNotation class
  • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object
  • DOMText — The DOMText class
    • DOMText::__construct — Creates a new DOMText object
    • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
    • DOMText::splitText — Breaks this node into two nodes at the specified offset
  • DOMXPath — The DOMXPath class
    • DOMXPath::__construct — Creates a new DOMXPath object
    • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query — Evaluates the given XPath expression
    • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions
  • DOM 函数
    • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

User Contributed Notes

chealer at gmail dot com 05-Jul-2018 05:12
This extension allows editing an HTML snippet, for example removing an element:
??$dom = new DOMDocument();
??$dom->loadHTML('keep<b id="simple">REMOVE</b>');
$??remove = $dom->getElementById('simple');
??$dom->removeChild($??remove);
echo ??$dom->saveHTML();
...would output "keep".

But it does not preserve formatting. If your code defines attributes using double quotes, saveHTML() may for instance return single quotes instead.
emmanuellutula at hotmail dot com 24-Apr-2018 04:35
If you want to  use DOMDocument in your PHPUnit Tests drive on Symfony Controller (testing form)! Use like :

namespace Tests\YourBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use YourBundle\Controller\TextController;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient(array(), array());

        $crawler = $client->request('GET', '/text/add');
        $this->assertTrue($crawler->filter("form")->count() > 0, "Text form exist !");

        $form = $crawler->filter("form")->form();

        $domDocument = new \DOMDocument;

        $domInput = $domDocument->createElement('input');
        $dom = $domDocument->appendChild($domInput);
        $dom->setAttribute('slug', 'bloc');

        $formInput = new \Symfony\Component\DomCrawler\Field\InputFormField($domInput);
        $form->set($formInput);

        $crawler = $client->submit($form);

        if ($client->getResponse()->isRedirect())
        {
            $crawler = $client->followRedirect(false);
        }

       // $this->assertTrue($client->getResponse()->isSuccessful());
        //$this->assertEquals(200, $client->getResponse()->getStatusCode(),
        //             "Unexpected HTTP status code for GET /backoffice/login");

    }
}
ohcc at 163 dot com 29-Oct-2015 05:31
<?php
    // this note is about how to get a DOMNode's outerHTML and innerHTML.
    $dom = new DOMDocument('1.0','UTF-8');
    $dom->loadHTML('<html><body><div><p>p1</p><p>p2</p></div></body></html>');
    $node = $dom->getElementsByTagName('div')->item(0);
    $outerHTML = $node->ownerDocument->saveHTML($node);
    $innerHTML = '';
    foreach ($node->childNodes as $childNode){
        $innerHTML .= $childNode->ownerDocument->saveHTML($childNode);
    }
    echo '<h2>outerHTML: </h2>';
    echo htmlspecialchars($outerHTML);
    echo '<h2>innerHTML: </h2>';
    echo htmlspecialchars($innerHTML);
?>
super dot puma at gmail dot com 13-May-2014 04:57
If  you want to print the DOM XML file content, you can use the next code:

$doc = new DOMDocument();
$doc->load($xmlFileName);
echo "<br>" . $doc->documentURI;
$x = $doc->documentElement;
getNodeContent($x->childNodes, 0);

function getNodeContent($nodes, $level){
    foreach ($nodes AS $item) {
    //  print "<br><br>TIPO: " . $item->nodeType ;
      printValues($item, $level);
      if ($item->nodeType == 1) { //DOMElement
          foreach ($item->attributes AS $itemAtt) {
              printValues($itemAtt, $level+3);
          }
          if($item->childNodes || $item->childNodes->lenth > 0) {
              getNodeContent($item->childNodes, $level+5);
          }
      }
    }
}

function printValues($item, $level){
    if ($item->nodeType == 1) { //DOMElement
        printLevel($level);
        print $item->nodeName . " = " . $item->nodeValue;
    }
    if ($item->nodeType == 2) { //DOMAttr
        printLevel($level);
        print $item->name . " = " . $item->value ;
    }
    if ($item->nodeType == 3) { //DOMText
      if ($item->isWhitespaceInElementContent() == false){
        printLevel($level);
        print $item->wholeText ;
      }
    }
}

function printLevel($level)
{
    print "<br>";
    if ($level == 0) {
        print "<br>";
    }
    for($i=0; $i < $level; $i++) {
        print "-";
    }
}
Drupella 16-Sep-2011 09:18
Here is a fast innerHTML function that returns the result without iterating over child nodes.

<?php
function innerHTML($el) {
  $doc = new DOMDocument();
  $doc->appendChild($doc->importNode($el, TRUE));
  $html = trim($doc->saveHTML());
  $tag = $el->nodeName;
  return preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>$@', '', $html);
}
?>

Example
<?php
$doc = new DOMDocument();
// A corrupt HTML string
$doc->loadHTML('<HTML><A HREF="ss">asd</A>');
$body = $doc->getElementsByTagName('body')->item(0);
print htmlspecialchars(innerHTML($body));
// Prints <a href="ss">asd</a>
?>
ben_demott at hotmail dot com 23-Apr-2010 01:36
A function among several others to parse a google results page, I wrote this some time ago - google has probably changed their site since then, but I thought this might be helpful to someone.

I'm moving servers, but I will probably throw this up on my blog when I get it back up.

<?php

function googleResult($listItem) {
    // given a LIST ITEM element, this will validate, and return an array for that LI entry as an inline result from google.
    /*
     * <li class='g w0'>
     *   <h3 class='r'>
     *     <a href='the URL' class='l'>
     *       Description <em>description</em>
     *     </a>
     *   </h3>
     * </li>
     *
       UPDATE:
       This function will now look for any subcontainer that has an href, it doesn't have to be an H3
       this will make it work with a few more formatted search results.
     */

    $listItem = $listItem->childNodes;
        // Yes I don't use instanceof - I guess you'll have to deal.
    foreach($listItem as $element) {
        if(is_object($element) && get_class($element) == 'DOMElement' && $element->hasChildNodes()) {
            $hrefContainer = $element->childNodes;
            foreach($hrefContainer as $element2) {
                if(is_object($element2) && get_class($element2) == 'DOMElement' && $element2->nodeName == 'a' && $element2->hasAttribute('href')) {
                    $anchor = $element2;
                    unset($h3);
                    unset($element2);
                    break;
                } else {
                  //print __LINE__ ." :: Breaking out of loop (normal result) element is not an annchor Element='".$element2->nodeName."'\n";
                }
            }
            unset($element);
            unset($listItem);
            break;
        }
    }
    if(empty($anchor) || !is_object($anchor) || get_class($anchor) != 'DOMElement') {
        //print __LINE__ ." :: Returning false, did not locate anchor through iteration...";
        return false;
    }
    $href = $anchor->getAttribute('href');
    if(empty($href)) {
        //print __LINE__ ." :: Found anchor object, could not read href attribute / href is empty? href='$href'\n";
        return false;
    }
    $description = $anchor->childNodes;
    $urlDescription = '';
    foreach($description as $words) {
        $name =  trim($words->nodeName);
        if($name == 'em' || $name == '#text' || $name == 'b') {
            if(!empty($words->nodeValue)) {
                $text = trim($words->nodeValue);
                $urlDescription = $urlDescription . $text . ' ';
            }
        }
    }
    $urlDescription = htmlspecialchars_decode($urlDescription, ENT_QUOTES);
    $urlDescription = trim($urlDescription);
    return array('description' => $urlDescription, 'href' => $href);
}
sweisman at pobox dot com 24-Sep-2009 01:19
I had problems with the dom2array_full function by "nospam at ya dot ru". Here's my function, which works correctly for my project, and might work for yours:

<?php
function dom_to_array($root)
{
    $result = array();

    if ($root->hasAttributes())
    {
        $attrs = $root->attributes;

        foreach ($attrs as $i => $attr)
            $result[$attr->name] = $attr->value;
    }

    $children = $root->childNodes;

    if ($children->length == 1)
    {
        $child = $children->item(0);

        if ($child->nodeType == XML_TEXT_NODE)
        {
            $result['_value'] = $child->nodeValue;

            if (count($result) == 1)
                return $result['_value'];
            else
                return $result;
        }
    }

    $group = array();

    for($i = 0; $i < $children->length; $i++)
    {
        $child = $children->item($i);

        if (!isset($result[$child->nodeName]))
            $result[$child->nodeName] = dom_to_array($child);
        else
        {
            if (!isset($group[$child->nodeName]))
            {
                $tmp = $result[$child->nodeName];
                $result[$child->nodeName] = array($tmp);
                $group[$child->nodeName] = 1;
            }

            $result[$child->nodeName][] = dom_to_array($child);
        }
    }

    return $result;
}
?>
odessa131 at aol dot nospam dot com 20-Sep-2009 06:49
I had the hardest time updating a complex XML document. Here's a quick example on how to do it.

<?php

// Load the XML from a file.
$xml = "a2062.xml"; // This is an XFDL form previously unencoded and ungzipped.
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->Load($xml);

// Create an XPath query.
// Note: you must define the namespace if the XML document has defined namespaces.
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xfdl', "http://www.PureEdge.com/XFDL/6.5");

// Locate the value for the first Item Description field.
$query = "//xfdl:page/xfdl:field[@sid='ITEMDESA']/xfdl:value";
$nodeList = $xpath->query($query);

$nodeList->item(0)->nodeValue = "This is the text in the value node of the first Item Description field inside the DA 2062 PureEdge form.";

$dom->save($xml);

?>

I hope this helps someone.
philipwaynerollins at gmail dot com 29-Jul-2009 02:06
You can get the "innerHTML" by nodeValue so

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p', 'Sensei Ninja' );
    print $ele->nodeValue;
?>

You can even set it if you want

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p' );
    $ele->nodeValue = 'Sensei Ninja';
    $doc->appendChild( $ele );
    print $doc->saveHTML( );
?>
Junior 20-Mar-2009 01:26
innerHTML in PHP DOM

<?php
function DOMinnerHTML($element)
{
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $tmp_dom = new DOMDocument();
        $tmp_dom->appendChild($tmp_dom->importNode($child, true));
        $innerHTML.=trim($tmp_dom->saveHTML());
    }
    return $innerHTML;
}
?>

Example:

<?php
$dom= new DOMDocument();
$dom->load($html_string);
$dom->preserveWhiteSpace = false;

$domTable = $dom->getElementsByTagName("table");

foreach ($domTable as $tables)
{
    echo DOMinnerHTML($tables);
}
?>
nospam at ya dot ru 06-Jan-2009 10:18
<?PHP
function dom2array_full($node){
    $result = array();
    if($node->nodeType == XML_TEXT_NODE) {
        $result = $node->nodeValue;
    }
    else {
        if($node->hasAttributes()) {
            $attributes = $node->attributes;
            if(!is_null($attributes))
                foreach ($attributes as $index=>$attr)
                    $result[$attr->name] = $attr->value;
        }
        if($node->hasChildNodes()){
            $children = $node->childNodes;
            for($i=0;$i<$children->length;$i++) {
                $child = $children->item($i);
                if($child->nodeName != '#text')
                if(!isset($result[$child->nodeName]))
                    $result[$child->nodeName] = dom2array($child);
                else {
                    $aux = $result[$child->nodeName];
                    $result[$child->nodeName] = array( $aux );
                    $result[$child->nodeName][] = dom2array($child);
                }
            }
        }
    }
    return $result;
}
?>
fantasyman3000 at gmail dot com 06-Dec-2008 05:37
In response to "simlee at indiana dot edu",
- First of all thanks for sharing your funciton.
- It didn't work for me so i rewrite it from scratch using different method.

Here is the new version, hope it helps someone :

<?php
/**
* result sample : /html[1]/body[1]/span[1]/fieldset[1]/div[1]
* @return string
*/
function getNodeXPath( $node ) {
    $result='';
    while ($parentNode = $node->parentNode) {
        $nodeIndex=-1;
        $nodeTagIndex=0;
        do {
            $nodeIndex++;
            $testNode = $parentNode->childNodes->item( $nodeIndex );

            if ($testNode->nodeName==$node->nodeName and $testNode->parentNode->isSameNode($node->parentNode) and $testNode->childNodes->length>0) {
                //echo "{$testNode->parentNode->nodeName}-{$testNode->nodeName}-{}<br/>";
                $nodeTagIndex++;
            }

        } while (!$node->isSameNode($testNode));

        $result="/{$node->nodeName}[{$nodeTagIndex}]".$result;
        $node=$parentNode;
    };
    return $result;
}
?>

By Sina.Salek.ws
miguelangelhdz at NOSPAM dot com 22-Sep-2008 06:19
After searching how to extend the DOMDocument and DOMElement I found a way in the bug: http://bugs.php.net/bug.php?id=35104. The following code shows how:

<?php
class extDOMDocument extends DOMDocument {
 public function createElement($name, $value=null) {
  $orphan = new extDOMElement($name, $value); // new  sub-class object
  $docFragment = $this->createDocumentFragment(); // lightweight container maintains "ownerDocument"
  $docFragment->appendChild($orphan); // attach
  $ret = $docFragment->removeChild($orphan); // remove
  return $ret; // ownerDocument set; won't be destroyed on  method exit
 }
 // .. more class definition
}

class extDOMElement extends DOMElement {
 function __construct($name, $value='', $namespaceURI=null) {
  parent::__construct($name, $value, $namespaceURI);
 }
  //  ... more class definition here
}

$doc = new extDOMDocument('test');
$el = $doc->createElement('tagname');
$el->setAttribute("attr", "val");
$doc->appendChild($el);

// append discards the DOMDocumentFragment and just adds its child nodes, but ownerDocument is maintained.
echo get_class($el)."<br/>";
echo get_class($doc->documentElement)."<br/>";
echo "<xmp>".$doc->saveXML()."</xmp>";
?>
tobiasz.cudnik[at]gmail.com 29-Jul-2008 06:47
If you need simple interface to DOM check out phpQuery - jQuery port to PHP:
http://code.google.com/p/phpquery/

It uses CSS selectors to fetch nodes.
Here's example how it works:
<?php
// just one file to include
require('phpQuery/phpQuery.php');

$html = '
<div>
    mydiv
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
</div>';

// intialize new DOM from markup
phpQuery::newDocument($markup)
    ->find('ul > li')
        ->addClass('my-new-class')
        ->filter(':last')
            ->addClass('last-li');

// query all unordered lists in last used DOM
pq('ul')->insertAfter('div');

// iterate all LIs from last used DOM
foreach(pq('li') as $li) {
    // iteration returns plain DOM nodes, not phpQuery objects
    pq($li)->addClass('my-second-new-class');
}

// same as pq('anything')->htmlOuter()
// but on document root (returns doctype etc)
print phpQuery::getDocument();
?>

It uses DOM extension and XPath so it works only in PHP5.
Sven Arduwie 16-Mar-2008 06:28
I needed a function that quickly converts an xml with key/value pairs to an array.

for example:
<?xml version="1.0" encoding="UTF-8"?>
<test>
    <key id="Array key #1" value="Value #1"/>
    <key id="Array key #2" value="Value #2"/>
    <key id="Dupe" value="Duplicate keys"/>
    <key id="Dupe" value="create numeric arrays"/>
    <key id="And another key">
        <![CDATA[
            Multiline
            data
            works
            just
            as
            well.
        ]]>
    </key>
    <nested>
        <key id="Nested key" value="Nested data works as well, but it still results in a 1 dimensional array."/>
    </nested>
</test>

Results in the following array:
array(5) {
  ["Array key #1"]=>
  string(8) "Value #1"
  ["Array key #2"]=>
  string(8) "Value #2"
  ["Dupe"]=>
  array(2) {
    [0]=>
    string(14) "Duplicate keys"
    [1]=>
    string(21) "create numeric arrays"
  }
  ["And another key"]=>
  string(49) "Multiline
            data
            works
            just
            as
            well."
  ["Nested key"]=>
  string(73) "Nested data works as well, but it still results in a 1 dimensional array."
}

Here's the code:
<?php
    function xml2array($xml) {
        $domDocument = new DOMDocument;
        $domDocument->loadXML($xml);
        $domXPath = new DOMXPath($domDocument);
        $array = array();
        foreach ($domXPath->query('//key') as $keyDOM) {
            $id = $keyDOM->getAttribute('id');
            $value = $keyDOM->hasAttribute('value') ? $keyDOM->getAttribute('value') : trim($keyDOM->textContent);
            if (array_key_exists($id, $array)) {
                if (is_array($array[$id])) {
                    $array[$id][] = $value;
                } else {
                    $array[$id] = array($array[$id]);
                    $array[$id][] = $value;
                }
            } else {
                $array[$id] = $value;
            }
        }
        return $array;
    }
?>
danf dot 1979 at []gmail[] dot com 24-Feb-2008 07:47
This is a couple of classes to deal with yahoo yui menu.

/*
  $menubar = new MenuBar();

  $file = new Menu("File");
  $file->setAttribute("href", "http://file.com");

  $quit = new Menu("Quit");
  $quit->setAttribute("href", "http://quit.com");

  $file->appendChild($quit);
  $menubar->appendChild($file);

  echo $menubar->grab();
*/

//
// Author: Daniel Queirolo.
// LGPL
//

/** ---------------------------------
/**  Class MenuBar()
/**  Creates a the menubar and appends
/**  yuimenubaritems to it.
/** ---------------------------------*/

class MenuBar extends DOMDocument
{

  public $menuID = "nav_menu";  // holds the css id that javascript yui menu code should have to recognize
  private $UL;                  // This node holds every menu, This is THE node.

  /** ---------------------------------
  /**  Constructor
  /**  Generates a menubar skeleton and the UL node
  /** ---------------------------------*/

  public function __construct() {

    parent::__construct();

    $rootdiv = parent::createElement("div");
    $rootdiv->setAttribute("class", "yui-skin-sam");

    parent::appendChild($rootdiv);

    $yui_menubar = parent::createElement("div");
    $yui_menubar->setAttribute("id", $this->menuID);
    $yui_menubar->setAttribute("class", "yuimenubar");

    $rootdiv->appendChild($yui_menubar);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yui_menubar->appendChild($bd);

    $ul = parent::createElement("ul");
    $ul->setAttribute("class", "first-of-type");

    // ALL Menu() instances ocurr inside an <ul> tag.

    $this->UL = $bd->appendChild($ul);

  }

  /** ---------------------------------
  /**  appendChild()
  /**  Appends a new yuimenubaritem to the menubar UL node.
  /**  This function changes <li> and <a> classes to yuiMENUBARsomething
  /** ---------------------------------*/

  public function appendChild($child) {

    $li = parent::importNode($child->LI, true);

    $li->setAttribute("class", "yuimenubaritem");

    $li->getElementsByTagName("a")->item(0)->setAttribute("class", "yuimenubaritemlabel");

    $this->UL->appendChild($li);

  }

  public function grab() {

    return parent::saveHTML();

  }

}

/** ---------------------------------
/**  Class Menu()
/**  Creates a yuimenuitem li node
/** ---------------------------------*/

class Menu extends DOMDocument {

  public $LI; // stores the <li> node (THE link) that will be exported to MenuBar() or used on appendChild()

  /** ---------------------------------
  /**  Constructor
  /**  Generates a yuimenuitem li node
  /**  No yuimenubar items are created here. MenuBar handles that.
  /** ---------------------------------*/

  public function __construct($link_name) {

    parent::__construct();

    $li = parent::createElement("li");
    $li->setAttribute("class", "yuimenuitem");

    // LI node stores THE link.
    // if appendChild is used, the new (sub) Menu() would be LI node child.

    $this->LI = parent::appendChild($li);

    $a = parent::createElement("a", $link_name);
    $a->setAttribute("class", "yuimenuitemlabel");

    $li->appendChild($a);

    $this->li = $li;
    $this->a = $a;

  }

  /** ---------------------------------
  /**  appendChild
  /**  Appends a (sub) Menu() to current Menu() in LI
  /** ---------------------------------*/

  public function appendChild($child) {

    $yuimenu = parent::createElement("div");
    $yuimenu->setAttribute("class", "yuimenu");

    $this->LI->appendChild($yuimenu);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yuimenu->appendChild($bd);

    $ul = parent::createElement("ul");

    $bd->appendChild($ul);

    // child->NODE holds THE link from the new child (from child's __construct())

    $ul->appendChild(parent::importNode($child->LI, true));

  }

  public function setAttribute($name, $value, $node="a") {

      if ($node == "a") {
        $this->a->setAttribute($name, $value);
      }

      else {
        $this->li->setAttribute($name, $value);
      }
  }

}
Anonymous 29-Jan-2008 11:37
In response to...
"If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement."

... it is not a bug, it is a feature. The DOMDocument::$documentElement property name may be misleading but according to the DOM Level 2 Core specification it is a convenience attribute meant to access the root element of your DOMDocument. See here: http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document
ryoroxdahouse at hotmail dot com 25-Jan-2008 12:14
I use DOM to generate dynamically XHTML document.

When trying to extend the DOMDocument and DOMElement classes, I found a very annoying bug concerning DOMDocument::$documentElement.

If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement.

In my situation, I cannot use DOMDocument::registerNodeClass() because the document element is not necessarily the base class for all the elements in my document.

*******
problem
*******

See bellow for the repro step:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $myDocument->appendChild(new MyElement('myElement','myElement'));
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

Notice: Undefined property: DOMElement::$myProp in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 11
$myElement->myProp :

Fatal error: Call to undefined method DOMElement::myMethod() in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 12

*******
solution
*******

After searching around, I found a pretty odd way to fix this problem. It seems that you have to stock a reference to your appended document element in an user-defined (and persistent) variable (in other words, not only in DOMDocument::$documentElement). See below:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $mydocumentElement=$myDocument->appendChild(new MyElement('myElement','myElement')); //here is the hack
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

$myElement->myProp :myProp
$myElement->myMethod :myMethod()

Hope it will help.
naudyj at aus3d.com 03-Jan-2008 05:06
The following can take a XML_TEXT_NODE node and return the contents in an array. Yanick's contribution rocks - but
it overwrote with duplicates only keeping the last line
in the returned array. All the other functions i tested from various sources failed to handle text nodes correctly. Hope this helps someone. It is adapted from code on this site.

function myTextNode($n, &$a)
{
 static $depth = 0;
 static $sz = '';

 if ($cn = $n->firstChild)
 {
  while ($cn)
  {
   if ($cn->nodeType == XML_TEXT_NODE)
   {
    $sz .= $cn->nodeValue;
   }
   elseif ($cn->nodeType == XML_ELEMENT_NODE)
   {
    $b = 1;
    if ($cn->hasChildNodes())
    {
     $depth++;
     if ($this->myHeadings($cn, $a))
     {
      if ($sz){
       array_push($a, $sz);
       $sz = '';
      }
     }
     $depth--;
    }
   }
   $cn = $cn->nextSibling;
  }
  return $b;
 }
}

so you could use:

$nodes = $dom->getElementsByTagName("td");
if($nodes){
 foreach ($nodes as $node){
  $a = Array();
  myTextNode($node, $a);
 }
}
jim.filter (at gmail.com) 03-Nov-2007 07:42
Array to DOM

Here is a recursive function to turn a multidimensional array into an XML document.  It will handle multiple elements of the same tag, but only one per parent element. IE:

Can't generate:         Can generate:
<root>                  <root>
  <sub1>data1</sub1>      <subs1>
  <sub1>data2</sub1>         <value>data1</value>
  <sub2>data1</sub2>         <value>data2</value>
  <sub2>data2</sub2>      </subs1>
</root>                   <subs2>
                            <value>data1</value>
                            <value>data2</value>
                          <subs2>
                        </root>

Also, the function performs no type of error checking on your array and will throw a DOMException if a key value you used in your array contains invalid characters for a proper DOM tag. This function is untested for "deep" multidimensional arrays.

Complete code ready to run with example:

<?PHP
  function AtoX($array, $DOM=null, $root=null){

    if($DOM  == null){$DOM  = new DOMDocument('1.0', 'iso-8859-1');}
    if($root == null){$root = $DOM->appendChild($DOM->createElement('root'));}

    $name = $array['#MULTIPLE_ELEMENT_NAME'];

      foreach($array as $key => $value){
        if(is_int($key) && $name != null){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($name));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($name, $value));
          }
        }
        else if(is_string($key) && $key != '#MULTIPLE_ELEMENT_NAME'){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($key));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($key, $value));
          }
        }
      }
    return $DOM;
  }

  $array = array(
                    '#MULTIPLE_ELEMENT_NAME' => 'GenericDatas',
                    'Date'      => 'November 03, 2007',
                    'Company'   => 'Facility One',
                    'Field'     => 'Facility Management Software',
                    'Employees' => array(
                                      '#MULTIPLE_ELEMENT_NAME' => 'Employee',
                                      'Cindy',
                                      'Sean',
                                      'Joe',
                                      'Owen',
                                      'Jim',
                                      'Dale',
                                      'Kelly',
                                      'Ryan',
                                      'Johnathan',
                                      'Robin',
                                      'William Marcus',
                                      'NewCoops' => array(
                                                          '#MULTIPLE_ELEMENT_NAME' => 'Coop',
                                                          'John',
                                                          'Tyler',
                                                          'Ray',
                                                          'Dawn'
                                                         )
                                    ),
                    'Datas',
                    'DATAS',
                    'OtherDatas'
                );

  $DOM  = new DOMDocument('1.0', 'iso-8859-1');
  $root = $DOM->appendChild($DOM->createElement('CompanyData'));
  $DOM  = AtoX($array, $DOM, $root);
  $DOM->save('C:\test.xml');
?>
PHPdeveloper 06-Sep-2007 02:46
The Yanik's dom2array() function (added on 14-Mar-2007 08:40) does not handle multiple nodes with the same name, i.e.:

<foo>
  <name>aa</name>
  <name>bb</name>
</foo>

It will overwrite former and your array will contain just the last one ("bb")
Francois Hill 01-Aug-2007 11:21
In response to lutfi at smartconsultant dot us :

(see my post on
http://fr2.php.net/manual/en/
function.dom-domdocument-getelementsbytagname.php
)

Use this class I wrote:

class XPathableNode extends DOMNode
{
    protected $Node;
    protected $DOMDocument_from_node;
    protected $DOMXpath_for_node;

    public function __construct(/* DOMNode */ $node)
    {
        $this->Node=$node;
        $this->DOMDocument_from_node=new
                                                          DomDocument();
        $domNode=$this->DOMDocument_from_node
                                  ->importNode($this->Node, true);
        $this->DOMDocument_from_node
                                 ->appendChild($domNode);
        $this->DomXpath_for_node =
                    new Domxpath($this->
                                         DOMDocument_from_node);
    }

    public function convertHTML()
    {    return $this->DOMDocument_from_node
                                                             ->saveHTML();
    }

    public /*DomNodeList*/ function applyXpath($xpath)
    {    return $this->DomXpath_for_node
                                                       ->query($xpath);
    }
}

(sorry for the display... What a terrible hinderance on the
part of php.net !)

Then :
Make a new XPathableNode out of your parent node.
You may then retrieve a DOMNodeList from it by applying a
xpath (thus being able to specify the depth  and name of
elements you want).

Has got me around some (of the many) DOM awkwardnesses a few times.

;o)
Sanados at failure dot at 05-Jun-2007 02:45
appended to
brian dot reynolds at risaris dot com
20-Feb-2007 10:09

when you got variable nodes at start you array fails and looses nodes  beneath.
solution that counts occurance though eats up performance:

function xmlToArray($n)
{
    $xml_array = array();
    $occurance = array();

     foreach($n->childNodes as $nc)
     {
         $occurance[$nc->nodeName]++;
     }

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() )
        {
            if($occurance[$nc->nodeName] > 1)
            {
                $xml_array[$nc->nodeName][] = xmlToArray($nc);
            }
            else
            {
                $xml_array[$nc->nodeName] = xmlToArray($nc);
            }
        }
        else
        {
            return utf8_decode($nc->nodeValue);
        }
    }
    return $xml_array;
}
Yanik <clonyara(at)ahoo(dot)com> 13-Mar-2007 11:40
I hate DOM model !
so I wrote dom2array simple function (simple for use):

function dom2array($node) {
  $res = array();
  print $node->nodeType.'<br/>';
  if($node->nodeType == XML_TEXT_NODE){
      $res = $node->nodeValue;
  }
  else{
      if($node->hasAttributes()){
          $attributes = $node->attributes;
          if(!is_null($attributes)){
              $res['@attributes'] = array();
              foreach ($attributes as $index=>$attr) {
                  $res['@attributes'][$attr->name] = $attr->value;
              }
          }
      }
      if($node->hasChildNodes()){
          $children = $node->childNodes;
          for($i=0;$i<$children->length;$i++){
              $child = $children->item($i);
              $res[$child->nodeName] = dom2array($child);
          }
      }
  }
  return $res;
}
Nevyn at N dot O dot S dot P dot A dot M dot emai dot it 10-Mar-2007 07:35
I wrote a couple of functions to:
 - create a DOMDocument from a file
 - parse the namespaces in it
 - create a XPath object with all the namespaces registered
 - load the schemalocations
 - validate the file on the main schema (the one without prefix)

It is useful for me, see if it is also for someone else!!

Giulio

function decodeNode($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<((?:\\w*:)?\\w*)". //the tag name
    "[\\s\n\r]*((?:[\\s\n\r]*".
    "(?:\\w*:)?\\w+[\\s\n\r]*=[\\s\n\r]*". //possible attribute name
    "(?:\"[^\"]*\"|\'[^\']*\'))*)". //attribute value
    "[\\s\n\r]*>[\r\n]*".
    "((?:.*[\r\n]*)*)". //content
    "[\r\n]*</\\1>$}"; //closing tag
    preg_match($re, $out, $mat);
    return $mat;
}

function innerXml($node)
{
    $mat = decodeNode($node);
    return $mat[3];
}

function getnodeAttributes($node)
{
    $mat = decodeNode($node);
    $txt = $mat[2];
    $re = "{((?:\\w*:)?\\w+)[\\s\n\r]*=[\\s\n\r]*(\"[^\"]*\"|\'[^\']*\')}";
    preg_match_all($re, $txt, $mat);
    $att = array();
    for ($i=0; $i<count($mat[0]); $i++)
    {
        $value = $mat[2][$i];
        if ($value[0] == "\'" || $value[0] == "\"")
        {
            $len = strlen($value);
            $value = substr($value, 1, strlen($value)-2);
        }
        $att[ $mat[1][$i] ] = $value;
    }
    return $att;
}

function loadXml($file)
{
    $doc = new DOMDocument();
    $doc->load($file);
    //cerca l'attributo xmlns
    $xsi = false;
    $doc->namespaces = array();
    $doc->xpath = new DOMXPath($doc);

    $attr = getnodeAttributes($doc->documentElement);
    foreach ($attr as $name => $value)
    {
        if (substr($name,0,5) == "xmlns")
        {
            $uri = $value;
            $pre = $doc->documentElement->lookupPrefix($uri);
            if ($uri == "http://www.w3.org/2001/XMLSchema-instance")
                $xsi = $pre;
            $doc->namespaces[$pre] = $uri;
            if ($pre == "")
                $pre = "noname";
            $doc->xpath->registerNamespace($pre, $uri);
        }
    }

    if ($xsi)
    {
        $doc->schemaLocations = array();
        $lst = $doc->xpath->query("//@$xsi:schemaLocation");
        foreach($lst as $el)
        {
            $re = "{[\\s\n\r]*([^\\s\n\r]+)[\\s\n\r]*([^\\s\n\r]+)}";
            preg_match_all($re, $el->nodeValue, $mat);
            for ($i=0; $i<count($mat[0]); $i++)
            {
                $value = $mat[2][$i];
                $doc->schemaLocations[ $mat[1][$i] ] = $value;
            }
        }

        $olddir = getcwd();
        chdir(dirname($file));
        $schema = $doc->schemaLocations[$doc->namespaces[""]];
        if (substr($schema,0,7) == "file://")
        {
            $schema = substr($value,7);
        }
        if (!$doc->schemaValidate($schema))
            dbg()->err("Invalid file");
        chdir($olddir);
    }

    return $doc;
}
brian dot reynolds at risaris dot com 20-Feb-2007 01:09
I found the xml2array function below very useful, but there seems to be a bug in it. The $item variable was never getting set. I've expanded this out to be a bit more readable, and the corrected code is :

function xmlToArray($n)
{
    $return=array();

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() ){
            if( $n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1){
                $item = $n->firstChild;
                $return[$nc->nodeName][]=$this->xmlToArray($item);
            }
            else{
                 $return[$nc->nodeName]=$this->xmlToArray($nc);
            }
       }
       else{
           $return=$nc->nodeValue;
       }
    }
    return $return;
}
cooper at asu dot ntu-kpi dot kiev dot ua 22-Nov-2006 02:32
If you are using not object-oriented functions and it takes too much time to change them all (or you'll be replacing them later) then as a temporary decision can be used this modules:

For DOM XML:
http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/

For XSLT:
http://alexandre.alapetite.net/doc-alex/xslt-php4-php5/
sean at lookin3d dot com 17-Aug-2006 10:21
$xmlDoc=<<<XML
<?xml version="1.0"?>
<methodCall>
   <methodName>examples.getStateName</methodName>
   <params>
      <param>
         <value><i4>41</i4></value>
         </param>
      </params>
   </methodCall>
XML;

$xml= new DOMDocument();
$xml->preserveWhiteSpace=false;
$xml->loadXML($xmlDoc);
print_r(xml2array($xml));

function xml2array($n)
{
    $return=array();
    foreach($n->childNodes as $nc)
    ($nc->hasChildNodes())
    ?($n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1)
    ?$return[$nc->nodeName][]=xml2array($item)
    :$return[$nc->nodeName]=xml2array($nc)
    :$return=$nc->nodeValue;
    return $return;
}
simlee at indiana dot edu 29-Dec-2005 12:16
The project I'm currently working on uses XPaths to dynamically navigate through chunks of an XML file.  I couldn't find any PHP code on the net that would build the XPath to a node for me, so I wrote my own function.  Turns out it wasn't as hard as I thought it might be (yay recursion), though it does entail using some PHP shenanigans...

Hopefully it'll save someone else the trouble of reinventing this wheel.

<?php
    function getNodeXPath( $node ) {
        // REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0!!!

        // Get the index for the current node by looping through the siblings.
        $parentNode = $node->parentNode;
        if( $parentNode != null ) {
            $nodeIndex = 0;
            do {
                $testNode = $parentNode->childNodes->item( $nodeIndex );
                $nodeName = $testNode->nodeName;
                $nodeIndex++;

                // PHP trickery!  Here we create a counter based on the node
                //  name of the test node to use in the XPath.
                if( !isset( $$nodeName ) ) $$nodeName = 1;
                else $$nodeName++;

                // Failsafe return value.
                if( $nodeIndex > $parentNode->childNodes->length ) return( "/" );
            } while( !$node->isSameNode( $testNode ) );

            // Recursively get the XPath for the parent.
            return( getNodeXPath( $parentNode ) . "/{$node->nodeName}[{$$nodeName}]" );
        } else {
            // Hit the root node!  Note that the slash is added when
            //  building the XPath, so we return just an empty string.
            return( "" );
        }
    }
?>
johanwthijs-at-hotmail-dot-com 14-Dec-2005 06:25
Being an experienced ASP developer I was wondering how to replace textual content of a node (with msxml this is simply acheived by setting the 'text' property of a node). Out of frustration I started to play around with SimpleXml but I could not get it to work in combination with xPath.

I took me a lot of time to find out so I hope this helps others:

function replaceNodeText($objXml, $objNode, $strNewContent){
    /*
    This function replaces a node's string content with strNewContent
    */
    $objNodeListNested = &$objNode->childNodes;
    foreach ( $objNodeListNested as $objNodeNested ){
         if ($objNodeNested->nodeType == XML_TEXT_NODE)$objNode->removeChild ($objNodeNested);
    }

    $objNode->appendChild($objXml->createTextNode($strNewContent));
}

$objXml= new DOMDocument();
$objXml->loadXML('<root><node id="1">bla</note></root>');
$objXpath = new domxpath($objXml);

$strXpath="/root/node[@id='1']";
$objNodeList = $objXpath ->query($strXpath);
foreach ($objNodeList as $objNode){
//pass the node by reference
replaceNodeText($objXml, &$objNode, $strImportedValue);
}
mark at vectrex dot org dot uk 17-Nov-2005 02:10
Note that these DOM functions expect (and presumably return) all their data in UTF-8 character encoding, regardless of what PHP's current encoding is. This means that text nodes, attribute values etc, should be in utf8.

This applies even if you're generating an XML document which is not ultimately in utf8.

Mark
toby at tobiasly dot com 22-Oct-2005 11:08
This module is not included by default either in the CentOS 4 "centosplus" repository. For those using PHP5 on CentOS 4, a simple "yum --enablerepo=centosplus install php-xml" will do the trick (this will install both the XML and DOM modules).
pes_cz 29-Sep-2005 12:32
When I tried to parse my XHTML Strict files with DOM extension, it couldn't understand xhtml entities (like &copy;). I found post about it here (14-Jul-2005 09:05) which adviced to add resolveExternals = true, but it was very slow. There was some small note about xml catalogs but without any glue. Here it is:

XML catalogs is something like cache. Download all needed dtd's to /etc/xml, edit file /etc/xml/catalog and add this line: <public publicId="-//W3C//DTD XHTML 1.0 Strict//EN" uri="file:///etc/xml/xhtml1-strict.dtd" />

Thats all. Thanks to http://www.whump.com/moreLikeThis/link/03815
amir.laherATcomplinet.com 22-Aug-2005 05:09
This particular W3C page provides invaluable documentation for the DOM classes implemented in php5 (via libxml2). It fills in plenty of php.net's gaps:

http://www.w3.org/TR/DOM-Level-2-Core/core.html

Some key examples:
* concise summary of the class heirachy (1.1.1)
* clarification that DOM level 2 doesn't allow for population of internal DTDs
* explanation of DOMNode->normalize()
* explanation of the DOMImplementation class

The interfaces are described in OMG's Interface Definition Language
aidan at php dot net 19-Jul-2005 06:04
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
aidan at php dot net 18-Jul-2005 08:27
When dealing with validation or loading, the output errors can be quite annoying.

PHP 5.1 introduces libxml_get_errors().

http://php.net/libxml_get_errors
php at webdevelopers dot cz 14-Jul-2005 12:05
[Editor's Note: If you're using entities, then you have no choice. XML Catalogs can speed DTD resolution.]

Never use

$dom->resolveExternals=true;

when parsing XHTML document that has the DOCTYPE declaration with DTD URL specified in it.

Otherwise parsing the XHTML with DOCTYPE like this one:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

will result in PHP/DOM downloading the DTD file from W3C site when parsing your document. It will add extra delay to your script - I experienced that $dom->load()'s total time was from 1 to 16 seconds.

elixon
spammable69 at hotmail dot com 11-Apr-2005 10:18
I wrote a framework to implement the StyleSheet interfaces as specified on the W3C website.  The code is written in PHP, and is NOT a complete implementation.  Use it how ya like.  I was planning on adding the CSSStyleSheet interfaces as well.  Feel free to ask.

<?
    class StyleSheetList {
        public length;
        private self;

        function __construct ( ) {
            $this->self = array();
        }

        function __get($property, $&ret) {
            if($property == 'length')
                $ret = count($this->self);
            return true;
        }

        function __set($property, $val) {
            if($property == 'length')
                return true;
        }

        function item( $index ) {
            return $this->self[$index];
        }
    }

    class MediaList extends StyleSheetList {

        function appendMedium ( $newMedium ) {
            array_push($this->self, $newMedium);
        }

        function deleteMedium ( $oldMedium ) {
            foreach($this->self as $item) {
                if( $item == $oldMedium ) {
                    $item = $this->self[ $this->length-1 ];
                    array_pop($this->self);
                    break;
                }
            }
        }
    }

    class DocumentStyle {
        public styleSheets;

        function __construct ( ) {
            $this->styleSheets = new StyleSheetList();
        }

        function __set($property, $val) {
            if($property == 'styleSheets')
                return true;
        }
    }

    class LinkStyle {
        public sheet;

        function __construct () {
            $this->sheet = new StyleSheet();
        }

        function __set($property, $val) {
            if($property == 'sheet')
                return true;
        }
    }

    class StyleSheet {
        public type;
        public disabled;
        public ownerNode;
        public parentStyleSheet;
        public href;
        public title;
        public media;

        function __construct( $type, $disabled, $ownerNode, $parentStyleSheet, $href, $title){
            $this->type = $type;
            $this->disabled = $disabled;
            $this->media = new MediaList();
            $this->ownerNode = $ownerNode;
            $this->parentStyleSheet = $parentStyleSheet;
            $this->href = $href;
            $this->title = $title;
        }
    }
?>

Only contactable via http://murpsoft.com/contact.html


简介

The DOM extension allows you to operate on XML documents through the DOM API with PHP.

Note:

此 DOM 扩展采用 UTF-8 编码。在 ISO-8859-1 编码下，使用 utf8_encode() 和 utf8_decode() 来处理，其它编码下使用 iconv 函数处理。

User Contributed Notes

Anonymous 15-Apr-2020 06:01
On some linux package managers, namely apt, this is called 'xml' for example as in:

sudo apt-get install -y php7.3-xml
captainjester at hotmail dot com 27-Mar-2020 12:59
Be careful when using this for partial HTML. This will only take complete HTML documents with at least an HTML element and a BODY element. If you are working on partial HTML and you fill in the missing elements around it and don't specify in META elements the character encoding then it will be treated as ISO-8859-1 and will mangle UTF-8 strings. Example:

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><body>".$body."</body></html>");
// $doc will treat your HTML ISO-8859-1.
// this is correct but may not be what you want if your source is UTF-8
?>

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><head><meta charset=\"UTF-8\"><meta http-equiv=\"Content-Type\" content=\"text/html; CHARSET=gb2312\"></head><body>".$body."</body></html>");
// $doc will treat your HTML correctly as UTF-8.
?>


安装／配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

d at duane dot com 10-May-2012 05:02
On Fedora 16, you can use
yum -y install php-xml
and then be sure to add
extension=dom.so
in the php.ini file for this to work.
Anonymous 05-Oct-2011 07:40
In Redhat 5.5 using php53 you need to not only install php53-xml but php53-devel as well to install DOMDocument
eugenekay at kashpureff dot org 24-Jan-2011 10:08
Certain Linux distributions do not have this extension included in the minimum PHP package. It can usually be found in one of the "optional" php-* packages.

For CentOS, you will need to run "yum install php-xml", which provides this extension.
Sergey A. 05-Apr-2010 05:38
don't forget
extension=dom.so
in extensions.ini
on freebsd
z1mok at yahoo dot com 22-Apr-2009 05:45
You need the DOM MODULE installed if you want to use Youtube Data Api with the Zend GData Library.

Otherwise you cannot obtain a valid Upload Form Token.


需求

此扩展需要 libxml PHP 扩展。这表示需要使用 --with-libxml，或在 PHP 7.4 之前的版本中使用 --enable-libxml， 尽管这将隐式完成因为 libxml 是缺省开启的。

User Contributed Notes

david at brayworth dot com dot au 12-Jun-2011 05:55
Under Fedora packaging ssystems you will need php-xml
 => yum install php-xml
James 18-Apr-2010 10:58
You also need to check libxml is installed. Check phpinfo() > Dom to see if it is. Bug report filed to get this added here.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-dom

User Contributed Notes

smleimberg at NOSPAM dot gmail dot com 26-Dec-2017 10:08
For Ubuntu:
sudo apt-get install php7.0-xml

For Fedora:
yum -y install php-xml


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

XML constants
Constant | Value | Description
XML_ELEMENT_NODE (int) | 1 | Node is a DOMElement
XML_ATTRIBUTE_NODE (int) | 2 | Node is a DOMAttr
XML_TEXT_NODE (int) | 3 | Node is a DOMText
XML_CDATA_SECTION_NODE (int) | 4 | Node is a DOMCharacterData
XML_ENTITY_REF_NODE (int) | 5 | Node is a DOMEntityReference
XML_ENTITY_NODE (int) | 6 | Node is a DOMEntity
XML_PI_NODE (int) | 7 | Node is a DOMProcessingInstruction
XML_COMMENT_NODE (int) | 8 | Node is a DOMComment
XML_DOCUMENT_NODE (int) | 9 | Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (int) | 10 | Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (int) | 11 | Node is a DOMDocumentFragment
XML_NOTATION_NODE (int) | 12 | Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (int) | 13 |
XML_DTD_NODE (int) | 14 |
XML_ELEMENT_DECL_NODE (int) | 15 |
XML_ATTRIBUTE_DECL_NODE (int) | 16 |
XML_ENTITY_DECL_NODE (int) | 17 |
XML_NAMESPACE_DECL_NODE (int) | 18 |
XML_ATTRIBUTE_CDATA (int) | 1 |
XML_ATTRIBUTE_ID (int) | 2 |
XML_ATTRIBUTE_IDREF (int) | 3 |
XML_ATTRIBUTE_IDREFS (int) | 4 |
XML_ATTRIBUTE_ENTITY (int) | 5 |
XML_ATTRIBUTE_NMTOKEN (int) | 7 |
XML_ATTRIBUTE_NMTOKENS (int) | 8 |
XML_ATTRIBUTE_ENUMERATION (int) | 9 |
XML_ATTRIBUTE_NOTATION (int) | 10 |
DOMException constants
Constant | Value | Description
DOM_PHP_ERR (int) | 0 | Error code not part of the DOM specification. Meant for PHP errors.
DOM_INDEX_SIZE_ERR (int) | 1 | If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (int) | 2 | If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (int) | 3 | If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (int) | 4 | If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (int) | 5 | If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (int) | 6 | If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (int) | 7 | If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (int) | 8 | If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (int) | 9 | If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (int) | 10 | If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (int) | 11 | If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (int) | 12 | If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (int) | 13 | If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (int) | 14 | If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (int) | 15 | If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (int) | 16 | If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.

User Contributed Notes

There are no user contributed notes for this page.


范例

Many examples in this reference require an XML file. We will use book.xml that contains the following:

Example #1 book.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>

User Contributed Notes

There are no user contributed notes for this page.


The DOMAttr class

(PHP 5, PHP 7)

简介

DOMAttr represents an attribute in the DOMElement object.

类摘要

DOMAttr extends DOMNode {
/* 属性 */
public readonly string $name ;
public readonly DOMElement $ownerElement ;
public readonly bool $schemaTypeInfo ;
public readonly bool $specified ;
public string $value ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public __construct ( string $name , string $value = "" )
public isId ( ) : bool
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

name

The name of the attribute

ownerElement

The element which contains the attribute

schemaTypeInfo

Not implemented yet, always is null

specified

Not implemented yet, always is null

value

The value of the attribute

参见

  • » W3C specification of Attr

Table of Contents

  • DOMAttr::__construct — Creates a new DOMAttr object
  • DOMAttr::isId — Checks if attribute is a defined ID

User Contributed Notes

greubel at nkey dot de 06-Dec-2014 03:04
Please take care on debugging DOMAttr related code. This will cause an E_WARNING that retrieving schemaTypeInfo attribute is not implemented yet. An IDE like Eclipse will inspect the object and its member elements. In conjunction with registered error handlers, which will translate the E_WARNING into Exception your debugging session will end unexpectedly. This has caused me some trouble while debugging my PHPUnit test case in eclipse using "Makegood" plugin.

A possible workarround is to deactivate the error handling during debugging using error_reporting(0). Remove the statement after finishing your debugging session.

Notable ticket in Bugtracker: https://bugs.php.net/bug.php?id=61858
And a xdebug tracker ticket: http://bugs.xdebug.org/view.php?id=910
chregu at php dot net 23-Mar-2009 11:20
See also the properties from the inherited class DOMNode ( http://php.net/manual/en/class.domnode.php ), eg. namespaceURI, prefix, localName, etc, especially if you have to deal with namespaced attributes


Creates a new DOMAttr object

  • ? DOMAttr
  • DOMAttr::isId ?
  • PHP Manual
  • DOMAttr
  • Creates a new DOMAttr object

DOMAttr::__construct

(PHP 5, PHP 7)

DOMAttr::__construct — Creates a new DOMAttr object

说明

public DOMAttr::__construct ( string $name , string $value = "" )

Creates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writable node, use DOMDocument::createAttribute.

参数

name

The tag name of the attribute.

value

The value of the attribute.

范例

Example #1 Creating a new DOMAttr object

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML();

?>

以上例程会输出：

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

参见

  • DOMDocument::createAttribute() - Create new attribute

User Contributed Notes

Anonymous 18-Sep-2014 10:48
The output should be:

<?xml version="1.0" encoding="iso-8859-1"?>
<root attr="attrvalue"/>


Checks if attribute is a defined ID

  • ? DOMAttr::__construct
  • DOMCdataSection ?
  • PHP Manual
  • DOMAttr
  • Checks if attribute is a defined ID

DOMAttr::isId

(PHP 5, PHP 7)

DOMAttr::isId — Checks if attribute is a defined ID

说明

public DOMAttr::isId ( ) : bool

This function checks if the attribute is a defined ID.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument::validate or DOMDocument::validateOnParse before using this function.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 DOMAttr::isId() Example

<?php

$doc = new DomDocument;

// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

User Contributed Notes

There are no user contributed notes for this page.


The DOMCdataSection class

(PHP 5, PHP 7)

简介

The DOMCdataSection inherits from DOMText for textural representation of CData constructs.

类摘要

DOMCdataSection extends DOMText {
/* 继承的属性 */
public readonly string $wholeText ;
public string $data ;
public readonly int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* Methods */
public __construct ( string $data )
/* Inherited methods */
public DOMText::isElementContentWhitespace ( ) : bool
public DOMText::isWhitespaceInElementContent ( ) : bool
public DOMText::splitText ( int $offset ) : DOMText|false
public DOMCharacterData::appendData ( string $data ) : bool
public DOMCharacterData::deleteData ( int $offset , int $count ) : bool
public DOMCharacterData::insertData ( int $offset , string $data ) : bool
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : bool
public DOMCharacterData::substringData ( int $offset , int $count ) : string|false
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

Table of Contents

  • DOMCdataSection::__construct — Constructs a new DOMCdataSection object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new DOMCdataSection object

  • ? DOMCdataSection
  • DOMCharacterData ?
  • PHP Manual
  • DOMCdataSection
  • Constructs a new DOMCdataSection object

DOMCdataSection::__construct

(PHP 5, PHP 7)

DOMCdataSection::__construct — Constructs a new DOMCdataSection object

说明

public DOMCdataSection::__construct ( string $data )

Constructs a new CDATA node. This works like the DOMText class.

参数

data

The value of the CDATA node. If not supplied, an empty CDATA node is created.

范例

Example #1 Creating a new DOMCdataSection object

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

以上例程会输出：

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

参见

  • DOMText::__construct() - Creates a new DOMText object
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

There are no user contributed notes for this page.


The DOMCharacterData class

(PHP 5, PHP 7)

简介

Represents nodes with character data. No nodes directly correspond to this class, but other nodes do inherit from it.

类摘要

DOMCharacterData extends DOMNode {
/* 属性 */
public string $data ;
public readonly int $length ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public appendData ( string $data ) : bool
public deleteData ( int $offset , int $count ) : bool
public insertData ( int $offset , string $data ) : bool
public replaceData ( int $offset , int $count , string $data ) : bool
public substringData ( int $offset , int $count ) : string|false
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

data

The contents of the node.

length

The length of the contents.

参见

  • » W3C specification of CharacterData

Table of Contents

  • DOMCharacterData::appendData — Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData — Remove a range of characters from the node
  • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData — Extracts a range of data from the node

User Contributed Notes

jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:35
In case you're looking for the CDATA class to which nodes /do/ correspond, it's called DOMCdataSection (per my PHP installation) and isn't documented on php.net.  Presumably, it doesn't add anything to this API.

See also: http://www.php.net/manual/en/domdocument.createcdatasection.php


Append the string to the end of the character data of the node

  • ? DOMCharacterData
  • DOMCharacterData::deleteData ?
  • PHP Manual
  • DOMCharacterData
  • Append the string to the end of the character data of the node

DOMCharacterData::appendData

(PHP 5, PHP 7)

DOMCharacterData::appendData — Append the string to the end of the character data of the node

说明

public DOMCharacterData::appendData ( string $data ) : bool

Append the string data to the end of the character data of the node.

参数

data

The string to append.

返回值

没有返回值。

参见

  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Remove a range of characters from the node

  • ? DOMCharacterData::appendData
  • DOMCharacterData::insertData ?
  • PHP Manual
  • DOMCharacterData
  • Remove a range of characters from the node

DOMCharacterData::deleteData

(PHP 5, PHP 7)

DOMCharacterData::deleteData — Remove a range of characters from the node

说明

public DOMCharacterData::deleteData ( int $offset , int $count ) : bool

Deletes count characters starting from position offset.

参数

offset

The offset from which to start removing.

count

The number of characters to delete. If the sum of offset and count exceeds the length, then all characters to the end of the data are deleted.

返回值

没有返回值。

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Insert a string at the specified 16-bit unit offset

  • ? DOMCharacterData::deleteData
  • DOMCharacterData::replaceData ?
  • PHP Manual
  • DOMCharacterData
  • Insert a string at the specified 16-bit unit offset

DOMCharacterData::insertData

(PHP 5, PHP 7)

DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset

说明

public DOMCharacterData::insertData ( int $offset , string $data ) : bool

Inserts string data at position offset.

参数

offset

The character offset at which to insert.

data

The string to insert.

返回值

没有返回值。

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Replace a substring within the DOMCharacterData node

  • ? DOMCharacterData::insertData
  • DOMCharacterData::substringData ?
  • PHP Manual
  • DOMCharacterData
  • Replace a substring within the DOMCharacterData node

DOMCharacterData::replaceData

(PHP 5, PHP 7)

DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node

说明

public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : bool

Replace count characters starting from position offset with data.

参数

offset

The offset from which to start replacing.

count

The number of characters to replace. If the sum of offset and count exceeds the length, then all characters to the end of the data are replaced.

data

The string with which the range must be replaced.

返回值

没有返回值。

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Extracts a range of data from the node

  • ? DOMCharacterData::replaceData
  • DOMComment ?
  • PHP Manual
  • DOMCharacterData
  • Extracts a range of data from the node

DOMCharacterData::substringData

(PHP 5, PHP 7)

DOMCharacterData::substringData — Extracts a range of data from the node

说明

public DOMCharacterData::substringData ( int $offset , int $count ) : string|false

Returns the specified substring.

参数

offset

Start offset of substring to extract.

count

The number of characters to extract.

返回值

The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node

User Contributed Notes

There are no user contributed notes for this page.


The DOMComment class

(PHP 5, PHP 7)

简介

Represents comment nodes, characters delimited by <!-- and -->.

类摘要

DOMComment extends DOMCharacterData {
/* 继承的属性 */
public string $data ;
public readonly int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public __construct ( string $data = "" )
/* 继承的方法 */
public DOMCharacterData::appendData ( string $data ) : bool
public DOMCharacterData::deleteData ( int $offset , int $count ) : bool
public DOMCharacterData::insertData ( int $offset , string $data ) : bool
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : bool
public DOMCharacterData::substringData ( int $offset , int $count ) : string|false
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

参见

  • » W3C specification of Comment

Table of Contents

  • DOMComment::__construct — Creates a new DOMComment object

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMComment object

  • ? DOMComment
  • DOMDocument ?
  • PHP Manual
  • DOMComment
  • Creates a new DOMComment object

DOMComment::__construct

(PHP 5, PHP 7)

DOMComment::__construct — Creates a new DOMComment object

说明

public DOMComment::__construct ( string $data = "" )

Creates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createComment.

参数

data

The value of the comment.

范例

Example #1 Creating a new DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

参见

  • DOMDocument::createComment() - Create new comment node

User Contributed Notes

There are no user contributed notes for this page.


The DOMDocument class

(PHP 5, PHP 7)

简介

Represents an entire HTML or XML document; serves as the root of the document tree.

类摘要

DOMDocument extends DOMNode {
/* 属性 */
public readonly string $actualEncoding ;
public readonly DOMConfiguration $config ;
public readonly DOMDocumentType $doctype ;
public readonly DOMElement $documentElement ;
public string|null $documentURI ;
public string $encoding ;
public bool $formatOutput ;
public readonly DOMImplementation $implementation ;
public bool $preserveWhiteSpace = true ;
public bool $recover ;
public bool $resolveExternals ;
public bool $standalone ;
public bool $strictErrorChecking = true ;
public bool $substituteEntities ;
public bool $validateOnParse = false ;
public string $version ;
public readonly string|null $xmlEncoding ;
public bool $xmlStandalone ;
public string $xmlVersion ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public __construct ( string $version = "1.0" , string $encoding = "" )
public createAttribute ( string $localName ) : DOMAttr|false
public createAttributeNS ( string|null $namespace , string $qualifiedName ) : DOMAttr|false
public createCDATASection ( string $data ) : DOMCdataSection|false
public createComment ( string $data ) : DOMComment|false
public createDocumentFragment ( ) : DOMDocumentFragment|false
public createElement ( string $localName , string $value = "" ) : DOMElement|false
public createElementNS ( string|null $namespace , string $qualifiedName , string $value = "" ) : DOMElement|false
public createEntityReference ( string $name ) : DOMEntityReference|false
public createProcessingInstruction ( string $target , string $data = "" ) : DOMProcessingInstruction|false
public createTextNode ( string $data ) : DOMText|false
public getElementById ( string $elementId ) : DOMElement|null
public getElementsByTagName ( string $qualifiedName ) : DOMNodeList
public getElementsByTagNameNS ( string $namespace , string $localName ) : DOMNodeList
public importNode ( DOMNode $node , bool $deep = false ) : DOMNode|false
public load ( string $filename , int $options = 0 ) : DOMDocument|bool
public loadHTML ( string $source , int $options = 0 ) : DOMDocument|bool
public loadHTMLFile ( string $filename , int $options = 0 ) : DOMDocument|bool
public loadXML ( string $source , int $options = 0 ) : DOMDocument|bool
public normalizeDocument ( ) : void
public registerNodeClass ( string $baseClass , string|null $extendedClass ) : bool
public relaxNGValidate ( string $filename ) : bool
public relaxNGValidateSource ( string $source ) : bool
public save ( string $filename , int $options = 0 ) : int|false
public saveHTML ( DOMNode|null $node = null ) : string|false
public saveHTMLFile ( string $filename ) : int|false
public saveXML ( DOMNode|null $node = null , int $options = 0 ) : string|false
public schemaValidate ( string $filename , int $flags = 0 ) : bool
public schemaValidateSource ( string $source , int $flags = 0 ) : bool
public validate ( ) : bool
public xinclude ( int $options = 0 ) : int|false
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

actualEncoding

Deprecated. Actual encoding of the document, is a readonly equivalent to encoding.

config

Deprecated. Configuration used when DOMDocument::normalizeDocument() is invoked.

doctype

The Document Type Declaration associated with this document.

documentElement

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

documentURI

The location of the document or null if undefined.

encoding

Encoding of the document, as specified by the XML declaration. This attribute is not present in the final DOM Level 3 specification, but is the only way of manipulating XML document encoding in this implementation.

formatOutput

Nicely formats output with indentation and extra space. This has no effect if the document was loaded with preserveWhitespace enabled.

implementation

The DOMImplementation object that handles this document.

preserveWhiteSpace

Do not remove redundant white space. Default to true. Setting this to false has the same effect as passing LIBXML_NOBLANKS as option to DOMDocument::load() etc.

recover

Proprietary. Enables recovery mode, i.e. trying to parse non-well formed documents. This attribute is not part of the DOM specification and is specific to libxml.

resolveExternals

Set it to true to load external entities from a doctype declaration. This is useful for including character entities in your XML document.

standalone

Deprecated. Whether or not the document is standalone, as specified by the XML declaration, corresponds to xmlStandalone.

strictErrorChecking

Throws DOMException on errors. Default to true.

substituteEntities

Proprietary. Whether or not to substitute entities. This attribute is not part of the DOM specification and is specific to libxml.

Caution

Enabling entity substitution may facilitate XML External Entity (XXE) attacks.

validateOnParse

Loads and validates against the DTD. Default to false.

version

Deprecated. Version of XML, corresponds to xmlVersion.

xmlEncoding

An attribute specifying, as part of the XML declaration, the encoding of this document. This is null when unspecified or when it is not known, such as when the Document was created in memory.

xmlStandalone

An attribute specifying, as part of the XML declaration, whether this document is standalone. This is false when unspecified.

xmlVersion

An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

注释

Note:

此 DOM 扩展采用 UTF-8 编码。在 ISO-8859-1 编码下，使用 utf8_encode() 和 utf8_decode() 来处理，其它编码下使用 iconv 函数处理。

Note:

When using json_encode() on a DOMDocument object the result will be that of encoding an empty object.

参见

  • » W3C specification for Document

Table of Contents

  • DOMDocument::__construct — Creates a new DOMDocument object
  • DOMDocument::createAttribute — Create new attribute
  • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection — Create new cdata node
  • DOMDocument::createComment — Create new comment node
  • DOMDocument::createDocumentFragment — Create new document fragment
  • DOMDocument::createElement — Create new element node
  • DOMDocument::createElementNS — Create new element node with an associated namespace
  • DOMDocument::createEntityReference — Create new entity reference node
  • DOMDocument::createProcessingInstruction — Creates new PI node
  • DOMDocument::createTextNode — Create new text node
  • DOMDocument::getElementById — Searches for an element with a certain id
  • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
  • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
  • DOMDocument::importNode — Import node into current document
  • DOMDocument::load — Load XML from a file
  • DOMDocument::loadHTML — Load HTML from a string
  • DOMDocument::loadHTMLFile — Load HTML from a file
  • DOMDocument::loadXML — Load XML from a string
  • DOMDocument::normalizeDocument — Normalizes the document
  • DOMDocument::registerNodeClass — Register extended class used to create base node type
  • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
  • DOMDocument::save — Dumps the internal XML tree back into a file
  • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
  • DOMDocument::saveXML — Dumps the internal XML tree back into a string
  • DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource — Validates a document based on a schema
  • DOMDocument::validate — Validates the document based on its DTD
  • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

User Contributed Notes

pastormontesinos at gmail dot com 04-Mar-2021 10:34
For using safely with script nodes when parsing, best option is extending DOMDocument, keeping script tags while DOMDocument process and rearrange them just after saveHTML function is called. Here is my custom class.

<?php

class SafeDOMDocument extends \DOMDocument
{
    const REGEX_JS            = '#(\s*<!--(\[if[^\n]*>)?\s*(<script.*</script>)+\s*(<!\[endif\])?-->)|(\s*<script.*</script>)#isU';
    const SUBSTITUTION_FORMAT = '<!--<script class="script_%s"></script>-->';
    private $matchedScripts = [];

    public function loadHTML($source, $options = 0)
    {
        $this->formatOutput        = false;
        $this->preserveWhiteSpace  = true;
        $this->validateOnParse     = false;
        $this->strictErrorChecking = false;
        $this->recover             = false;
        $this->resolveExternals    = false;
        $this->substituteEntities  = false;
        $matches = [];
        $success = preg_match_all(self::REGEX_JS, $source, $matches);

        if ($success && !empty($matches)) {
            foreach ($matches[0] as $match) {
                $storedScript = rtrim(ltrim($match, "\n\r\t "), "\n\r\t ");
                $scriptId = md5($storedScript);
                $key = sprintf(self::SUBSTITUTION_FORMAT, $scriptId);
                $source = str_replace($match, $key, $source);
                $this->matchedScripts[$key] = $storedScript;
            }
        }

        return parent::loadHTML($source, $options);
    }

    public function saveHTML(DOMNode $node = null)
    {
        $output = parent::saveHTML($node);

        if (count($this->matchedScripts)) {
            foreach ($this->matchedScripts as $substitution => $originalSnippet) {
                $output = str_replace($substitution, $originalSnippet, $output);
            }
        }

        return $output;
    }
}
?>
ashjkshdu283 at gmail dot com 07-Jul-2018 11:39
/* Function evolved from jay at jaygilford dot com post
  * This function will return an array of the values of the specified
  * attribute ($attr) for all the Dom Document object's elements
  */

<?php

function getAttrData(string $attr, DomDocument $dom) {
    // Empty array to hold all classes to return
    $attrData = array();

    //Loop through each tag in the dom and add it's attribute data to the array
    foreach($dom->getElementsByTagName('*') as $tag) {
        if(empty($tag->getAttribute($attr)) === false) {
            array_push($attrData, $tag->getAttribute($attr));
        }
    }

    //Return the array of attribute data
    return array_unique($attrData);
}

$html = '
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<a href="#someLink" id="someLink" class="link-class">Some Link</a>
<a href="#someOtherLink" id="someOtherLink" class="link-class">Some Other Link</a>
<h1 id="header1" class="header-class">My First Heading</h1>
<p id="para1" class="para-class">My first paragraph.</p>
</body>
</html>';
$dom = new DOMDocument();
$dom->loadHtml($html);
$dom->saveHTML();
var_dump(getAttrData('class', $dom));
biker dot mike at gmx dot com 22-Aug-2016 01:36
Look out for the following gotcha when loading XML from a string:

<?php
$doc = new \DOMDocument;
$doc->documentURI = $myXmlFilename;
$doc->loadXML($myXmlString);
?>

documentURI is now set to the value of $myXmlFilename, right?

Wrong!

It's set to the current working directory.  If you want to manually set documentURI to something other than the CWD, do so AFTER the call to loadXML().

E.g.:
<?php
$doc = new \DOMDocument;
$doc->loadXML($myXmlString);
$doc->documentURI = $myXmlFilename;
?>

documentURI really is now set to the value of $myXmlFilename.
developer at nabtron dot com 17-Dec-2015 07:34
For those landing here and checking for encoding issue with utf-8 characteres, it's pretty easy to correct it, without adding any additional output tag to your html.

We'll be utilizing: mb_convert_encoding

Thanks to the user who shared: SmartDOMDocument in previous comments, I got the idea of solving it. However I truly wish that he shared the method instead of giving a link.

Anyway coming back to the solution, you can simply use:

<?php

            // checks if the content we're receiving isn't empty, to avoid the warning
            if ( empty( $content ) ) {
                return false;
            }

            // converts all special characters to utf-8
            $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8');

            // creating new document
            $doc = new DOMDocument('1.0', 'utf-8');

            //turning off some errors
            libxml_use_internal_errors(true);

            // it loads the content without adding enclosing html/body tags and also the doctype declaration
            $doc->LoadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

            // do whatever you want to do with this code now

?>

I hope it solves the issue for someone! If you need my help or service to fix your code, you can reach me on nabtron.com or contact me at the email mentioned with this comment.
ingjetel at gmail dot com 13-May-2015 11:54
Easy function for basic output of XML file via DOM parsing

<?php
$dom = new DomDocument();
$dom->load("./file.xml") or die("error");
$start = $dom->documentElement;
fc($start);

function fc($node) {
  $child = $node->childNodes;
  foreach($child as $item) {
    if ($item->nodeType == XML_TEXT_NODE) {
      if (strlen(trim($item->nodeValue))) echo trim($item->nodeValue)."<br/>";
    }
    else if ($item->nodeType == XML_ELEMENT_NODE) fc($item);
  }
}
?>
qrworld.net 11-Nov-2014 04:35
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
danny dot nunez15 at gmail dot com 28-Oct-2013 02:54
A simple function to grab all links in a page.

    function get_links($url) {

        // Create a new DOM Document to hold our webpage structure
        $xml = new DOMDocument();

        // Load the url's contents into the DOM

        $xml->loadHTMLFile($url);

        // Empty array to hold all links to return
        $links = array();

        //Loop through each <a> tag in the dom and add it to the link array
        foreach ($xml->getElementsByTagName('a') as $link) {
            $url = $link->getAttribute('href');
            if (!empty($url)) {
                $links[] = $link->getAttribute('href');
            }
        }

        //Return the links
        return $links;
    }
sites.sitesbr.net 22-Jan-2013 12:37
How to objetify a DomDocument with hierarchy like:
<root>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
</root>

It's possible to use in object style to retrieve information, as:

<?php
     $theNodeValue = $aitem->prop1;
?>

Here is the code: one Class and 2 functions.

<?php
 class ArrayNode{
       public $nodeName, $nodeValue;
 }

 function getChildNodeElements( $domNode ){
     $nodes = array();
     for( $i=0; $i < $domNode->childNodes->length; $i++){
       $cn = $domNode->childNodes->item($i);
       if( $cn->nodeType == 1){
           $nodes[] = $cn;
           }
     }
    return $nodes;
 }

 function getArrayNodes( $domDoc ){
     $res = array();

       for( $i=0; $i < $domDoc->childNodes->length; $i++){
       $cn = $domDoc->childNodes->item($i);
       # The first is the root tag...
          if( $cn->nodeType == 1){
               # But we want it's childNodes.
                $sub_cn = getChildNodeElements( $cn);
                # Found the tagName:
                $baseItemTagName = $sub_cn[0]->nodeName;
                break;
            }
        }

       $dnl = $domDoc->getElementsByTagName( $baseItemTagName);

       for( $i=0; $i< $dnl->length; $i++){
          $arrayNode = new ArrayNode();

      # Summary
      $arrayNode->nodeName = $dnl->item($i)->nodeName;
      $arrayNode->nodeValue = $dnl->item($i)->nodeValue;

      # Child Nodes
      $cn = $dnl->item($i)->childNodes;
      for( $k=0; $k<$cn->length; $k++){
           if( $cn->item($k)->nodeName == "#text" && trim($cn->item($k)->nodeValue) == "") continue;
           $arrayNode->{$cn->item($k)->nodeName} = $cn->item($k)->nodeValue;
      }

      # Attributes
      $attr = $dnl->item($i)->attributes;
      for( $k=0; $k < $attr->length; $k++){
           if(! is_null($attr)){
            if( $attr->item($k)->nodeName == "#text" && trim($attr->item($k)->nodeValue) == "") continue;
            $arrayNode->{$attr->item($k)->nodeName} = $attr->item($k)->nodeValue;
           }
      }

      $res[] = $arrayNode;

       }

     return $res;
 }
?>

To use it:

<?php

  # First you load a XML in a DomDocument variable.

   $url = "/path/to/yourxmlfile.xml";
   $domSrc = file_get_contents($url);
   $dom = new DomDocument();
   $dom->loadXML( $domSrc );

  # Then, you get the ArrayNodes from the DomDocument.

    $ans = getArrayNodes( $dom );

    for( $i=0; $i < count( $ans ) ; $i++){

    $cn =  $ans[ $i];

    $info1 =  $cn->prop1;
    $info2 =  $cn->prop2;
    $info3 =  $cn->prop3;

         // ...

   }

?>
Nick M 01-Jun-2011 10:16
You may need to save all or part of a DOMDocument as an XHTML-friendly string, something compliant with both XML and HTML 4. Here's the DOMDocument class extended with a saveXHTML method:

<?php

/**
 * XHTML Document
 *
 * Represents an entire XHTML DOM document; serves as the root of the document tree.
 */
class XHTMLDocument extends DOMDocument {

  /**
   * These tags must always self-terminate. Anything else must never self-terminate.
   *
   * @var array
   */
  public $selfTerminate = array(
      'area','base','basefont','br','col','frame','hr','img','input','link','meta','param'
  );

  /**
   * saveXHTML
   *
   * Dumps the internal XML tree back into an XHTML-friendly string.
   *
   * @param DOMNode $node
   *         Use this parameter to output only a specific node rather than the entire document.
   */
  public function saveXHTML(DOMNode $node=null) {

    if (!$node) $node = $this->firstChild;

    $doc = new DOMDocument('1.0');
    $clone = $doc->importNode($node->cloneNode(false), true);
    $term = in_array(strtolower($clone->nodeName), $this->selfTerminate);
    $inner='';

    if (!$term) {
      $clone->appendChild(new DOMText(''));
      if ($node->childNodes) foreach ($node->childNodes as $child) {
        $inner .= $this->saveXHTML($child);
      }
    }

    $doc->appendChild($clone);
    $out = $doc->saveXML($clone);

    return $term ? substr($out, 0, -2) . ' />' : str_replace('><', ">$inner<", $out);

  }

}

?>

This hasn't been benchmarked, but is probably significantly slower than saveXML or saveHTML and should be used sparingly.
evert at er dot nl 20-Nov-2010 02:17
A nice and simple node 2 array I wrote, worth a try ;)

<?php
function getArray($node)
{
    $array = false;

    if ($node->hasAttributes())
    {
        foreach ($node->attributes as $attr)
        {
            $array[$attr->nodeName] = $attr->nodeValue;
        }
    }

    if ($node->hasChildNodes())
    {
        if ($node->childNodes->length == 1)
        {
            $array[$node->firstChild->nodeName] = $node->firstChild->nodeValue;
        }
        else
        {
            foreach ($node->childNodes as $childNode)
            {
                if ($childNode->nodeType != XML_TEXT_NODE)
                {
                    $array[$childNode->nodeName][] = $this->getArray($childNode);
                }
            }
        }
    }

    return $array;
}
?>
admin at beerpla dot net 12-Mar-2010 02:12
After seeing many complaints about certain DOMDocument shortcomings, such as bad handling of encodings and always saving HTML fragments with <html>, <head>, and DOCTYPE, I decided that a better solution is needed.

So here it is: SmartDOMDocument. You can find it at http://beerpla.net/projects/smartdomdocument/

Currently, the main highlights are:

- SmartDOMDocument inherits from DOMDocument, so it's very easy to use - just declare an object of type SmartDOMDocument instead of DOMDocument and enjoy the new behavior on top of all existing functionality (see example below).

- saveHTMLExact() - DOMDocument has an extremely badly designed "feature" where if the HTML code you are loading does not contain <html> and <body> tags, it adds them automatically (yup, there are no flags to turn this behavior off).
Thus, when you call $doc->saveHTML(), your newly saved content now has <html><body> and DOCTYPE in it. Not very handy when trying to work with code fragments (XML has a similar problem).
SmartDOMDocument contains a new function called saveHTMLExact() which does exactly what you would want - it saves HTML without adding that extra garbage that DOMDocument does.

- encoding fix - DOMDocument notoriously doesn't handle encoding (at least UTF-8) correctly and garbles the output.
SmartDOMDocument tries to work around this problem by enhancing loadHTML() to deal with encoding correctly. This behavior is transparent to you - just use loadHTML() as you would normally.

- SmartDOMDocument Object As String - you can use a SmartDOMDocument object as a string which will print out its contents.
For example:
<?php
echo "Here is the HTML: $smart_dom_doc";
?>

I'm going to maintain this code and try to fix bugs as they come in.

Enjoy.
tloach at gmail dot com 05-Feb-2010 10:01
For anyone else who has been having issues with formatOuput not working, here is a work-around:

rather than just doing something like:

<?php
$outXML = $xml->saveXML();
?>

force it to reload the XML from scratch, then it will format correctly:

<?php
$outXML = $xml->saveXML();
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML($outXML);
$outXML = $xml->saveXML();
?>
jay at jaygilford dot com 27-Jan-2010 08:46
Here's a small function I wrote to get all page links using the DOMDocument which will hopefully be of use to others

<?php
/**
 * @author Jay Gilford
 */

/**
 * get_links()
 *
 * @param string $url
 * @return array
 */
function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <a> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) {
        $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
    }

    //Return the links
    return $links;
}
?>
fcartegnie 31-Oct-2009 01:30
Be careful with formatOutput().

Creating an empty node like this:
createElement('foo','')
instead of
createElement('foo')
will break formatOutput.
PhilipWayneRollins at gmail dot com 15-Aug-2009 01:32
If you want to use the DOMDocument to create xHTML documents here is a simple class

Note this is designed for creating xHTML documents from scratch but could be easily extended to work with xHTML documents. Also this is for xHTML not XML.

<?php
    class Document
    {
        public $doctype;
        public $head;
        public $title = 'Sensei Ninja';
        public $body;
        private $styles;
        private $metas;
        private $scripts;
        private $document;

        function __construct (  )
        {
            $this->document = new DOMDocument( );
            $this->head = $this->document->createElement( 'head', ' ' );
            $this->body = $this->document->createElement( 'body', ' ' );
        }

        public function addStyleSheet ( $url, $media='all' )
        {
            $element = $this->document->createElement( 'link' );
            $element->setAttribute( 'type', 'text/css' );
            $element->setAttribute( 'href', $url );
            $element->setAttribute( 'media', $media );
            $this->styles[] = $element;
        }

        public function addScript ( $url )
        {
            $element = $this->document->createElement( 'script', ' ' );
            $element->setAttribute( 'type', 'text/javascript' );
            $element->setAttribute( 'src', $url );
            $this->scripts[] = $element;
        }

        public function addMetaTag ( $name, $content )
        {
            $element = $this->document->createElement( 'meta' );
            $element->setAttribute( 'name', $name );
            $element->setAttribute( 'content', $content );
            $this->metas[] = $element;
        }

        public function setDescription ( $dec )
        {
            $this->addMetaTag( 'description', $dec );
        }

        public function setKeywords ( $keywords )
        {
            $this->addMetaTag( 'keywords', $keywords );
        }

        public function createElement ( $nodeName, $nodeValue=null )
        {
          return $this->document->createElement( $nodeName, $nodeValue );
        }

        public function assemble ( )
        {
            // Doctype creation
            $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML TRANSITIONAL 1.0//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

            // Create the head element
            $title = $this->document->createElement( 'title', $this->title );
            // Add stylesheets if needed
            if ( is_array( $this->styles ))
                foreach ( $this->styles as $element )
                    $this->head->appendChild( $element );
            // Add scripts if needed
            if(  is_array( $this->scripts ))
                foreach ( $this->scripts as $element )
                    $this->head->appendChild( $element );
            // Add meta tags if needed
            if ( is_array( $this->metas ))
                foreach ( $this->metas as $element )
                    $this->head->appendChild( $element );
            $this->head->appendChild( $title );

            // Create the document
            $html = $this->document->createElement( 'html' );
            $html->setAttribute( 'xmlns', 'http://www.w3.org/1999/xhtml' );
            $html->setAttribute( 'xml:lang', 'en' );
            $html->setAttribute( 'lang', 'en' );
            $html->appendChild( $this->head );
            $html->appendChild( $this->body );

            $this->document->appendChild( $html );
            return $doctype . $this->document->saveXML( );
        }

    }

?>

Small example

<?php
        $document = new Document( );
    $document->title = 'Hello';
    $document->addStyleSheet( 'StyleSheets/main.css' );
    $div = $document->createElement( 'div' );
    $div->nodeValue = 'Hello, world!';
    $div->setAttribute( 'style', 'color: red;' );
    $document->body->appendChild( $div );
    printf( '%s', $document->assemble( ) );
?>
cmyk777 at gmail dot com 23-May-2009 12:31
This function may help to debug current dom element:

<?php
function dom_dump($obj) {
    if ($classname = get_class($obj)) {
        $retval = "Instance of $classname, node list: \n";
        switch (true) {
            case ($obj instanceof DOMDocument):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->saveXML($obj);
                break;
            case ($obj instanceof DOMElement):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMAttr):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                //$retval .= $obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMNodeList):
                for ($i = 0; $i < $obj->length; $i++) {
                    $retval .= "Item #$i, XPath: {$obj->item($i)->getNodePath()}\n".
"{$obj->item($i)->ownerDocument->saveXML($obj->item($i))}\n";
                }
                break;
            default:
                return "Instance of unknown class";
        }
    } else {
        return 'no elements...';
    }
    return htmlspecialchars($retval);
}
?>

Example usage:

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$body = $dom->documentElement->getElementsByTagName('book');
echo '<pre>'.dom_dump($body).'<pre>';
?>

Output:

Instance of DOMNodeList, node list:
Item #0, XPath: /library/book[1]
<book isbn="0345342968">
<title>Fahrenheit 451</title>
<author>R. Bradbury</author>
<publisher>Del Rey</publisher>
</book>
Item #1, XPath: /library/book[2]
<book isbn="0048231398">
<title>The Silmarillion</title>
<author>J.R.R. Tolkien</author>
<publisher>G. Allen &amp; Unwin</publisher>
</book>
Item #2, XPath: /library/book[3]
<book isbn="0451524934">
<title>1984</title>
<author>G. Orwell</author>
<publisher>Signet</publisher>
</book>
Item #3, XPath: /library/book[4]
<book isbn="031219126X">
<title>Frankenstein</title>
<author>M. Shelley</author>
<publisher>Bedford</publisher>
</book>
Item #4, XPath: /library/book[5]
<book isbn="0312863551">
<title>The Moon Is a Harsh Mistress</title>
<author>R. A. Heinlein</author>
<publisher>Orb</publisher>
</book>
Fernando H 11-Apr-2008 12:48
Showing a quick example of how to use this class, just so that new users can get a quick start without having to figure it all out by themself. ( At the day of posting, this documentation just got added and is lacking examples. )

<?php

// Set the content type to be XML, so that the browser will   recognise it as XML.
header( "content-type: application/xml; charset=ISO-8859-15" );

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

// Create some elements.
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track", "The ninth symphony" );

// Set the attributes.
$xml_track->setAttribute( "length", "0:01:15" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );

// Create another element, just to show you can add any (realistic to computer) number of sublevels.
$xml_note = $xml->createElement( "Note", "The last symphony composed by Ludwig van Beethoven." );

// Append the whole bunch.
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );

// Repeat the above with some different values..
$xml_track = $xml->createElement( "Track", "Highway Blues" );

$xml_track->setAttribute( "length", "0:01:33" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
$xml_album->appendChild( $xml_track );

$xml->appendChild( $xml_album );

// Parse the XML.
print $xml->saveXML();

?>

Output:
<Album>
  <Track length="0:01:15" bitrate="64kb/s" channels="2">
    The ninth symphony
    <Note>
      The last symphony composed by Ludwig van Beethoven.
    </Note>
  </Track>
  <Track length="0:01:33" bitrate="64kb/s" channels="2">Highway Blues</Track>
</Album>

If you want your PHP->DOM code to run under the .xml extension, you should set your webserver up to run the .xml extension with PHP ( Refer to the installation/configuration configuration for PHP on how to do this ).

Note that this:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

is NOT the same as this:
<?php
// Will NOT work.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml_track = new DOMElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

although this will work:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml->appendChild( $xml_album );
?>


Creates a new DOMDocument object

  • ? DOMDocument
  • DOMDocument::createAttribute ?
  • PHP Manual
  • DOMDocument
  • Creates a new DOMDocument object

DOMDocument::__construct

(PHP 5, PHP 7)

DOMDocument::__construct — Creates a new DOMDocument object

说明

public DOMDocument::__construct
 ( string $version = "1.0"
, string $encoding = ""
)

Creates a new DOMDocument object.

参数

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

范例

Example #1 Creating a new DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

参见

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

User Contributed Notes

qrworld.net 11-Nov-2014 04:36
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
_ michael 01-Jun-2010 07:23
The constuctor arguments are useful if you want to build a new document using createElement, appendChild etc.

By contrast, these arguments are overriden as soon as you load a document from source by calling load() or loadXML().

* If the source contains an XML declaration specifying an encoding, that encoding is used.
* If the XML declaration does not specify an encoding, or if the source does not contain a declaration at all, UTF-8 is assumed.

This behaviour applies no matter what you declared when you called new DOMDocument().
blackhailang at gmail dot com 09-Oct-2008 07:54
domdocument::domdocument() expects at least
At the least, I found that It due to ZEND optimizer, uninstall it,working well, but the speeds will be slowlly :-(.

Comment :
item 1 : 2008-10-03 17:10:58, gkrong said:
"Warning: domdocument::domdocument() expects at least 1
 parameter"
If you use PHP 5 in windows, you don't need to declare
php_domxml.dll in your php.ini file.
so u can give comment in the line php_domxml.dll in your
php.ini file.
you only need to comment it out, but do not delete the
php_domxml.dll file in the ext directory.
steve at mrclay dot org 08-Oct-2008 09:45
To expand on bholbrook's comment, if you receive this: "Warning: domdocument::domdocument() expects at least 1 parameter", it is due to the old domxml extension, which you need to disable.

domxml overwrites DOMDocument::_construct with an alias to domxml_open_mem, so this code:
<?php
$doc = new DOMDocument();
?>
...essentially does this:
<?php
$dom = domxml_open_mem();
?>
...which is why PHP complains about expecting at least 1 parameter (it expects a string of XML).
christian dot reinecke at web dot de 15-Jul-2008 07:09
If you get the error message "domdocument::domdocument() expects parameter 2 to be long, string given"  for a code sample like this:

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

which is obviously correct if you compare the constructor signature:

__construct  ([ string $version  [, string $encoding  ]] )

make sure you're not overwritting this dom library by another (f.e. extension=php_domxml.dll in php.ini). XAMPP f.e. delivers its standard version with php_domxml.dll which ends up in this error message
dave at revlob dot com 14-Feb-2008 02:07
@Jarl

Not sure if this is what you meant when you said "The constructor example clearly shows that version and encoding only end up in the XML header", but you can also affect other parameters in the generated XML header, by accessing the DOMDocument's properties, for example:

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
bholbrook at servillian dot com 05-Dec-2007 02:25
Make sure that php_domxml.dll on windows is removed before using the domdocument class as they cannot coexist.
jarl kringelding skim punt com 24-Sep-2007 02:22
Be aware using the encoding parameter in the constructor.
It does not mean that all data is automatically encoded for you in the supplied encoding. You need to do that yourself once you choose an encoding other than the default UTF-8. See the note on DOM Functions on how to properly work with other encodings...

The constructor example clearly shows that version and encoding only end up in the XML header.


Create new attribute

  • ? DOMDocument::__construct
  • DOMDocument::createAttributeNS ?
  • PHP Manual
  • DOMDocument
  • Create new attribute

DOMDocument::createAttribute

(PHP 5, PHP 7)

DOMDocument::createAttribute — Create new attribute

说明

public DOMDocument::createAttribute ( string $localName ) : DOMAttr|false

This function creates a new instance of class DOMAttr. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

localName

The name of the attribute.

返回值

The new DOMAttr or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Skateside 05-Apr-2013 04:16
This may be obvious to most people, but it gave me a few minutes of head-scratching before I figured it out, but ampersands need to be properly escaped as HTML entities.

<?php
$doc= new DOMDocument('1.0', "UTF-8");

$invalid_elem = $doc->createElement('field', 'incorrect attribute');
$invalid_attr = $doc->createAttribute('name');
$invalid_attr->value = 'foo&bar';
$invalid_elem->appendChild($invalid_attr);
$doc->appendChild($invalid_elem);

$valid_elem = $doc->createElement('field', 'correct attribute');
$valid_attr = $doc->createAttribute('name');
$valid_attr->value = 'foo&amp;bar';
$valid_elem->appendChild($valid_attr);
$doc->appendChild($valid_elem);

?>

Will output:
<?xml version="1.0" encoding="UTF-8"?>
<field name="foo">incorrect attribute</field>
<field name="foo&bar">correct attribute</field>

As near as I can figure out, no exception is thrown for an invalid attribute. This will affect DOMDocuments created as HTML as well as XML.
Beerkeeper 09-Nov-2011 07:19
Just in case it isn't clear (like I had), an example:

<?php

$domDocument = new DOMDocument('1.0', "UTF-8");
$domElement = $domDocument->createElement('field','some random data');
$domAttribute = $domDocument->createAttribute('name');

// Value for the created attribute
$domAttribute->value = 'attributevalue';

// Don't forget to append it to the element
$domElement->appendChild($domAttribute);

// Append it to the document itself
$domDocument->appendChild($domElement);

?>

Will output:
<?xml version="1.0" encoding="UTF-8"?>
<field name="attributevalue">some random data</field>


Create new attribute node with an associated namespace

  • ? DOMDocument::createAttribute
  • DOMDocument::createCDATASection ?
  • PHP Manual
  • DOMDocument
  • Create new attribute node with an associated namespace

DOMDocument::createAttributeNS

(PHP 5, PHP 7)

DOMDocument::createAttributeNS — Create new attribute node with an associated namespace

说明

public DOMDocument::createAttributeNS ( string|null $namespace , string $qualifiedName ) : DOMAttr|false

This function creates a new instance of class DOMAttr. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

namespace

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

返回值

The new DOMAttr or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespace is null.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

_ michael 01-Jun-2010 07:35
If a new namespace is introduced while creating and inserting an attribute, createAttributeNS() does not behave in the same way as createElementNS().

(1) Location: With createAttributeNS(), the new namespace is declared at the level of the document element. By contrast, createElementNS() declares the new namespace at the level of the affected element itself.

(2) Timing: With createAttributeNS(), the new namespace is declared in the document as soon as the attribute is created - the attribute does not actually have to be inserted. createElementNS() doesn't affect the document as long as the element is not inserted.

An example:

<?php

    $source = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root><tag></tag></root>
XML;

    /*

     I. createAttributeNS:
     * a new namespace shows up immediately, even without insertion of the attribute
     * the new namespace is declared at the level of the document element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We just create a "namespace'd" attribute without appending it to any element.
    $attr_ns = $doc->createAttributeNS( '{namespace_uri_here}', 'example:attr' );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, having been added to the document element. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag/></root>

    */

    // (2) Next, we give the attribute a value and insert it.
    $attr_ns->value = 'value';
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $attr_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The "namespace'd" attribute shows up as well. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag example:attr="value"/></root>

    */

    /*

     II. createElementNS:
     * a new namespace shows up only when the element is inserted
     * the new namespace is declared at the level of the inserted element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We create a "namespace'd" element without inserting it into the document.
    $elem_ns = $doc->createElementNS( '{namespace_uri_here}', 'example:newtag' );

    print $doc->saveXML() . "\n";

    /*
      Result: The document remains unchanged. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root><tag/></root>

    */

    // (2) Next, we insert the new element.
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $elem_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, and it is embedded in the element using it. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root><tag><example:newtag xmlns:example="{namespace_uri_here}"/></tag></root>

    */

?>


Create new cdata node

  • ? DOMDocument::createAttributeNS
  • DOMDocument::createComment ?
  • PHP Manual
  • DOMDocument
  • Create new cdata node

DOMDocument::createCDATASection

(PHP 5, PHP 7)

DOMDocument::createCDATASection — Create new cdata node

说明

public DOMDocument::createCDATASection ( string $data ) : DOMCdataSection|false

This function creates a new instance of class DOMCDATASection. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

data

The content of the cdata.

返回值

The new DOMCDATASection or false if an error occurred.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Marc info[at]braincast.nl 08-Mar-2011 01:55
Here's some code that takes an associative array and prints it asXML() but creates CDATA sections for each string

<?php
class SimpleXMLExtended extends SimpleXMLElement{
    public function addCData($string){
        $dom = dom_import_simplexml($this);
        $cdata = $dom->ownerDocument->createCDATASection($string);
        $dom->appendChild($cdata);
    }
}
function assocArrayToXML($root_element_name,$ar){
    $xml = new SimpleXMLExtended("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    if (!is_numeric($k))$ch=$c->addChild($k);
                    else $ch = $c->addChild(substr($c->getName(),0,-1));
                    $f($f,$ch,$v);
                } else {
                    if (is_numeric($v)){ $c->addChild($k, $v);
                    }else{$n = $c->addChild($k); $n->addCData($v);}
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}

/* sample */
$result = array("title"=>"CDATA Sample");
$result['items'] = array();
$result['items'][] = array('title'=>'Some string', 'number' => 1);
$result['items'][] = array('title'=>'Some string', 'number' => 2);
$result['items'][] = array('title'=>'Some string', 'number' => 3);

echo assocArrayToXML('result',$result);
?>

The is_numeric check could be changed by a more elaborate regular expression to check if the string is actually xml unsafe but this worked for me.
jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:44
If you would like to refer to the documentation for the class of the returned object, see http://www.php.net/manual/en/class.domcharacterdata.php
info at troptoek dot com 24-Mar-2008 09:40
A common issue seems to be adding javascript to CDATA and the browser throwing a javascript error. To ensure the javascript works use the following code when adding CDATA:

<?php
/**
 * Append Caracter Data to a node and check for a javascript node
 *
 * @param DOMElement $appendToNode
 * @param string $text
 */
function appendCdata($appendToNode, $text)
{
    if (strtolower($appendToNode->nodeName) == 'script') {  // Javascript hack
        $cm = $appendToNode->ownerDocument->createTextNode("\n//");
        $ct = $appendToNode->ownerDocument->createCDATASection("\n" . $text . "\n//");
        $appendToNode->appendChild($cm);
        $appendToNode->appendChild($ct);
    } else {  // Normal CDATA node
        $ct = $appendToNode->ownerDocument->createCDATASection($text);
        $appendToNode->appendChild($ct);
    }
}
?>
The result should be:

<script type="text/javascript">
//<![CDATA[
function someJsText() {
   document.write('Some js with <a href="#">HTML</a> content');
}
//]]></script>
loathsome 04-Aug-2007 02:28
Here's a function that will create a CDATA-section around a string coming from SimpleXML.

<?php
function sxml_cdata($path, $string){
  $dom = dom_import_simplexml($path);
  $cdata = $dom->ownerDocument->createCDATASection($string);
  $dom->appendChild($cdata);
}
?>


Create new comment node

  • ? DOMDocument::createCDATASection
  • DOMDocument::createDocumentFragment ?
  • PHP Manual
  • DOMDocument
  • Create new comment node

DOMDocument::createComment

(PHP 5, PHP 7)

DOMDocument::createComment — Create new comment node

说明

public DOMDocument::createComment ( string $data ) : DOMComment|false

This function creates a new instance of class DOMComment. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

data

The content of the comment.

返回值

The new DOMComment or false if an error occurred.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

php dot sirlancelot at spamgourmet dot com 25-Nov-2009 12:10
To prevent a parser error when the comment string would contain the character sequence "--", do this:

<?php

$CommentString = 'This contains -- some weird -- characters.';

$CommentNode = $DomDocument->createComment(
        str_replace('--', '-'.chr(194).chr(173).'-', $CommentString)
);
?>

This will insert a Soft Hyphen in between the two hyphens which will not cause the parser to error out.
capps at solareclipse dot net 29-Mar-2007 03:55
Use caution: this function does NOT escape, encode, or otherwise change the contents of the string.

This means that if your string contains two hyphens in a row (--), that will *end* the comment, which can easily create invalid XML when the document is serialized.


Create new document fragment

  • ? DOMDocument::createComment
  • DOMDocument::createElement ?
  • PHP Manual
  • DOMDocument
  • Create new document fragment

DOMDocument::createDocumentFragment

(PHP 5, PHP 7)

DOMDocument::createDocumentFragment — Create new document fragment

说明

public DOMDocument::createDocumentFragment ( ) : DOMDocumentFragment|false

This function creates a new instance of class DOMDocumentFragment. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

返回值

The new DOMDocumentFragment or false if an error occurred.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

There are no user contributed notes for this page.


Create new element node

  • ? DOMDocument::createDocumentFragment
  • DOMDocument::createElementNS ?
  • PHP Manual
  • DOMDocument
  • Create new element node

DOMDocument::createElement

(PHP 5, PHP 7)

DOMDocument::createElement — Create new element node

说明

public DOMDocument::createElement ( string $localName , string $value = "" ) : DOMElement|false

This function creates a new instance of class DOMElement. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

localName

The tag name of the element.

value

The value of the element. By default, an empty element will be created. The value can also be set later with DOMElement::$nodeValue.

The value is used verbatim except that the < and > entity references will escaped. Note that & has to be manually escaped; otherwise it is regarded as starting an entity reference. Also " won't be escaped.

返回值

Returns a new instance of class DOMElement or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

范例

Example #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

以上例程会输出：

<?xml version="1.0" encoding="utf-8"?>
<test>This is the root element!</test>

Example #2 Passing text containing an unescaped & as value

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('foo', 'me & you');
$dom->appendChild($element);
echo $dom->saveXML();
?>

以上例程的输出类似于：

Warning: DOMDocument::createElement(): unterminated entity reference             you in /in/BjTCg on line 4
<?xml version="1.0" encoding="utf-8"?>
<foo/>

注释

Note:

The value will not be escaped. Use DOMDocument::createTextNode() to create a text node with escaping support.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

dignat at yahoo dot com 15-Nov-2017 10:25
To create an element with DomDocument and to escape ampersand in the value.

Do this:

$element = new DOMDocument('1.0', 'UTF-8');

$test = $element->createElement('text');

$test ->appendChild($element->createElement('name'))
      ->appendChild($element->createtextNode('& I am ampersand');
tschmieder at bitworks dot de 24-Mar-2015 05:42
Remember:

If you want to perform multiple actions with a new node, you may need to create a copy of it before

means:
## Create an address to an unique memory block !
$td = $dom->createElement('td');
## Change some things in this original unique pattern
$td->setAttribute('class', 'saldo');

## clone the unique pattern to two own one's
$td1 = clone $td;
$td2 = clone $td;

## alter properties in each one
$td1->nodeValue = 'Ich bin die erste neue Node';
$td2->nodeValue = 'Ich bin die zweite neue Node';

## find the parent element
$tr = $dom->getElementById('t001-tr001');
## find the first and the last child (here only for clearity)
$first = $tr->firstChild;
$last = $tr->lastChild;

## produce the new nodes
$newtd1 = $tr->insertBefore($td1, $first);
$newtd2 = $tr->appendChild($td2);

conclusion:
YOU NEED AN ORIGINAL NEW NODE FOR EACH ACTION!
funkathustra 04-Mar-2012 08:44
Although the built-in DOM functions are great, since they're designed to support generic XML, generating HTML DOMs becomes particularly verbose. I ended up writing this function to drastically speed things up.
Instead of calling something like
<?php
  $div = $dom->createElement("div");
  $div->setAttribute("class","MyClass");
  $div->setAttribute("id","MyID");
  $someOtherDiv->appendChild($div);
?>
you can accomplish the same thing with:
<?php
  $div = newElement("div", $someOtherDiv, "class=MyClass;id=MyID");
?>
The "key1=value;key2=value" syntax is really fast to use, but obviously doesn't hold up if your content has those characters in it. So, you can also pass it an array:
<?php
  $div = newElement("div", $someOtherDiv, array("class","MyClass"));
?>
Or an array of arrays, representing different attributes:
<?php
  $div = newElement("form", $someOtherDiv, array(array("method","get"), array("action","/refer/?id=5");
?>

Here's the function:

<?php
function newElement($type, $insertInto = NULL, $params=NULL, $content="")
    {
        $tempEl =  $this->dom->createElement($type, $content);
        if(gettype($params) == "string" && strlen($params) > 0)
        {
            $attributesCollection =split(";", $params);
            foreach($attributesCollection  as $attribute)
            {
                $keyvalue = split("=", $attribute);
                $tempEl->setAttribute($keyvalue[0], $keyvalue[1]);
            }
        }
        if(gettype($params) == "array")
        {
            if(gettype($params[0]) == "array")
            {
                foreach($params as $attribute)
                {
                    $tempEl->setAttribute($attribute[0], $attribute[1]);
                }
            } else {
                $tempEl->setAttribute($params[0], $params[1]);
            }
        }
?>
lars dot c dot magnusson at gmail dot com 26-Nov-2010 01:56
You may think insertBefore and insertAfter is a direct alternative for appendChild, this is not the case.

<?php
$dom = new DOMDocument();
$dom->load($file);

$dom->appendChild($newNode); //Works fine
$dom->insertBefore($newNode, $refNode); //Will fail

$refNode->parentNode->insertBefore($newNode, $refNode); // thanx to yasindagli (first post)
?>
yasindagli at gmail dot com 17-Jun-2009 02:01
To create elements with attributes,

<?php

function createElement($domObj, $tag_name, $value = NULL, $attributes = NULL)
{
    $element = ($value != NULL ) ? $domObj->createElement($tag_name, $value) : $domObj->createElement($tag_name);

    if( $attributes != NULL )
    {
        foreach ($attributes as $attr=>$val)
        {
            $element->setAttribute($attr, $val);
        }
    }

    return $element;
}

$dom = new DOMDocument('1.0', 'utf-8');

$elm = createElement($dom, 'foo', 'bar', array('attr_name'=>'attr_value'));

$dom->appendChild($elm);

echo $dom->saveXML();

?>

outputs :
<?xml version="1.0" encoding="utf-8"?>
<foo attr_name="attr_value">bar</foo>
chris AT cmbuckley DOT co DOT uk 26-May-2009 07:45
Note that the NUL character "\0" is not in the list of invalid characters for $name, so no error is triggered, but the tag name will be truncated at the null byte:

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$el = $dom->createElement('foo' . "\0" . 'bar', 'Hello World');
echo $el->tagName; // outputs "foo"

?>
estill at gvtc dot com 12-Jun-2007 02:38
Note that the second parameter (value), although convenient, is non-standard. You should create elements like this instead:

<?php
$doc = new DOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElement('test');
$doc->appendChild($root);

$root_text = $doc->createTextNode('This is the root element!');
$root->appendChild($root_text);

print $doc->saveXML();
?>

Or, alternatively, extend the DOMDocument class and add your own custom, convenience method to avoid intruding on the standard:

<?php
class CustomDOMDocument extends DOMDocument {
  function createElementWithText($name, $child_text) {
    // Creates an element with a child text node

    // @param  string  $name        element tag name
    // @param  string  $child_text  child node text

    // @return  object  new element

    $element = $this->createElement($name);

    $element_text = $this->createTextNode($child_text);
    $element->appendChild($element_text);

    return $element;
  }
}

$doc = new CustomDOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElementWithText('test', 'This is the root element!');
$doc->appendChild($root);

print $doc->saveXML();
?>

Also use caution with (or avoid) the 'DOMElement->nodeValue' property. It can return some unexpected values and changing its value will replace (remove) all descendants of the element with a single text node. It's also non-standard; according to the DOM spec it should return NULL.
mikek dot nospam at nospam dot muonics dot com 03-Mar-2007 05:24
With regard to the note below about needing htmlentities to avoid warnings about unterminated entity references, I thought it worthwhile to mention that that you don't need to with createTextNode and DOMText::__construct.  If you mix both methods of setting text nodes and do (or don't) apply htmlentities consistently to all data to be displayed, you'll get &amp;s (or warnings and badly-formed xml).

It's probably in one's best interest to extend DOMElement and DOMDocument so that it creates a DOMText node and appends it, rather than passing it up to the DOMElement constructor.  Otherwise, good luck using (or not using) htmlentities in all the right places in your code, especially as code changes get made.

<?php

class XDOMElement extends DOMElement {
    function __construct($name, $value = null, $namespaceURI = null) {
        parent::__construct($name, null, $namespaceURI);
    }
}

class XDOMDocument extends DOMDocument {
    function __construct($version = null, $encoding = null) {
        parent::__construct($version, $encoding);
        $this->registerNodeClass('DOMElement', 'XDOMElement');
    }

    function createElement($name, $value = null, $namespaceURI = null) {
        $element = new XDOMElement($name, $value, $namespaceURI);
        $element = $this->importNode($element);
        if (!empty($value)) {
            $element->appendChild(new DOMText($value));
        }
        return $element;
    }
}

$doc1 = new XDOMDocument();
$doc1_e1 = $doc1->createElement('foo', 'bar & baz');
$doc1->appendChild($doc1_e1);
echo $doc1->saveXML();

$doc2 = new XDOMDocument();
$doc2_e1 = $doc2->createElement('foo');
$doc2->appendChild($doc2_e1);
$doc2_e1->appendChild($doc2->createTextNode('bar & baz'));
echo $doc2->saveXML();

?>

Text specified in createElement:
<?xml version=""?>
<foo>bar &amp; baz</foo>

Text added via createTextNode:
<?xml version=""?>
<foo>bar &amp; baz</foo>
sergsokolenko at gmail dot com 30-Jan-2007 04:11
To avoid warning message "unterminated entity reference" you may use htmlentities() for escaping supplied value:
<?php
//...
$dom->createElement('name', htmlentities($text))
//...
?>


Create new element node with an associated namespace

  • ? DOMDocument::createElement
  • DOMDocument::createEntityReference ?
  • PHP Manual
  • DOMDocument
  • Create new element node with an associated namespace

DOMDocument::createElementNS

(PHP 5, PHP 7)

DOMDocument::createElementNS — Create new element node with an associated namespace

说明

public DOMDocument::createElementNS ( string|null $namespace , string $qualifiedName , string $value = "" ) : DOMElement|false

This function creates a new element node with an associated namespace. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

namespace

The URI of the namespace.

qualifiedName

The qualified name of the element, as prefix:tagname.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement::$nodeValue.

返回值

The new DOMElement or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a maformed qualified name.

范例

Example #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

以上例程会输出：

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

Example #2 A namespace prefix example

<?php
$doc  = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);

echo $doc->saveXML(), "\n";

echo $item->namespaceURI, "\n"; // Outputs: http://base.google.com/ns/1.0
echo $item->prefix, "\n";       // Outputs: g
echo $item->localName, "\n";    // Outputs: item_type
?>

以上例程会输出：

<?xml version="1.0" encoding="utf-8"?>
<element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
  <g:item_type>house</g:item_type>
</element>

http://base.google.com/ns/1.0
g
item_type

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Martin 27-Dec-2011 09:39
To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).


Create new entity reference node

  • ? DOMDocument::createElementNS
  • DOMDocument::createProcessingInstruction ?
  • PHP Manual
  • DOMDocument
  • Create new entity reference node

DOMDocument::createEntityReference

(PHP 5, PHP 7)

DOMDocument::createEntityReference — Create new entity reference node

说明

public DOMDocument::createEntityReference ( string $name ) : DOMEntityReference|false

This function creates a new instance of class DOMEntityReference. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

返回值

The new DOMEntityReference or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

alicewonder at shastaherps dot org 24-Sep-2015 07:48
It appears that this does not work with numbered entities, only named entities.

$nbspace = $dom->createEntityReference('nbsp');

works

$nbspace = $dom->createEntityReference('#160');

does not. This makes this function rather useless when generating an XSL unless you modify the XSL doctype to include the named entity for the character you want.
Tuhin Bepari 04-Nov-2013 06:00
<?php
/*Entity is a group of words which print a special symbol.
Like if we want to show copy right symbol in html page then we use &copy; code and browser convert this to actual copyright symbol.
There have lots of entity, you can find them all form http://dev.w3.org/html5/html-author/charref
if you want to use < or > or both <> into a node value than xml will give and warning or make this value as a node.
So tell the xml parser that < or > is not tag symbol it is a entity.To do that you have to right &lt(<) and &gt;(>) instead of < and > symbol.

Entity references always begin with an ampersand (&) and end with a semicolon (;).
DO not need to use & and ; symbol begin and end of entity.Remove it when you want to use it to DOMDocument::createEntityReference
Then append to to a tag where you want to show this symbol.Like below
*/
$dom=new DOMDocument("1.0","UTF-8");
$example=$dom->createElement("example","This is copyright ");
$entity=$dom->createEntityReference("copy");
$example->appendChild($entity);
$dom->appendChild($example);
echo $dom->saveXML();

output is
This is copyright ©


Creates new PI node

  • ? DOMDocument::createEntityReference
  • DOMDocument::createTextNode ?
  • PHP Manual
  • DOMDocument
  • Creates new PI node

DOMDocument::createProcessingInstruction

(PHP 5, PHP 7)

DOMDocument::createProcessingInstruction — Creates new PI node

说明

public DOMDocument::createProcessingInstruction ( string $target , string $data = "" ) : DOMProcessingInstruction|false

This function creates a new instance of class DOMProcessingInstruction. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

target

The target of the processing instruction.

data

The content of the processing instruction.

返回值

The new DOMProcessingInstruction or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

romain at supinfo dot com 03-Feb-2009 11:57
A use exemple of this method :

Usefull for generating an XML linked with a XSLT !

<?php

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

//to have indented output, not just a line
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;

// ------------- Interresting part here ------------

//creating an xslt adding processing line
$xslt = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="base.xsl"');

//adding it to the xml
$xml->appendChild($xslt);

// ----------- / Interresting part here -------------

//adding some elements
$root = $xml->createElement("list");
$node = $xml->createElement("contact", "John Doe");
$root-> appendChild($node);
$xml-> appendChild($root);

//creating the file
$xml-> save("output.xml");

?>

output.xml :

<?xml version="1.0" encoding="ISO-8859-15"?>
<?xml-stylesheet type="text/xsl" href="base.xsl"?> //the line has been created successfully
<list>
  <contact>John Doe</contact>
</list>


Create new text node

  • ? DOMDocument::createProcessingInstruction
  • DOMDocument::getElementById ?
  • PHP Manual
  • DOMDocument
  • Create new text node

DOMDocument::createTextNode

(PHP 5, PHP 7)

DOMDocument::createTextNode — Create new text node

说明

public DOMDocument::createTextNode ( string $data ) : DOMText|false

This function creates a new instance of class DOMText. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

data

The content of the text.

返回值

The new DOMText or false if an error occurred.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node

User Contributed Notes

drewish at katherinehouse dot com 16-Dec-2014 10:03
The docs don't mention it but this method performs escaping on the value. If you don't want that use createElement() instead.
Alex Kaye 25-Jul-2009 07:04
A quick note to anyone who is using character entities (e.g. &copy;) in this, and finding them automatically escaped. The correct thing to do here is to use the createEntityReference method (e.g. createEntityReference("copy");), and then appendChild this entity between text nodes.

Example:

<?php
$copyright_text_1 = $this->document->createTextNode("Copyright ");
$copyright_text_2 = $this->document->createTextNode(" Alex Kaye 2009");
$copyright_symbol = $this->document->createEntityReference("copy");
$copyright->appendChild($copyright_text_1);
$copyright->appendChild($copyright_symbol);
$copyright->appendChild($copyright_text_2);
?>


Searches for an element with a certain id

  • ? DOMDocument::createTextNode
  • DOMDocument::getElementsByTagName ?
  • PHP Manual
  • DOMDocument
  • Searches for an element with a certain id

DOMDocument::getElementById

(PHP 5, PHP 7)

DOMDocument::getElementById — Searches for an element with a certain id

说明

public DOMDocument::getElementById ( string $elementId ) : DOMElement|null

This function is similar to DOMDocument::getElementsByTagName but searches for an element with a given id.

For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

参数

elementId

The unique id value for an element.

返回值

Returns the DOMElement or null if the element is not found.

范例

Example #1 DOMDocument::getElementById() Example

以下范例使用了 book.xml，其内容如下：

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [
  <!ELEMENT books   (book+)>
  <!ELEMENT book    (title, author+, xhtml:blurb?)>
  <!ELEMENT title   (#PCDATA)>
  <!ELEMENT blurb   (#PCDATA)>
  <!ELEMENT author  (#PCDATA)>
  <!ATTLIST books   xmlns        CDATA  #IMPLIED>
  <!ATTLIST books   xmlns:xhtml  CDATA  #IMPLIED>
  <!ATTLIST book    id           ID     #IMPLIED>
  <!ATTLIST author  email        CDATA  #IMPLIED>
]>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://books.php/" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <book id="php-basics">
    <title>PHP Basics</title>
    <author email="jim.smith@basics.php">Jim Smith</author>
    <author email="jane.smith@basics.php">Jane Smith</author>
    <xhtml:blurb><![CDATA[
<p><em>PHP Basics</em> provides an introduction to PHP.</p>
]]></xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>PHP Advanced Programming</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>
  </book>
</books>
<?php

$doc = new DomDocument;

// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

以上例程会输出：

The element whose id is 'php-basics' is: book

参见

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

User Contributed Notes

Hoi 07-Jul-2020 10:39
To set a hidden id that can be used by $dom->getElementById() apply setAttribute('id', true) as in the following example

                    $createItemNode = function ($data) use ($dom) {
                        $node = $dom->createElement("Item");
                        $node->setAttribute('id', $data->id);
                        $node->setAttribute('hed', $data->hed);
                        $node->setAttribute('run_time', $data->run_time);
                        $node->setAttribute('date', $data->date);

                        // Internally mark the id as 'xml:id' for getElementById to work. Adding xml:id manually to the tag will cause loadXML to throw an error DOMDocument: xml:id is not a NCName in Entity
                        $node->setIdAttribute('id', true);

                        return $node;
                    };

With $node->setIdAttribute('id', true), $dom->getElementById($id) will work

When you do $dom->saveXML(), the final doc will not contain any xml:id attribute.
ed at edgiardina dot com 13-Oct-2010 11:41
Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null.
paradox_haze at live dot de 02-Mar-2010 10:53
Had some issues with getElementById() while searching for a specific element in a XHTML document.
I wrote a small function what was solving my problem:

<?php
function getElementById($id)
{
    $xpath = new DOMXPath($this->domDocument);
    return $xpath->query("//*[@id='$id']")->item(0);
}
?>
carl2088 at gmail dot com 11-Apr-2009 12:41
From my experience, getElementById seem to work fine without any setups if you have loaded a HTML document. But in order for getElementById to work with a simple XML document that you've "constructed", you have to set up the id with "xml:" prefix and use setIdAttribute on the element you created or it won't work. See following example, hope this will save someone's frustration. If you have loaded the xml file, then all you have to make sure is the ID has a xml: prefix for the attribute.  But if you start to append the XML document, don't forget to setIdAttribute on the id name or those elements or getElementById will return null when you try to find them.

<?php

    /* test.xml
    <?xml version="1.0" encoding="utf-8"?>
    <root>
        <child xml:id="id_xxxxxx" status="partial">
            <sub_child>Some Data</sub_child>
        </child>
    </root>
    */

    $xmlDom = new DOMDocument('1.0', 'utf-8');
    $xmlDom->formatOutput = true;                        // we want a nice output

    // create a root
    $eltRoot = $xmlDom->createElement("root");
    $xmlDom->appendChild($eltRoot);

    $eltChild = $xmlDom->createElement("child");
    $eltRoot->appendChild($eltChild);

    // add a id attribute
    $attr = $xmlDom->createAttribute("xml:id");    // needs xml prefix or getElementById won't work
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("id_8120528");
    $attr->appendChild($tNode);
    $eltChild->setIdAttribute("xml:id", true);    // VERY IMPORT or getElementById won't work

    // add a id attribute
    $attr = $xmlDom->createAttribute("status");
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("partial");
    $attr->appendChild($tNode);

    // add a subchild
    $eltSub = $xmlDom->createElement("sub_child");
    $eltChild->appendChild($eltSub);

    $tNode = $xmlDom->createTextNode("Some Data");
    $eltSub->appendChild($tNode);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // bug? empty
    $strStatus = $id->getAttribute("status"); // this works!

    assert ($id !=null);

    $xmlDom->save("./_data/test.xml");

    $xmlDom->load("./_data/test.xml"); // reloading fixes the problem

    $nodeRoot = $xmlDom->getElementsByTagName("root");
    if ($nodeRoot->length > 0) {
        $eltRoot = $nodeRoot->item(0);
    }

    assert($eltRoot != null);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // this works now!
    $strStatus = $id->getAttribute("status"); // this works!

?>
guillaume dot crico at gmail dot com 01-Oct-2008 07:55
You don't want to use "xml:id" ?
Here is the relaxNG trick (with a generic schema):
(tested with libxml 2.6.26)

<?php
$doc = new DOMDocument();
$doc->load(...);

$rng = '
<grammar xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
    <start>
        <element>
            <anyName/>
            <ref name="anythingID"/>
        </element>
    </start>
    <define name="anythingID">
        <zeroOrMore>
            <choice>
                <element>
                    <anyName/>
                    <ref name="anythingID"/>
                </element>
                <attribute name="id">
                    <data type="ID"/>
                </attribute>
                <zeroOrMore>
                    <attribute><anyName/></attribute>
                </zeroOrMore>
                <text/>
            </choice>
        </zeroOrMore>
    </define>
</grammar>
';

$doc->relaxNGValidateSource($rng);
var_dump($doc->getElementById('id1'));
?>

Note that ID values must be valid ones :
  - integers do no work!
  - @see http://www.w3.org/TR/REC-xml/#id
  - => (Letter | '_' | ':') ( Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender  )*
simon at somewhere dot com 29-Jan-2007 08:07
SAVE YOURSELF A MAJOR HEADACHE AND A LOT OF SEARCHING THROUGH DOCUMENTATION -

Instead of using $object->setAttribute('id', 'id_name_here')
USE THIS: $object->setAttribute('xml:id', 'id_name_here')

Then, to get the node value: $domDocumentObject->getElementById('id_name_here');

The xml:id attribute should AUTOMATICALLY be defined!!

Woohoo!  That was easy......
jonbarnett at gmail dot com 01-Nov-2006 08:36
If your XML document does not have a DTD that defines the "id" attribute as an ID, then the easiest thing to do is to use XPath->query() to find an element that matches "//[@id='x']"
Tangui dot Le-Pense at laposte dot net 08-Apr-2006 06:00
Validating a document from a DTD so as to use getElementById is sometimes impossible (for example when the head and body elements are not included yet in a XHtml document : the validation failed).
Fortunately, xml:id is supported by this function :)
That may be useful.
http://www.w3.org/TR/xml-id/
20-Dec-2005 07:04
If you're trying to use getElementById with a xml file validated on a xsd file you must first use the schemaValidate function or getElementById will return null
Example:

  $dom = new DomDocument();
  $dom->load("users.xml");
  $dom->schemaValidate("users.xsd");

  $curruser = $dom->getElementById($user->name);
bart at mediawave dot nl 11-Sep-2005 04:46
It seems getElementById works fine without setting validateOnParse to true. Which is nice since setting this to true caused some performance problems with my script.


Searches for all elements with given local tag name

  • ? DOMDocument::getElementById
  • DOMDocument::getElementsByTagNameNS ?
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given local tag name

DOMDocument::getElementsByTagName

(PHP 5, PHP 7)

DOMDocument::getElementsByTagName — Searches for all elements with given local tag name

说明

public DOMDocument::getElementsByTagName ( string $qualifiedName ) : DOMNodeList

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

参数

qualifiedName

The local name (without namespace) of the tag to match on. The special value * matches all tags.

返回值

A new DOMNodeList object containing all the matched elements.

范例

Example #1 Basic Usage Example

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
 <book>Patterns of Enterprise Application Architecture</book>
 <book>Design Patterns: Elements of Reusable Software Design</book>
 <book>Clean Code</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}
?>

以上例程会输出：

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

参见

  • DOMDocument::getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace

User Contributed Notes

Mateusz K 19-Dec-2019 08:04
If you want to move all nodes to another tag you can do it like that
Eg: replace <div> with nodes to <p> with the same nodes.

function replaceDomElementTag(DOMDocument $dom, DOMElement $node, string $tagName)
{
        $newElement = $dom->createElement($tagName);
        while ($node->childNodes->length)
            $newElement->appendChild($node->childNodes[0]);

        $node->parentNode->replaceChild($newElement, $node);
}

$dom = new DOMDocument();
replaceDomElementTag($dom, $divElementToReplace, 'p');
rsvvuuren at hotmail dot com 10-Jan-2014 10:00
I was in need of $dom->getElementsByTagName that would hist magic within a contextNode.

Why i needed getElementsByTagName instead of just simple using an xPath->query is because while looping through the returned nodelist, more nodes with the tagName i was looking for where created.

When using getElementsByTagName, the new nodes are "added" to the nodelist i already am looping through.

When using an xpath query, you wil only loop through the original nodelist, the newly created elements wil not appear in that nodelist.

I was already using an extended class on domDocument, so it was simple to create an kind of getElementsByTagName that would accept an contextNode.

<?php
class SmartDocument extends DOMDocument {
    private $localDom;
    public $xpath;
    private $serialize = array('localDom');

    private $elemName;
    private $elemCounter;

    /**
     * Constructor
     */
    function __construct() {
        parent::__construct ( '1.0', 'UTF-8' );
        $this->preserveWhiteSpace = false;
        $this->recover = TRUE;
        $this->xpath = new DOMXpath ( $this );
    }

    /**
     * GetElementsByTagname within an contextNode
     *
     * @param string $name
     * @param DomNode $contextNode
     * @return DOMNode|NULL
     */
    public function getElementsByTagNameContext($name, $contextNode) {

        if($this->elemName!=$name) {
            $this->elemCounter     = 0;
            $this->elemName        =$name;
        }

        $this->elemLength      = $this->xpath->evaluate('count(.//*[name()="'.$this->elemName.'"])', $contextNode);
        while($this->elemCounter < $this->elemLength) {
            $this->elemCounter++;
            $nl = $this->xpath->query('.//*[name()="'.$this->elemName.'"]['.$this->elemCounter.']', $contextNode);
            if($nl->length == 1) {
                return $nl->item(0);
            }
        }

        $this->elemLength      = null;
        $this->elemCounter     = null;
        $this->elemName        = null;
        return null;
    }
}

?>

Usage:

<?php

 $doc = new SmartDocument();
 $doc->load('book.xml');

 $nl = $doc->query('//books');
 foreach($nl as $node) {
  while($book = $doc->getElementsByTagNameContext('book', $node)) {
   //When you now create new nodes within this loop as child or following-sibling of this node
  // They show up within this loop
  }

 }

?>
simon at onepointltd dot com 10-Sep-2013 07:54
Here is a function to convert the populated tables in and HTML document into an array.

<?php
//Create an array containing all the populated tables in an HTML page
//Returned array: tables_to_array[table number][row number][column number]
function tables_to_array ($url) {
  $htmlDocDom = new DOMDocument();

  @$htmlDocDom->loadHTMLFile($url);
  $htmlDocDom->preserveWhiteSpace = false;
  $tableCounter = 0;
  $htmlDocTableArray = array();
  $htmlDocTables = $htmlDocDom->getElementsByTagName('table');
  foreach ($htmlDocTables as $htmlDocTable) {
    $htmlDocTableArray[$tableCounter] = array();
    $htmlDocRows= $htmlDocTable->getElementsByTagName('tr');
    $htmlDocRowCount = 0;
    $htmlDocTableArray[$tableCounter] = array();
    foreach ($htmlDocRows as $htmlDocRow) {
      if (strlen($htmlDocRow->nodeValue) > 1)
      {
        $htmlDocColCount = 0;
        $htmlDocTableArray[$tableCounter][$htmlDocRowCount] = array();
        $htmlDocCols = $htmlDocRow->getElementsByTagName('td');
        foreach ($htmlDocCols as $htmlDocCol) {
          $htmlDocTableArray[$tableCounter][$htmlDocRowCount][] = $htmlDocCol->nodeValue;
          $htmlDocColCount++;
        }
        $htmlDocRowCount++;
      }
    }
    if ($htmlDocRowCount > 1) $tableCounter++;
  }
  return($htmlDocTableArray);
}
?>
yaakov dot moddel at gmail dot com 28-Aug-2012 10:47
This is a very simplistic way to traverse xml nodes and childnodes using the DOMDocument class

<?php
$xml ='<?xml version="1.0" encoding="utf-8"?>
<root>
    <Parent>
        <child>child 1</child>
        <child>child 2</child>
        <child>child 3</child>
        <subParent>
            <Grandchild>Grandchild 1</Grandchild>
            <Grandchild>Grandchild 2</Grandchild>
            <Grandchild>Grandchild 3</Grandchild>
        </subParent>
    </Parent>
    <Parent>
        <child>child 4</child>
        <child>child 5</child>
        <child>child 6</child>
        <subParent>
            <Grandchild>Grandchild 4</Grandchild>
            <Grandchild>Grandchild 5</Grandchild>
            <Grandchild>Grandchild 6</Grandchild>
        </subParent>
    </Parent>
</root>';
      $doc = new DOMDocument();
      $doc->preserveWhiteSpace = false;
      $doc->loadXML($xml);
      $i=0;
            while(is_object($finance = $doc->getElementsByTagName("Parent")->item($i)))
            {
                     foreach($finance->childNodes as $nodename)
                     {
                             if($nodename->nodeName=='subParent')
                                {
                                     foreach($nodename->childNodes as $subNodes)
                                     {
                                     echo $subNodes->nodeName." - ".$subNodes->nodeValue."<br>";
                                     }
                                }
                             else
                                {
                                echo $nodename->nodeName." - ".$nodename->nodeValue."<br>";
                                }
                     }
      $i++;
            }
?>
metron at underhive-planet dot com 08-Oct-2010 05:28
My first try to get a stable solution with this function, failed with this Exception:

"Fatal error: Call to undefined method DOMNodeList::getElementsByTagName()"
This is the xml snipplet:
<?xml version="1.0" encoding="UTF-8"?>
<root>
 <component>
  <properties>
    ....<any element>
  </properties>
 </component>
</root>

So the php code to climb along the elements is:
<?php

$src = new DOMDocument('1.0', 'utf-8');
$src->formatOutput = true;
$src->preserveWhiteSpace = false;

//Loading extern file
$src->load('../xml/Item_component.xml');

//Check each child of first indexed branch node of: <component>
//First get element after root element: <component>

//1st level
$component = $src->getElementsByTagName('component')->item(0);

//2nd level, get next element after component, here it fails!!
$properties = $component->getElementsByTagName('properties')->item(0);
...
?>

I realised, that there is a different when using different libxml2 versions on Apache2. This code will fail with libxml2 version 2.6.23 and PHP version 5.2.6
--
->It works fine with libxml2 version 2.6.32 and PHP version 5.2.6-3ubuntu4.6
->...and finally it also works with libxml2 2.7.7 and PHP >= 5.3

So if you bored to search for solutions with DOM like I did, please ensure that your www environment has the correct libxml2 / PHP Version installed on your apache2 server.
calvin at g mail 02-Oct-2010 04:41
My first post!
And this is how I get elements by attribute and its value.
For an example, if I want to grab all DIV tags with class name 'className', then...

<?php
$some_link = 'some website';
$tagName = 'div';
$attrName = 'class';
$attrValue = 'className';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile($some_link);

$html = getTags( $dom, $tagName, $attrName, $attrValue );
echo $html;

function getTags( $dom, $tagName, $attrName, $attrValue ){
    $html = '';
    $domxpath = new DOMXPath($dom);
    $newDom = new DOMDocument;
    $newDom->formatOutput = true;

    $filtered = $domxpath->query("//$tagName" . '[@' . $attrName . "='$attrValue']");
    // $filtered =  $domxpath->query('//div[@class="className"]');
    // '//' when you don't know 'absolute' path

    // since above returns DomNodeList Object
    // I use following routine to convert it to string(html); copied it from someone's post in this site. Thank you.
    $i = 0;
    while( $myItem = $filtered->item($i++) ){
        $node = $newDom->importNode( $myItem, true );    // import node
        $newDom->appendChild($node);                    // append node
    }
    $html = $newDom->saveHTML();
    return $html;
}

?>

Please, improve it, and share it.
Philip N 01-Sep-2010 03:17
Note that when using getElementsByTagName that it is a dynamic list. Thus if you have code which adjusts the DOM structure it will change the results of the getElementsByTagName results list.

The following code iterates through a complete set of results and changes them all to a new tag:

<?php
 $nodes = $xml->getElementsByTagName ("oldtag");

 $nodeListLength = $nodes->length; // this value will also change
 for ($i = 0; $i < $nodeListLength; $i ++)
 {
    $node = $nodes->item(0);

    // some code to change the tag name from "oldtag" to something else
    // e.g. encrypting a tag element
 }
?>

Since the list is dynamically updating, $nodes->item(0) is the next "unchanged" tag.
Marco Maranao 27-Apr-2010 10:22
The following takes a list of news items from an XML file (or an RSS feed), assigning it to an array first for a name value pair and then generating an HTML list.

<?php

$xml  =<<<EOT
<?xml version="1.0" encoding="ISO-8859-1"?>
<news>
    <item>
        <title>News 1</title>
        <created>04/2/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 2</title>
        <created>04/25/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 3</title>
        <created>04/27/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
</news>
EOT;

$doc = new DOMDocument();

if ($doc->loadXML($xml)) {
    $items = $doc->getElementsByTagName('item');
    $headlines = array();

    foreach($items as $item) {
        $headline = array();

        if($item->childNodes->length) {
            foreach($item->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }

        $headlines[] = $headline;
    }

    if(!empty($headlines)) {
        $hc = 0;

        echo '<ul>';

        foreach($headlines as $headline) {
            if(++$hc <= 3) {
                echo '<li>'
                    .'<a href="'.$headline['url'].'" target="_blank">'
                        .'<span>'.date('F j, Y', strtotime($headline['created'])).'</span><br />'
                        .$headline['title']
                    .'</a>'
                .'</li>';
            }
        }

        echo '</ul>';
    }
}

?>
james 01-Feb-2010 07:03
Problem:
You have an XML document that contains filename references to, say, images. Each filename reference is defined by <file>filename.ext</file> tag. You'd like to perform perform additional validation, say, after running the XML document through XSD validation. The additional validation can be any of your choice, in this example, it would be ideal to convert the PHP code to a function. The function would then determine if the images exist and return either an integer value or a boolean.

<?xml version="1.0"?>
<root>
<box>
<file>example.png</file>
</box>
<content>
<item>
<image><file>example2.png</file></image>
<caption>The above image is an example</caption>
</item>
</content>
</root>

Solution:
<?php

$dom = new DomDocument();
$dom->prevservWhiteSpace = false;

if (!@$dom->load("example.xml")) {
    echo "example.xml doesn't exist!\n";
    return;
}

$imageList = $dom->getElementsByTagName('file');
$imageCnt  = $imageList->length;

for ($idx = 0; $idx < $imageCnt; $idx++) {
    print $imageList->item($idx)->nodeValue . "\n";
}

?>

The above PHP code could easily be turned into a function that returns an array of image filenames, an integer value relative to the number of images found, etc.

Hope this is helpful.
gurmukh24 at gmail dot com 03-Mar-2009 04:06
Following Example is of multiple attributes and multiple child nodes. this is being used to make joomla plugin for bulk upload of articles. Gurmukh Singh Bhatti

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<root>
<section name="Section1">
  <category id="Category1" name="google">
   <arti name="article1">
   <p>any html code here</p>
   <b>my name is so so</b>
    </arti>
   <arti name="article2">value2</arti>
   <arti name="article3">value3</arti>
   <arti name="article4">value4</arti>
  </category>
    <category id="Category2" name="yahoo">
   <arti name="articleSection2">Test value</arti>
  </category>
</section>
<section name="Section2">
  <category id="category1_of_section2" name="msn">
   <arti name="article2">value1</arti>
   <arti name="article3">value2</arti>
  </category>
    <category id="Category2_of_section2" name="webcare">
    <arti name="param3">value4</arti>
   </category>
</section>
</root>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('section'); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
         echo "Section Attribute :-> ".$params->item($k)->getAttribute('name')."<br>";   //get section attribute
         $params2 = $params->item($k)->getElementsByTagName('category'); //digg categories with in Section
      $i=0; // values is used to iterate categories
        foreach ($params2 as $p) {
           echo "&nbsp;&nbsp;- Category Attribute Name :-> ".$params2->item($i)->getAttribute('name')."<br>"; //get Category attributes
            $params3 = $params2->item($i)->getElementsByTagName('arti'); //dig Arti into Categories
                 $j=0;//values used to interate Arti
                     foreach ($params3 as $p2)
                   {
                    echo "&nbsp;&nbsp;&nbsp;- Article Attribute Name : ".$params3->item($j)->getAttribute('name').""; //get arti atributes
echo "&nbsp;&nbsp; Value : ".$params3->item($j)->nodeValue."<br>"; //get Node value ;
                              $j++;
                   }
         $i++;
      }
$k++;

}
?>

output :
 Section Attribute :-> Section1
  - Category Attribute Name :-> google
            - Article Attribute Name : article1   Value : any html code heremy name is so so
            - Article Attribute Name : article2   Value : value2
            - Article Attribute Name : article3   Value : value3
            - Article Attribute Name : article4   Value : value4
  - Category Attribute Name :-> yahoo
            - Article Attribute Name : articleSection2   Value : Test value
Section Attribute :-> Section2
  - Category Attribute Name :-> msn
            - Article Attribute Name : article2   Value : value1
            - Article Attribute Name : article3   Value : value2
  - Category Attribute Name :-> webcare
            - Article Attribute Name : param3   Value : value4
James L 19-Aug-2008 04:04
Return if there are no matches is an empty DOMNodeList. Check using length property, e.g.:

<?php
$nodes=$domDocument->getElementsByTagName('book') ;
if ($nodes->length==0) {
   // no results
}
?>
jason at shaped dot ca 11-Feb-2008 04:59
in response to tildy at pr dot hu

my preferred way is (in example to gather country data from an iso 3166 xml flie)

$countries = new DOMDocument();
$countries->load("./lib/iso_3166.xml");

$countriesList = $countries->getElementsByTagName("ISO_3166-1_Entry");

foreach($countriesList as $country) {
    $values = $country->getElementsByTagName("*");
    foreach($values as $node) {
      echo $node->nodeName."=".$node->nodeValue;
    }
}
Finding values of a node 14-Mar-2007 02:01
I don't know if this is that obvious but it was not for me, so in addition to gem at rellim dot com's posting:
adding

<?php
echo $param -> nodeValue.'<br>';
?>

to the loop will output
value1
value2
value3
gem at rellim dot com 29-Sep-2004 04:20
Here is an example of getElementsByTagName():

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<config>
  <section id="section1">
   <param name="param1">value1</param>
   <param name="param2">value2</param>
  </section>
  <section id="section2">
   <param name="param3">value3</param>
  </section>
</config>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('param');

foreach ($params as $param) {
       echo $param -> getAttribute('name').'<br>';
}
?>

Expected result:
--------------
param1
param2
param3


Searches for all elements with given tag name in specified namespace

  • ? DOMDocument::getElementsByTagName
  • DOMDocument::importNode ?
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given tag name in specified namespace

DOMDocument::getElementsByTagNameNS

(PHP 5, PHP 7)

DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace

说明

public DOMDocument::getElementsByTagNameNS ( string $namespace , string $localName ) : DOMNodeList

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

参数

namespace

The namespace URI of the elements to match on. The special value * matches all namespaces.

localName

The local name of the elements to match on. The special value * matches all local names.

返回值

A new DOMNodeList object containing all the matched elements.

范例

Example #1 Get all the XInclude elements

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
 <xi:include href="book.xml">
  <xi:fallback>
   <error>xinclude: book.xml not found</error>
  </xi:fallback>
 </xi:include>
 <include>
  This is another namespace
 </include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

以上例程会输出：

local name: include, prefix: xi
local name: fallback, prefix: xi

参见

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

User Contributed Notes

RiKdnUA at mail dot ru 19-Mar-2015 07:47
<?php
ini_set("display_errors","on"); error_reporting(-1);
$doc="<?xml version='1.0' encoding='WINDOWS-1251'?>
<htm:body xmlns:htm='w3.org'>
<span>Text</span>
<htm:img htm:src='imgSrc'/>
</htm:body>";
$dom = new DOMDocument('1.0','WINDOWS-1251');
$dom->preserveWhiteSpace=false;
$dom->loadXML($doc);
$domList=$dom->getElementsByTagNameNS('*','*');//all namespaces, all local names
echo "Количество элементов. The number of elements: ".$domList->length."<br />";// 2 (not 3)
for ($i=0; $i<$domList->length; $i++)
{echo "Элемент $i. The element $i: ".$domList->item($i)->tagName."<br />";
}
/*
Tested in PHP 5.2.9-2 and 5.2.17
The above example will output:
Количество элементов. The number of elements: 2
Элемент 0. The element 0: htm:body
Элемент 1. The element 1: htm:img

Вывод. Не найден элемент span
Conclusion. Not found span element
*/
?>


Import node into current document

  • ? DOMDocument::getElementsByTagNameNS
  • DOMDocument::load ?
  • PHP Manual
  • DOMDocument
  • Import node into current document

DOMDocument::importNode

(PHP 5, PHP 7)

DOMDocument::importNode — Import node into current document

说明

public DOMDocument::importNode ( DOMNode $node , bool $deep = false ) : DOMNode|false

This function returns a copy of the node to import and associates it with the current document.

参数

node

The node to import.

deep

If set to true, this method will recursively import the subtree under the node.

Note:

To copy the nodes attributes deep needs to be set to true

返回值

The copied node or false, if it cannot be copied.

错误／异常

DOMException is thrown if node cannot be imported.

范例

Example #1 DOMDocument::importNode() example

Copying nodes between documents.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// The node we want to import to a new document
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Create a new document
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Add some markup
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo "The 'new document' before copying nodes into it:\n";
echo $newdoc->saveXML();

// Import the node, and all its children, to the document
$node = $newdoc->importNode($node, true);
// And then append it to the "<root>" node
$newdoc->documentElement->appendChild($node);

echo "\nThe 'new document' after copying the nodes into it:\n";
echo $newdoc->saveXML();
?>

以上例程会输出：

The 'new document' before copying nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
</root>

The 'new document' after copying the nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
  <element>
    <child>text in child</child>
  </element>
</root>

User Contributed Notes

rikdnua at mail dot ru 11-Sep-2013 01:54
The behavior of importNode($node, false) is different in PHP 5.2.9-2 and PHP 5.2.17.
The second option is explicitly set to false. In PHP 5.2.9-2 importNode() imports the elements WITHOUT attributes. In PHP 5.2.17 the elements imported ALONG with their attributes.
<?php
$xml="
<html>
<a href='yandex.com'>Yandex.com</a>
<a href='rik.dn.ua'>RiK.dn.ua</a>
</html>
";
$doc=new domDocument('1.0');
$doc->loadXML($xml);
$list=$doc->getElementsByTagName('a');
$doc1=new domDocument('1.0');
$doc1->formatOutput=true;
for($i=0; $i<$list->length; $i++) $doc1->appendChild($doc1->importNode($list->item($i), false));
$doc1->save('file.xml');
?>

file.xml PHP 5.2.9-2
<?xml version="1.0"?>
<a/>
<a/>

file.xml PHP 5.2.17
<?xml version="1.0"?>
<a href="yandex.com"/>
<a href="rik.dn.ua"/>
c dot 1 at smithies dot org 19-Oct-2009 06:40
Assume that $source and $dest are instances of DOMDocument. Assume that $sourcedoc contains an element with ID 'sourceID' and that $destdoc contains an element with ID 'destID'. Assume that we have already set up source and destination element variables thus:

<?php
 $src = $sourcedoc->getElementById('sourceID');
 $dst = $destdoc->getElementById('destID');
?>

Finally, assume that $sel has more than one child node.

In order to import the child elements of $src as children of $dst, you might do something like this:

<?php
$src = $dest->importNode($src, TRUE);

foreach ($src->childNodes as $el) $dst->appendChild($el);
?>

But this does not work. foreach gets confused, because (as noted below) appending an imported element to another existing element in the same document causes it to be removed from its current parent element.

Therefore, the following technique should be used:

<?php
foreach ($src->childNodes as $el) $dst->appendChild($destdoc->importNode($el, TRUE));
?>
p dot reisinger at gmail dot com 29-Dec-2008 03:43
When you use function/method below, php automaticaly inserts namespaces (if you have some). If you want to join xml files exactly, then you can just use placeholders and treat xml as a string.
<?php
function joinXMLStrings($file1, $file2)
{
    //remove xml declaration
    $file2 = trim(preg_replace('/<\?xml.*\?>/', '', $file2, 1));

    //insert file2 in the place of placeholder in the first file
    $file1 = trim(preg_replace('/<\?file2\s\?>/', $file2, $file1, 1));
}
?>

so function looks like this and you insert two xml files. First file has to have placeholder (where you insert file2). Placeholder in this case will be <?file2 ?>

!!!this is only for ilustration - test before you use it
p dot reisinger at gmail dot com 23-Dec-2008 07:32
method (can be used as a function as well) that joins two xml files. first argument is parent xml (the one to be inserted into), second child (the one to be inserted) and third is optional argument that specifies the parent's tag where to insert children xml. If not specified then children is inserted as the last element, just before end of the root
<?php
    protected function joinXML($parent, $child, $tag = null)
    {
        $DOMChild = new DOMDocument;
        $DOMChild->loadXML($child);
        $node = $DOMChild->documentElement;

        $DOMParent = new DOMDocument;
        $DOMParent->formatOutput = true;
        $DOMParent->loadXML($parent);

        $node = $DOMParent->importNode($node, true);

        if ($tag !== null) {
            $tag = $DOMParent->getElementsByTagName($tag)->item(0);
            $tag->appendChild($node);
        } else {
            $DOMParent->documentElement->appendChild($node);
        }

        return $DOMParent->saveXML();
    }
?>
mailme at sove dot nl 11-Jun-2008 05:29
DOMDocument->importNode with seconds argument false will leave attributes behind. To fix this:

$__DOM->importNode
   (
      $__INPUT->cloneNode(false), true
   );

$__DOM (DOMDocument) will import the $__INPUT node (DOMElement) INCLUDING attributes.
mark at 4inloop dot de 05-Apr-2007 05:51
When you left out the second argument or enter false, not only the child nodes are ommited. The attributes of the node are also cut off.
adjwilli 05-Oct-2006 01:08
Editing XML with PHP can be a pain in the Secretary of State Powell, so here's a script to replace an XML node with a user-provided one through the POST. It's usually a good idea to run the $_POST['xml'] through a validation check and clean it for other thing before running this.

Pretty much this script expects a user-provided node called $_POST['xml'] and the XPath of the node in the original document that you want to replace called $_POST['XPath']. It also loads the original XML document from $xml. The function nodeRunner begins with the root node of the document you're editting and the XPath for the root element (these are more to make recursion easy than anything else).

$doc = new DOMDocument();
$doc->loadXML($xml); // $xml expects an XML string

function nodeRunner ($node,$xpath) {
    global $doc;
    if ($xpath == $_POST['XPath']) {

        $xmlPost = new DOMDocument();
        $xmlPost->loadXML($_POST['xml']);

        $newNode = $doc->importNode($xmlPost->firstChild,true);

        $node->parentNode->replaceChild($newNode,$node);
    } else {

        $page = 1;
        $section = 1;

        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $nodling) {
                $nodeName = $nodling->nodeName;
                if ($nodeName == 'page' || $nodeName == 'section') {
                    nodeRunner ($nodling,$xpath."/".$nodeName."[".$$nodeName."]");
                    $$nodeName++;
                }
            }
        }
    }
}

nodeRunner ($doc->documentElement,"/root[1]"); // /root should be explicit name of the root  element of the XPath

$doc->saveXML();
stomas 19-Sep-2006 06:14
I think this should do the same:

<?
 // Import $b into $a's document
 function myimport($a, $b)
 {
   if ($a->ownerDocument->isSameNode($b->ownerDocument))
   {
    return $b->cloneNode(TRUE);
   }
   else
   {
    return $a->ownerDocument->importNode($b, TRUE);
   }
 }
 ?>
Colin 12-Sep-2006 09:11
As of PHP 5.1.6 with libxml 2.6.26 and DOM/XML API version 20031129, importNode() does nothing if attempting to import from the same document.  Meaning, if you do an $ret = importNode and then appendChild($ret) or insertBefore($ret, ...) then you will end up *moving* the node instead of ending up with a copy.

If you expect importNode to give you a copy of the source (in this case, a deep copy) then you must account for them being from the same document.  This function addresses this:

<?
// Import $b into $a's document
function myimport($a, $b)
{
  if ($a->ownerDocument->isSameNode($b->ownerDocument))
  {
    $temp = new DOMDocument();
    $ret = $temp->importNode($b, TRUE);
    return $a->ownerDocument->importNode($ret, TRUE);
  }
  else
  {
    return $a->ownerDocument->importNode($b, TRUE);
  }
}
?>

(Function was freshly coded for this note but I based it off another, working function of mine.)

This function checks if the documents are the same and uses a new document (guaranteed to be different this way) to force a copy into $temp and then force a copy back into $a->ownerDocument.

Obviously, no error checking has been done.
andy dot clark at dial dot pipex dot com 15-Aug-2006 08:20
One useful use of importNode is to copy one node onto another.

function CopyXMLNode($SourceNode,$DestNode)
 {
  if ($SourceNode->nodeName != '#text')
   {
     //Copy this node
    $node = $DestNode->ownerDocument->importNode($SourceNode, true);
    $node = $DestNode->appendChild($node);
    //Now copy the child nodes
    foreach ($SourceNode->childNodes AS $item)
     {
     $this->CopyXMLNode($item,$node);
     }
    }
  }
Fitopaldi 03-Aug-2005 11:29
importNode returns a copy of the node to import and associates it with the current document, but not import the node to the current DOMDocument. Use appendChild for import the copy of the node to current DOMDocument.

<?
 $domNode = $dom->importNode($aDomNode, true);
 $currentDomDocument->appendChild($domNode);
?>


Load XML from a file

  • ? DOMDocument::importNode
  • DOMDocument::loadHTML ?
  • PHP Manual
  • DOMDocument
  • Load XML from a file

DOMDocument::load

(PHP 5, PHP 7)

DOMDocument::load — Load XML from a file

说明

public DOMDocument::load ( string $filename , int $options = 0 ) : DOMDocument|bool

Loads an XML document from a file.

Warning

Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call realpath() in such a case.

参数

filename

The path to the XML document.

options

Bitwise OR of the libxml option constants.

返回值

成功时返回 true， 或者在失败时返回 false。 If called statically, returns a DOMDocument 或者在失败时返回 false.

错误／异常

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

此方法可以被静态调用,但会抛出一个 E_STRICT 错误。

范例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

参见

  • DOMDocument::loadXML() - Load XML from a string
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

User Contributed Notes

sainthyoga2003 at gmail dot com 09-Feb-2012 03:37
in the default example:

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

you must enter the absolute path for book.xml due for get a false result in load function.
sainthyoga2003 at gmail dot com 25-Feb-2011 05:38
i've found the partial solution for xml:id warning,is explained at this address: https://fosswiki.liip.ch/display/BLOG/GetElementById+Pitfalls

there explains that:
The ID does have to be a valid NCName, which for example means, that the first letter can't be a number.

and in my xml:id i had a number. :D
sainthyoga2003 at gmail dot com 16-Feb-2011 09:31
adding an id for a child, when i use abstract mode i get the following warning:

[quote]Warning: DOMDocument::load() [domdocument.load]: xml:id : attribute value xx is not an NCName in /fake/path/to/xmlfile[/quote]
_ michael 01-Jun-2010 08:34
load() will handle non-ASCII characters depending on the details of the XML declaration, but in a somewhat surprising way. One would assume that the declarations '<?xml version="1.0" encoding="UTF-8"?>' and '<?xml version="1.0"?>' are treated in the same way because UTF-8 is the default encoding anyway. But not so.

* If there is an XML declaration defining the encoding *explicitly*, the non-ASCII characters remain unchanged.
* If the XML declaration does not define the encoding explicitly, or if the XML declaration is missing, non-ASCII characters are converted into numeric entities.

So the document

    <?xml version="1.0"?>
    <root><nonascii>?</nonascii></root>

will be converted to

    <?xml version="1.0"?>
    <root><nonascii>&#xE4;</nonascii></root>

The same happens if there is no XML declaration at all. On the other hand, the document

    <?xml version="1.0" encoding="UTF-8"?>
    <root><nonascii>?</nonascii></root>

will remain as it is.

This behaviour applies to loadXML() as well.
_ michael 19-Apr-2010 07:50
XHTML and entities: The solution proposed below by zachatwork at gmail dot com didn't work for me. I checked on a number of servers (both LAMPP and WAMPP) - on each of them, calling loadXML() with the LIBXML_DTDLOAD option triggered an external request for the DTD. And that's bad news.

If allow_url_fopen is turned off, the request for the DTD fails with a warning. If it is turned on, the request fails because these w3c URLs return a 503 Service Unavailable.

HTML entities still generate a warning in either case.

The best solution, as far as I can tell, is simply to ignore the warnings and suppress them using '@'. I can't recommend parsing XHTML with loadHTML() instead of loadXML() - yes, you get rid of the entity problem, but loadHTML() changes the source while parsing it (tries to 'fix' it even though there is nothing to fix).
zachatwork at gmail dot com 30-Jun-2009 11:28
You can easily avoid the warning about &nbsp; references by using the LIBXML_DTDLOAD option.

<?php

$html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  </head>
  <body>
    <p>&nbsp;</p>
  </body>
</html>
EOF;

// This one works perfectly.
$dom = new DOMDocument();
$dom->loadXML($html, LIBXML_DTDLOAD);
print $dom->saveXML();

// This one produces a warning.
$dom = new DOMDocument();
$dom->loadXML($html);
print $dom->saveXML();

?>

See also: http://www.php.net/manual/en/libxml.constants.php

Note that libxml will detect that your DTD is locally available via /etc/xml/catalog. So there is no worry about this causing your DOM loads to make external network requests.
Jonas Due Vesterheden 09-Jun-2009 08:18
I had a problem with loading documents over HTTP. I would get errors looking like this:

Warning: DOMDocument::load(http://external/document.xml): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

The document would load fine in browsers and using wget. The problem is that DOMDocument::load() on my systems (both OS X and Linux) didn't send any User-Agent header which for some weird reason made Microsoft-IIS/6.0 respond with the 500 error.

The solution is found on http://php.net/manual/en/function.libxml-set-streams-context.php :

<?php
$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');
?>
syntaxiko 04-Apr-2009 10:16
Function will not work if using XML DOM PECL module
darren at viamedia dot co dot za 05-Aug-2008 07:17
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
the_N_Channel 15-Jul-2008 04:53
NOTE, will not load successfully if there is a comment at the beginning of the file before the <?xml version="1.0" ?> declaration!
hh dot lohmann at yahoo dot de 30-Aug-2007 03:48
BadGuy′s note may be confusing since what he depicts is no special property of the relevant method. PHP works always in and on a local file system which means that if you want to use resources from other systems or - what is, indeed, BadGuy′s problem - need resources that have been dealt with by other programs or processes, you have to state and manage that explicitly in your code. PHP is just a quite normal program in that.

BadGuy′s solution is using the "http wrapper" to get output from another process (see "wrappers" in the PHP manual). Doing this, the appropriate syntax for http calls has to be respected.
admin at tijnema dot tijnema dot info 02-Jun-2007 04:39
In reply to BadGuy [at] BadGuy [dot] nl

When the news.php file is located on the same server, like you said in the first example then http://my.beautiful-website.com/xmlsource/news.php wouldn't work, but you should use http://localhost/xmlsource/news.php or http://127.0.0.1/xmlsource/news.php
BadGuy [at] BadGuy [dot] nl 18-Jan-2007 08:50
Note that this method uses the local file system before doing anything remote. The 'disadvantage' would be that if you would do the following:
<?php
$xml = new DOMDocument;
$xml->load("xmlsource/news.php");
?>

This would not make the method read the actual output of the news.php file --presumably valid xml data--, but the file contents --obviously this would be php code. So this will return an error saying news.php is missing the xml declaration and maybe the xml start-tag

What would work is the following:

<?php
$xml = new DOMDocument;
$xml->load("http://my.beautiful-website.com/xmlsource/news.php");
?>

This will force a http request to be used to get this file instead of just locally reading it and the file just returning code
daevid at daevid dot com 18-Oct-2005 05:08
Suppose you wanted to dynamically load an array from an .XSD file. This method is your guy. just remember to use the actual xs: portion in xpaths and such.

All the other "load" methods will error out.

<?php
$attributes = array();
$xsdstring = "/htdocs/api/xsd/common.xsd";
$XSDDOC = new DOMDocument();
$XSDDOC->preserveWhiteSpace = false;
if ($XSDDOC->load($xsdstring))
{
    $xsdpath = new DOMXPath($XSDDOC);
    $attributeNodes =
              $xsdpath->
              query('//xs:simpleType[@name="attributeType"]')
              ->item(0);
    foreach ($attributeNodes->childNodes as $attr)
    {
        $attributes[ $attr->getAttribute('value') ] = $attr->getAttribute('name');
    }
    unset($xsdpath);
}
print_r($attributes);
?>


Load HTML from a string

  • ? DOMDocument::load
  • DOMDocument::loadHTMLFile ?
  • PHP Manual
  • DOMDocument
  • Load HTML from a string

DOMDocument::loadHTML

(PHP 5, PHP 7)

DOMDocument::loadHTML — Load HTML from a string

说明

public DOMDocument::loadHTML ( string $source , int $options = 0 ) : DOMDocument|bool

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

参数

source

The HTML string.

options

Since PHP 5.4.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

返回值

成功时返回 true， 或者在失败时返回 false。 If called statically, returns a DOMDocument 或者在失败时返回 false.

错误／异常

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

此方法可以被静态调用,但会抛出一个 E_STRICT 错误。

尽管非正确格式化的 HTML 仍应该被成功调入，但此函数会在遇到错误标记时产生 E_WARNING 错误。libxml 错误处理函数可以用来处理这类错误。

范例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

参见

  • DOMDocument::loadHTMLFile() - Load HTML from a file
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

User Contributed Notes

deepakrajpal dot com at gmail dot com 20-Nov-2020 06:16
If we are loading html5 tags such as <section>, <svg> there is following error:

DOMDocument::loadHTML(): Tag section invalid in Entity

We can disable standard libxml errors (and enable user error handling) using libxml_use_internal_errors(true); before loadHTML();

This is quite useful in phpunit custom assertions as given in following example (if using phpunit test cases):

// Create a DOMDocument
$dom = new DOMDocument();

// fix html5/svg errors
libxml_use_internal_errors(true);

// Load html
$dom->loadHTML("<section></section>");
$htmlNodes = $dom->getElementsByTagName('section');

if ($htmlNodes->length == 0) {
    $this->assertFalse(TRUE);
} else {
    $this->assertTrue(TRUE);
}
divinity76+spam at gmail dot com 14-Sep-2020 09:25
if you want to get rid of all the "DOMText elements containing ONLY whitespace", maybe try

<?php

function loadHTML_noemptywhitespace(string $html, int $extra_flags = 0, int $exclude_flags = 0): DOMDocument
{
    $flags = LIBXML_HTML_NODEFDTD | LIBXML_NOBLANKS | LIBXML_NONET;
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;

    $domd = new DOMDocument();
    $domd->preserveWhiteSpace = false;
    @$domd->loadHTML('<?xml encoding="UTF-8">' . $html, $flags);
    $removeAnnoyingWhitespaceTextNodes = function (\DOMNode $node) use (&$removeAnnoyingWhitespaceTextNodes): void {
        if ($node->hasChildNodes()) {
            // Warning: it's important to do it backwards; if you do it forwards, the index for DOMNodeList might become invalidated;
            // that's why i don't use foreach() - don't change it (unless you know what you're doing, ofc)
            for ($i = $node->childNodes->length - 1; $i >= 0; --$i) {
                $removeAnnoyingWhitespaceTextNodes($node->childNodes->item($i));
            }
        }
        if ($node->nodeType === XML_TEXT_NODE && !$node->hasChildNodes() && !$node->hasAttributes() && empty(trim($node->textContent))) {
            //echo "Removing annoying POS";
            // var_dump($node);
            $node->parentNode->removeChild($node);
        } //elseif ($node instanceof DOMText) { echo "not removed"; var_dump($node, $node->hasChildNodes(), $node->hasAttributes(), trim($node->textContent)); }
    };
    $removeAnnoyingWhitespaceTextNodes($domd);
    return $domd;
}
BychkovVV at mail dot ru 03-Apr-2020 08:30
If you are loading html content from any website, in "utf-8" encoding, when meta width content-type is not first child of HEAD, it would not be acknowledged by parser (encoding); So you can make this fix:
  function domLoadHTML($html)
           {$testDOM = new DOMDocument('1.0', 'UTF-8');
            $testDOM->loadHTML($html);
            $charset = NULL;
            $searchInElemnt = function(&$item) use (&$searchInElemnt, &$charset)
              {if($item->childNodes)
                 {foreach($item->childNodes as $childItem)
                    {switch($childItem->nodeName)
                       {case 'html':
                        case 'head':
                          $searchInElemnt($childItem);
                          break;
                        case 'meta':
                          $attributes = array();
                          foreach ($childItem->attributes as $attr)
                            {$attributes[mb_strtoupper($attr->localName)] = $attr->nodeValue;
                            }
                          if(array_key_exists('HTTP-EQUIV', $attributes) && (mb_strtoupper($attributes['HTTP-EQUIV']) == 'CONTENT-TYPE') && array_key_exists('CONTENT', $attributes) && preg_match('~[\s]*;[\s]*charset[\s]*=[\s]*([^\s]+)~', $attributes['CONTENT'], $matches))
                            {$charset = preg_replace('~[\s\']~', '', $matches[1]);
                            }
                       }
                    }
                 }
              };
            $searchInElemnt($testDOM);
            if(isset($charset))
              {$dom = new DOMDocument('1.0', $charset);
               $dom->loadHTML('<?xml encoding="'.$charset.'">'.$html);
               foreach ($dom->childNodes as $item)
               if($item->nodeType == XML_PI_NODE)
                 {$dom->removeChild($item);
                 }
               $dom->encoding = $charset;
              }
            else
              {$dom = $testDOM;
              }
            return $dom;
           };
kerim-yagmurcu at gmx dot de 24-Dec-2016 03:13
For those of you who want to get an external URL's class element, I have 2 usefull functions. In this example we get the '<h3 class="r">'
 elements back (search result headers) from google search:

1. Check the URL (if it is reachable, existing)
<?php
# URL Check
function url_check($url) {
    $headers = @get_headers($url);
    return is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false;
};
?>

2. Clean the element you want to get (remove all tags, tabs, new-lines etc.)
<?php
# Function to clean a string
function clean($text){
    $clean = html_entity_decode(trim(str_replace(';','-',preg_replace('/\s+/S', " ", strip_tags($text)))));// remove everything
    return $clean;
    echo '\n';// throw a new line
}
?>

After doing that, we can output the search result headers with following method:
<?php
$searchstring = 'djceejay';
$url = 'http://www.google.de/webhp#q='.$searchstring;
if(url_check($url)){
    $doc = new DomDocument;
    $doc->validateOnParse = true;
    $doc->loadHtml(file_get_contents($url));
    $output = clean($doc->getElementByClass('r')->textContent);
    echo $output . '<br>';
}else{
    echo 'URL not reachable!';// Throw message when URL not be called
}
?>
fr at felix-riesterer dot de 13-Feb-2016 01:43
Remember: If you use an HTML5 doctype and a meta element like so

<meta CHARSET=gb2312">

your HTML code will get interpreted as ISO-8859-something and non-ASCII chars will get converted into HTML entities. However the HTML4-like version will work (as has been pointed out 10 years ago by "bigtree at 29a"):

<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312">
finkenb2 at mail dot lib dot msu dot edu 05-Oct-2015 04:03
Warning:  This does not function well with HTML5 elements such as SVG.  Most of the advice on the Web is to turn off errors in order to have it work with HTML5.
cake at brothercake dot com 16-Dec-2012 05:57
Be aware that this function doesn't actually understand HTML -- it fixes tag-soup input using the general rules of SGML, so it creates well-formed markup, but has no idea which element contexts are allowed.

For example, with input like this where the first element isn't closed:

    <span>hello <div>world</div>

loadHTML will change it to this, which is well-formed but invalid:

    <span>hello <div>world</div></span>
Alex 10-Apr-2010 08:45
Beware of the "gotcha" (works as designed but not as expected): if you use loadHTML, you cannot validate the document. Validation is only for XML. Details here: http://bugs.php.net/bug.php?id=43771&edit=1
Shane Harter 04-Jan-2010 08:42
DOMDocument is very good at dealing with imperfect markup, but it throws warnings all over the place when it does.

This isn't well documented here. The solution to this is to implement a separate aparatus for dealing with just these errors.

Set libxml_use_internal_errors(true) before calling loadHTML. This will prevent errors from bubbling up to your default error handler. And you can then get at them (if you desire) using other libxml error functions.

You can find more info here http://www.php.net/manual/en/ref.libxml.php
mdmitry at gmail dot com 21-Dec-2009 09:02
You can also load HTML as UTF-8 using this simple hack:

<?php

$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="UTF-8">' . $html);

// dirty fix
foreach ($doc->childNodes as $item)
    if ($item->nodeType == XML_PI_NODE)
        $doc->removeChild($item); // remove hack
$doc->encoding = 'UTF-8'; // insert proper

?>
piopier 14-Jun-2009 08:29
Here is a function I wrote to capitalize the previous remarks about charset problems (UTF-8...) when using loadHTML and then DOM functions.
It adds the charset meta tag just after <head> to improve automatic encoding detection, converts any specific character to an html entity, thus PHP DOM functions/attributes will return correct values.

<?php
mb_detect_order("ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
function loadNprepare($url,$encod='') {
        $content        = file_get_contents($url);
        if (!empty($content)) {
                if (empty($encod))
                        $encod  = mb_detect_encoding($content);
                $headpos        = mb_strpos($content,'<head>');
                if (FALSE=== $headpos)
                        $headpos= mb_strpos($content,'<HEAD>');
                if (FALSE!== $headpos) {
                        $headpos+=6;
                        $content = mb_substr($content,0,$headpos) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr($content,$headpos);
                }
                $content=mb_convert_encoding($content, 'HTML-ENTITIES', $encod);
        }
        $dom = new DomDocument;
        $res = $dom->loadHTML($content);
        if (!$res) return FALSE;
        return $dom;
}
?>

NB: it uses mb_strpos/mb_substr instead of mb_ereg_replace because that seemed more efficient with huge html pages.
Errol 11-Feb-2009 08:05
It should be noted that when any text is provided within the body tag
outside of a containing element, the DOMDocument will encapsulate that
text into a paragraph tag (<p>).

For example:
<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>Test<br></p>
<div>Text</div>
</body></html>

while:
<?php
$doc = new DOMDocument();
$doc->loadHTML(
    "<html><body><i>Test</i><br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<i>Test</i><br><div>Text</div>
</body></html>
jamesedwardcooke+php at gmail dot com 19-Oct-2008 11:37
Using loadHTML() automagically sets the doctype property of your DOMDocument instance(to the doctype in the html, or defaults to 4.0 Transitional). If you set the doctype with DOMImplementation it will be overridden.

I assumed it was possible to set it and then load html with the doctype I defined(in order to decide the doctype at runtime), and ran into a huge headache trying to find out where my doctype was going. Hopefully this helps someone else.
xuanbn at yahoo dot com 04-Oct-2007 01:38
If you use loadHTML() to process utf HTML string (eg in Vietnamese), you may experience result in garbage text, while some files were OK. Even your HTML already have meta charset  like

  <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">

I have discovered that, to help loadHTML() process utf file correctly, the meta tag should come first, before any utf string appear. For example, this HTML file

<html>
 <head>
    <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">
    <title> Vietnamese - Ti?ng Vi?t</title>
  </head>
<body></body>
</html>

will be OK with loadHTML() when <meta> tag appear <title> tag.

But the file below will not regcornize by loadHTML() because <title> tag contains utf string appear before <meta> tag.

<html>
 <head>
    <title> Vietnamese - Ti?ng Vi?t</title>
    <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">
  </head>
<body></body>
</html>
hanhvansu at yahoo dot com 26-Apr-2007 08:50
When using loadHTML() to process UTF-8 pages, you may meet the problem that the output of dom functions are not like the input. For example, if you want to get "C?nh tranh", you will receive "Cáo?nh tranh".  I suggest we use mb_convert_encoding before load UTF-8 page :
<?php
    $pageDom = new DomDocument();
    $searchPage = mb_convert_encoding($htmlUTF8Page, 'HTML-ENTITIES', "UTF-8");
    @$pageDom->loadHTML($searchPage);

?>
romain dot lalaut at laposte dot net 15-Feb-2007 08:31
Note that the elements of such document will have no namespace even with <html xmlns="http://www.w3.org/1999/xhtml">
bigtree at DONTSPAM dot 29a dot nl 26-Apr-2005 02:15
Pay attention when loading html that has a different charset than iso-8859-1. Since this method does not actively try to figure out what the html you are trying to load is encoded in (like most browsers do), you have to specify it in the html head. If, for instance, your html is in utf-8, make sure you have a meta tag in the html's head section:

<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312"/>
</head>

If you do not specify the charset like this, all high-ascii bytes will be html-encoded. It is not enough to set the dom document you are loading the html in to UTF-8.


Load HTML from a file

  • ? DOMDocument::loadHTML
  • DOMDocument::loadXML ?
  • PHP Manual
  • DOMDocument
  • Load HTML from a file

DOMDocument::loadHTMLFile

(PHP 5, PHP 7)

DOMDocument::loadHTMLFile — Load HTML from a file

说明

public DOMDocument::loadHTMLFile ( string $filename , int $options = 0 ) : DOMDocument|bool

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

参数

filename

The path to the HTML file.

options

Since PHP 5.4.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

返回值

成功时返回 true， 或者在失败时返回 false。 If called statically, returns a DOMDocument 或者在失败时返回 false.

错误／异常

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

此方法可以被静态调用,但会抛出一个 E_STRICT 错误。

尽管非正确格式化的 HTML 仍应该被成功调入，但此函数会在遇到错误标记时产生 E_WARNING 错误。libxml 错误处理函数可以用来处理这类错误。

范例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

参见

  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

User Contributed Notes

qrworld.net 11-Nov-2014 04:37
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
onemanbanddan at gmail dot com 04-Mar-2014 12:28
The options for surpressing errors and warnings will not work with this as they do for loadXML()
e.g.
<?php
$doc->loadHTMLFile($file, LIBXML_NOWARNING | LIBXML_NOERROR);
?>
will not work.
you must use:
<?php
libxml_use_internal_errors(true);
$doc->loadHTMLFile($file);
?>
and handle the exceptions as neccesarry.
Mark Omohundro, ajamyajax dot com 28-Nov-2008 06:32
<?php
// try this html listing example for all nodes / includes a few getElementsByTagName options:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

// example 1:
$elements = $doc->getElementsByTagName('*');
// example 2:
$elements = $doc->getElementsByTagName('html');
// example 3:
//$elements = $doc->getElementsByTagName('body');
// example 4:
//$elements = $doc->getElementsByTagName('table');
// example 5:
//$elements = $doc->getElementsByTagName('div');

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>". $element->nodeName. ": ";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>
gzech at SPAMFILTER dot eso dot org 21-Feb-2007 02:09
If you want to suppress output warnings from loadHTMLFile($url), put an @ sign in front. This even works in:
<?php
$load = @$dom->loadHTMLFile($url);
?>
andy at carobert dot com 25-May-2005 01:24
This puts the HTML into a DOM object which can be parsed by individual tags, attributes, etc..  Here is an example of getting all the 'href' attributes and corresponding node values out of the 'a' tag. Very cool....

<?php
$myhtml = <<<EOF
<html>
<head>
<title>My Page</title>
</head>
<body>
<p><a href="/mypage1">Hello World!</a></p>
<p><a href="/mypage2">Another Hello World!</a></p>
</body>
</html>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($myhtml);

$tags = $doc->getElementsByTagName('a');

foreach ($tags as $tag) {
       echo $tag->getAttribute('href').' | '.$tag->nodeValue."\n";
}
?>

This should output:

/mypage1 | Hello World!
/mypage2 | Another Hello World!
bens at effortlessis dot com 08-Apr-2005 05:11
Note that this function doesn't parse the individual tags WITHIN the html file - it's all loaded as a "black box", and you end up with an XML widget that comprises nothing but the complete chunk of HTML.

I was hoping it would function as a sort of HTML-validator/parser, but that doesn't seem to be the case.


Load XML from a string

  • ? DOMDocument::loadHTMLFile
  • DOMDocument::normalizeDocument ?
  • PHP Manual
  • DOMDocument
  • Load XML from a string

DOMDocument::loadXML

(PHP 5, PHP 7)

DOMDocument::loadXML — Load XML from a string

说明

public DOMDocument::loadXML ( string $source , int $options = 0 ) : DOMDocument|bool

Loads an XML document from a string.

参数

source

The string containing the XML.

options

Bitwise OR of the libxml option constants.

返回值

成功时返回 true， 或者在失败时返回 false。 If called statically, returns a DOMDocument 或者在失败时返回 false.

错误／异常

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

此方法可以被静态调用,但会抛出一个 E_STRICT 错误。

范例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Example #2 Static invocation of loadXML

<?php
// Issues an E_STRICT error
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

参见

  • DOMDocument::load() - Load XML from a file
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

User Contributed Notes

Adrian Wiik 13-Nov-2019 09:02
A call to loadXML() will overwrite the XML declaration previously created in the constructor of DOMDocument. This can cause encoding problems if there is no XML declaration in the loaded XML and you don't have control over the source (e.g. if the XML is coming from a webservice). To fix this, set encoding AFTER loading the XML using the 'encoding' class property of DOMDocument. Example:

Bad situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>?</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0"?>
<test>
    <hello>hi</hello>
    <field>&#xF8;</field>
</test>

Good situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>?</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
$xmlDoc->encoding = "utf-8";
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0" encoding="utf-8"?>
<test>
    <hello>hi</hello>
    <field>?</field>
</test>
Gustavo L. Fabro 14-Nov-2013 04:41
Always remember that with the default parameters this function doesn't handle well large files, i.e. if a text node is longer than 10Mb it can raise an exception stating:

DOMDocument::loadXML(): internal error Extra content at the end of the document in Entity

even though the XML is fine.

The cause is a definition in parserInternals.h of lixml:
#define XML_MAX_TEXT_LENGTH 10000000

To allow the function to process larger files, pass the LIBXML_PARSEHUGE as an option and it will work just fine:

$domDocument->loadXML($xml, LIBXML_PARSEHUGE);
szalma dot laszlo at zengo dot eu 27-Oct-2009 08:14
Loading from a string works fine without the <?xml version="1.0" encoding="utf-8"?> header, but in this case the xmlEncoding won't be set, and this makes the utf-8 characters (international, and special characters) to be encoded as hexa entities when saved with saveXML()!
remacg 26-Feb-2009 07:33
Instead of doing this:

<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

simply use:

loadHTML() rather than loadXML().
olalonde at NOSPAM dot gmail dot com 21-Mar-2008 05:00
For some reason, when you set DOMDocument's property 'recover' to true, using '@' to mask errors thrown by loadXml() won't work.

Here's my workaround:

function maskErrors() {}
set_error_handler('maskErrors');
$dom->loadXml($xml);
restore_error_handler();

You could also simply do this: error_reporting(0); and then set back error_reporting to its original state.
Stuart Grimshaw 26-Jun-2007 01:57
Possible values for the options parameter can be found here:

http://us3.php.net/manual/en/ref.libxml.php#libxml.constants
Marc Liyanage 18-Jun-2007 07:08
The documentation states that loadXML can be called statically, but this is misleading. This feature seems to be a special case hack and its use seems to be discouraged according to http://bugs.php.net/bug.php?id=41398.

Calling the method statically will fail with an error if the code runs with E_STRICT error reporting enabled.

The documentation should be changed to make it clear that a static call is against recommended practice and won't work with E_STRICT.
jazzslider at hotmail dot com 30-Apr-2007 01:14
When using loadXML() to parse a string that contains entity references (e.g., &nbsp;), be sure that those entity references are properly declared through the use of a DOCTYPE declaration; otherwise, loadXML() will not be able to interpret the string.

Example:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd1 = new DOMDocument();
$dd1->loadXML($str);

echo $dd1->saveXML();
?>

Given the above code, PHP will issue a Warning about the entity 'nbsp' not being properly declared.  Also, the call to saveXML() will return nothing but a trimmed-down version of the original processing instruction...everything else is gone, and all because of the undeclared entity.

Instead, explicitly declare the entity first:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

Since the 'nbsp' entity is defined in the DOCTYPE, PHP no longer issues that Warning; the string is now well-formed, and loadXML() understands it perfectly.

You can also use references to external DTDs in the same way (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">), which is particularly important if you need to do this for many different documents with many different possible entities.

Also, as a sidenote...entity references created by createEntityReference() do not need this kind of explicit declaration.
shaoyu73 at gmail dot com 15-Mar-2007 08:53
earth at anonymous dot com,

preserveWhiteSpace property needs to be set to false for formatOutput to work properly, for some reason.

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xmlStr);
...
$element->appendChild(...);
...
$dom->formatOutput = true;
$xmlStr = $dom->saveXML();
echo $xmlStr;

This would format the output nicely.
Gavin Sinai gsinai at gmx dot net 30-Aug-2006 07:34
loadXml reports an error instead of throwing an exception when the xml is not well formed. This is annoying if you are trying to to loadXml() in a try...catch statement. Apparently its a feature, not a bug, because this conforms to a spefication.

If you want to catch an exception instead of generating a report, you could do something like

<?php
function HandleXmlError($errno, $errstr, $errfile, $errline)
{
    if ($errno==E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0))
    {
        throw new DOMException($errstr);
    }
    else
        return false;
}

function XmlLoader($strXml)
{
    set_error_handler('HandleXmlError');
    $dom = new DOMDocument();
    $dom->loadXml($strXml);
    restore_error_handler();
    return $dom;
 }

?>

Returning false in function HandleXmlError() causes a fallback to the default error handler.
mp at webfactory dot de 08-Aug-2006 08:26
While loadXML() expects its input to have a leading XML processing instruction to deduce the encoding used, there's no such concept in (non-XML) HTML documents. Thus, the libxml library underlying the DOM functions peeks at the <META> tags to figure out the encoding used.

See http://xmlsoft.org/encoding.html.
earth at anonymous dot com 12-Apr-2006 02:28
Note that loadXML crops off beginning and trailing whitespace and linebreaks.

When using loadXML and appendChild to add a chunk of XML to an existing document, you may want to force a linebreak between the end of the XML chunk and the next line (usually a close tag) in the output file:

$childDocument = new DOMDocument;
$childDocument>preserveWhiteSpace = true;
$childDocument->loadXML(..XML-Chunk..);
$mNewNode = $mainDOcument->importNode($childDocument->documentElement, true);
$ParentNode->appendChild($mNewNode);
$ParentNode->appendChild($mainDocument->createTextNode("\\n  ");

Although it is said that DOM should not be used to make 'pretty' XML output, it is something I struggled with to get something that was readable for testing.  Another solution is to use the createDocumentFragment()->appendXML(..XML-Chunk..) instead, which seems not to trim off linebreaks like DOMDocument->loadXML() does.


Normalizes the document

  • ? DOMDocument::loadXML
  • DOMDocument::registerNodeClass ?
  • PHP Manual
  • DOMDocument
  • Normalizes the document

DOMDocument::normalizeDocument

(PHP 5, PHP 7)

DOMDocument::normalizeDocument — Normalizes the document

说明

public DOMDocument::normalizeDocument ( ) : void

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

返回值

没有返回值。

参见

  • » The DOM Specification
  • DOMNode::normalize() - Normalizes the node

User Contributed Notes

lingasamy dot sakthivel at gmail dot com 16-Apr-2015 05:44
You can use this in this way.

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML($content); // html content
$xpath = new DOMXPath($doc);
$doc->normalizeDocument();

Note that, you can use $doc->normalizeDocument(); at any point of time.


Register extended class used to create base node type

  • ? DOMDocument::normalizeDocument
  • DOMDocument::relaxNGValidate ?
  • PHP Manual
  • DOMDocument
  • Register extended class used to create base node type

DOMDocument::registerNodeClass

(PHP 5 >= 5.2.0, PHP 7)

DOMDocument::registerNodeClass — Register extended class used to create base node type

说明

public DOMDocument::registerNodeClass ( string $baseClass , string|null $extendedClass ) : bool

This method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension.

This method is not part of the DOM standard.

参数

baseClass

The DOM class that you want to extend. You can find a list of these classes in the chapter introduction.

extendedClass

Your extended class name. If null is provided, any previously registered class extending baseClass will be removed.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Adding a new method to DOMElement to ease our code

<?php

class myElement extends DOMElement {
   function appendElement($name) {
      return $this->appendChild(new myElement($name));
   }
}

class myDocument extends DOMDocument {
   function setRoot($name) {
      return $this->appendChild(new myElement($name));
   }
}

$doc = new myDocument();
$doc->registerNodeClass('DOMElement', 'myElement');

// From now on, adding an element to another costs only one method call !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

以上例程会输出：

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Example #2 Retrieving elements as custom class

<?php
class myElement extends DOMElement {
    public function __toString() {
        return $this->nodeValue;
    }
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// And take advantage of the __toString method..
echo $element;
?>

以上例程会输出：

string(9) "myElement"
text in child

Example #3 Retrieving owner document

When instantiating a custom DOMDocument the ownerDocument property will refer to the instantiated class, meaning there is no need (and in fact not possible) to use DOMDocument::registerNodeClass() with DOMDocument

<?php
class myDOMDocument extends DOMDocument {
}

class myOtherDOMDocument extends DOMDocument {
}

// Create myDOMDocument with some XML
$doc = new myDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// The current owner of the node is myDOMDocument
var_dump(get_class($child->ownerDocument));

// Import a node from myDOMDocument
$newdoc = new myOtherDOMDocument;
$child = $newdoc->importNode($child);

// The new owner of the node has changed to myOtherDOMDocument
var_dump(get_class($child->ownerDocument));
?>

以上例程会输出：

string(13) "myDOMDocument"
string(18) "myOtherDOMDocument"

Example #4 Custom objects are transient

Caution

Objects of the registered node classes are transient, i.e. they are destroyed when they are no longer referenced from PHP code, and recreated when being retrieved again. That implies that custom property values will be lost after recreation.

<?php
class MyDOMElement extends DOMElement
{
    public $myProp = 'default value';
}

$doc = new DOMDocument();
$doc->registerNodeClass('DOMElement', 'MyDOMElement');

$node = $doc->createElement('a');
$node->myProp = 'modified value';
$doc->appendChild($node);

echo $doc->childNodes[0]->myProp, PHP_EOL;
unset($node);
echo $doc->childNodes[0]->myProp, PHP_EOL;
?>

以上例程会输出：

modified value
default value

User Contributed Notes

crh3675 at gmail dot com 25-Sep-2009 08:23
Creating innerHTML and outerHTML

<?php

class DOMHTMLElement extends DOMElement
{
    function __construct() { parent::__construct();}

    public function innerHTML()
    {
        $doc = new DOMDocument();
      foreach ($this->childNodes as $child){
          $doc->appendChild($doc->importNode($child, true));
        }
        $content = $doc->saveHTML();
        return $content;
    }

    public function outerHTML()
    {
        $doc = new DOMDocument();
        $doc->appendChild($doc->importNode($this, true));
        $content = $doc->saveHTML();
        return $content;
    }
}

$dom = DOMDocument::loadHTMLFile($file);
$dom->registerNodeClass('DOMElement','DOMHTMLElement');

if($dom)
{
    $xpath = new DOMXpath($dom);
    $regions = $xpath->query("//*[contains(@class, 'editable')]");
    $content = '';

    foreach($regions as $region){
        $content .= $region->outerHTML();
    }

    return $content;

}else{
    throw new Exception('Cannot parse HTML.  Please verify the syntax is correct.');
}
?>
arnold at adaniels dot nl 22-Jul-2009 03:10
Note than save and saveXML are not affected by __toString().


Performs relaxNG validation on the document

  • ? DOMDocument::registerNodeClass
  • DOMDocument::relaxNGValidateSource ?
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidate

(PHP 5, PHP 7)

DOMDocument::relaxNGValidate — Performs relaxNG validation on the document

说明

public DOMDocument::relaxNGValidate ( string $filename ) : bool

Performs » relaxNG validation on the document based on the given RNG schema.

参数

filename

The RNG file.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

scarywound at gmail dot com 17-Oct-2012 11:39
Keep in mind that this method can't handle schemas in compact syntax!
mitchell dot beaumont at mitchellbeaumont dot com 26-Aug-2007 07:28
It's worth noting that when validation fails this function also triggers a warning.

You can suppress the warning using the set_error_handler and restore_error_handler functions.


Performs relaxNG validation on the document

  • ? DOMDocument::relaxNGValidate
  • DOMDocument::save ?
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidateSource

(PHP 5, PHP 7)

DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document

说明

public DOMDocument::relaxNGValidateSource ( string $source ) : bool

Performs » relaxNG validation on the document based on the given RNG source.

参数

source

A string containing the RNG schema.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

There are no user contributed notes for this page.


Dumps the internal XML tree back into a file

  • ? DOMDocument::relaxNGValidateSource
  • DOMDocument::saveHTML ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a file

DOMDocument::save

(PHP 5, PHP 7)

DOMDocument::save — Dumps the internal XML tree back into a file

说明

public DOMDocument::save ( string $filename , int $options = 0 ) : int|false

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

返回值

Returns the number of bytes written or false if an error occurred.

范例

Example #1 Saving a DOM tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?>

参见

  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

User Contributed Notes

dubois-holvoet dot patrick at neuf dot fr 25-Feb-2016 08:13
I just intend to bring my little contribution to the use of DOMDocument::save() function along with PHP serialize() function.

Sometimes you could have to serialize a PHP object before you put it into a XML structure (or other..). And then I suppose you could have to save this XML structure in a file. Of course, you will further need to read this file and unserialize it before to use its content.

The problem appears when there are some properties described as Protected in the object to be serialized.

As it's written in the PHP documentation, serialize function add for those protected properties an asterisk before the name of the property along with a NULL character on each side of the asterisk.
In this case, the DOMDocument::save function will stop the save operation just before the first NULL character met in the string to be saved, because PHP consider it as a potential risk.
So, after that, the unserialize operation of the file become impossible.

To solve that, here is a first solution to apply :

For the serialize , before the DOMDocument::save() ::
$data_serial = explode("\x00\x2A\x00", serialize($object));  //take off the 'NULL * NULL' string
$data_serial = implode("\x5C\x30\x2A\x5C\x30", $data_serial);    //and replace with '\0*\0' string

Before the unserialize :
$data_serial = explode("\x5C\x30\x2A\x5C\x30", $serialized_object);    // take off the '\0*\0' string
$serial_object = implode("\x00\x2A\x00", $data_serial);      // and replace with 'NULL * NULL' string as included by the previous serialize

And a second solution :

For the serialize, before the DOMDocument::save() :
$serialized_object = addslashes(serialize($object)) ;

Before re-using the object in your application :
$object = unserialize(stripslashes($serialized_object)) ;

Hope this will help some.
ludvig at ergopedia dot no 31-Oct-2014 10:21
When creating a DOMDocument from scratch and saving it, the encoding will be utf-8, although it's declared as iso-8859-1.

When loading an XML-file declared and saved as iso-8859-1, php will keep the correct encoding when it's saved after changes are made.

Php converts files declared as iso-8859-1 to utf-8 internally. To add text containing special characters, the text must be encoded as utf-8. When the document is saved, special characters are converted to iso-8859-1.

To save an xml created from scratch, use fopen/fwrite and utf8_decode:

   $doc = new DOMDocument('1.0', 'iso-8859-1');

//Add som nodes and text with apropriate methods

   $f = fopen('xmlfile.xml', 'w+');
   fwrite($f, utf8_decode($doc->saveXML()));
   fclose($f);
john at johnreid dot it 06-Aug-2013 09:42
I had been hitting my head against the wall when I couldn't get an edited XML file to save due to file permissions, even though I knew that it was OK.

Eventually I realised that for some odd reason, when I went to save the XML file, it would try to write the file to the root directory.

As such, use realpath() to keep the complete system path to the XML file when you load it:

<?php
$myfile = 'myxml.xml';
$myfile = realpath($myfile);
$doc = new DOMDocument('1.0');
$doc->load($myfile);

// Let's just add a couple of elements for good measure
$root = $doc->documentElement;

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is a title');
$text = $title->appendChild($text);

$doc->save($myfile);
?>
ss at littlerain dot com 01-Feb-2009 12:05
In addition to:
DOMDocument->formatOutput = true
DOMDocument->preserveWhiteSpace = false

...you also have to ensure you don't add text nodes as siblings of element nodes, or formatOutput won't work.
chenel324 at gmail dot com 19-Oct-2008 06:38
It took me forever to discover that
DOMDocument->formatOutput = true
will only have an effect on documents that are loaded from disk if one also sets
DOMDocument->preserveWhiteSpace = false ....

Hope this saves somebody a headache.
siegparr at NOSPAM dot web dot de 07-Jul-2006 08:00
The XML parser converts the text of an XML document into UTF-8, even if you have set the character encoding of the XML, for example as a second parameter of the DOMDocument constructor. After parsing the XML with the load() command all its texts have been converted to UTF-8.

In case you append text nodes with special characters (e. g. Umlaut) to your XML document you should therefore use utf8_encode() with your text to convert it into UTF-8 before you append the text to the document. Otherwise you will get an error message like "output conversion failed due to conv error" at the save() command. See example below:

<?php
// Text to insert into XML below
$txt = "a text with special characters like '?', '?', 'ü' etc.";

// Create Instance of DOMDocument
$dom =  new DOMDocument;
// Load XML file
// Was created before with DOMDocument('1.0', 'iso-8859-1')
$dom = $dom->load("file.xml");
// Find the parent node
$parent = $dom->documentElement;
// Create Instance of DomXPath
$xpath = new DomXPath($dom);
// new node will be inserted before this node
$next = $xpath->query("//parentnode/childnode");
// Create the new element
$new_elem = $dom->createElement('new_elem');
// Insert the new element
$parent->insertBefore($new_elem, $next->item(0));
// DOMXML = utf-8! (will be converted to iso-8859-1 only at 'save()')
// prevents error message "output conversion failed due to conv error" at 'save()'
$txt = utf8_encode($txt);
// Create new text node with utf-8 encoded string
$nodetext = $dom->createTextNode("$txt");
// Append text node to new element
$nodetext = $new_elem->appendChild($nodetext);
// save
$dom->save("file.xml");
?>

Hope this helps someone.

siegparr


Dumps the internal document into a string using HTML formatting

  • ? DOMDocument::save
  • DOMDocument::saveHTMLFile ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a string using HTML formatting

DOMDocument::saveHTML

(PHP 5, PHP 7)

DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting

说明

public DOMDocument::saveHTML ( DOMNode|null $node = null ) : string|false

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

node

Optional parameter to output a subset of the document.

返回值

Returns the HTML, or false if an error occurred.

范例

Example #1 Saving a HTML tree into a string

<?php

$doc = new DOMDocument('1.0');

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

参见

  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

User Contributed Notes

jeboy 28-Sep-2017 02:57
LIBXML_HTML_NOIMPLIED doesn't work on PHP 7.1.9 with libxml2-2.7.8
sasha @ goldnet dot ca 27-Jul-2017 04:21
When saving HTML fragment initiated with LIBXML_HTML_NOIMPLIED option, it will end up being "broken" as libxml requires root element. libxml will attempt to fix the fragment by adding closing tag at the end of string based on the first opened tag it encounters in the fragment.

For an example:

<h1>Foo</h1><p>bar</p>

will end up as:

<h1>Foo<p>bar</p></h1>

Easiest workaround is adding root tag yourself and stripping it later:

$html->loadHTML('<html>' . $content .'</html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$content = str_replace(array('<html>','</html>') , '' , $html->saveHTML());
contact at cathexis dot de 31-Aug-2016 10:41
If you load HTML from a string ensure the charset is set.

<?php
...
$html_src = '<html><head><meta content="text/html; CHARSET=gb2312" http-equiv="Content-Type"></head><body>';
$html_src .= '...';
...
?>

Otherwise the charset will be ISO-8859-1!
tomas dot strejcek at ghn dot cz 20-Aug-2016 12:34
As of PHP 5.4 and Libxml 2.6, there is currently simpler approach:

when you load html as this

$html->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

in the output, there will be no doctype, html or body tags
Anonymous 11-Dec-2015 03:38
To solve the script tag problem just add an empty text node to the script node and DOMDocument will render <script src="your.js"></script> nicely.
RiKdnUA at mail dot ru 29-Apr-2015 03:49
Tested in PHP 5.2.9-2 and PHP 5.2.17.
saveHTML() игнорирует свойство DOMDocument->encoding. Метод saveHTML() сохраняет html-документ в кодировке, которая указана в теге <meta> исходного (загруженного) html-документа.
saveHTML() ignores property DOMDocument->encoding. Method saveHTML() saves the html-document encoding, which is specified in the tag <meta> source (downloaded) html-document.
Example:
file.html. Кодировка файла должна совпадать с указанной в теге <meta>. The encoding of the file must match the specified tag <meta>.
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Russian language</title></head>
<body>Русский язык</body></html>

<?php
error_reporting(-1);
$document=new domDocument('1.0', 'UTF-8');
$document->preserveWhiteSpace=false;
$document->loadHTMLFile('file.html');
$document->formatOutput=true;
$document->encoding='UTF-8';
$htm=$document->saveHTML();
echo"Записано байт. Recorded bytes: ".file_put_contents('file_new.html', $htm);
?>
file_new.html будет в кодировке Windows-1251 (НЕ в UTF-8).
file_new.html will be encoded in Windows-1251 (not in UTF-8).

saveHTML() и file_put_contents() позволяют преодолеть недостаток метода saveHTMLFile().
Смотрите мой комментарий к методу saveHTMLFile().
saveHTML() and file_put_contents() allows you to overcome the lack of a method saveHTMLFile().
See my comment on the method saveHTMLFile().
http://php.net/manual/ru/domdocument.savehtmlfile.php
qrworld.net 11-Nov-2014 04:34
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
alvaro at demogracia dot com 29-Mar-2011 11:04
Since PHP/5.3.6, DOMDocument->saveHTML() accepts an optional DOMNode parameter similarly to DOMDocument->saveXML():

http://bugs.php.net/bug.php?id=39771
Yajo 24-Nov-2010 07:21
Another way to workaround the <script/> problem is putting a semicolon (;) inside the script element.
Anonymous 09-Feb-2010 07:52
If you want a simpler way to get around the <script> tag problem try:

<?php

  $script = $doc->createElement ('script');\
  // Creating an empty text node forces <script></script>
  $script->appendChild ($doc->createTextNode (''));
  $head->appendChild ($script);

?>
Anonymous 12-May-2009 07:35
To avoid script tags from being output as <script />, you can use the DOMDocumentFragment class:

<?php

$doc = new DOMDocument();
$doc -> loadXML($xmlstring);
$fragment = $doc->createDocumentFragment();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */
if($fragment->appendXML("<script type='text/javascript' src='$source'></script>") {
  $xpath = new DOMXpath($doc);
  $resultlist = $xpath->query("//*[local-name() = 'html']/*[local-name() = 'head']"); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
  foreach($resultlist as $headnode)  // insert the script tag
     $headnode->appendChild($fragment);
}
$doc->saveXML(); /* and our script tags will still be <script></script> */

?>
Bart Feenstra 18-Jan-2009 10:17
I am using this solution to prevent tags and the doctype from being added to the HTML string automatically:

<?php
$html = '<h1>Hello world!</h1>';
$html = '<div>' . $html . '</div>';
$doc = new DOMDocument;
$doc->loadHTML($html);
echo substr($doc->saveXML($doc->getElementsByTagName('div')->item(0)), 5, -6)

// Outputs: "<h1>Hello world!</h1>"
?>
m at hbblogs daught calm 18-Aug-2008 08:41
This method, as of 5.2.6, will automatically add <html><body> and <!DOCTYPE> tags to the document if they are missing, without asking whether you want them. In my application, I needed to use the DOM methods to manipulate just a fragment of html, so these tags were rather unhelpful.

Here's a simple hack to remove them in case, like me, all you wanted to do was perform a few operations on an HTML fragment.

$html_fragment = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
Anonymous 25-Apr-2008 08:15
<?php
function getDOMString($retNode) {
  if (!$retNode) return null;
  $retval = strtr($retNode-->ownerDocument->saveXML($retNode),
  array(
    '></area>' => ' />',
    '></base>' => ' />',
    '></basefont>' => ' />',
    '></br>' => ' />',
    '></col>' => ' />',
    '></frame>' => ' />',
    '></hr>' => ' />',
    '></img>' => ' />',
    '></input>' => ' />',
    '></isindex>' => ' />',
    '></link>' => ' />',
    '></meta>' => ' />',
    '></param>' => ' />',
    'default:' => '',
    // sometimes, you have to decode entities too...
    '&quot;' => '&#34;',
    '&amp;' =>  '&#38;',
    '&apos;' => '&#39;',
    '&lt;' =>   '&#60;',
    '&gt;' =>   '&#62;',
    '&nbsp;' => '&#160;',
    '&copy;' => '&#169;',
    '&laquo;' => '&#171;',
    '&reg;' =>   '&#174;',
    '&raquo;' => '&#187;',
    '&trade;' => '&#8482;'
  ));
  return $retval;
}
?>
mjaque at ilkebenson dot com 19-Feb-2008 11:34
DOMDocument->saveXML() doesn't generate a proper XHTML format either.

There is a problem with "script" empty elements. For example:

This will be the code generated by saveXML, with an empty script tag.

<html>
  <head>
    <script type="text/JavaScript" src="myScript.js"/>
  </head>
  <body>
    <p>I will not appear</p>
    <script type="text/JavaScript">
    alert("Not working");
    </script>
  </body>
</html>

I don't know if this is valid XHTML (W3C Validator doesn't complain), but both FF 2.0 and IE 6 will not render it properly. Both will use </script> as the closing tag for the first script causing js errors and ignoring in between elements.

You can post-process saveXML string in order to close empty tags with the following function:

<?php
    function cerrarTag($tag, $xml){
        $indice = 0;
        while ($indice< strlen($xml)){
            $pos = strpos($xml, "<$tag ", $indice);
            if ($pos){
                $posCierre = strpos($xml, ">", $pos);
                if ($xml[$posCierre-1] == "/"){
                    $xml = substr_replace($xml, "></$tag>", $posCierre-1, 2);
                }
                $indice = $posCierre;
            }
            else break;
        }
        return $xml;
    }
?>

At least script and select empty elements should be closed. This example shows how it can be used:

<?php
    define("CABECERA_XHTML", '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');

  $xhtml = $docXML->saveXML($docXML->documentElement);
  $xhtml = cerrarTag("script", $xhtml);
  $xhtml = cerrarTag("select", $xhtml);
  $xhtml = CABECERA_XHTML."\n".$xhtml;
  echo $xhtml;
?>
archanglmr at yahoo dot com 27-Nov-2007 03:28
If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you're reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

<?php
header('Content-Type: text/html; charset=iso-8859-1');
?>
xoplqox 20-Nov-2007 11:07
XHTML:

If the output is XHTML use the function saveXML().

Output example for saveHTML:

<select name="pet" size="3" multiple>
    <option selected>mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>

XHTML conform output using saveXML:

<select name="pet" size="3" multiple="multiple">
    <option selected="selected">mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>
tyson at clugg dot net 21-Apr-2005 05:44
<?php
// Using DOM to fix sloppy HTML.
// An example by Tyson Clugg <tyson@clugg.net>
//
// vim: syntax=php expandtab tabstop=2

function tidyHTML($buffer)
{
  // load our document into a DOM object
  $dom = @DOMDocument::loadHTML($buffer);
  // we want nice output
  $dom->formatOutput = true;
  return($dom->saveHTML());
}

// start output buffering, using our nice
// callback funtion to format the output.
ob_start("tidyHTML");

?>
<html>
<p>It's like comparing apples to oranges.
</html>
<?php

// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();

?>

The above code takes out sloppy HTML:
 <html>
 <p>It's like comparing apples to oranges.
 </html>

And cleans it up to the following:
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
 <html><body><p>It's like comparing apples to oranges.
 </p></body></html>


Dumps the internal document into a file using HTML formatting

  • ? DOMDocument::saveHTML
  • DOMDocument::saveXML ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a file using HTML formatting

DOMDocument::saveHTMLFile

(PHP 5, PHP 7)

DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting

说明

public DOMDocument::saveHTMLFile ( string $filename ) : int|false

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

filename

The path to the saved HTML document.

返回值

Returns the number of bytes written or false if an error occurred.

范例

Example #1 Saving a HTML tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?>

参见

  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

User Contributed Notes

RiKdnUA at mail dot ru 27-Jul-2013 04:15
saveHTMLFile() always saves the file in UTF-8. Even if the DOMDocument->encoding explicitly prescribe different from UTF-8 encoding. All "non-Latin" characters will be converted to HTML-entities. Tested in PHP 5.2.9-2 and PHP 5.2.17. Example:

<?php
$document=new domDocument('1.0', 'WINDOWS-1251');
$document->loadHTML('<html><head><title>Russian language</title></head><body>Русский язык</body></html>');
$document->formatOutput=true;
$document->encoding='WINDOWS-1251';
echo "Записано байт. Recorded bytes: ".$document->saveHTMLFile('html.html');
?>

Method recorded file in UTF-8 encoding. The contents of the file html.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312">
<title>Russian language</title>
</head>
<body>Dó??êèé ???ê</body>
</html>
naebeth at hotmail dot NOSPAM dot com 24-Sep-2012 10:03
Not mentioned in the documentation is the fact that using DOMDocument::saveHTMLFile() will automatically overwrite the contents if an existing file is used - with no notice, warning or error thrown.

Make sure you check the filename before using this function so that you don't accidentally overwrite important files.

Example:
<?php

$file = fopen('test.html', 'w');
fwrite($file, 'this is some text');
fclose($file);

$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->loadHTML('<html><head><title>Test</title></head><body></body></html>');
$doc->saveHTMLFile('test.html');

// test.html
/*
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312">
<title>Test</title>
</head>
<body></body>
</html>
*/

?>

If you're dynamically generating a series of pages using DOMDocument objects, make sure you are also dynamically generating the file or directory names using something that can't easily be confused for an existing file/folder, or check if the desired path already exists before saving so that you don't accidentally delete previous files.
deep42thouSPAMght42 at y_a_h_o_o dot com 14-Jan-2011 03:46
I foolishly assumed that this function was equivalent to
<?php
file_put_contents($filename, $document->saveHTML());
?>
but there are differences in the generated HTML:
<?php
$doc = new DOMDocument();
$doc->loadHTML(
    '<html><head><title>Test</title></head><body></body></html>'
);
$doc->encoding = 'iso-8859-1';

echo $doc->saveHTML();
#<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#<html>
#<head><title>Test</title></head>
#<body></body>
#</html>

$doc->saveHTMLFile('output.html');
#<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#<html><head><meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312"><title>Test</title></head><body></body></html>

?>
Note that saveHTMLFile() adds a UTF-8 meta tag despite the ISO-8859-1 document encoding.


Dumps the internal XML tree back into a string

  • ? DOMDocument::saveHTMLFile
  • DOMDocument::schemaValidate ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a string

DOMDocument::saveXML

(PHP 5, PHP 7)

DOMDocument::saveXML — Dumps the internal XML tree back into a string

说明

public DOMDocument::saveXML ( DOMNode|null $node = null , int $options = 0 ) : string|false

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

返回值

Returns the XML, or false if an error occurred.

错误／异常

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

范例

Example #1 Saving a DOM tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc->saveXML($title);

?>

以上例程会输出：

Saving all the document:
<?xml version="1.0"?>
<book>
  <title>This is the title</title>
</book>

Saving only the title part:
<title>This is the title</title>

参见

  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

User Contributed Notes

liumenglei0211 at 163 dot com 17-Jan-2019 07:50
How to display two tags when the node content is empty.

<?php
$dom     = new \DOMDocument('1.0');
$document = $dom->createElement('document');
$document = $dom->appendChild($document);
$head = $dom->createElement('title','this is title');
$content = $dom->createElement('content','');
$document->appendChild($head);
$document->appendChild($content);
echo $dom->saveXML();
?>

In XML, they are considered exactly the same thing, and any parser should recognize both forms.However, you can write it this way if you still need it

<?php
echo $dom->saveXML($dom->documentElement, LIBXML_NOEMPTYTAG);
?>

Example 1：

<?xml version="1.0"?>
<document>
    <title>this is title</title>
    <content/>
</document>

Example 2：
<document>
    <title>this is test</title>
    <content></content>
</document>
Frank 29-Mar-2017 06:40
I would like to create a DOM document Xml Guestbook ..can somebody help to me?

Username, Comments in form read/write the task.

Thanks if somebody save me :)
Alexander Fedulin 05-Mar-2014 08:29
As @fbernodi said earlier, there is a problem with saveXML of DOMNode when you have a number of defined namespaces. The simple solution for this:

<code>
   // $node is some node of some other document
   $temp_document = new DOMDocument('1.0', 'utf-8');
   $temp_document->appendChild($temp_document->importNode($node, true));
   echo $temp_document->saveXML();
</code>
fbernoldi at gmail dot com 01-Aug-2013 08:24
Hello,

I had an unexpected behavior in some parsing code, because of this saveXML method that is saving the tags without namespace specification. If you try to load into a DOMDocument a string saved from a DOMNode that has a referenced namespace but it the original document it was not defined in that element, you get a not well formed xml. In the example you can see the issue and a possible solution, the other solution may be add to the ChildElement node the namespace reference (<testNS:ChildElement testNS="http://example.org">), but in my scenario it was not needed.

<?php

//Test XML
$test_xml =
"<?xml version=\"1.0\"?>
<testNS:RootNode xmlns:testNS=\"http://example.org\">
    <testNS:ChildElement>
        <testNS:AnotherChildElement>I'm a Another Child node.</testNS:AnotherChildElement>
    </testNS:ChildElement>
</testNS:RootNode>";

//We define our Test DOMDocument
$domDoc = new DOMDocument("1.0");
$domDoc->loadXML($test_xml);

//We use xpath to search ChildElement:
$domXPath = new DOMXPath($domDoc);
$domXPath->registerNamespace("testNS", "http://example.org");
$DOMNodeList_ChildElement = $domXPath->query("//testNS:RootNode/testNS:ChildElement");
$ChildElement = $DOMNodeList_ChildElement->item(0);

echo "Not usefull xml to load in another document:\n\n";
echo $domDoc->saveXML($ChildElement);

/* Output here:
 *
 * Not usefull xml to load in another document:
 *
 *  <testNS:ChildElement>
 *        <testNS:AnotherChildElement>I'm a Another Child node.</testNS:AnotherChildElement>
 *    </testNS:ChildElement>
 *
 */

/**
 * Function to help us clone the element to another document.
 * @param DOMElement $node The node to clone.
 * @param DOMDocument $doc The document where we are going to reference the elements.
 * @return DOMElement The new cloned element without namespace.
 */
function cloneNode($node, $doc) {
    //Create new element with the original localName (w/o namespace)
    $nd = $doc->createElement($node->localName);

    //Clone attributes
    foreach($node->attributes as $value)
        $nd->setAttribute($value->localName, $value->value);

    //No more childs then we finish.
    if (!$node->childNodes)
        return $nd;
    //We have childs, add them
    foreach($node->childNodes as $child) {
        if ($child->nodeName=="#text") //Only needed to clone text nodes, i.e. text comments, spaces, tabs. etc.
            $nd->appendChild($doc->createTextNode($child->nodeValue));
        else
            $nd->appendChild(cloneNode($child, $doc)); //recursion to clone all children.
    }
    return $nd;
}

//New Document to reference the new node without namespaces
$domDoc2 = new DOMDocument("1.0");

//We clone this node taking out the namespace
$new_node = cloneNode($ChildElement, $domDoc2);

echo "\n\nWe can load this into a DOMDocument without problems:\n\n";
echo $domDoc2->saveXML($new_node);

/*
 * We can load this into a DOMDocument without problems:
 *
 *    <ChildElement>
 *        <AnotherChildElement>I'm a Another Child node.</AnotherChildElement>
 *    </ChildElement>
 */

?>
xianrenb at gmail dot com 15-Jul-2012 10:54
If you want to save xhtml (in a string), you may try the following method:
<?php
    $doc = new DOMDocument('1.0');

    // ...

    $xhtml = (string) $doc->saveXML($doc->doctype);
    $xhtml .= "\n";
    $xhtml .= (string) $doc->saveXML($doc->documentElement);
?>
samstah at gmail dot com 19-Mar-2010 03:56
We discovered using DOMDocument::saveHTML() that it converts to HTML 4.01 compatible markup; rather than XHTML. The simple answer is to use saveXML() instead, although this adds the XML declaration to the top.

To qjerry.com at gmail.com, thanks for the pointer below - but I think that the simplest way seems to be using:
<?php $domDocument->saveXML($domDocument->documentElement); ?>

Of course, if you're dealing with XHTML, this will strip any <!DOCTYPE> declarations in the document too.
qjerry.com at gmail.com 04-May-2009 04:24
The simpliest (and probably the fastest) way to strip an XML declaration (<?xml version="1.0" ... ?>) out of output document, is to output child nodes of DOMDocument separately:

<?php

$document = new DOMDocument();
$document->load('/some/file.xml');

// this will also output doctype and comments at top level
foreach($document->childNodes as $node)
    $result .= $document->saveXML($node)."\n";

echo $result;

?>

This might be userful when dealing with browser compatibility issues, for example, well known problem with valid XHTML in IE6.
vikramvmalhotra at hotmail dot com 27-Jan-2009 03:49
if you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. It will spit out the characters converted in encoded format.

<?php
$str = domdoc->saveXML(); // gives "&x#1245;" some encoded data
?>

Instead do the following

<?php
$str = domdoc->saveXML(domdoc->documentElement); // gives "保存しました" correct multi-byte data
?>
shinsh at shinmugen dot net 23-May-2008 07:57
Be careful, this function has been changed in 5.2.6 version. Adding a required parameter which is not that required wasn't the most intelligent idea ever, especially for a function which is often used.

To fix your programs if you have an error, fill the first parameter like this:

$dom->saveXML($dom->documentElement);

Why didn't the devs simply implement this as optional parameter, fixing the default parameter as documentElement?
Kriogen 26-Dec-2007 12:57
Create before test.xml with:
<?xml version="1.0" encoding="utf-8"?>
<Photos>
</Photos>

and past after in your php-file:

<?php
$simp = simplexml_load_file('test.xml');
$node = $simp->addChild('home');
$node->addChild('mychild', 'insert text');
$s = simplexml_import_dom($simp);
$s->saveXML('test.xml');
?>

This code creating a child-nod in the root.
Owner http://www.mensfashion.ru
JITR 02-Aug-2007 05:10
Comment to `devin at SPAMISBAD dot tritarget dot com''s post:

Thanks for pointing out the pitfalls of `formatOutput' vs. `load*()'. This has certainly saved me from some possible surprises.

I think the seemingly strange behaviour can be explained. Warning: The following stuff is mostly based on deductions and experiments. Much less on studying the sources and specs (I'm not sure some of these would provide answer anyway, at least not easily).

As you point out, `preserveWhiteSpace' must be set before loading the DOM from the source string (I'm working with `loadXML()' but I believe the situation should be the same with `load()' you used). This looks logical, as this property seems to control the parsing and DOM creation process during which text nodes containing the whitespace are either included or dropped. This can be proven by dumping the DOM structure and comparing the results based on the value of `preserveWhiteSpace'. With `preserveWhiteSpace' set to `FALSE', no text nodes containing whitespace will be present in the returned DOM. When this property is `TRUE', these nodes will be present.

Note: When speaking about the whitespace in the previous paragraph, we're most certainly speaking about so called `whitespace in element content' or `element content whitespace', if I'm not mistaken. See also my comment in the notes of `DOMText->isWhitespaceInElementContent()' method.

As for the mysterious effect on the output of `saveXLM()', I think the explanation lies in the presence or absence of the above mentioned whitespace text nodes. This was also proven by experiments: After adding such a node into a DOM which contained none (the DOM was created using `loadXML()' with `preserveWhiteSpace' set to `FALSE'), the output formatting got affected in a such a way, the formatting got lost for the rest of the document after the added node. I think the presence of whitespace text nodes forces such rendering, that the content of these nodes is used to separate adjoining nodes thus disabling default formatting. Only when there are no such text nodes present, the ouput formatting takes effect (provided the `formatOutput' is set to `TRUE', of course).

Well, the thing I don't really understand is how you did get an output of a signle line with `formatOutput' set to `TRUE'. This has happened to me when no whitespace text nodes were present (ie. when loading the XML with `preserveWhiteSpace' set to `FALSE') *and* with `formatOutput' set to *`FALSE'* (with the opposite value of `formatOutput', the formatting should do it's work and you should not end up with just one line). But I haven't seen your source. Perhaps you had whitespace nodes containing no new-lines in your DOM?

As for the CAUTION about root element, I didn't see any problems with empty root element neither in shortened nor full form. What did you have in mind, when you said it `WORKS' or `DOES NOT WORK'?
Sander 25-Apr-2007 05:35
Note that for large DOM trees (tens of thousands of elements nested at least a few levels deep), setting formatOutput to true drives up memory usage to rather insane levels when you call saveXML(). (Tested with PHP 5.2.1) Pretty output is not worth that cost.
nevyn at NOSPAM dot email dot PLEASE dot it 27-Dec-2006 01:41
A little function to get the full xml contents of a Xml node.

function innerXml($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<(\\w*)(?:\\s*\\w+=(?:\"[^\"]*\"|\'[^\']*\'))*\\s*>(.*)</\\1>$}";
    preg_match($re, $out, $mat);
    return $mat[2];
}
devin at SPAMISBAD dot tritarget dot com 14-Aug-2006 10:52
It took some searching to figure this one out. I didn't see much in the way of explaining this glitch in the manual thus far. (For PHP5 I believe)

formatOutput = true; appears to fail when the origin of the DOM came from a file via load(). EX:

<?php
    $dom = new DOMDocument();
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

Will not indent the output and will display the modified nodes all in one long line. Makes for editing a config.xml a bit difficult when saving to a file.

By adding the preserveWhiteSpace = false; BEFORE the load() the formatOutput works as expected. EX:

<?php
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

CAUTION: If your loaded xml file (test.xml) has an empty root node that is not shortened or has no children this will NOT work.

Example:

DOES NOT WORK:
<?xml version="1.0"?>
<root>
</root>

WORKS:
<?xml version="1.0"?>
<root/>

WORKS:
<?xml version="1.0"?>
<root>
  <!-- comment -->
</root>

WORKS:
<?xml version="1.0"?>
<root>
  <child/>
</root>
26-Mar-2006 04:20
I used the function posted by "joe" but the following works to me for get the innerXML
<?php
$itemLeido = $XMLRespuesta->getElementsByTagName("articulos");
foreach($itemLeido as $node) {
    echo($node->ownerDocument->saveXML($node));
}
?>
mswiercz at mwerk dot com 10-Sep-2004 03:43
Quick tip to minimize memory when generating documents with DOM.

Rather than using
   $xmlStr = DOMDocument->saveXML();
   echo $xmlStr;

to dump a large DOM to the output buffer, use a PHP output stream, as in

   DOMDocument->save('php://output');

A lot of memory will be saved when generating large DOMs.
padys at tlen dot pl 05-Aug-2004 07:36
When you save whole document:
DOMDocument->saveXML() produces string in encoding defined in property DOMDocument->encoding.

When you save only one node:
DOMDocument->saveXML(DOMNode) produces always string in UTF-8.


Validates a document based on a schema. Only XML Schema 1.0 is supported.

  • ? DOMDocument::saveXML
  • DOMDocument::schemaValidateSource ?
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema. Only XML Schema 1.0 is supported.

DOMDocument::schemaValidate

(PHP 5, PHP 7)

DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.

说明

public DOMDocument::schemaValidate ( string $filename , int $flags = 0 ) : bool

Validates a document based on the given schema file.

参数

filename

The path to the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since PHP 5.5.2 and Libxml 2.6.14.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
5.5.2 | Added the flags parameter

参见

  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

mmamsch at googlemail dot com 16-Sep-2015 10:01
A note for people trying to validate complex schemas with PHP.  It seems that libxml will not automatically try to import referenced schemas, but simply skip the validation if the schemas were not explicitly imported.

In our example we tried to validate an XML file against a schema with the namespace "xttp://automotive-his.de/200706/rif" that contains a reference to the namespace "xttp://automotive-his.de/200706/rif-xhtml":

  <xsd:complexType name="XHTML-CONTENT">
    <xsd:sequence>
      <xsd:any namespace="xttp://automotive-his.de/200706/rif-xhtml"/>
    </xsd:sequence>
  </xsd:complexType>

which basically says that an xhtml-content element can contain any element from the rif-xhtml namespace.

However since libxml does not know where to find the schema file, it will stop the validation if the elements from the referenced namespace, passing also document with invalid xhtml content as valid.

The solution was to create a combined schema, which contains import statements for all files matching the referenced schemas:

<xsd:schema xmlns:xs="xttp://www.w3.org/2001/XMLSchema">
<xs:import namespace="xttp://automotive-his.de/200706/rif-xhtml" schemaLocation="rif-xhtml.xsd"/>
<xs:import namespace="xttp://automotive-his.de/200706/rif" schemaLocation="rif.xsd"/>
<xs:import namespace="xttp://www.w3.org/XML/1998/namespace" schemaLocation="../xml.xsd"/>
</xsd:schema>

Note that the schemaLocation tells the validator, where to find the files for the corresponding namespaces. When validating the XML document against this combined schema, libxml validated correctly the content inside the XHTML-Content.

Hope this helps someone out there.
wkoehler at ce-gmbh dot com 11-Jan-2011 02:37
In older versions of PHP5 this function might cause error messages when dealing with namespaces. I had problems with PHP 5.2.14 which comes with libXML V2.6.16. After switching to PHP 5.3.5 with libXML V2.7.7 I no longer had problems. Took me only about 30 hrs to figure that one out.
NetPanther 27-Mar-2009 01:42
Initial situation:
- Debian Lenny
- Apache 2 with PHP 5.2.6
- libxml 2.6.32

Problem: While trying to validate a manually created (!) DOMDocument against an existing XML Schema, I ran into a warning like the one below. Validation fails, even though the document IS valid and the command line tool xmllint confirms this (even with libxml 2.6.32, so this must be a problem with DOM). The validation works fine with libxml 2.7.3.

Warning: DOMDocument::schemaValidate() [domdocument.schemavalidate]: Element 'YourRootElementName': No matching global declaration available for the validation root. in /var/www/YourFile.php on line X

Solution: As libxml 2.7.3 is not provided for Debian Lenny yet and this problem seems to be caused by DOM (s.o.), I currently use the following workaround on my machines. DOM obviously has some namespace problems with documents, that have been created manually (i.e. they were not loaded from a file).

So my workaround is saving the DOMDocument temporarily, re-loading it and then validating the temporary DOMDocument. Strangely enough the validation of the same document (= same content) now works. Sure, creating a temporary file is not a nice solution, but unless this bug is fixed, this workaround should do just fine.

<?php

// Works with libxml 2.7.3 and higher.
public function isValid()
{
  return $this->dom->schemaValidate('schema.xsd');
}

// Workaround for prior libxml versions, e.g. 2.6.32.
public function isValid()
{
  // Create temporary file and save manually created DOMDocument.
  $tempFile = time() . '-' . rand() . '-document.tmp';
  $this->dom->save($tempFile);

  // Create temporary DOMDocument and re-load content from file.
  $tempDom = new DOMDocument();
  $tempDom->load($tempFile);

  // Delete temporary file.
  if (is_file($tempFile))
  {
    unlink($tempFile);
  }

  // Validate temporary DOMDocument.
  return $tempDom->schemaValidate('schema.xsd');
}

?>
poletto at jeuxvideo dot com 13-Feb-2008 12:32
I had a tricky issue using this method, i thought it was bug but i realized i misundestood something about namespaces.
When you want to use a schema to describe an xml document, you basically put the default namespace to a personnal namespace (and you refer to this namespace in the targetNamespace attribute of your schema).

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://my.uri.net">
  <elt>
    <x>blabla</x>
    <y>blabla</y>
  </elt>
</root>

That xmlns attribute specifies a "default namespace" and means that the root element and its children are in this namespace.
What i misunderstood is that, there's no way with the DOM api to specify a "default namespace" for each children of the root element.
Thus you may need to use createElementNS() and createAttributeNS() methods for each created element or attribute in the document specifying the URI of your namespace each time ("http://my.uri.net").

This only applies if you want to validate a document built with the API, not with a document loaded from an xml file or stream.
justin at redwiredesign dot com 08-Nov-2006 03:32
In his previous comment, Mike A wrote about validating documents using an XSD. However, you can validate without one. In my case, I needed to ensure that the content entered was just valid XML or not, and I couldn't find an XSD to support that. So I wrote this:

public static function validate($xml)
{
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();
    if (empty($errors))
    {
        return true;
    }

    $error = $errors[0];
    if ($error->level < 3)
    {
        return true;
    }

    $lines = explode("\r", $xml);
    $line = $lines[($error->line)-1];

    $message = $error->message.' at line '.$error->line.':<br />'.htmlentities($line);

    return $message;
}

The catch here is that the function only checks for the first error is LIBXML_ERR_FATAL, which would break XSL/XML compilation.

In my experience, the errors are returned by libxml_get_errors in descending severity, so this may be an OK thing to do.
Mike A. 17-Feb-2006 12:03
For more detailed feedback from DOMDocument::schemaValidate, disable libxml errors and fetch error information yourself.  See http://php.net/manual/en/ref.libxml.php for more info.

example.xml
<?xml version="1.0"?>
<example>
    <child_string>This is an example.</child_string>
    <child_integer>Error condition.</child_integer>
</example>

example.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
    <xs:element name="example">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child_string" type="xs:string"/>
                <xs:element name="child_integer" type="xs:integer"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

<?php

function libxml_display_error($error)
{
    $return = "<br/>\n";
    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "<b>Warning $error->code</b>: ";
            break;
        case LIBXML_ERR_ERROR:
            $return .= "<b>Error $error->code</b>: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "<b>Fatal Error $error->code</b>: ";
            break;
    }
    $return .= trim($error->message);
    if ($error->file) {
        $return .=    " in <b>$error->file</b>";
    }
    $return .= " on line <b>$error->line</b>\n";

    return $return;
}

function libxml_display_errors() {
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        print libxml_display_error($error);
    }
    libxml_clear_errors();
}

// Enable user error handling
libxml_use_internal_errors(true);

$xml = new DOMDocument();
$xml->load('example.xml');

if (!$xml->schemaValidate('example.xsd')) {
    print '<b>DOMDocument::schemaValidate() Generated Errors!</b>';
    libxml_display_errors();
}

?>

Old error message:
Warning: DOMDocument::schemaValidate() [function.schemaValidate]: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.php on line 40

New error message:
DOMDocument::schemaValidate() Generated Errors!
Error 1824: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.xml on line 4


Validates a document based on a schema

  • ? DOMDocument::schemaValidate
  • DOMDocument::validate ?
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema

DOMDocument::schemaValidateSource

(PHP 5, PHP 7)

DOMDocument::schemaValidateSource — Validates a document based on a schema

说明

public DOMDocument::schemaValidateSource ( string $source , int $flags = 0 ) : bool

Validates a document based on a schema defined in the given string.

参数

source

A string containing the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since PHP 5.5.2 and Libxml 2.6.14.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
5.5.2 | Added the flags parameter

参见

  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

There are no user contributed notes for this page.


Validates the document based on its DTD

  • ? DOMDocument::schemaValidateSource
  • DOMDocument::xinclude ?
  • PHP Manual
  • DOMDocument
  • Validates the document based on its DTD

DOMDocument::validate

(PHP 5, PHP 7)

DOMDocument::validate — Validates the document based on its DTD

说明

public DOMDocument::validate ( ) : bool

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

返回值

成功时返回 true， 或者在失败时返回 false。 If the document has no DTD attached, this method will return false.

范例

Example #1 Example of DTD validation

<?php
$dom = new DOMDocument;
$dom->load('book.xml');
if ($dom->validate()) {
    echo "This document is valid!\n";
}
?>

You can also validate your XML file while loading it:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->load('book.xml');
?>

参见

  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document

User Contributed Notes

cabral dot brc at gmail dot com 08-Sep-2010 12:46
I was trying to validate my SVG file just to get the IDs with getElementById(),

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text id="text_titulo" x="150" y="20" font-family="Arial" font-size="15px" style="font-weight:bold;">Title</text>
<text id="text_subtitulo" x="200" y="35" font-family="Arial" font-size="10px">Sub Title</text>
<g transform="translate(0,50) scale(0.1)">
  <a id="a_AC" ...... >
    <polygon id="polygon_AC" ....... />
  </a>
</g>
</svg>

but when calling $dom->load(), it was getting the errors "failed to open stream" and "Validation failed: no DTD found !I/O warning : failed to load external entity"
so I created my own validation wrapper (I just want to find the IDs with getElementById() )

<?php
  $docSVG = new DOMDocument();
  $docSVG->load(realpath($filepath));
  setAllId($docSVG);

function setAllId($DOMNode){
  if($DOMNode->hasChildNodes()){
    foreach ($DOMNode->childNodes as $DOMElement) {
      if($DOMElement->hasAttributes()){
        $id=$DOMElement->getAttribute("id");
        if($id){
          $DOMElement->setIdAttribute("id",$id);
        }
      }
      setAllId($DOMElement);
    }
  }
}
?>
a dot schaffhirt at sedna-soft dot de 17-Sep-2008 02:22
When validating documents with this method there are two issues I don't like about it. First, it creates a bunch of warnings, which one would not expect, as the plot of calling this method is preventing any warnings that could occur when erroneously relying on the document's validity. Second, it only returns a boolean with no chance of getting additional details about the reasons for rendering invalid.

That's the reason for me to use a little wrapper, which I post here in case anyone finds it useful.

Please note that it only works with PHP5 or later.

<?php
    class MyDOMDocument {
        private $_delegate;
        private $_validationErrors;

        public function __construct (DOMDocument $pDocument) {
            $this->_delegate = $pDocument;
            $this->_validationErrors = array();
        }

        public function __call ($pMethodName, $pArgs) {
            if ($pMethodName == "validate") {
                $eh = set_error_handler(array($this, "onValidateError"));
                $rv = $this->_delegate->validate();
                if ($eh) {
                    set_error_handler($eh);
                }
                return $rv;
            }
            else {
                return call_user_func_array(array($this->_delegate, $pMethodName), $pArgs);
            }
        }
        public function __get ($pMemberName) {
            if ($pMemberName == "errors") {
                return $this->_validationErrors;
            }
            else {
                return $this->_delegate->$pMemberName;
            }
        }
        public function __set ($pMemberName, $pValue) {
            $this->_delegate->$pMemberName = $pValue;
        }
        public function onValidateError ($pNo, $pString, $pFile = null, $pLine = null, $pContext = null) {
            $this->_validationErrors[] = preg_replace("/^.+: */", "", $pString);
        }
    }
?>

<?php
    // $doc is a DOMDocument object
    $myDoc = new MyDOMDocument($doc); // copy constructor

    // do anything with $myDoc that you would with $doc

    $isValid = $myDoc->validate(); // won't create warnings
    if (!$isValid) {
        print_r($myDoc->errors); // the array all warnings are collected in
    }
?>

Maybe you need to change the the part
preg_replace("/^.+: */", "", $pString)
to something different depending on your system's error reporting settings (HTML or plain text), whatsoever

Best Regards,

Anja
darren at viamedia dot co dot za 05-Aug-2008 07:19
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>


Substitutes XIncludes in a DOMDocument Object

  • ? DOMDocument::validate
  • DOMDocumentFragment ?
  • PHP Manual
  • DOMDocument
  • Substitutes XIncludes in a DOMDocument Object

DOMDocument::xinclude

(PHP 5, PHP 7)

DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

说明

public DOMDocument::xinclude ( int $options = 0 ) : int|false

This method substitutes » XIncludes in a DOMDocument object.

Note:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

参数

options

libxml parameters. Available since PHP 5.1.0 and Libxml 2.6.7.

返回值

Returns the number of XIncludes in the document, -1 if some processing failed, or false if there were no substitutions.

范例

Example #1 DOMDocument::xinclude() example

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
 <title>Books of the other guy..</title>
 <para>
  <xi:include href="book.xml">
   <xi:fallback>
    <error>xinclude: book.xml not found</error>
   </xi:fallback>
  </xi:include>
 </para>
</chapter>
EOD;

$dom = new DOMDocument;

// let's have a nice output
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// load the XML string defined above
$dom->loadXML($xml);

// substitute xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

以上例程的输出类似于：

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

User Contributed Notes

nicolas_rainardNOSPAM at yahoo dot fr 12-Jul-2007 04:56
If you use the loadXML() method instead of the load() one (let's say, to process the XML string before loading and parsing it), you will have problems with xinclude(), because the parser will not know where to find the files to include.
Using chdir() before xinclude() will not help.

The solution is to set the documentURI property of the DOMDocument object accordingly to it's original filename, and everything will work fine !

<?php

$xml = file_get_contents($file);
$xml = do_something_with($xml);

$doc = new DOMDocument;
$doc->documentURI = $file;
$doc->loadXML($xml);
$doc->xinclude();

?>


The DOMDocumentFragment class

(PHP 5, PHP 7)

类摘要

DOMDocumentFragment extends DOMNode {
/* 属性 */
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public appendXML ( string $data ) : bool
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

Table of Contents

  • DOMDocumentFragment::appendXML — Append raw XML data

User Contributed Notes

peter at softcoded dot com 03-May-2017 03:31
DOMDocumentFragment makes it easy to add (or replace)
nodes. Individually creating nodes using DOM methods can
be tedious. Instead, do something like this:

/**
* Create fragment of colgroup
* @param DOMDocument $doc The DOMDocument
* @return DOMDocumentFragment
*/
function makeFragment($d){
  $chunk = <<<HTML
  <colgroup>
    <col class="c1"/>
    <col class="c2"/>
    <col class="c3"/>
    <col class="c4"/>
  </colgroup>
HTML;
  $fragment = $d->createDocumentFragment();
  $fragment->appendXML($chunk);
  return $fragment;
}
Ricki 29-Mar-2011 06:00
DOMDocumentFragment only appears useful if created from a parent DOMDocument eg.

1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = $dom->createDocumentFragment();
3. Now append items to $docFrag
4. Graft $docFrag contents back onto $dom at the desired location

Conversely taking this approach:
1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = new DOMDocumentFragment();
3. Now append items to $docFrag

...will fail on step 3 with a "read only" error as $docFrag is not created as a child of  DOMDocument.

I'm not sure of the reason for this: on the web people have cited security, and others have cited poor design however whatever the reason, it is really limiting when wanting to encapsulating generic independent DocumentFragments into classes for easy grafting to the desired tree. The only workarounds i have seen look expensive from a performance perspective and cumbersome from a coding perspective ie. create a  dummy $dom for temporary use.

(This is valid as of PHP 5.3) I've put this here as i've wasted a lot of time finding it out - I hope this saves others some heartache.

Using new DOMDocumentFramt
matthijs at stdin dot nl 29-Mar-2011 03:06
Note that DOMDocumentFragment is a bit special when it's added to another node. When that happens, not the fragment itself is added as a child, but all of the children of the fragment are moved over to the new parent node.

For example, consider this script:

<?php

/* Create a document and a fragment containing a single node */
$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement('foo'));

/* Now, the foo node is a child of the fragment */
var_dump($fragment->firstChild);

/* After appending the fragment to another node, the children of the
 * fragment will have been transfered to that node (and the fragment is
 * not present in the children list!) */
$doc->appendChild($fragment);
/* So the fragment has no children anymore */
var_dump($fragment->firstChild);
/* But $doc has a single child, which is the foo element, not the
 * fragment */
var_dump($doc->childNodes->length);
var_dump($doc->firstChild);

?>

This produces the following output:

object(DOMElement)#3 (0) {
}
NULL
int(1)
object(DOMElement)#3 (0) {
}


Append raw XML data

  • ? DOMDocumentFragment
  • DOMDocumentType ?
  • PHP Manual
  • DOMDocumentFragment
  • Append raw XML data

DOMDocumentFragment::appendXML

(PHP 5 >= 5.1.0, PHP 7)

DOMDocumentFragment::appendXML — Append raw XML data

说明

public DOMDocumentFragment::appendXML ( string $data ) : bool

Appends raw XML data to a DOMDocumentFragment.

This method is not part of the DOM standard. It was created as a simpler approach for appending an XML DocumentFragment in a DOMDocument.

If you want to stick to the standards, you will have to create a temporary DOMDocument with a dummy root and then loop through the child nodes of the root of your XML data to append them.

参数

data

XML to append.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Appending XML data to your document

<?php
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
?>

以上例程会输出：

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

User Contributed Notes

lpetrov(AT)axisvista.com 20-Jul-2007 05:45
Here is (maybe) a better example:
/**
* Helper function for replacing $node (DOMNode)
* with an XML code (string)
*
* @var DOMNode $node
* @var string $xml
*/
public function replaceNodeXML(&$node,$xml) {
 $f = $this->dom->createDocumentFragment();
 $f->appendXML($xml);
 $node->parentNode->replaceChild($f,$node);
}

Copied from the "PHP5 Dom Based Template" article at:
http://blog.axisvista.com/?p=35


The DOMDocumentType class

(PHP 5, PHP 7)

简介

Each DOMDocument has a doctype attribute whose value is either null or a DOMDocumentType object.

类摘要

DOMDocumentType extends DOMNode {
/* 属性 */
public readonly string $publicId ;
public readonly string $systemId ;
public readonly string $name ;
public readonly DOMNamedNodeMap $entities ;
public readonly DOMNamedNodeMap $notations ;
public readonly string $internalSubset ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

publicId

The public identifier of the external subset.

systemId

The system identifier of the external subset. This may be an absolute URI or not.

name

The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

entities

A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

notations

A DOMNamedNodeMap containing the notations declared in the DTD.

internalSubset

The internal subset as a string, or null if there is none. This does not contain the delimiting square brackets.

User Contributed Notes

There are no user contributed notes for this page.


The DOMElement class

(PHP 5, PHP 7)

类摘要

DOMElement extends DOMNode {
/* 属性 */
public readonly bool $schemaTypeInfo ;
public readonly string $tagName ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public __construct ( string $qualifiedName , string|null $value = null , string $namespace = "" )
public getAttribute ( string $qualifiedName ) : string
public getAttributeNode ( string $qualifiedName ) : DOMAttr|DOMNamespaceNode|false
public getAttributeNodeNS ( string|null $namespace , string $localName ) : DOMAttr|DOMNamespaceNode|null
public getAttributeNS ( string|null $namespace , string $localName ) : string
public getElementsByTagName ( string $qualifiedName ) : DOMNodeList
public getElementsByTagNameNS ( string $namespace , string $localName ) : DOMNodeList
public hasAttribute ( string $qualifiedName ) : bool
public hasAttributeNS ( string|null $namespace , string $localName ) : bool
public removeAttribute ( string $qualifiedName ) : bool
public removeAttributeNode ( DOMAttr $attr ) : DOMAttr|false
public removeAttributeNS ( string|null $namespace , string $localName ) : void
public setAttribute ( string $qualifiedName , string $value ) : DOMAttr|bool
public setAttributeNode ( DOMAttr $attr ) : DOMAttr|null|false
public setAttributeNodeNS ( DOMAttr $attr ) : DOMAttr|null|false
public setAttributeNS ( string|null $namespace , string $qualifiedName , string $value ) : void
public setIdAttribute ( string $qualifiedName , bool $isId ) : void
public setIdAttributeNode ( DOMAttr $attr , bool $isId ) : void
public setIdAttributeNS ( string $namespace , string $qualifiedName , bool $isId ) : void
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

schemaTypeInfo

Not implemented yet, always return null

tagName

The element name

注释

Note:

此 DOM 扩展采用 UTF-8 编码。在 ISO-8859-1 编码下，使用 utf8_encode() 和 utf8_decode() 来处理，其它编码下使用 iconv 函数处理。

Table of Contents

  • DOMElement::__construct — Creates a new DOMElement object
  • DOMElement::getAttribute — Returns value of attribute
  • DOMElement::getAttributeNode — Returns attribute node
  • DOMElement::getAttributeNodeNS — Returns attribute node
  • DOMElement::getAttributeNS — Returns value of attribute
  • DOMElement::getElementsByTagName — Gets elements by tagname
  • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
  • DOMElement::hasAttribute — Checks to see if attribute exists
  • DOMElement::hasAttributeNS — Checks to see if attribute exists
  • DOMElement::removeAttribute — Removes attribute
  • DOMElement::removeAttributeNode — Removes attribute
  • DOMElement::removeAttributeNS — Removes attribute
  • DOMElement::setAttribute — Adds new attribute
  • DOMElement::setAttributeNode — Adds new attribute node to element
  • DOMElement::setAttributeNodeNS — Adds new attribute node to element
  • DOMElement::setAttributeNS — Adds new attribute
  • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

User Contributed Notes

johnny 03-Mar-2014 03:48
Get html of a node
 $html .= $dom->saveHTML($node);
Janne Enberg 07-Nov-2013 11:02
This page doesn't list the inherited properties from DOMNode, e.g. the quite important textContent property. It would be immensely helpful if it would list those as well.
felix dot klee at inka dot de 26-Feb-2013 03:23
How to rename an element and preserve attributes:

<?php

// Changes the name of element $element to $newName.
function renameElement($element, $newName) {
  $newElement = $element->ownerDocument->createElement($newName);
  $parentElement = $element->parentNode;
  $parentElement->insertBefore($newElement, $element);

  $childNodes = $element->childNodes;
  while ($childNodes->length > 0) {
    $newElement->appendChild($childNodes->item(0));
  }

  $attributes = $element->attributes;
  while ($attributes->length > 0) {
    $attribute = $attributes->item(0);
    if (!is_null($attribute->namespaceURI)) {
      $newElement->setAttributeNS('http://www.w3.org/2000/xmlns/',
                                  'xmlns:'.$attribute->prefix,
                                  $attribute->namespaceURI);
    }
    $newElement->setAttributeNode($attribute);
  }

  $parentElement->removeChild($element);
}

function prettyPrint($d) {
  $d->formatOutput = true;
  echo '<pre>'.htmlspecialchars($d->saveXML()).'</pre>';
}

$d = new DOMDocument( '1.0' );
$d->loadXML('<?xml version="1.0"?>
<library>
  <data a:foo="1" x="bar" xmlns:a="http://example.com/a">
    <invite>
      <username>jmansa</username>
      <userid>1</userid>
    </invite>
    <update>1</update>
  </data>
</library>');

$xpath = new DOMXPath($d);
$elements = $xpath->query('/library/data');
if ($elements->length == 1) {
  $element = $elements->item(0);
  renameElement($element, 'invites');
}

prettyPrint($d);

?>
loopduplicate at burningtoken dot com 22-Apr-2011 02:34
This works perfect for me as well:

<?php $xml = $domElement->ownerDocument->saveXML($domElement); ?>
Anonymous 24-Dec-2010 08:22
you can use DOMNode::nodeValue
DOMElement inherits this public property.

$elem->nodeValue
dpetroff ( at ) gmail.com 04-Dec-2010 11:24
Hi!

Combining all th comments, the easiest way to get inner HTML of the node is to use this function:

<?php
function get_inner_html( $node ) {
    $innerHTML= '';
    $children = $node->childNodes;
    foreach ($children as $child) {
        $innerHTML .= $child->ownerDocument->saveXML( $child );
    }

    return $innerHTML;
}
?>
nawaman at gmail dot com 03-Sep-2009 08:08
The following code shows can text-only content be extracted from a document.

<?php
function getTextFromNode($Node, $Text = "") {
    if ($Node->tagName == null)
        return $Text.$Node->textContent;

    $Node = $Node->firstChild;
    if ($Node != null)
        $Text = getTextFromNode($Node, $Text);

    while($Node->nextSibling != null) {
        $Text = getTextFromNode($Node->nextSibling, $Text);
        $Node = $Node->nextSibling;
    }
    return $Text;
}

function getTextFromDocument($DOMDoc) {
    return getTextFromNode($DOMDoc->documentElement);
}

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");
echo getTextFromDocument($Doc)."\n";
?>
Daniel Morlock 07-May-2009 09:22
It would be nice to have a function which converts a document/node/element into a string.

Anyways, I use the following code snippet to get the innerHTML value of a DOMNode:

<?php
function getInnerHTML($Node)
{
     $Body = $Node->ownerDocument->documentElement->firstChild->firstChild;
     $Document = new DOMDocument();
     $Document->appendChild($Document->importNode($Body,true));
     return $Document->saveHTML();
}
?>
patrick smith 04-Nov-2008 08:14
Although it may be preferable to use the dom to manipulate elements, sometimes it's useful to actually get the innerHTML from a document element (e.g. to load into a client-side editor).

To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath):

<?php
$innerHTML = '';
$doc = new DOMDocument();
$doc->loadHTMLFile($filepath);
$elem = $doc->getElementById($elem_id);

// loop through all childNodes, getting html
$children = $elem->childNodes;
foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $innerHTML .= $tmp_doc->saveHTML();
}
?>
Pinochet 25-Oct-2008 05:33
Hi to get the value of DOMElement just get the nodeValue public parameter (it is inherited from DOMNode):
<?php
echo $domElement->nodeValue;
?>
Everything is obvious if you now about this thing ;-)
j DOT wagner ( AT ) medieninnovation.com 08-Oct-2008 09:11
Caveat!
It took me almost an hour to figure this out, so I hope it saves at least one of you some time.

If you want to debug your DOM tree and try var_dump() or similar you will be fooled into thinking the DOMElement that you are looking at is empty, because var_dump() says: object(DOMElement)#1 (0) { }

After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.

The solution is simple (if you know it):
$xml = $domElement->ownerDocument->saveXML($domElement);

This will give you an XML representation of $domElement.
Severin 14-Sep-2008 06:18
I wanted to find similar Elements - thats why I built an Xpath-String like this - maybe somebody needs it... its not very pretty - but neither is domdocument :)

<?php

$dom->load($xmlFile))

$xpathQuery = '//*';
$xmlNodes = $xpath->query($xpathQuery);

$pathlist = array();
$attrlist = array();
foreach ($xmlNodes as $node) {

  $depth = $this->_getDomDepth($node);   //get Path-Depth (for array key)
  $pathlist[$depth] = $node->tagName;     // tagname

  $attrs = $node->attributes;
  $attr='';
  $a=0;
  foreach ($attrs as $attrName => $attrNode)  // attributes
            {
              if ($attrName !='reg')
              {
                if ($a++!=0) $attr .= ' and ';
                $attr .= '@'.$attrName.'='."'".$attrNode->value."'";
              }
            }

          $attrlist[$depth] = $attr?'['.$attr.']':'';

          $path = ''; for ($i=0;$i<=$depth;$i++) $path .= '/'.$pathlist[$i].$attrlist[$i];  // the xpath of the actual Element

    // ... now you can go on and user $path to find similar elements
    }
  }
}

 private function _getDomDepth(DomNode $node)
   {
     $r = -2;
     while ($node) {
       $r++;
       $node = $node->parentNode;
     }
     return  $r;
   }
?>
ae.fxx 18-Jul-2008 01:49
Hi there.

Remember to append a DOMNode (or any of its descendants) to a DOMDocument __BEFORE__ you try to append a child to it.

I don't know why it has to be this way but it can't be done without it.

bye


Creates a new DOMElement object

  • ? DOMElement
  • DOMElement::getAttribute ?
  • PHP Manual
  • DOMElement
  • Creates a new DOMElement object

DOMElement::__construct

(PHP 5, PHP 7)

DOMElement::__construct — Creates a new DOMElement object

说明

public DOMElement::__construct ( string $qualifiedName , string|null $value = null , string $namespace = "" )

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.

参数

qualifiedName

The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.

value

The value of the element.

namespace

A namespace URI to create the element within a specific namespace.

范例

Example #1 Creating a new DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

参见

  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace

User Contributed Notes

Fabian dot Blech at gmx dot de 22-Jul-2010 08:30
Remember, Dom-Nodes mustn't start with a number:

allowed:
<t12345t4>Value</t12345t4>

Not allowed:
<12345t4>VALUE</12345t4>
troelskn at gmail dot com 03-Jun-2008 07:46
Note that this function is buggy. You have to manually escape the $value argument with htmlspecialchars.
See: http://bugs.php.net/bug.php?id=31191
adar at darkpoetry dot de 07-May-2007 01:27
If you like to view an element simply do:

<?php
echo htmlentities($element->C14N());
?>

Undocumented but found ;)


Returns value of attribute

  • ? DOMElement::__construct
  • DOMElement::getAttributeNode ?
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttribute

(PHP 5, PHP 7)

DOMElement::getAttribute — Returns value of attribute

说明

public DOMElement::getAttribute ( string $qualifiedName ) : string

Gets the value of the attribute with name qualifiedName for the current node.

参数

qualifiedName

The name of the attribute.

返回值

The value of the attribute, or an empty string if no attribute with the given qualifiedName is found.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttribute() - Adds new attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

mpalmer at cybersource dot com 09-Nov-2007 03:32
- - - - - - - - - - - - - -

XML Data:
<data>
<Report ID="1">
    <Date>REVIEW</Date>
    <AuthorID>1</AuthorID>
</Report>
<Report ID="2">
    <Date>REVIEW</Date>
    <AuthorID>2</AuthorID>
</Report>
</data>

- - - - - - - - - - - - - -

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load( 'data.xml' );

$searchNode = $xmlDoc->getElementsByTagName( "Report" );

foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('ID');

    $xmlDate = $searchNode->getElementsByTagName( "Date" );
    $valueDate = $xmlDate->item(0)->nodeValue;

    $xmlAuthorID = $searchNode->getElementsByTagName( "AuthorID" );
    $valueAuthorID = $xmlAuthorID->item(0)->nodeValue;

    echo "$valueID - $valueDate - $valueAuthorID\n";
}
?>

- - - - - - - - - - - - - -

Output:

1 - REVIEW - 1
2 - REVIEW - 2

- - - - - - - - - - - - - -


Returns attribute node

  • ? DOMElement::getAttribute
  • DOMElement::getAttributeNodeNS ?
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNode

(PHP 5, PHP 7)

DOMElement::getAttributeNode — Returns attribute node

说明

public DOMElement::getAttributeNode ( string $qualifiedName ) : DOMAttr|DOMNamespaceNode|false

Returns the attribute node with name qualifiedName for the current element.

参数

qualifiedName

The name of the attribute.

返回值

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttributeNode() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

lowezar at gmail dot com 28-Feb-2011 08:22
It may also return DOMNameSpaceNode if you`re requesting 'xmlns:_prefix_'. So you`re unable to remove it with removeAttributeNode() which requires DOMAttr as parameter.
Alex 18-Feb-2009 08:33
Just trying to add some clarification: this function will return boolean "false" when there is not a $name attribute :)

Cheers, Alex


Returns attribute node

  • ? DOMElement::getAttributeNode
  • DOMElement::getAttributeNS ?
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNodeNS

(PHP 5, PHP 7)

DOMElement::getAttributeNodeNS — Returns attribute node

说明

public DOMElement::getAttributeNodeNS ( string|null $namespace , string $localName ) : DOMAttr|DOMNamespaceNode|null

Returns the attribute node in namespace namespace with local name localName for the current node.

参数

namespace

The namespace URI.

localName

The local name.

返回值

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr object.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNodeNS() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Returns value of attribute

  • ? DOMElement::getAttributeNodeNS
  • DOMElement::getElementsByTagName ?
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttributeNS

(PHP 5, PHP 7)

DOMElement::getAttributeNS — Returns value of attribute

说明

public DOMElement::getAttributeNS ( string|null $namespace , string $localName ) : string

Gets the value of the attribute in namespace namespace with local name localName for the current node.

参数

namespace

The namespace URI.

localName

The local name.

返回值

The value of the attribute, or an empty string if no attribute with the given localName and namespace is found.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Gets elements by tagname

  • ? DOMElement::getAttributeNS
  • DOMElement::getElementsByTagNameNS ?
  • PHP Manual
  • DOMElement
  • Gets elements by tagname

DOMElement::getElementsByTagName

(PHP 5, PHP 7)

DOMElement::getElementsByTagName — Gets elements by tagname

说明

public DOMElement::getElementsByTagName ( string $qualifiedName ) : DOMNodeList

This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag qualifiedName, in the order in which they are encountered in a preorder traversal of this element tree.

参数

qualifiedName

The tag name. Use * to return all elements within the element tree.

返回值

This function returns a new instance of the class DOMNodeList of all matched elements.

参见

  • DOMElement::getElementsByTagNameNS() - Get elements by namespaceURI and localName

User Contributed Notes

rudiger at greatdealsenterprises dot com 12-Jun-2019 11:45
Note that even though getElementsByTagName returns a NodeList which is defined as a list of DOMNodes, you're actually getting a list of DOMElements. That allows to call getElementsByTagName on each of the results.

$tables = $doc->getElementsByTagName('table');
foreach ($tables as $table) {
  $trs = $table->getElementsByTagName('tr');
  // etc...
}
Brennon Brimhall 18-Jan-2017 11:51
Be aware that this function returns all descendants, not just immediate children.
ddkkdd twenty twenty at gmail dot com 08-Sep-2010 03:15
A simple function that uses this method to print the nodes it finds in an xml document. Improvements welcomed.

<?php
function printTags($tag){

  $node = $this->doc->getElementsByTagName($tag);
   for($c = 0; $c<$node->length; $c++){
     $text[$c] =$this->doc->saveXML($node->item($c));
     echo $text[$c];

   }

}
?>


Get elements by namespaceURI and localName

  • ? DOMElement::getElementsByTagName
  • DOMElement::hasAttribute ?
  • PHP Manual
  • DOMElement
  • Get elements by namespaceURI and localName

DOMElement::getElementsByTagNameNS

(PHP 5, PHP 7)

DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName

说明

public DOMElement::getElementsByTagNameNS ( string $namespace , string $localName ) : DOMNodeList

This function fetch all the descendant elements with a given localName and namespace.

参数

namespace

The namespace URI.

localName

The local name. Use * to return all elements within the element tree.

返回值

This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.

参见

  • DOMElement::getElementsByTagName() - Gets elements by tagname

User Contributed Notes

spam at chovy dot com 03-Jun-2009 05:36
I had some difficulty stripping all default NS attributes for an ns-uri in one shot, the following will work though...first strip the documentElement namespace, then getElementsByTagNameNS() -- the documentation should reflect that the 2nd argument is actually the name of the tag, not the local namespace prefix as I first expected:

<?php

function strip_default_ns( $xml = null, $ns_uri = 'http://example.com/XML-Foo' ) {
    $ns_local = '';
    $ns_tag = '*';

    if ( empty($xml) ) return false;

    //remove document namespace
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $dom->documentElement->removeAttributeNS($ns_uri, $ns_local);

    //strip element namespaces
    foreach ( $dom->getElementsByTagNameNS($ns_uri, $ns_tag) as $elem ) {
        $elem->removeAttributeNS($ns_uri, $ns_local);
    }

    return $dom->saveXML();
}

$stripped_xml = strip_default_ns($the_xml);

?>

$stripped_xml can now take advantage of running XPath queries on it for the NULL namespace.


Checks to see if attribute exists

  • ? DOMElement::getElementsByTagNameNS
  • DOMElement::hasAttributeNS ?
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttribute

(PHP 5, PHP 7)

DOMElement::hasAttribute — Checks to see if attribute exists

说明

public DOMElement::hasAttribute ( string $qualifiedName ) : bool

Indicates whether attribute named qualifiedName exists as a member of the element.

参数

qualifiedName

The attribute name.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Checks to see if attribute exists

  • ? DOMElement::hasAttribute
  • DOMElement::removeAttribute ?
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttributeNS

(PHP 5, PHP 7)

DOMElement::hasAttributeNS — Checks to see if attribute exists

说明

public DOMElement::hasAttributeNS ( string|null $namespace , string $localName ) : bool

Indicates whether attribute in namespace namespace named localName exists as a member of the element.

参数

namespace

The namespace URI.

localName

The local name.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Removes attribute

  • ? DOMElement::hasAttributeNS
  • DOMElement::removeAttributeNode ?
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttribute

(PHP 5, PHP 7)

DOMElement::removeAttribute — Removes attribute

说明

public DOMElement::removeAttribute ( string $qualifiedName ) : bool

Removes attribute named qualifiedName from the element.

参数

qualifiedName

The name of the attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new attribute

User Contributed Notes

suwayan at mail dot ru 30-Mar-2012 12:19
<?php
/*When I try to get a some attribute from not validated HTML or XML document, PHP dies with no errors in logs or output:
*/
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
//And this check helped to me:
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj->attributes)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
?>
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:38
<?php

//Store your html into $html variable.

$html="<html>
<head>
<title>Rakesh Verma</title>
</head>

<body>
    <a href='http://example.com'>Example</a>
    <a href='http://google.com'>Google</a>
    <a href='http://www.yahoo.com'>Yahoo</a>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url.".au";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>


Removes attribute

  • ? DOMElement::removeAttribute
  • DOMElement::removeAttributeNS ?
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNode

(PHP 5, PHP 7)

DOMElement::removeAttributeNode — Removes attribute

说明

public DOMElement::removeAttributeNode ( DOMAttr $attr ) : DOMAttr|false

Removes attribute attr from the element.

参数

attr

The attribute node.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if attr is not an attribute of the element.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::setAttributeNode() - Adds new attribute node to element

User Contributed Notes

xr07354 at gmx dot de 18-Jun-2013 01:16
Basic: I use PHP5.4.9 from Ubuntu 13.04 repository. The aim of my code is to iterate HTML source (as a DomDocument) recursively and cleanup everything that is not valid to be used inside Epub files (i.e. and attribute align is not valid for paragraphs in Epubs).

FIRST: Today I tried removing attributes from a DOMElement using this simple code:
<?php
for ( $k=0; $k < $element->attributes->length; $k++) {
    if( /* some rule */ ){
        var_dump( $element->attributes->item($k)->nodeName);
        $element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
Unfortunately all attributes still existed when this loop was finished, even if these var_dumps told me that deleting them was tried.

I solved this problem iterating the attributes list backward:
<?php
for ( $k = $element->attributes->length - 1; $k >= 0; --$k) {
    if( /* same rule */ ){
        var_dump( $element->attributes->item($k)->nodeName);
        $element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
SECOND: DOMElement::removeAttributeNode does NOT return a bool but a DOMAttr object.


Removes attribute

  • ? DOMElement::removeAttributeNode
  • DOMElement::setAttribute ?
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNS

(PHP 5, PHP 7)

DOMElement::removeAttributeNS — Removes attribute

说明

public DOMElement::removeAttributeNS ( string|null $namespace , string $localName ) : void

Removes attribute localName in namespace namespace from the element.

参数

namespace

The namespace URI.

localName

The local name.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute

User Contributed Notes

primaryspace at hotmail dot com 10-Aug-2005 12:56
This method can be used to remove a namespace declaration from an element, even though the declaration is not considered an attribute by the DOM.  The prefix will be removed from any element or attribute using it.

<?php

$dom = DOMDocument::loadXML('<foo:root xmlns:foo="http:bar"/>');
$element = $dom->childNodes->item(0);

// prints '0':
echo (int) $element->hasAttributeNS('http:bar', 'foo');

$element->removeAttributeNS('http:bar', 'foo');

/* prints '<?xml version="1.0"?> <root/>': */
print htmlentities($dom->saveXML());

?>


Adds new attribute

  • ? DOMElement::removeAttributeNS
  • DOMElement::setAttributeNode ?
  • PHP Manual
  • DOMElement
  • Adds new attribute

DOMElement::setAttribute

(PHP 5, PHP 7)

DOMElement::setAttribute — Adds new attribute

说明

public DOMElement::setAttribute ( string $qualifiedName , string $value ) : DOMAttr|bool

Sets an attribute with name qualifiedName to the given value. If the attribute does not exist, it will be created.

参数

qualifiedName

The name of the attribute.

value

The value of the attribute.

返回值

The new DOMAttr or false if an error occurred.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

范例

Example #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

lehal2@hotmail 06-Jun-2013 09:44
The use of Dom to first remove and then add the width and height to the first img tag from the text.I hope it help you to save your time
<?php
$html = '

            <img src="http://www.example.com/images/header.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        <img src="http://www.example.com/images/header2.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        ';

$doc = DOMDocument::loadHTML($html);
$c =0;
foreach($doc->getElementsByTagName('img') as $image){
    if ($c>0) continue;
    foreach(array('width', 'height') as $attribute_to_remove){
        echo $attribute_to_remove;
        if($image->hasAttribute($attribute_to_remove)){
            $image->removeAttribute($attribute_to_remove);

        }
        if($attribute_to_remove=='height'){
            if(!$image->hasAttribute($attribute_to_remove)){
                $image->setAttribute($attribute_to_remove,'220');

            }}
        if($attribute_to_remove=='width'){
      if(!$image->hasAttribute($attribute_to_remove)){
            $image->setAttribute($attribute_to_remove,'700');

        }}
        $c = $c+1;
    }
}
echo $doc->saveHTML();
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:27
<?php
//Store your html into $html variable.
$html="
<html>
<head>
<title>Untitled Document</title>
</head>

<body>
    <a href='http://example.com'>Example</a><br>
    <a href='http://google.com'>Google</a><br>

    <a href='http://www.yahoo.com'>Yahoo</a><br>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url."/newurl";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>
address at gmail dot com 03-Jul-2008 07:25
If wanting to set an attribute of an element with unique id of "1"

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$xp = new DomXPath($dom);
$res = $xp->query("//*[@id = '1']");
$res->item(0)->setAttribute('title','2');
$dom->save('test.xml');
?>
Vasil Rangelov 31-Jul-2007 04:44
@karvjorm,
Using this method is not exactly a good practice. Infact, I think it may be a bug.
Names beginning with "xml" are reserved (for namespaces in this case).
setAttribute() should return false in this case I think, but I suppose it doesn't.

Still, the right way to do it is with createElementNS().
It lets you specify the namespace when creating the element node.

So the equivalent to yours ($html added to allow word wrapping) is:

$dom = new DomDocument('1.0','iso-8859-15');
$html = $dom->createElementNS('http://www.w3.org/1999/xhtml', 'html');
$ht_ml = $dom->appendChild($html);
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');
karvjorm at users.sourceforge.net 02-Mar-2007 03:05
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));
$ht_ml->setAttribute('xmlns','http://www.w3.org/1999/xhtml');
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi" lang="fi">


Adds new attribute node to element

  • ? DOMElement::setAttribute
  • DOMElement::setAttributeNodeNS ?
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNode

(PHP 5, PHP 7)

DOMElement::setAttributeNode — Adds new attribute node to element

说明

public DOMElement::setAttributeNode ( DOMAttr $attr ) : DOMAttr|null|false

Adds new attribute node attr to element.

参数

attr

The attribute node.

返回值

Returns old node if the attribute has been replaced or null.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

karvjorm at users.sourceforge.net 02-Mar-2007 04:01
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));

$he_ad = $ht_ml->appendChild($dom->createElement('head'));

$tit_le= $he_ad->appendChild($dom->createElement('title'));
$tit_le->appendChild($dom->createTextNode('DOMAttr test'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Description'));
$me_ta->setAttributeNode(new DOMAttr('content', 'example'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Author'));
$me_ta->setAttributeNode(new DOMAttr('content', 'karvjorm'));

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html>
  <head>
    <title>DOMAttr test</title>
    <meta name="Description" content="example"/>
    <meta name="Author" content="karvjorm"/>
  </head>


Adds new attribute node to element

  • ? DOMElement::setAttributeNode
  • DOMElement::setAttributeNS ?
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNodeNS

(PHP 5, PHP 7)

DOMElement::setAttributeNodeNS — Adds new attribute node to element

说明

public DOMElement::setAttributeNodeNS ( DOMAttr $attr ) : DOMAttr|null|false

Adds new attribute node attr to element.

参数

attr

The attribute node.

返回值

Returns the old node if the attribute has been replaced.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNodeNS() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Adds new attribute

  • ? DOMElement::setAttributeNodeNS
  • DOMElement::setIdAttribute ?
  • PHP Manual
  • DOMElement
  • Adds new attribute

DOMElement::setAttributeNS

(PHP 5, PHP 7)

DOMElement::setAttributeNS — Adds new attribute

说明

public DOMElement::setAttributeNS ( string|null $namespace , string $qualifiedName , string $value ) : void

Sets an attribute with namespace namespace and name name to the given value. If the attribute does not exist, it will be created.

参数

namespace

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespace is null.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

catalinenache78 at gmail dot com 18-May-2011 07:39
To add new brand xml namespace use:

<?php
    $element->setAttributeNS(
        'http://www.w3.org/2000/xmlns/', // xmlns namespace URI
        'xmlns:mynamespace',
        'example.com/mynamespace'
    );
?>

'http://www.w3.org/2000/xmlns/' URI is important
to be able to add  new namespaces !!!

Later you can use your namespace like:

<?php
    $element->setAttributeNS(
        'example.com/mynamespace',
        'mynamespace:something',
        'value'
    );
?>


Declares the attribute specified by name to be of type ID

  • ? DOMElement::setAttributeNS
  • DOMElement::setIdAttributeNode ?
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by name to be of type ID

DOMElement::setIdAttribute

(PHP 5, PHP 7)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

说明

public DOMElement::setIdAttribute ( string $qualifiedName , bool $isId ) : void

Declares the attribute qualifiedName to be of type ID.

参数

qualifiedName

The name of the attribute.

isId

Set it to true if you want qualifiedName to be of type ID, false otherwise.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if qualifiedName is not an attribute of this element.

参见

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Declares the attribute specified by node to be of type ID

  • ? DOMElement::setIdAttribute
  • DOMElement::setIdAttributeNS ?
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by node to be of type ID

DOMElement::setIdAttributeNode

(PHP 5, PHP 7)

DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID

说明

public DOMElement::setIdAttributeNode ( DOMAttr $attr , bool $isId ) : void

Declares the attribute specified by attr to be of type ID.

参数

attr

The attribute node.

isId

Set it to true if you want name to be of type ID, false otherwise.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

参见

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Declares the attribute specified by local name and namespace URI to be of type ID

  • ? DOMElement::setIdAttributeNode
  • DOMEntity ?
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by local name and namespace URI to be of type ID

DOMElement::setIdAttributeNS

(PHP 5, PHP 7)

DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

说明

public DOMElement::setIdAttributeNS ( string $namespace , string $qualifiedName , bool $isId ) : void

Declares the attribute specified by qualifiedName and namespace to be of type ID.

参数

namespace

The namespace URI of the attribute.

qualifiedName

The local name of the attribute, as prefix:tagname.

isId

Set it to true if you want name to be of type ID, false otherwise.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

参见

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


The DOMEntity class

(PHP 5, PHP 7)

简介

This interface represents a known entity, either parsed or unparsed, in an XML document.

类摘要

DOMEntity extends DOMNode {
/* 属性 */
public readonly string $publicId ;
public readonly string $systemId ;
public readonly string $notationName ;
public string $actualEncoding ;
public readonly string $encoding ;
public readonly string $version ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

publicId

The public identifier associated with the entity if specified, and null otherwise.

systemId

The system identifier associated with the entity if specified, and null otherwise. This may be an absolute URI or not.

notationName

For unparsed entities, the name of the notation for the entity. For parsed entities, this is null.

actualEncoding

An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is null if it an entity from the internal subset or if it is not known.

encoding

An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is null otherwise.

version

An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is null otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The DOMEntityReference class

(PHP 5, PHP 7)

类摘要

DOMEntityReference extends DOMNode {
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public __construct ( string $name )
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

Table of Contents

  • DOMEntityReference::__construct — Creates a new DOMEntityReference object

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMEntityReference object

  • ? DOMEntityReference
  • DOMException ?
  • PHP Manual
  • DOMEntityReference
  • Creates a new DOMEntityReference object

DOMEntityReference::__construct

(PHP 5, PHP 7)

DOMEntityReference::__construct — Creates a new DOMEntityReference object

说明

public DOMEntityReference::__construct ( string $name )

Creates a new DOMEntityReference object.

参数

name

The name of the entity reference.

范例

Example #1 Creating a new DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>&nbsp;</root> */

?>

参见

  • DOMDocument::createEntityReference() - Create new entity reference node

User Contributed Notes

There are no user contributed notes for this page.


The DOMException class

(PHP 5, PHP 7)

简介

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also 异常.

类摘要

DOMException extends Exception {
/* 属性 */
public readonly int $code ;
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

属性

code

An integer indicating the type of error generated

User Contributed Notes

There are no user contributed notes for this page.


The DOMImplementation class

(PHP 5, PHP 7)

简介

The DOMImplementation class provides a number of methods for performing operations that are independent of any particular instance of the document object model.

类摘要

DOMImplementation {
/* 属性 */
/* 方法 */
__construct ( )
public createDocument ( string $namespace = "" , string $qualifiedName = "" , DOMDocumentType|null $doctype = null ) : DOMDocument|false
public createDocumentType ( string $qualifiedName , string $publicId = "" , string $systemId = "" ) : DOMDocumentType|false
public hasFeature ( string $feature , string $version ) : bool
}

Table of Contents

  • DOMImplementation::__construct — Creates a new DOMImplementation object
  • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
  • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
  • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

User Contributed Notes

LANGE.LUDO 07-Nov-2014 06:05
Ok got it working like a charm using "proxy pattern" with traits. The idea being declaring the common methods inside a "trait" in order for extended and registered Node Classes to have access even if not derived / child of the extended DOMNode...

Here a small snippet :
<?php
    namespace my;

    trait tNode
    {    // We need the magic method __get in order to add properties such as DOMNode->parentElement
        public function __get($name)
        {    if(property_exists($this, $name)){return $this->$name;}
            if(method_exists($this, $name)){return $this->$name();}
            throw new \ErrorException('my\\Node property \''.(string) $name.'\' not found...', 42, E_USER_WARNING);
        }

        // parentElement property definition
        private function parentElement()
        {    if($this->parentNode === null){return null;}
            if($this->parentNode->nodeType === XML_ELEMENT_NODE){return $this->parentNode;}
            return $this->parentNode->parentElement();
        }

        // JavaScript equivalent
        public function isEqualNode(\DOMNode $node){return $this->isSameNode($node);}
        public function compareDocumentPosition(\DOMNode $otherNode)
        {    if($this->ownerDocument !== $otherNode->ownerDocument){return DOCUMENT_POSITION_DISCONNECTED;}
            $c = strcmp($this->getNodePath(), $otherNode->getNodePath());
            if($c === 0){return 0;}
            else if($c < 0){return DOCUMENT_POSITION_FOLLOWING | ($c < -1 ? DOCUMENT_POSITION_CONTAINED_BY : 0);}
            return DOCUMENT_POSITION_PRECEDING | ($c > 1 ? DOCUMENT_POSITION_CONTAINS : 0);
        }
        public function contains(\DOMNode $otherNode){return ($this->compareDocumentPosition($otherNode) >= DOCUMENT_POSITION_CONTAINED_BY);}
    }

    class Document extends \DomDocument
    {    public function __construct($version=null, $encoding=null)
        {    parent::__construct($version, $encoding);
            $this->registerNodeClass('DOMNode', 'my\Node');
            $this->registerNodeClass('DOMElement', 'my\Element');
            $this->registerNodeClass('DOMDocument', 'my\Document');
            /* [...] */
        }
    }

    class Element extends \DOMElement
    {    use tNode;
        /* [...] */
    }

    class Node extends \DOMNode
    {    use tNode;
        /* [...] */
    }

?>
LANGE.LUDO 07-Nov-2014 08:14
From what I've seen you must "recode" the "createDocument" method in order to call your own object extension...

<?php
[...]
    public function createDocument($namespaceURI=null, $qualifiedName=null, DOMDocumentType $docType=null)
    {    $doc=new Document();
        $doc->appendChild(parent::createDocumentType('html'));
        $this->doc->appendChild($namespaceURI ? $this->doc->createElementNS($namespaceURI,$qualifiedName) : $this->doc->createElement($qualifiedName));
    return $doc;
    }
[...]
?>

Where I am struggling is extending the whole tree so that calling the customized Implementation method returns a whole extended tree...
Expected result : Implementation > Document > DOMDocument > Node > DOMNode
Actual result : Implementation > Document > DOMDocument > DOMNode :(
LANGE.LUDO 05-Nov-2014 10:59
Why not use the DOMImplementation to directly register your DOM Class extensions ?

<?php
namespace My;
class Implementation extends \DOMImplementation
{    private $doc;
    public function __construct(){return $this->createDocument();}
    public function __get($name){return $this->doc->{$name};}
    public function __set($name,$value){$this->doc->{$name}=$value;}
    public function __isset($name){return isset($this->doc->{$name});}
    public function __unset($name){return $this->doc->__unset($name);}
    public function __call($name,$args){return call_user_func_array(array($this->doc,$name),$args);}

    public function createDocument($namespaceURI=null,$qualifiedName=null,DOMDocumentType $docType=null)
    {    $this->doc=parent::createDocument($namespaceURI,$qualifiedName,$docType);
        $this->doc->xmlVersion='1.0';
        $this->doc->xmlEncoding='UTF-8';
        $this->doc->registerNodeClass('DOMDocument','My\Document');
        $this->doc->registerNodeClass('DOMDocumentFragment','My\DocumentFragment');
        $this->doc->registerNodeClass('DOMElement','My\Element');
        $this->doc->registerNodeClass('DOMComment','My\Comment');
        $this->doc->registerNodeClass('DOMNode','My\Node');
        /* ..., ..., ... */
        return $this->doc;
    }
}
?>
giorgio dot liscio at email dot it 20-Jul-2010 06:26
officially, the w3 specifies that the way to access dom interfaces is through this class

so if you use

$doc = new DOMDocument("1.0", "UTF-8");

use instead:

$x = new DOMImplementation();
$doc = $x->createDocument(NULL,"rootElementName");
$doc->xmlVersion="1.0";
$doc->xmlEncoding="UTF-8";

it is not required by php's implementation, but, probably, it is a good practice

see:

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementation

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationList

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationSource


Creates a new DOMImplementation object

  • ? DOMImplementation
  • DOMImplementation::createDocument ?
  • PHP Manual
  • DOMImplementation
  • Creates a new DOMImplementation object

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Creates a new DOMImplementation object

说明

DOMImplementation::__construct ( )

Creates a new DOMImplementation object.

User Contributed Notes

There are no user contributed notes for this page.


Creates a DOMDocument object of the specified type with its document element

  • ? DOMImplementation::__construct
  • DOMImplementation::createDocumentType ?
  • PHP Manual
  • DOMImplementation
  • Creates a DOMDocument object of the specified type with its document element

DOMImplementation::createDocument

(PHP 5, PHP 7)

DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element

说明

public DOMImplementation::createDocument
 ( string $namespace = ""
, string $qualifiedName = ""
, DOMDocumentType|null $doctype = null
) : DOMDocument|false

Creates a DOMDocument object of the specified type with its document element.

参数

namespace

The namespace URI of the document element to create.

qualifiedName

The qualified name of the document element to create.

doctype

The type of document to create or null.

返回值

A new DOMDocument object. If namespace, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

错误／异常

DOM_WRONG_DOCUMENT_ERR

Raised if doctype has already been used with a different document or was created from a different implementation.

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by namespace and qualifiedName.

此方法可以被静态调用,但会抛出一个 E_STRICT 错误。

更新日志

版本 | 说明
8.0.0 | doctype is now nullable.

参见

  • DOMDocument::__construct() - Creates a new DOMDocument object
  • DOMImplementation::createDocumentType() - Creates an empty DOMDocumentType object

User Contributed Notes

sleistico at gmail dot com 02-Jul-2018 03:48
I just recently got an error, having to do with deprecation, by using the type of calls in the other example listed here.  What I had to do instead looks like this...

$htmldoc = (new DOMImplementation)->createDocument(null, 'html', (new DOMImplementation)->createDocumentType("html"));

This creates a document with <!DOCTYPE html> at the top of it.
eboyjr 22-Jul-2010 12:48
To add on to the other example, here's how to create an XHTML 1.0 transitional document with head, title, and body elements.

<?php

$document = DOMImplementation::createDocument(null, 'html',
    DOMImplementation::createDocumentType("html",
        "-//W3C//DTD XHTML 1.0 Transitional//EN",
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"));
$document->formatOutput = true;

$html = $document->documentElement;
$head = $document->createElement('head');
$title = $document->createElement('title');
$text = $document->createTextNode('Title of Page');
$body = $document->createElement('body');

$title->appendChild($text);
$head->appendChild($title);
$html->appendChild($head);
$html->appendChild($body);

echo $document->saveXML();
?>

This outputs: (http links removed due to spam)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "doctype.dtd">
<html xmlns="w3org1999xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312" />
    <title>Title of Page</title>
  </head>
  <body></body>
</html>

Note the saveXML function. If saveHTML was used instead, you get the output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "doctype.dtd">
<html>
<head><title>Title of Page</title></head>
<body></body>
</html>
arturm at union dot com dot pl 06-May-2006 10:23
To create HTML document with doctype:

<?php
$doctype = DOMImplementation::createDocumentType("html",
                "-//W3C//DTD HTML 4.01//EN",
                "http://www.w3.org/TR/html4/strict.dtd");
$doc = DOMImplementation::createDocument(null, 'html', $doctype);
?>


Creates an empty DOMDocumentType object

  • ? DOMImplementation::createDocument
  • DOMImplementation::hasFeature ?
  • PHP Manual
  • DOMImplementation
  • Creates an empty DOMDocumentType object

DOMImplementation::createDocumentType

(PHP 5, PHP 7)

DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object

说明

public DOMImplementation::createDocumentType ( string $qualifiedName , string $publicId = "" , string $systemId = "" ) : DOMDocumentType|false

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

参数

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

返回值

A new DOMDocumentType node with its ownerDocument set to null.

错误／异常

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

此方法可以被静态调用,但会抛出一个 E_STRICT 错误。

范例

Example #1 Creating a document with an attached DTD

<?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

// Set other properties
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Create an empty element
$element = $dom->createElement('graph');

// Append the element
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

以上例程会输出：

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

参见

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

User Contributed Notes

until-all-bytes-are-free at example dot org 09-Apr-2011 04:28
I had problems to use a DTD from a file. It needed to be resolved relatively and it contained characters that made DomDocument failed to resolve the file.

Encoding and an absolute filename did not help much. So I used the data:// streamwrapper ( http://php.net/manual/en/wrappers.data.php ) as a work-around:

<?php

// relative or absolute filename
$path = '...';

// convert file contents into a filename
$data = file_get_contents($path);
$systemId = 'data://text/plain;base64,'.base64_encode($data);

// ...

// Creates a DOMDocumentType instance
$dtd = $aImp->createDocumentType('qualified name', '', $systemId);

?>

Works like a charm.


Test if the DOM implementation implements a specific feature

  • ? DOMImplementation::createDocumentType
  • DOMNamedNodeMap ?
  • PHP Manual
  • DOMImplementation
  • Test if the DOM implementation implements a specific feature

DOMImplementation::hasFeature

(PHP 5, PHP 7)

DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

说明

public DOMImplementation::hasFeature ( string $feature , string $version ) : bool

Test if the DOM implementation implements a specific feature.

You can find a list of all features in the » Conformance section of the DOM specification.

参数

feature

The feature to test.

version

The version number of the feature to test. In level 2, this can be either 2.0 or 1.0.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

此方法可以被静态调用,但会抛出一个 E_STRICT 错误。

范例

Example #1 Testing your DOM Implementation

<?php

$features = array(
  'Core'           => 'Core module',
  'XML'            => 'XML module',
  'HTML'           => 'HTML module',
  'Views'          => 'Views module',
  'Stylesheets'    => 'Style Sheets module',
  'CSS'            => 'CSS module',
  'CSS2'           => 'CSS2 module',
  'Events'         => 'Events module',
  'UIEvents'       => 'User interface Events module',
  'MouseEvents'    => 'Mouse Events module',
  'MutationEvents' => 'Mutation Events module',
  'HTMLEvents'     => 'HTML Events module',
  'Range'          => 'Range module',
  'Traversal'      => 'Traversal module'
);

foreach ($features as $key => $name) {
  if (DOMImplementation::hasFeature($key, '2.0')) {
    echo "Has feature $name\n";
  } else {
    echo "Missing feature $name\n";
  }
}

?>

参见

  • DOMNode::isSupported() - Checks if feature is supported for specified version

User Contributed Notes

There are no user contributed notes for this page.


The DOMNamedNodeMap class

(PHP 5, PHP 7)

类摘要

DOMNamedNodeMap implements Traversable , Countable {
/* 属性 */
public readonly int $length ;
/* 方法 */
public count ( ) : int|false
public getNamedItem ( string $qualifiedName ) : DOMNode|null
public getNamedItemNS ( string|null $namespace , string $localName ) : DOMNode|null
public item ( int $index ) : DOMNode|null
}

属性

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

Table of Contents

  • DOMNamedNodeMap::count — Get number of nodes in the map
  • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
  • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
  • DOMNamedNodeMap::item — Retrieves a node specified by index

User Contributed Notes

sirajshaikh96 at yahoo dot com 01-Jan-2021 02:48
I have tried to solve the general problem occurs in DOMNamedNodeMap that during executing for/foreachloop after executing removeAttribute('$name') for item(0), item(1) is not executing and warning occurs. Following codes give the solution of this problem that in loop item(0) should be applied rather than item($i) because after removing first attribute node now present element has only one attribute node.

<?php
$html  = '<h1 id="h1test" class="h2test">Heading</h1>';
$html .= '<p align="left" class="right">Hello World</p>';

$doc = new DOMDocument();
$doc->loadHTML($html);

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; $i++) {
    $name = $h1->attributes->item(0)->nodeName;
    $value = $h1->attributes->item(0)->nodeValue;
    $h1->removeAttribute($name);
    echo "h1: removed attribute name :- " .$name."</br>";
    echo "h1: removed attribute value :- " .$value."</br>";
    }
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
for ($i = 0; $i < $length; $i++) {
    $name = $p->attributes->item(0)->nodeName;
    $value = $p->attributes->item(0)->nodeValue;
    $p->removeAttribute($name);
    echo "p: removed attribute name :- " .$name."</br>";
    echo "p: removed attribute value :- " .$value."</br>";
}
?>

OUTPUT:

h1: removed attribute name :- id
h1: removed attribute value :- h1test
h1: removed attribute name :- class
h1: removed attribute value :- h2test
p: removed attribute name :- align
p: removed attribute value :- left
p: removed attribute name :- class
p: removed attribute value :- right
kendsnyder at gmail dot com 29-Oct-2009 07:55
To add to xafford's comment. When iterating a named node map collection using ->item() or using foreach, removing a attribute with DOMNode->removeAttribute() or DOMNode->removeAttributeNode() alters the collection as if it were a stack. To illustrate, the code below tries to remove all attributes from each element but only removes the first. One work around is to copy the named node map into an array before removing attributes. Using PHP 5.2.9 on Windows XP.

<?php
error_reporting(E_ALL);
$html  = '<h1 id="h1test" class="h1test">Heading</h1>';
$html .= '<p align="left" class="ptest">Hello World</p>';

$doc = new DOMDocument();
$doc->loadHTML($html);

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; ++$i) {
    $name = $h1->attributes->item($i)->name;
    $h1->removeAttribute($name);
    echo "h1: removed attribute `$name`<br>";
}
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
foreach ($p->attributes as $name => $attrNode) {
    $p->removeAttribute($name);
    echo "p: removed attribute `$name`<br>";
}

?>

OUTPUT:
-------
h1: removed attribute `id`

Notice: Trying to get property of non-object in nodemap.php on line 13
h1: removed attribute ``
p: removed attribute `align`
xafford 15-Oct-2009 03:16
I stumbled upon a problem with DOMNamedNodeMap. If you iterate over a DOMNamedNodeMap, representing the attributes of a DOMElement with foreach and you use DOMElement::removeAttributeNode only the first attribute will be handled.

Example (not complete):

<?php

/*
 * Imagine you got a node like this:
 * <a onclick="alert('evil')" href="http://example.com">evil</a>
 * and onclick should be removed, href would not be tested.
 */

foreach ( $node->attributes as $attribute )
{

    echo 'checking attribute ', $attribute->name, '<br />';

    if ( ! in_array ( $attribute->name, $allowed_attributes ) )
    {
        $node->removeAttributeNode ( $attribute );
    }

}

?>

The output would be:

checking attribute onclick


Get number of nodes in the map

  • ? DOMNamedNodeMap
  • DOMNamedNodeMap::getNamedItem ?
  • PHP Manual
  • DOMNamedNodeMap
  • Get number of nodes in the map

DOMNamedNodeMap::count

(PHP 7 >= 7.2.0)

DOMNamedNodeMap::count — Get number of nodes in the map

说明

public DOMNamedNodeMap::count ( ) : int|false

Gets the number of nodes in the map.

参数

此函数没有参数。

返回值

Returns the number of nodes in the map, which is identical to the length property.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by name

  • ? DOMNamedNodeMap::count
  • DOMNamedNodeMap::getNamedItemNS ?
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by name

DOMNamedNodeMap::getNamedItem

(PHP 5, PHP 7)

DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name

说明

public DOMNamedNodeMap::getNamedItem ( string $qualifiedName ) : DOMNode|null

Retrieves a node specified by its nodeName.

参数

qualifiedName

The nodeName of the node to retrieve.

返回值

A node (of any type) with the specified nodeName, or null if no node is found.

参见

  • DOMNamedNodeMap::getNamedItemNS() - Retrieves a node specified by local name and namespace URI

User Contributed Notes

franp at free dot fr 03-Mar-2006 07:28
Basic example of use :

<?xml version="1.0" encoding="UTF-8"?>
<racine version="2.0a">
  <article/>
</racine>

<?php
(...)
 echo $doc->documentElement->attributes->getNamedItem("version")->nodeValue;

// returns "2.0a"
?>


Retrieves a node specified by local name and namespace URI

  • ? DOMNamedNodeMap::getNamedItem
  • DOMNamedNodeMap::item ?
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by local name and namespace URI

DOMNamedNodeMap::getNamedItemNS

(PHP 5, PHP 7)

DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI

说明

public DOMNamedNodeMap::getNamedItemNS ( string|null $namespace , string $localName ) : DOMNode|null

Retrieves a node specified by localName and namespace.

参数

namespace

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

返回值

A node (of any type) with the specified local name and namespace URI, or null if no node is found.

参见

  • DOMNamedNodeMap::getNamedItem() - Retrieves a node specified by name

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by index

  • ? DOMNamedNodeMap::getNamedItemNS
  • DOMNode ?
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by index

DOMNamedNodeMap::item

(PHP 5, PHP 7)

DOMNamedNodeMap::item — Retrieves a node specified by index

说明

public DOMNamedNodeMap::item ( int $index ) : DOMNode|null

Retrieves a node specified by index within the DOMNamedNodeMap object.

参数

index

Index into this map.

返回值

The node at the indexth position in the map, or null if that is not a valid index (greater than or equal to the number of nodes in this map).

User Contributed Notes

reyjacobs at yahoo dot com 07-Mar-2008 11:24
Nevermind: I got it, and here it is:

<?php
if($element->hasAttributes())
{
    $attributes = $element->attributes;
    if(!is_null($attributes))
    {
        foreach ($attributes as $index=>$attr)
        {
            echo $attr->name."=\"".$attr->value."\"";
        }
    }
}
?>


The DOMNode class

(PHP 5, PHP 7)

类摘要

DOMNode {
/* 属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public appendChild ( DOMNode $node ) : DOMNode|false
public C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public cloneNode ( bool $deep = false ) : DOMNode|false
public getLineNo ( ) : int
public getNodePath ( ) : string|null
public hasAttributes ( ) : bool
public hasChildNodes ( ) : bool
public insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public isDefaultNamespace ( string $namespace ) : bool
public isSameNode ( DOMNode $otherNode ) : bool
public isSupported ( string $feature , string $version ) : bool
public lookupNamespaceUri ( string $prefix ) : string
public lookupPrefix ( string $namespace ) : string|null
public normalize ( ) : void
public removeChild ( DOMNode $child ) : DOMNode|false
public replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

nodeName

Returns the most accurate name for the current node type

nodeValue

The value of this node, depending on its type. Contrary to the W3C specification, the node value of DOMElement nodes is equal to DOMNode::textContent instead of null.

nodeType

Gets the type of the node. One of the predefined XML_xxx_NODE constants

parentNode

The parent of this node. If there is no such node, this returns null.

childNodes

A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.

firstChild

The first child of this node. If there is no such node, this returns null.

lastChild

The last child of this node. If there is no such node, this returns null.

previousSibling

The node immediately preceding this node. If there is no such node, this returns null.

nextSibling

The node immediately following this node. If there is no such node, this returns null.

attributes

A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or null otherwise.

ownerDocument

The DOMDocument object associated with this node, or null if this node is a DOMDOcument

namespaceURI

The namespace URI of this node, or null if it is unspecified.

prefix

The namespace prefix of this node, or null if it is unspecified.

localName

Returns the local part of the qualified name of this node.

baseURI

The absolute base URI of this node or null if the implementation wasn't able to obtain an absolute URI.

textContent

The text content of this node and its descendants.

注释

Note:

此 DOM 扩展采用 UTF-8 编码。在 ISO-8859-1 编码下，使用 utf8_encode() 和 utf8_decode() 来处理，其它编码下使用 iconv 函数处理。

更新日志

版本 | 说明
5.6.1 | The textContent property has been made writable (formerly it has been readonly).

参见

  • » W3C specification of Node

Table of Contents

  • DOMNode::appendChild — Adds new child at the end of the children
  • DOMNode::C14N — Canonicalize nodes to a string
  • DOMNode::C14NFile — Canonicalize nodes to a file
  • DOMNode::cloneNode — Clones a node
  • DOMNode::getLineNo — Get line number for a node
  • DOMNode::getNodePath — Get an XPath for a node
  • DOMNode::hasAttributes — Checks if node has attributes
  • DOMNode::hasChildNodes — Checks if node has children
  • DOMNode::insertBefore — Adds a new child before a reference node
  • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
  • DOMNode::isSameNode — Indicates if two nodes are the same node
  • DOMNode::isSupported — Checks if feature is supported for specified version
  • DOMNode::lookupNamespaceUri — Gets the namespace URI of the node based on the prefix
  • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
  • DOMNode::normalize — Normalizes the node
  • DOMNode::removeChild — Removes child from list of children
  • DOMNode::replaceChild — Replaces a child

User Contributed Notes

Anonymous 06-May-2018 04:12
It would be helpful if docs for concrete properties mentioned readonly status of some properties:
"
ownerDocument

    The DOMDocument object associated with this node.

"
zlk1214 at gmail dot com 15-Jan-2016 01:07
A function that can set the inner HTML without encoding error. $html can be broken content such as "<a ID=id20>ssss"
function setInnerHTML($node, $html) {
    removeChildren($node);
    if (empty($html)) {
        return;
    }

    $doc = $node->ownerDocument;
    $htmlclip = new DOMDocument();
    $htmlclip->loadHTML('<meta http-equiv="Content-Type" content="text/html;CHARSET=gb2312"><div>' . $html . '</div>');
    $clipNode = $doc->importNode($htmlclip->documentElement->lastChild->firstChild, true);
    while ($item = $clipNode->firstChild) {
        $node->appendChild($item);
    }
}
metanull 24-Jul-2014 03:11
Yet another DOMNode to php array conversion function.
Other ones on this page are generating too "complex" arrays; this one should keep the array as tidy as possible.
Note: make sure to set LIBXML_NOBLANKS when calling DOMDocument::load, loadXML or loadHTML
See: http://be2.php.net/manual/en/libxml.constants.php
See: http://be2.php.net/manual/en/domdocument.loadxml.php

<?php
         /**
         * Returns an array representation of a DOMNode
         * Note, make sure to use the LIBXML_NOBLANKS flag when loading XML into the DOMDocument
         * @param DOMDocument $dom
         * @param DOMNode $node
         * @return array
         */
        function nodeToArray( $dom, $node) {
            if(!is_a( $dom, 'DOMDocument' ) || !is_a( $node, 'DOMNode' )) {
                return false;
            }
            $array = false;
            if( empty( trim( $node->localName ))) {// Discard empty nodes
                return false;
            }
            if( XML_TEXT_NODE == $node->nodeType ) {
                return $node->nodeValue;
            }
            foreach ($node->attributes as $attr) {
                $array['@'.$attr->localName] = $attr->nodeValue;
            }
            foreach ($node->childNodes as $childNode) {
                if ( 1 == $childNode->childNodes->length && XML_TEXT_NODE == $childNode->firstChild->nodeType ) {
                    $array[$childNode->localName] = $childNode->nodeValue;
                }  else {
                    if( false !== ($a = self::nodeToArray( $dom, $childNode))) {
                        $array[$childNode->localName] =     $a;
                    }
                }
            }
            return $array;
        }
?>
pizarropablo at gmail dot com 16-Apr-2014 02:36
In response to: alastair dot dallas at gmail dot com about "#text" nodes.
"#text" nodes appear when there are spaces or new lines between end tag and next initial tag.

Eg "<data><age>10</age>[SPACES]<other>20</other>[SPACES]</data>"

"data" childNodes has 4 childs:
- age = 10
- #text = spaces
- other = 20
- #text =  spaces
matej dot golian at gmail dot com 29-Aug-2013 01:15
Here is a little function that truncates a DomNode to a specified number of text characters. I use it to generate HTML excerpts for my blog entries.

<?php

function makehtmlexcerpt(DomNode $html, $excerptlength)
{
$remove = 0;
$htmllength = strlen(html_entity_decode($html->textContent, ENT_QUOTES, 'UTF-8'));
$truncate = $htmllength - $excerptlength;
if($htmllength > $excerptlength)
{
if($html->hasChildNodes())
{
$children = $html->childNodes;
for($counter = 0; $counter < $children->length; $counter ++)
{
$child = $children->item($children->length - ($counter + 1));
$childlength = strlen(html_entity_decode($child->textContent, ENT_QUOTES, 'UTF-8'));
if($childlength <= $truncate)
{
$remove ++;
$truncate = $truncate - $childlength;
}
else
{
$child = makehtmlexcerpt($child, $childlength - $truncate);
break;
}
}
if($remove != 0)
{
for($counter = 0; $counter < $remove; $counter ++)
{
$html->removeChild($html->lastChild);
}
}
}
else
{
if($html->nodeName == '#text')
{
$html->nodeValue = substr(html_entity_decode($html->nodeValue, ENT_QUOTES, 'UTF-8'), 0, $htmllength - $truncate);
}
}
}
return $html;
}

?>
alastair dot dallas at gmail dot com 25-Sep-2011 08:44
The issues around mixed content took me some experimentation to remember, so I thought I'd add this note to save others time.

When your markup is something like: <div><p>First text.</p><ul><li><p>First bullet</p></li></ul></div>, you'll get XML_ELEMENT_NODEs that are quite regular. The <div> has children <p> and <ul> and the nodeValue for both <p>s yields the text you expect.

But when your markup is more like <p>This is <b>bold</b> and this is <i>italic</i>.</p>, you realize that the nodeValue for XML_ELEMENT_NODEs is not reliable. In this case, you need to look at the <p>'s child nodes. For this example, the <p> has children: #text, <b>, #text, <i>, #text.

In this example, the nodeValue of <b> and <i> is the same as their #text children. But you could have markup like: <p>This <b>is bold and <i>bold italic</i></b>, you see?</p>. In this case, you need to look at the children of <b>, which will be #text, <i>, because the nodeValue of <b> will not be sufficient.

XML_TEXT_NODEs have no children and are always named '#text'. Depending on how whitespace is handled, your tree may have "empty" #text nodes as children of <body> and elsewhere.

Attributes are nodes, but I had forgotten that they are not in the tree expressed by childNodes. Walking the full tree using childNodes will not visit any attribute nodes.
imranomar at gmail dot com 20-Mar-2011 06:10
Just discovered that node->nodeValue strips out all the tags
I. Cook 19-Apr-2010 02:43
For a reference with more information about the XML DOM node types, see http://www.w3schools.com/dom/dom_nodetype.asp

(When using PHP DOMNode, these constants need to be prefaced with "XML_")
R. Studer 13-Jan-2010 09:03
For clarification:
The assumingly 'discoverd' by previous posters and seemingly undocumented methods (.getElementsByTagName and .getAttribute) on this class (DOMNode) are in fact methods of the class DOMElement, which inherits from DOMNode.

See: http://www.php.net/manual/en/class.domelement.php
David Rekowski 08-Jan-2010 01:54
You cannot simply overwrite $textContent, to replace the text content of a DOMNode, as the missing readonly flag suggests. Instead you have to do something like this:

<?php

$node->removeChild($node->firstChild);
$node->appendChild(new DOMText('new text content'));

?>

This example shows what happens:

<?php

$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
echo "Content 1: ".$node->textContent."\n";

$node->textContent = 'new content';
echo "Content 2: ".$node->textContent."\n";

$newText = new DOMText('new content');

$node->appendChild($newText);
echo "Content 3: ".$node->textContent."\n";

$node->removeChild($node->firstChild);
$node->appendChild($newText);
echo "Content 4: ".$node->textContent."\n";

?>

The output is:

Content 1: old content // starting content
Content 2: old content // trying to replace overwriting $node->textContent
Content 3: old contentnew content // simply appending the new text node
Content 4: new content // removing firstchild before appending the new text node

If you want to have a CDATA section, use this:

<?php
$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
$node->removeChild($node->firstChild);
$newText = $doc->createCDATASection('new cdata content');
$node->appendChild($newText);
echo "Content withCDATA: ".$doc->saveXML($node)."\n";
?>
Steve K 03-Nov-2009 11:47
This class apparently also has a getElementsByTagName method.

I was able to confirm this by evaluating the output from DOMNodeList->item() against various tests with the is_a() function.
marc at ermshaus dot org 05-May-2009 08:36
It took me forever to find a mapping for the XML_*_NODE constants. So I thought, it'd be handy to paste it here:

 1 XML_ELEMENT_NODE
 2 XML_ATTRIBUTE_NODE
 3 XML_TEXT_NODE
 4 XML_CDATA_SECTION_NODE
 5 XML_ENTITY_REFERENCE_NODE
 6 XML_ENTITY_NODE
 7 XML_PROCESSING_INSTRUCTION_NODE
 8 XML_COMMENT_NODE
 9 XML_DOCUMENT_NODE
10 XML_DOCUMENT_TYPE_NODE
11 XML_DOCUMENT_FRAGMENT_NODE
12 XML_NOTATION_NODE
matt at lamplightdb dot co dot uk 06-Apr-2009 05:39
And apparently also a setAttribute method too:

$node->setAttribute( 'attrName' , 'value' );
brian wildwoodassociates.info 07-Dec-2008 11:27
This class has a getAttribute method.

Assume that a DOMNode object $ref contained an anchor taken out of a DOMNode List.  Then

    $url = $ref->getAttribute('href');

would isolate the url associated with the href part of the anchor.


Adds new child at the end of the children

  • ? DOMNode
  • DOMNode::C14N ?
  • PHP Manual
  • DOMNode
  • Adds new child at the end of the children

DOMNode::appendChild

(PHP 5, PHP 7)

DOMNode::appendChild — Adds new child at the end of the children

说明

public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false

This function appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument::createElement(), DOMDocument::createTextNode() etc. or simply by using any other node.

When using an existing node it will be moved.

参数

node

The appended child.

返回值

The node added.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

范例

The following example will add a new element node to a fresh document.

Example #1 Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Example #2 Nested children

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

参见

  • DOMNode::insertBefore() - Adds a new child before a reference node
  • DOMNode::removeChild() - Removes child from list of children
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

cweiske at php dot net 05-Nov-2017 01:56
If you want to move the children of one node to another, you cannot simply iterate on $element->childNodes - you have to make an array first:

<?php
$children = [];
foreach ($elemWithChildren->childNodes as $child) {
    $children[] = $child;
}
foreach ($children as $child) {
    $targetElement->appendChild($child);
}
?>
frame at dynamiccreated dot de 01-Dec-2010 04:14
Aware dealing with DOMNodeList and appendChild() on the same Node.

If you want to replace only the children not the DOMElement itself you probably foreach childNodes-property or get the DOMElements with a for-loop and item()-method of the DOMNodeList.

You will fail if you not clone the received single DOMElement. Actually the count of the DOMNodelist will be decreased on appendChild count but appendChild seems to refer to the old Nodelist and nothing visible will happen. Cloning will help.
krisdover at hotmail dot com 31-May-2008 08:49
What's not mentioned here is that DOMNode::appendChild() can also be used to move an existing node to another part of the DOMDocument, e.g.

<?php
$doc = new DOMDocument();
$doc->loadXML("<foobar><bar/><foo/></foobar>");
$bar = $doc->documentElement->firstChild;
$foo = $doc->documentElement->lastChild;
$foo->appendChild($bar);
print $doc->saveXML();
?>

This produces:

<?xml version="1.0"?>
<foobar><foo><bar/></foo></foobar>

Note that the nodes "<foo/>" and "<bar/>" were siblings, i.e. the first and last child of "<foobar>" but using appendChild() we were able to move "<bar/>" so that it is a child of "<foo/>".

This saves you the trouble of doing a DOMNode::removeChild($bar) to remove "<bar/>" before appending it as a child of "<foo/>".

Kris Dover
jrtayloriv at gmail dot com 30-Mar-2008 04:56
If you want to create nested DOM elements:

<?php
    $doc = new DOMDocument();

    $foo = $doc->createElement("foo");
    $doc->appendChild($foo);

    $bar = $doc->createElement("bar");
    $foo->appendChild($bar);

    $bazz = $doc->createElement("bazz");
    $foo->appendChild($bazz);

    echo $doc->saveXML();
?>

Is equivalent to:

<foo>
  <bar></bar>
  <bazz></bazz>
</foo>


Canonicalize nodes to a string

  • ? DOMNode::appendChild
  • DOMNode::C14NFile ?
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a string

DOMNode::C14N

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::C14N — Canonicalize nodes to a string

说明

public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false

Canonicalize nodes to a string

参数

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

withComments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

nsPrefixes

An array of namespace prefixes to filter the nodes by.

返回值

Returns canonicalized nodes as a string 或者在失败时返回 false

参见

  • DOMNode::C14NFile() - Canonicalize nodes to a file

User Contributed Notes

lordbaco 28-Jan-2016 09:57
Good to know:

<< Due to a known issue in XML canonicalization in PHP, processing large metadata files in SimpleSAMLphp takes a big amount of resources, with that amount growing approximately by the square of the number of entities in the metadata set >>
https://simplesamlphp.org/metaprocessing

<< The C14N() function appears to have a runtime that is O(N^2) (or possibly worse?) depending on input size, which means that it becomes very slow as the input grows. For example, an input with around 196000 nodes takes about 290 seconds, while an input with 486000 nodes takes 2200 seconds. >>
https://bugs.php.net/bug.php?id=53655

We had the same issue with a 4.1 MB XML (105k lines). The sample code of ticket  #53655 takes 1h36 minute to canonicalize it!
jorda at edpsciences dot org 13-Mar-2015 09:11
C14N() returns an empty string if the node is not included in the document tree:
<?php
$d = new DOMDocument('1.0');
$d->loadXML('<foo></foo>');
$n = $d->createElement('bar');
var_dump($n->C14N());
$d->documentElement->appendChild($n);
var_dump($n->C14N());
?>
output:
string(0) ""
string(11) "<bar></bar>"
Rijk 27-Mar-2013 09:26
When working with (malformed) HTML, you're probably better off using DOMDocument's saveHTML() method instead. C14N() will attempt to make your HTML valid XML, for example by converting <br> to <br></br>.

So instead of:
$html = $Node->C14N();

Use:
$html = $Node->ownerDocument->saveHTML( $Node );


Canonicalize nodes to a file

  • ? DOMNode::C14N
  • DOMNode::cloneNode ?
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a file

DOMNode::C14NFile

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::C14NFile — Canonicalize nodes to a file

说明

public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false

Canonicalize nodes to a file.

参数

uri

Path to write the output to.

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

withComments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

nsPrefixes

An array of namespace prefixes to filter the nodes by.

返回值

Number of bytes written 或者在失败时返回 false

参见

  • DOMNode::C14N() - Canonicalize nodes to a string

User Contributed Notes

There are no user contributed notes for this page.


Clones a node

  • ? DOMNode::C14NFile
  • DOMNode::getLineNo ?
  • PHP Manual
  • DOMNode
  • Clones a node

DOMNode::cloneNode

(PHP 5, PHP 7)

DOMNode::cloneNode — Clones a node

说明

public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false

Creates a copy of the node.

参数

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to false.

返回值

The cloned node.

User Contributed Notes

cmd at 1xinternet dot de 16-Nov-2016 12:11
If you need to clone node including all child DOMNode elements:

private function cloneNode($node){

        $nd = new DOMNode();

        for ($i = 0; $i < $node->childNodes->length; $i++) {
            $child = $node->childNodes->item($i);
            if ($child->nodeType === XML_TEXT_NODE) {
                $nd->appendChild($node->cloneNode(true));
            }
            else{
                $nd->appendChild($this->cloneNode($child));
            }
        }

        return $nd;
    }
h-fate at gmx dot net 01-Oct-2014 07:48
If you have an object that holds a DOMNode, cloning the object won't clone the DOMNode with it. If you simply copy the object or add its DOMNode several times, you will in fact only move the DOMNode in the tree, not multiply it. That might seem obvious, but took me half a day to find out.

The object needs to use __clone and clone the node manually:

<?php
class containsNode {
    public $node; //set from somewhere

    public function __clone() {
        $this->node = $this->node->cloneNode(TRUE);
    }
}
?>
frame at dynamiccreated dot de 02-Dec-2012 02:19
Remeber that DOMNode always needs a reference to a parent node or DOMDocument.

For example, if you try to clone a node - copy all children - and overwrite or delete the variable which holds the cloned node - all children will loose any reference and getting invalid.

This will cause a nice message like "Couldn't... node no longer exists" if you have luck. In most cases PHP only gives you the poor information "Couldn't fetch DOM[...]" which makes hard to find out whats going on, depending on the current operation.
cemkalyoncu at gmail dot com 28-Apr-2009 03:04
If you need some function to clone a node without touching namespaces you can use the following.

<?php
private function cloneNode($node,$doc){
    $nd=$doc->createElement($node->nodeName);

    foreach($node->attributes as $value)
        $nd->setAttribute($value->nodeName,$value->value);

    if(!$node->childNodes)
        return $nd;

    foreach($node->childNodes as $child) {
        if($child->nodeName=="#text")
            $nd->appendChild($doc->createTextNode($child->nodeValue));
        else
            $nd->appendChild(cloneNode($child,$doc));
    }

    return $nd;
}
?>
[montana] at [percepticon] dot [com] 16-Feb-2009 02:23
<?php

//@oliver thanks for example source...

/*
 cloneNode(false) does not omit
 Attributes of cloned node,
 to achieve this an iteration is required.
 this is probably less efficient
 than merely creating a new
 node from the desired nodeName
 but in some cases could be useful.

use case:

omit subnodes and attributes of
secured portions of an xml document
without altering expected general structure;
*/
//xml to use

$file="<?xml version='1.0'?>
<book type='paperback'>
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first='Robert' middle='E' last='Howard'/>
        <birthdate disco='false' nirvana='definitely'>
            9/21/1977
            <month title='september' />
        </birthdate>
    </author>
    <author>
        <name first='Arthur' middle='Mc' last='Kayn'/>
    </author>
</book>";

$doc = new domDocument;

$doc->loadXML($file);

$xpath = new domXPath($doc);

$query = "//author/birthdate";
$xpathQuery = $xpath->query($query);

//would be a loop in production code...
$child = $xpathQuery->item(0);

$parent = $child->parentNode;

$doppel = $child->cloneNode(false);

$limit = $doppel->attributes->length;

for ($a=0;$a<$limit;$a++) {
    $doppel->removeAttributeNode($doppel->attributes->item(0));
}
//swap for now empty node
$parent->replaceChild( $doppel, $child);

print $doc->saveXML();

?>
oliver dot christen at camptocamp dot com 19-Nov-2004 08:48
simple exemple of node cloning

<?xml version="1.0"?>

<book type="paperback">
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first="Robert" middle="E" last="Howard"/>
        <birthdate>9/21/1977</birthdate>
    </author>
    <author>
        <name first="Arthur" middle="Mc" last="Kayn"/>
    </author>
</book>

<?php

//filename xml file to use
$file = 'book.xml';

$doc = new domDocument;

if (file_exists($file)) {
    $doc->load($file);
} else {
    exit('Erreur !.');
}

$xpath = new domXPath($doc);

$query = "//author/*";
$xpathQuery = $xpath->query($query);

$size = $xpathQuery->length;
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if ($node->nodeName == 'birthdate' && $node->hasChildNodes() && $node->firstChild->textContent != ''){
        $clonenode = $node->cloneNode(true);
        $refnode = $node;
    }
}
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if (!$node->isSameNode($refnode)){
        $newnode = $node->appendChild($clonenode);
    }
}

print $doc->saveXML();

?>


Get line number for a node

  • ? DOMNode::cloneNode
  • DOMNode::getNodePath ?
  • PHP Manual
  • DOMNode
  • Get line number for a node

DOMNode::getLineNo

(PHP 5 >= 5.3.0, PHP 7)

DOMNode::getLineNo — Get line number for a node

说明

public DOMNode::getLineNo ( ) : int

Gets line number for where the node is defined.

参数

此函数没有参数。

返回值

Always returns the line number where the node was defined in.

范例

Example #1 DOMNode::getLineNo() example

<?php
// XML dump for below example
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node />
</root>
XML;

// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML($xml);

// Print where the line where the 'node' element was defined in
printf('The <node> tag is defined on line %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

以上例程会输出：

The <node> tag is defined in line 3

User Contributed Notes

ruud at vanmelick dot com 25-Oct-2013 09:15
The 65535 line number limit is no longer a problem when you use libxml 2.9 or higher, but you have to explicitly enable support for big line numbers:

<?php
define('XML_PARSE_BIG_LINES', 4194304);
$dom = new DOMDocument;
$dom->loadXML($xml, XML_PARSE_BIG_LINES);
?>
Anonymous 19-May-2012 02:21
The DOMNode::getLineNo() method doesn't work properly due to a libxml2 bug.

https://bugzilla.gnome.org/show_bug.cgi?id=676026
luke dot NOREPLY at webconnex dot com 04-Mar-2011 06:28
This function is buggy. It doesn't always return the correct line number, especially for text elements. As an alternative you can do something like this:

<?php
$text = $node->ownerDocument->saveXML($node);
$line += substr_count($text, "\n");
?>

You'll want to keep a reference to $line (starting at 0) and add to it as you parse over the document recursively.

In order for this to work you have to tell DOMDocument to preserve white space before loading the document.


Get an XPath for a node

  • ? DOMNode::getLineNo
  • DOMNode::hasAttributes ?
  • PHP Manual
  • DOMNode
  • Get an XPath for a node

DOMNode::getNodePath

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::getNodePath — Get an XPath for a node

说明

public DOMNode::getNodePath ( ) : string|null

Gets an XPath location path for the node.

参数

此函数没有参数。

返回值

Returns a string containing the XPath, or null in case of an error.

范例

Example #1 DOMNode::getNodePath() example

<?php
// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML('
<fruits>
 <apples>
  <apple>braeburn</apple>
  <apple>granny smith</apple>
 </apples>
 <pears>
  <pear>conference</pear>
 </pears>
</fruits>
');

// Print XPath for each element
foreach ($dom->getElementsByTagName('*') as $node) {
    echo $node->getNodePath() . "\n";
}
?>

以上例程会输出：

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

参见

  • DOMXPath

User Contributed Notes

There are no user contributed notes for this page.


Checks if node has attributes

  • ? DOMNode::getNodePath
  • DOMNode::hasChildNodes ?
  • PHP Manual
  • DOMNode
  • Checks if node has attributes

DOMNode::hasAttributes

(PHP 5, PHP 7)

DOMNode::hasAttributes — Checks if node has attributes

说明

public DOMNode::hasAttributes ( ) : bool

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMNode::hasChildNodes() - Checks if node has children

User Contributed Notes

There are no user contributed notes for this page.


Checks if node has children

  • ? DOMNode::hasAttributes
  • DOMNode::insertBefore ?
  • PHP Manual
  • DOMNode
  • Checks if node has children

DOMNode::hasChildNodes

(PHP 5, PHP 7)

DOMNode::hasChildNodes — Checks if node has children

说明

public DOMNode::hasChildNodes ( ) : bool

This function checks if the node has children.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMNode::hasAttributes() - Checks if node has attributes

User Contributed Notes

Anonymous 21-Mar-2015 04:33
Hi what if its a dynamic file and we cannot use get elements by tag name then how do we print the contents of all level tags?
richard dot gildx at gmail dot com 29-Jul-2012 01:20
This "hasChildNodes()" exercise is simple enough to make it clear and understandable. Or, you could take it as a tag empty check. By Richard Holm, Sweden.

<?php
$xmldoc=
'<?xml version="1.0" ?>
<root>
<text>Text</text>
<none/>
<empty></empty>
<space> </space>
</root>';

$domdoc=new DOMDocument();
$domdoc->loadXML($xmldoc);

$tag=$domdoc->getElementsByTagName('root')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('text')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('none')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('empty')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('space')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";
?>

Output:
root hasChildNodes
text hasChildNodes
none hasNoChildNodes
empty hasNoChildNodes
space hasChildNodes
sansana 14-Oct-2010 07:04
Personally I think using a simple:[code]if($DOMNode->childNodes <>0){}[/code] works better.
syngcw at syncgw.com 04-Jan-2010 05:53
This function is a bit tricky. If you want to find XML childnodes it is useless. You need to create a work-around:

<?php

$x = new DOMDocument();
$x->loadXML('
<A>
 <B>b-text</B>
 <C>
  <D>d-text</D>
 </C>
 <E/>
</A>');

shownode($x->getElementsByTagName('A')->item(0));
function shownode($x) {
 foreach ($x->childNodes as $p)
  if (hasChild($p)) {
      echo $p->nodeName.' -> CHILDNODES<br>';
      shownode($p);
  } elseif ($p->nodeType == XML_ELEMENT_NODE)
   echo $p->nodeName.' '.$p->nodeValue.'<br>';
}
function hasChild($p) {
 if ($p->hasChildNodes()) {
  foreach ($p->childNodes as $c) {
   if ($c->nodeType == XML_ELEMENT_NODE)
    return true;
  }
 }
 return false;
}

?>

shows:
B b-text
C -> CHILDNODES
D d-text
E
jintoppy at gmail dot com 28-Apr-2009 04:13
<?php

$doc = new DOMDocument;
$node = $doc->createElement("FirstMain", "First Main Node. This have child");
$doc->appendChild($node);
$childnode = $doc->createElement("childnode", "child node");
$node->appendChild($childnode);
$secondnode = $doc->createElement("SecondMain", "First Main Node. This don't have child");
$doc->appendChild($secondnode);
$doc->saveXML();
$nodeElmt = $doc->getElementsByTagName("FirstMain");
/*
if given as $nodeElmt = $doc->getElementsByTagName("childnode");
the output would be "This node has childnodes"

if given as $nodeElmt = $doc->getElementsByTagName("SecondMain");
the output would be "This node has no childnodes"

*/

foreach($nodeElmt as $nodeElmt)
{
if($nodeElmt->hasChildNodes())
{
echo "This node has childnodes";
}
else
{
echo "This node has no childnodes";
}
}

  ?>

- - - - - - - - - - - - - -

Output:

This node has childnodes

- - - - - - - - - - - - - -


Adds a new child before a reference node

  • ? DOMNode::hasChildNodes
  • DOMNode::isDefaultNamespace ?
  • PHP Manual
  • DOMNode
  • Adds a new child before a reference node

DOMNode::insertBefore

(PHP 5, PHP 7)

DOMNode::insertBefore — Adds a new child before a reference node

说明

public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false

This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.

When using an existing node it will be moved.

参数

node

The new node.

child

The reference node. If not supplied, node is appended to the children.

返回值

The inserted node.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if child is not a child of this node.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children

User Contributed Notes

jarry1250 at gmail dot com 30-May-2015 01:59
Note that supplying the same node for $newnode and $refnode leads to an E_WARNING ("Couldn't add newnode as the previous sibling of refnode"). For example imagine one wanted to make $newnode the first child of its parent by doing:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Bad:
$newnode->parentNode->insertBefore( $newnode, $firstSibling );
?>

This would generate a warning if it already was the first child of its parent, since $newnode and $firstSibling are identical. Easy to work around though:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Better:
if( $newnode !== $firstSibling ) {
    $newnode->parentNode->insertBefore( $newnode, $firstSibling );
}
?>
DrTebi at Yahoo 03-Oct-2007 05:54
Sorry, my previous posting worked only for the top node. Here the corrected version, which will work for any node:

XML
----
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person>
  <person>Thomas</person>
</contacts>

PHP
---
<?php
// load XML, create XPath object
$xml = new DomDocument();
$xml->preserveWhitespace = false;
$xml->load('contacts.xml');
$xpath = new DOMXPath($xml);

// get node eva, which we will append to
$eva = $xpath->query('/contacts/person[.="Eva"]')->item(0);

// create node john
$john = $xml->createElement('person', 'John');

// insert john after eva
//   "in eva's parent node (=contacts) insert
//   john before eva's next node"
// this also works if eva would be the last node
$eva->parentNode->insertBefore($john, $eva->nextSibling);

// show result
header('Content-Type: text/plain');
print $xml->saveXML();
?>

Result
------
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person><person>John</person>
  <person>Thomas</person>
</contacts>
justin at redwiredesign dot com 07-Feb-2007 08:20
The previous example is incorrect, and causes a DOM_NOT_FOUND error, as the child nodes are not direct descendants of the root node.

Therefore, the line:

$parent_path = "/root";

needs to change to:

$parent_path = "/root/parent";

or

$parent_path = "//parent";

for this example to work
jg at handcode dot de 18-Aug-2005 12:18
example to insert <newnode/> between <chid1/> and <child2/>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
  <parent>
    <child nr="1"/>
    <child nr="2"/>
  </parent>
</root>

<?php

$xml_src = 'test.xml';

// XPath-Querys
$parent_path = "//parent";
$next_path = "//parent/child[@nr='2']";

// Create a new DOM document
$dom = new DomDocument();
$dom->load($xml_src);

// Find the parent node
$xpath = new DomXPath($dom);

// Find parent node
$parent = $xpath->query($parent_path);

// new node will be inserted before this node
$next = $xpath->query($next_path);

// Create the new element
$element = $dom->createElement('newnode');

// Insert the new element
$parent->item(0)->insertBefore($element, $next->item(0));

echo $dom->saveXML();

?>
Jerry Ellis 03-Jun-2005 12:45
1st argument) a node to insert
2nd argument) a reference node - this is the node that the new node will be inserted before

The trick to using this method is that the OBJECT on which you actually CALL the insertBefore() method is actually the PARENT node of the reference node!

INCORRECT:
$DOMNode_refNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);

CORRECT:
$DOMNode_refNode->parentNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);


Checks if the specified namespaceURI is the default namespace or not

  • ? DOMNode::insertBefore
  • DOMNode::isSameNode ?
  • PHP Manual
  • DOMNode
  • Checks if the specified namespaceURI is the default namespace or not

DOMNode::isDefaultNamespace

(PHP 5, PHP 7)

DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not

说明

public DOMNode::isDefaultNamespace ( string $namespace ) : bool

Tells whether namespace is the default namespace.

参数

namespace

The namespace URI to look for.

返回值

Return true if namespace is the default namespace, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Indicates if two nodes are the same node

  • ? DOMNode::isDefaultNamespace
  • DOMNode::isSupported ?
  • PHP Manual
  • DOMNode
  • Indicates if two nodes are the same node

DOMNode::isSameNode

(PHP 5, PHP 7)

DOMNode::isSameNode — Indicates if two nodes are the same node

说明

public DOMNode::isSameNode ( DOMNode $otherNode ) : bool

This function indicates if two nodes are the same node. The comparison is not based on content

参数

otherNode

The compared node.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Checks if feature is supported for specified version

  • ? DOMNode::isSameNode
  • DOMNode::lookupNamespaceUri ?
  • PHP Manual
  • DOMNode
  • Checks if feature is supported for specified version

DOMNode::isSupported

(PHP 5, PHP 7)

DOMNode::isSupported — Checks if feature is supported for specified version

说明

public DOMNode::isSupported ( string $feature , string $version ) : bool

Checks if the asked feature is supported for the specified version.

参数

feature

The feature to test. See the example of DOMImplementation::hasFeature() for a list of features.

version

The version number of the feature to test.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMImplementation::hasFeature() - Test if the DOM implementation implements a specific feature

User Contributed Notes

There are no user contributed notes for this page.


Gets the namespace URI of the node based on the prefix

  • ? DOMNode::isSupported
  • DOMNode::lookupPrefix ?
  • PHP Manual
  • DOMNode
  • Gets the namespace URI of the node based on the prefix

DOMNode::lookupNamespaceUri

(PHP 5, PHP 7)

DOMNode::lookupNamespaceUri — Gets the namespace URI of the node based on the prefix

说明

public DOMNode::lookupNamespaceUri ( string $prefix ) : string

Gets the namespace URI of the node based on the prefix.

参数

prefix

The prefix of the namespace.

返回值

The namespace URI of the node.

参见

  • DOMNode::lookupPrefix() - Gets the namespace prefix of the node based on the namespace URI

User Contributed Notes

_ michael 30-Apr-2010 02:22
You have to pass *null* to lookupNamespaceURI if you want to read the default namespace. Passing an empty string doesn't work - even though the documentation says that lookupNamespaceURI takes a string as argument (and null would just be converted to an empty string).
lewar 05-Jun-2007 05:20
Simple way to get the URI of the default namespace:

<?php
    $document = new DOMDocument();
    $document->load($xml_file);
    $uri = $document->documentElement->lookupnamespaceURI(NULL);
?>


Gets the namespace prefix of the node based on the namespace URI

  • ? DOMNode::lookupNamespaceUri
  • DOMNode::normalize ?
  • PHP Manual
  • DOMNode
  • Gets the namespace prefix of the node based on the namespace URI

DOMNode::lookupPrefix

(PHP 5, PHP 7)

DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI

说明

public DOMNode::lookupPrefix ( string $namespace ) : string|null

Gets the namespace prefix of the node based on the namespace URI.

参数

namespace

The namespace URI.

返回值

The prefix of the namespace.

参见

  • DOMNode::lookupNamespaceUri() - Gets the namespace URI of the node based on the prefix

User Contributed Notes

There are no user contributed notes for this page.


Normalizes the node

  • ? DOMNode::lookupPrefix
  • DOMNode::removeChild ?
  • PHP Manual
  • DOMNode
  • Normalizes the node

DOMNode::normalize

(PHP 5, PHP 7)

DOMNode::normalize — Normalizes the node

说明

public DOMNode::normalize ( ) : void

Remove empty text nodes and merge adjacent text nodes in this node and all its children.

返回值

没有返回值。

参见

  • » The DOM Specification
  • DOMDocument::normalizeDocument() - Normalizes the document

User Contributed Notes

Amir Laher 22-Aug-2005 04:45
This is a quote from the DOM level 2 spec, explaining the normalize() function.
----
normalize
Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer [XPointer] lookups) that depend on a particular document tree structure are to be used.
----
(source: http://www.w3.org/TR/DOM-Level-2-Core/core.html)

i.e. the idea of normalize is to make text nodes the same as they would be if the xml document was re-loaded into DOM. It's handy if you want to compare DOM nodes.


Removes child from list of children

  • ? DOMNode::normalize
  • DOMNode::replaceChild ?
  • PHP Manual
  • DOMNode
  • Removes child from list of children

DOMNode::removeChild

(PHP 5, PHP 7)

DOMNode::removeChild — Removes child from list of children

说明

public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false

This functions removes a child from a list of children.

参数

child

The removed child.

返回值

If the child could be removed the function returns the old child.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if child is not a child of this node.

范例

The following example will delete the chapter element of our XML document.

Example #1 Removing a child

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

以上例程会输出：

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>

</book>

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

nggit@phpindonesia 01-Feb-2019 02:29
You can use foreach to remove multiple elements from a DOMNodeList, only if you use a temporary array or via XPath query.
If not, the simplest way will be:

<?php

while ($element = $nodeList->item(0)) {
    $element->parentNode->removeChild($element);
}

?>
Kenney 28-Mar-2013 10:19
This method will remove all child nodes but leave the attributes (and namespace declarations) intact.

<?php
function removeChildren( &$node )
{
  $node->parentNode->replaceChild(
    $n = $node->cloneNode( false ),
    $node );

  $node = $n;
}
?>
drimsun at gmail dot com 11-Feb-2010 03:37
If you try to remove children of a nested node (e.g. a <ul> list that contains another <ul>) and only remove the first level of child nodes, you'll get a messed-up node object.

Upon re-use of the messed-up node you'll get an error message that says: "Fatal error: Call to a member function blahblah() on a non-object".

To remove ALL child nodes, use this recursive function instead:
<?php
/**
 * Helper function that removes all child nodes of $node recursively
 * (i.e. including child nodes of the child nodes and so forth).
 */
function remove_children(&$node) {
  while ($node->firstChild) {
    while ($node->firstChild->firstChild) {
      remove_children($node->firstChild);
    }
    $node->removeChild($node->firstChild);
  }
}
?>
Justin Carlson 05-Nov-2009 11:46
Just a note, if you remove a node the whitespace it occupied will remain if you save the file.

To avoid this, use $document->preserveWhiteSpace = false;

For Example:

<?php
$document = new DomDocument();
$document->preserveWhiteSpace = false;
?>
crazy888s at hotmail dot com 15-Apr-2009 01:50
You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
foreach ( $domNodeList as $domElement ) {
  //  ...do stuff with $domElement...
  $domElement->parentNode->removeChild($domElement);
}
?>

... will seemingly leave the internal iterator on the foreach out of wack and results will be quite strange. Though, making a queue of items to remove seems to work. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
  // ...do stuff with $domElement...
  $domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
  $domElement->parentNode->removeChild($domElement);
}
?>
Justin Sheckler 30-Jan-2009 08:44
These two functions might be helpful to anyone trying to delete a node and all of its children:

<?php
function deleteNode($node) {
    deleteChildren($node);
    $parent = $node->parentNode;
    $oldnode = $parent->removeChild($node);
}

function deleteChildren($node) {
    while (isset($node->firstChild)) {
        deleteChildren($node->firstChild);
        $node->removeChild($node->firstChild);
    }
}
?>
tim cameron ryan 19-Jul-2008 01:00
Or something like:

<?php

while ($node->childNodes->length)
     $node->removeChild($node->firstChild);

?>
Michael D (DigitalGemstones.com) 05-Jul-2008 04:15
Note that iterating through the childNodes array and removing those children will stop the iteration.

For example:
<?php
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
     $child->parentNode->removeChild($child);
}
?>

Will not work.  Note that in removing the node, the childNodes array gets rebuilt (it seems) and so only the first item will be removed.  In order to properly remove all the children you want to remove, you will need to do something like the following:

<?php
$nodesToDelete = array();
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
    $nodesToDelete[] = $child;
}
foreach($nodesToDelete as $node)
{
  $node->parentNode->removeChild($node);
}
?>

I believe this is actually more efficient than the first snippet would be (if it worked) but obviously I cannot benchmark it.
Wala 04-Apr-2008 10:57
I used the following to delete an entire node using the child element:

<?php
$childElement->parentNode->parentNode-> removeChild($childElement->parentNode);
?>

I could not have thought of it without the help of everyone who contributed to this thread.

Thanks!

(I had to introduce the extra space between parentNode->removeChild to get rid of the wordwrap() warning while posting this note)
Vasil Rangelov 06-Oct-2007 10:14
At the time of writing, I suppose rightfully, removeChild() removes only the selected node, but when you remove an element, it's child elements are not removed. If you want to achieve that, replaceChild() is the solution.

The following should remove all descendants of the $node DOMNode, regardless of it's name:
<?php
$node->replaceChild(new DOMElement($node->nodeName), $node);
?>
If you're replacing the root element, you must explicitly state that with $node->documentElement as the second argument.
mytto at openxtrem dot com 07-Sep-2005 02:20
Back again on removing childs and iterators robustness.

Things get a bit more complicated when you only want to remove 'some' nodes according to a certain condition. Then you can't just remove the first one repeatedly.

The trick is to copy the content of the node list into a more robust collection than DOMNodeList, I name array!

The following piece of code will, for instance, remove all empty child nodes:

<?php
// Copy childNodes array
$childNodes = array();
foreach($node->childNodes as $childNode) {
  $childNodes[] = $childNode;
}

// Browse with the copy
foreach ($childNodes as $childNode) {
  if (!$childNode->hasChildNodes()); {
    $childNode->parentNode->removeChild($childNode);
  }
}
?>
blaine (at) blainegarrett (dot com) 23-Aug-2005 10:10
This might be obvious, but might help someone as well...

If you simply have a node that you need to remove (perhaps from an xpath) and don't know the parent node offhand (the examples seem to assume you have the parent in a variable), then you can do something easy like this...

$node->parentNode->removeChild($node);

parentNode is a scalar property of the Element.

Hope that helps.

--
Blaine Garrett
pedro at leb dot usp dot br 30-May-2005 04:24
You may also use the hasChild function:
<?php

while($node->hasChildNodes()) {
  $node->removeChild($node->childNodes->item(0));
}

?>

When you remove a childNode, the next node becomes the first one!
vsematika at centrum dot cz 13-Feb-2005 03:35
For those who don't understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07< 'hack', here's a little discussion:

First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
   $parent->removeChild($child);
?>
This doesn't work because DOM tree id modified on-the-fly and this confuses foreach loop.

The idea behind sbeam's trick is that after removing the first item in the first iteration, the second item in childNodes nodelist immediately becomes the first item. That's why we must _always_ remove the first child. Here's another implementation:

<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
   $oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>


Replaces a child

  • ? DOMNode::removeChild
  • DOMNodeList ?
  • PHP Manual
  • DOMNode
  • Replaces a child

DOMNode::replaceChild

(PHP 5, PHP 7)

DOMNode::replaceChild — Replaces a child

说明

public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false

This function replaces the child child with the passed new node. If the node is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

参数

node

The new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument::importNode.

child

The old node.

返回值

The old node or false if an error occur.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if child is not a child of this node.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

chealer at gmail dot com 15-Aug-2018 03:07
As of version 5.6, PHP still behaves as reported by jb at jbpros dot com. To use replaceChild() in a loop, the more standard pattern used in the following example can be used:

for ($currentNode = 0; $currentNode < $link->childNodes->length; $currentNode++) {
    $child = $link->childNodes[$currentNode];

    // "Remove" links, since links can't contain links
    if ($child instanceof DOMElement && $child->tagName == 'a') {
        $replacement = $dom->createTextNode($child->textContent);
        $link->replaceChild($replacement, $child);
    }
}
jb at jbpros dot com 01-Mar-2005 08:08
If you are trying to replace more than one node at once, you have to be careful about iterating over the DOMNodeList.  If the old node has a different name from the new node, it will be removed from the list once it has been replaced.  Use a regressive loop:

<?php

$xml = new DOMDocument;
$xml->load('docfile.xml');

$elements = $xml->getElementsByTagNameNS('http://www.example.com/NS/', '*');
$i = $elements->length - 1;
while ($i > -1) {
    $element = $elements->item($i);
    $ignore = false;

    $newelement = $xml>createTextNode('Some new node!');
    $element->parentNode->replaceChild($newelement, $element);
    $i--;
}

?>

The loop counter ($i) will always be in the list's interval as removed elements indexes are above the counter.
aidan at php dot net 26-Dec-2004 02:17
Here is a simple example for replacing a node:

Let's define our XML like so:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<root>
  <parent>
     <child>bar</child>
     <child>foo</child>
  </parent>
</root>
XML;
?>

If we wanted to replace the entire <parent> node, we could do something like this:

<?php
// Create a new document fragment to hold the new <parent> node
$parent = new DomDocument;
$parent_node = $parent ->createElement('parent');

// Add some children
$parent_node->appendChild($parent->createElement('child', 'somevalue'));
$parent_node->appendChild($parent->createElement('child', 'anothervalue'));

// Add the keywordset into the new document
// The $parent variable now holds the new node as a document fragment
$parent->appendChild($parent_node);
?>

Next, we need to locate the old node:

<?php
// Load the XML
$dom = new DomDocument;
$dom->loadXML($xml);

// Locate the old parent node
$xpath = new DOMXpath($dom);
$nodelist = $xpath->query('/root/parent');
$oldnode = $nodelist->item(0);
?>

We then import and replace the new node:

<?php
// Load the $parent document fragment into the current document
$newnode = $dom->importNode($parent->documentElement, true);

// Replace
$oldnode->parentNode->replaceChild($newnode, $oldnode);

// Display
echo $dom->saveXML();
?>

Our new node is successfully imported:

<?xml version="1.0"?>
<root>
<parent><child>somevalue</child><child>anothervalue</child></parent>
</root>
franp at free dot fr 23-Sep-2004 08:39
1) If your XPath query returns a NodeList including a unique item, or if you know for sure the order of the items returned, you can use the "item(n)" syntax instead of the "foreach" syntax.
This can greatly improve you code lisibility.
s the method name implies, replaceChild cannot replace a node itself but a child of a node.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
 <actionGlobal>
  <actionGlobalFR>sometext</actionGlobalFR>
 <actionGlobal>
</action>

$frag = $doc->createElement("actionGlobalFR");
$fragA = $doc->createTextNode("anothertext");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/actionGlobal/actionGlobalFR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($ajout, $xpResult->item(0));

2) Also, as the method name implies, replaceChild cannot replace a node itself but a child of a node.
Still it is possible to replace a node pointed by XPath istead of its child.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
  <FR>French Text</FR>
</action>

<?php
$frag = $doc->createElement("EN");
$fragA = $doc->createTextNode("English Text");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/FR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($fragA, $xpResult->item(0));
?>

Et voil? !

This produces :
<?xml version="1.0" ?>
<action>
  <EN>English Text</EN>
</action>

....................................................

3) Also, be carefull, you CANNOT replace a node that doesn't exist.
While this may seems obvious, it is easy to forget.

Consider this :
<?xml version="1.0" ?>
<action>
  <EN></EN>
</action>

You cannot use replaceChild() to turn this into :
<?xml version="1.0" ?>
<action>
  <EN>Some text</EN>
</action>

The reason is that since the <EN></EN> element is empty, it has no child (this is clearer to understand if you consider that <EN></EN> can be written <EN />).
The fact that you intend to put some text inbetween <EN> and </EN> does not change the fact that it has no text yet, thus no child yet.
When dealing with DOM, do not take your dream for the reality. The DOM parser doen't care about your dreams. If an element is currently empty, it has no child, whatever you intend to fill in.

Thus, the solution to teh problem is to use appendChild intead of replaceChild :

<?php
$fragA = $doc->createTextNode("Some Text");
$xpResult = $xp->query("/action/EN");
$blipblip = $xpResult->item(0)->appendChild($fragA);
?>

This produces the awaited :
<?xml version="1.0" ?>
<action>
  <EN>Some Text</EN>
</action>

....................................................

4) Note that the description of replaceChild in the doc is wrong. Arguments have been inverted.
The correct description is :
object DOMNode->replaceChild (object newnode, object oldnode)


The DOMNodeList class

(PHP 5, PHP 7)

类摘要

DOMNodeList implements Traversable , Countable {
/* 属性 */
public readonly int $length ;
/* 方法 */
public count ( ) : int|false
public item ( int $index ) : DOMNode|null
}

属性

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

更新日志

版本 | 说明
7.2.0 | The Countable interface is implemented and returns the value of the length property.

参见

  • » W3C specification of NodeList

Table of Contents

  • DOMNodeList::count — Get number of nodes in the list
  • DOMNodeList::item — Retrieves a node specified by index

User Contributed Notes

ignitedfirestarter at gmail dot com 04-Jul-2012 10:39
If you want to recurse over a DOM then this might help:
<?php

/**
 * PHP's DOM classes are recursive but don't provide an implementation of
 * RecursiveIterator. This class provides a RecursiveIterator for looping over DOMNodeList
 */
class DOMNodeRecursiveIterator extends ArrayIterator implements RecursiveIterator {

  public function __construct (DOMNodeList $node_list) {

    $nodes = array();
    foreach($node_list as $node) {
      $nodes[] = $node;
    }

    parent::__construct($nodes);

  }

  public function getRecursiveIterator(){
    return new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST);
  }

  public function hasChildren () {
    return $this->current()->hasChildNodes();
  }

  public function getChildren () {
    return new self($this->current()->childNodes);
  }

}
?>
geompse at gmail dot com 19-May-2010 08:39
Note that $length is calculated (php5.3.2).
Iterating over a large NodeList may be time expensive.

Prefer :
$nb = $nodelist->length;
for($pos=0; $pos<$nb; $pos++)

Than:
for($pos=0; $pos<$nodelist->length; $pos++)

I had a hard time figuring that out...
bobvandell at hotmail dot com 26-Aug-2008 09:12
That's actually incorrect. You can use function results as objects. It makes building an API for your database very clean and neat. For example:

Our code:

$articles = Node::screate('tags', 123456)->assets('like:title:test')->articles;

We use the above code to get articles that are linked to assets that are linked to a specific tag in our database.
c dot 1 at smithies dot org 23-May-2008 05:43
You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards:

$els = $document->getElementsByTagName('input');
for ($i = $els->length; --$i >= 0; ) {
  $el = $els->item($i);
  switch ($el->getAttribute('name')) {
    case 'MAX_FILE_SIZE' :
      $el->parentNode->removeChild($el);
    break;
    case 'inputfile' :
      $el->setAttribute('type', 'text');
    //break;
  }
}
drichter at muvicom dot de 14-May-2008 06:11
Addition to my first note:

An traditional for-loop does not allow you to change the DOM-tree while looping - the effects are the nearly the same as with foreach. So you have to collect the nodes in an array and do the tree-altering stuff within a second loop (looping the array this time ...)
drichter at muvicom dot de 14-May-2008 04:56
I have done some testing and have found 2 results:
(My System: Win XP with PHP 5.2.1)

1) Iteration with foreach does function correctly as "james dot j dot hackett at gmail dot com" writes, _if_ you only do readonly stuff with foreach or minor writings of some attributes.

2) foreach does not function, if you are doing some DOM-Operations while iterating. In my situation it was adding the iterated $node as an child to an new node:

$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as $node) {
  echo $node->nodeValue ;
  $newNode->appendChild($node) ;
}

This only gives you the first element ...

I'm interpreting it as an confusing but correct behavior because of the changes within the $dom-object while appending the node at an additional place ...

So, if you want to do something like 2) use for, length and item() :)
james dot j dot hackett at gmail dot com 08-May-2008 09:47
In Response to 'kassah at gmail'

You don't need to convert a DOMNodeList to an array in order iterate through it using 'foreach'.  You can use foreach directly with the DOMNodeList.

$nodeList = $someDomDocument->getElementsbytagname('user');

foreach ($nodeList as $node) {
    echo $node->nodeValue;
}
brack at wjp dot de 21-Apr-2008 02:35
In PHP 5.2.5 (Windows) it is not possible to iterate correctly over the DOMNodeList object returned by DOMNode->childNodes using foreach. Instead I had to use the for loop in conjunction with the item() method of DOMNodeList for iterating over all child nodes correctly.

I don't know whether this is really a bug, but apparently it is.


Get number of nodes in the list

  • ? DOMNodeList
  • DOMNodeList::item ?
  • PHP Manual
  • DOMNodeList
  • Get number of nodes in the list

DOMNodeList::count

(PHP 7 >= 7.2.0)

DOMNodeList::count — Get number of nodes in the list

说明

public DOMNodeList::count ( ) : int|false

Gets the number of nodes in the list.

参数

此函数没有参数。

返回值

Returns the number of nodes in the list, which is identical to the length property.

User Contributed Notes

plimpton47 at example dot com 04-May-2018 08:09
Be careful with using this function as it's not available for anything before PHP 7.2, use the length property instead


Retrieves a node specified by index

  • ? DOMNodeList::count
  • DOMNotation ?
  • PHP Manual
  • DOMNodeList
  • Retrieves a node specified by index

DOMNodeList::item

(PHP 5, PHP 7)

DOMNodeList::item — Retrieves a node specified by index

说明

public DOMNodeList::item ( int $index ) : DOMNode|null

Retrieves a node specified by index within the DOMNodeList object.

Tip

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

参数

index

Index of the node into the collection.

返回值

The node at the indexth position in the DOMNodeList, or null if that is not a valid index.

范例

Example #1 Traversing all the entries of the table

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}

?>

Alternatively, you can use foreach, which is a much more convenient way:

<?php

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}

?>

以上例程会输出：

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

User Contributed Notes

jeffpuckett2 at gmail dot com 15-Jun-2016 02:55
DOMNodelist::item can return a DOMElement object, which extends DOMNode class. But it can also return a DOMText object.

<?php
$xml = '
<root>
  <node/>
  <node>
    <sub>more</sub>
  </node>
  <node>
    <sub>another</sub>
  </node>
  <node>value</node>
</root>
';

$doc = new DOMDocument();
$doc->loadXML($xml);

$items = $doc->documentElement->childNodes;
for ($i = 0; $i < $items->length; $i++)
  echo get_class($items->item($i)).PHP_EOL;
?>

Results in this output:

DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
Anonymous 25-Jun-2012 11:36
calling domnodelist->item($i) with an index $i greater than domnodelist->length - 1 , will return the entire document, will not produce an error, and will not circle back to the start of the list.
Nagy Attila 06-Jan-2011 09:02
DOMNodeList::item does not return in constant time!

If you need to iterate over large nodelist then you'd better use standard navigation.

Instead of:

<?php
foreach ($nodelist as $node) {
    // do something
}
?>

you could do:

<?php
$node = $parentnode->firstChild;

do {
    // do something
} while ($node = $node->nextSibling);
?>
olivier dot berger at it-sudparis dot eu 21-Aug-2008 02:56
It seems that with zend.ze1_compatibility_mode on, the only way to iterate over the items list is with :
for ($i = 0; $i < $nodeList->length; ++$i) {
    $nodeName = $nodeList->item($i)->nodeName;
    $nodeValue = $nodeList->item($i)->nodeValue;
}

As other attemps failed :

for ($i = 0; $i < $nodeList->length; ++$i) {
    $node = &$nodeList->item($i);
    $nodeName = $node->nodeName;
    $nodeValue = $node->nodeValue;
}

or :
foreach ($nodeList as $node) {
    echo $node->nodeName;
    echo $node->nodeValue;
}
vinyanov at poczta dot onet dot pl 05-Jan-2008 10:12
SimpleXML has its own SPL iterator. See http://www.php.net/~helly/php/ext/spl/classSimpleXMLIterator.html . But I guess that there are none for DOM nodes. By the way, two out of three implementations I found over the Net were not recursive, so I wrote my own. Here is the snippet:

<?php

class DOMNodeListIterator implements RecursiveIterator
{
    private
        $nodes,
        $offset;

    function __construct(DOMNodeList $nodes)
    {
        return $this -> nodes = $nodes;
    }

    function rewind()
    {
        return $this -> offset = 0;
    }

    function current()
    {
        return $this -> nodes -> item($this -> offset);
    }

    function key()
    {
        return $this -> current() -> nodeName;
    }

    function next()
    {
        return $this -> offset++;
    }

    function valid()
    {
        return $this -> offset < $this -> nodes -> length;
    }

    function hasChildren()
    {
        return isset($this -> current() -> childNodes -> length) && $this -> current() -> childNodes -> length > 0;
    }

    function getChildren()
    {
        return new self($this -> current() -> childNodes);
    }
}

?>

Remember to use RecursiveIteratorIterator::SELF_FIRST flag when you create your iterator iterator.

<?php

$iterator = new DOMNodeListIterator($document -> childNodes);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

?>

Should work, has just few minutes though. :)
Hayley Watson 29-Oct-2007 02:14
Keep in mind that DOMNodelists are "live" - changes to the document or node that the DOMNodelist was derived from will be reflected in the DOMNodelist. In other words, a list of a parent node's children will change if you change the parent's children!
james dot dunmore at gmai dot com 27-Jul-2007 08:57
tfg_allardyce at gmail dot com

I have had exactly this problem.

To rectify I've had to do this:
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0);
$new_element = $doc->createElement('NewElement1');

$old_element_childNodes = $old_element->childNodes;
$length = $old_element_childNodes->length;

for($i = 0; $i < $length; $i++)
{
    $oldChildren_array[] = $old_element_childNodes->item($i);
}

foreach($oldChildren_array as $old_c)
{
    $new_element->appendChild($old_c);
}
?>

Rather than this:
(which I will bug report)
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0):
$new_element = $doc->createElement('NewElement1');

foreach($old_element->childNode as $node)
{
     $new_element->appendChild($node);
}

?>

Using the latter, randomally removes the children!
Geoffrey Thubron 26-May-2007 02:47
@ tfg_allardyce at gmail dot com

You could loop through the list backwards, that way, you are only ever taking off the last item from the list, and hence wont have disrupted the order.
oliver dot christen at camptocamp dot com 13-Feb-2007 07:27
NodeList are something annoying because you can't output the content with a simple print_r, so I did a little function that add all the node to a new empty DOMDocument and output it as a string.
Have fun.

<?php

public function domNodeList_to_string($DomNodeList) {
    $output = '';
    $doc = new DOMDocument;
    while ( $node = $DomNodeList->item($i) ) {
        // import node
        $domNode = $doc->importNode($node, true);
        // append node
        $doc->appendChild($domNode);
        $i++;
    }
    $output = $doc->saveXML();
    $output = print_r($output, 1);
    // I added this because xml output and ajax do not like each others
    $output = htmlspecialchars($output);
    return $output;
}

?>


The DOMNotation class

(PHP 5, PHP 7)

类摘要

DOMNotation extends DOMNode {
/* 属性 */
public readonly string $publicId ;
public readonly string $systemId ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

publicId

systemId

User Contributed Notes

There are no user contributed notes for this page.


The DOMProcessingInstruction class

(PHP 5, PHP 7)

类摘要

DOMProcessingInstruction extends DOMNode {
/* 属性 */
public readonly string $target ;
public string $data ;
/* 继承的属性 */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public __construct ( string $name , string $value = "" )
/* 继承的方法 */
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

target

data

Table of Contents

  • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMProcessingInstruction object

  • ? DOMProcessingInstruction
  • DOMText ?
  • PHP Manual
  • DOMProcessingInstruction
  • Creates a new DOMProcessingInstruction object

DOMProcessingInstruction::__construct

(PHP 5, PHP 7)

DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

说明

public DOMProcessingInstruction::__construct ( string $name , string $value = "" )

Creates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createProcessingInstruction.

参数

name

The tag name of the processing instruction.

value

The value of the processing instruction.

范例

Example #1 Creating a new DOMProcessingInstruction object

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

以上例程会输出：

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

参见

  • DOMDocument::createProcessingInstruction() - Creates new PI node

User Contributed Notes

There are no user contributed notes for this page.


The DOMText class

(PHP 5, PHP 7)

简介

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

类摘要

DOMText extends DOMCharacterData {
/* 属性 */
public readonly string $wholeText ;
/* 继承的属性 */
public string $data ;
public readonly int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode|null $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode|null $firstChild ;
public readonly DOMNode|null $lastChild ;
public readonly DOMNode|null $previousSibling ;
public readonly DOMNode|null $nextSibling ;
public readonly DOMNamedNodeMap|null $attributes ;
public readonly DOMDocument|null $ownerDocument ;
public readonly string|null $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string|null $baseURI ;
public string $textContent ;
/* 方法 */
public __construct ( string $data = "" )
public isElementContentWhitespace ( ) : bool
public isWhitespaceInElementContent ( ) : bool
public splitText ( int $offset ) : DOMText|false
/* 继承的方法 */
public DOMCharacterData::appendData ( string $data ) : bool
public DOMCharacterData::deleteData ( int $offset , int $count ) : bool
public DOMCharacterData::insertData ( int $offset , string $data ) : bool
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : bool
public DOMCharacterData::substringData ( int $offset , int $count ) : string|false
public DOMNode::appendChild ( DOMNode $node ) : DOMNode|false
public DOMNode::C14N ( bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : string|false
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $withComments = false , array|null $xpath = null , array|null $nsPrefixes = null ) : int|false
public DOMNode::cloneNode ( bool $deep = false ) : DOMNode|false
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string|null
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $node , DOMNode|null $child = null ) : DOMNode|false
public DOMNode::isDefaultNamespace ( string $namespace ) : bool
public DOMNode::isSameNode ( DOMNode $otherNode ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespace ) : string|null
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $child ) : DOMNode|false
public DOMNode::replaceChild ( DOMNode $node , DOMNode $child ) : DOMNode|false
}

属性

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

Table of Contents

  • DOMText::__construct — Creates a new DOMText object
  • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
  • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
  • DOMText::splitText — Breaks this node into two nodes at the specified offset

User Contributed Notes

Trititaty 20-Oct-2016 11:47
Text replacement function for DOM.

<?php
function domTextReplace( $search, $replace, DOMNode &$domNode, $isRegEx = false ) {
  if ( $domNode->hasChildNodes() ) {
    $children = array();
    // since looping through a DOM being modified is a bad idea we prepare an array:
    foreach ( $domNode->childNodes as $child ) {
      $children[] = $child;
    }
    foreach ( $children as $child ) {
      if ( $child->nodeType === XML_TEXT_NODE ) {
        $oldText = $child->wholeText;
        if ( $isRegEx ) {
          $newText = preg_replace( $search, $replace, $oldText );
        } else {
          $newText = str_replace( $search, $replace, $oldText );
        }
        $newTextNode = $domNode->ownerDocument->createTextNode( $newText );
        $domNode->replaceChild( $newTextNode, $child );
      } else {
        domTextReplace( $search, $replace, $child, $isRegEx );
      }
    }
  }
}


Creates a new DOMText object

  • ? DOMText
  • DOMText::isElementContentWhitespace ?
  • PHP Manual
  • DOMText
  • Creates a new DOMText object

DOMText::__construct

(PHP 5, PHP 7)

DOMText::__construct — Creates a new DOMText object

说明

public DOMText::__construct ( string $data = "" )

Creates a new DOMText object.

参数

data

The value of the text node. If not supplied an empty text node is created.

范例

Example #1 Creating a new DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

参见

  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Thomas 27-Apr-2012 01:54
I experinced that DOMText, given a integer as only value to the constructor failed to return valid data. I had to typecast the input to a string first:

$intValue = 3252; // Post/Zip-code
$some_element->appendChild( new DOMText( (string) $intValue) );

When not typecasting using "(string)" the XML output from $root->saveXML() would not validate.


Returns whether this text node contains whitespace in element content

  • ? DOMText::__construct
  • DOMText::isWhitespaceInElementContent ?
  • PHP Manual
  • DOMText
  • Returns whether this text node contains whitespace in element content

DOMText::isElementContentWhitespace

(No version information available, might only be in Git)

DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content

说明

public DOMText::isElementContentWhitespace ( ) : bool

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

riking 28-Jun-2018 12:17
This is the recommended (W3C) function name for the equivalent:
http://php.net/manual/en/domtext.iswhitespaceinelementcontent.php

See there for additional notes.


Indicates whether this text node contains whitespace

  • ? DOMText::isElementContentWhitespace
  • DOMText::splitText ?
  • PHP Manual
  • DOMText
  • Indicates whether this text node contains whitespace

DOMText::isWhitespaceInElementContent

(PHP 5, PHP 7)

DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace

说明

public DOMText::isWhitespaceInElementContent ( ) : bool

Indicates whether this text node contains only whitespace or it is empty. The text node is determined to contain whitespace in element content during the load of the document.

返回值

Returns true if node contains zero or more whitespace characters and nothing else. Returns false otherwise.

User Contributed Notes

JITR 07-Jul-2007 03:36
To add to `permidion at yahoo dot com''s comment:

Quite true. According to DOM Level 3 Core, the `isWhitespaceInElementContent()' method indicates, whether the node contains `whitespace in element content' (or `element content whitespace' according to the newer spec), see [1].

Btw, it seems the `isWhitespaceInElementContent()' method was replaced with the `isElementContentWhitespace' attribute in the current W3C recommendation, see [2].

I have the feeling, though, it would be more precise with the word `only' added, like: `... indicates, whether the node contains *only* element content whitespace.' This would better correspond with the fact the result is false, when there are any non-whitespace characters present (in addition to the whitespace ones), as already noted.

[1] (please concatenate the following two lines)
http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html
#core-Text3-isWhitespaceInElementContent
[2] (please concatenate the following two lines)
http://www.w3.org/TR/DOM-Level-3-Core/core.html
#Text3-isElementContentWhitespace
permidion at yahoo dot com 28-Oct-2004 08:30
if you have an xml element such as <name>Foo Bar</name> (note the space), isWhitespaceInElementContent will return false.
However it will return true for <name><name> or <name/>
so, that function can be used to determine if the element has a text content or not


Breaks this node into two nodes at the specified offset

  • ? DOMText::isWhitespaceInElementContent
  • DOMXPath ?
  • PHP Manual
  • DOMText
  • Breaks this node into two nodes at the specified offset

DOMText::splitText

(PHP 5, PHP 7)

DOMText::splitText — Breaks this node into two nodes at the specified offset

说明

public DOMText::splitText ( int $offset ) : DOMText|false

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

After being split, this node will contain all the content up to the offset. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

参数

offset

The offset at which to split, starting from 0.

返回值

The new node of the same type, which contains all the content at and after the offset.

User Contributed Notes

Flix Cloutier 28-Oct-2013 05:31
It should be noted that $offset is a **character offset**, not a **byte offset**. This means that most other PHP string functions that deal with lengths and offsets (strlen, strpos, preg_match with PREG_OFFSET_CAPTURE, etc.) use and return values unsuitable for this method if used with multibyte strings (like UTF-8 strings).

Byte offsets can be converted to character offsets with mb_strlen:

<?php
function char_offset($string, $byte_offset, $encoding = null)
{
    $substr = substr($string, 0, $byte_offset);
    return mb_strlen($substr, $encoding ?: mb_internal_encoding());
}
?>


The DOMXPath class

(PHP 5, PHP 7)

简介

Supports XPath 1.0

类摘要

DOMXPath {
/* 属性 */
public DOMDocument $document ;
/* 方法 */
public __construct ( DOMDocument $document , bool $registerNodeNS = true )
public evaluate ( string $expression , DOMNode|null $contextNode = null , bool $registerNodeNS = true ) : mixed
public query ( string $expression , DOMNode|null $contextNode = null , bool $registerNodeNS = true ) : mixed
public registerNamespace ( string $prefix , string $namespace ) : bool
public registerPhpFunctions ( string|array|null $restrict = null ) : void
}

属性

document

Table of Contents

  • DOMXPath::__construct — Creates a new DOMXPath object
  • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
  • DOMXPath::query — Evaluates the given XPath expression
  • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
  • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

User Contributed Notes

TechNyquist 08-Jan-2020 09:16
When working with XML (as a strict format) might be very important to give a namespace to XPath object in order to make it work properly.

I was experiencing "query" always returning empty node lists, it could not find anything. Only a broad "//*" was able to show off only the root element.

Then found out that registering the namespace reported in the "xmlns" attribute of the root element in the XPath object, and writing the namespace near the elements name, made it work properly.

So for an XML like this (from a sitemap):

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://example.com/index.php</loc>
        <lastmod>2005-01-01</lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
</urlset>

I needed the following XPath configuration:

<?php

    $doc = new DOMDocument;
    $doc->load("sitemap.xml");
    $xpath = new DOMXPath($doc);
    $xpath->registerNamespace('ns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
    $nodes = $xpath->query('//ns:urlset/ns:url');

?>

Then again, that "xmlns" could be provided dynamically from the root element attribute of course.
peter at softcoded dot com 03-May-2017 05:51
You may not always know at runtime whether your file has
a namespace or not. This can make it difficult to create
XPath queries. Use the seriously underdocumented
"namespaceURI" property of the documentElement of a
DOMDocument to determine if there is a namespace.
Use code such as the following:

$doc = new DOMDocument();
$doc->load($file);
$xpath = new DOMXPath($doc);
$ns = $doc->documentElement->namespaceURI;
if($ns) {
  $xpath->registerNamespace("ns", $ns);
  $nodes = $xpath->query("//ns:em[@class='glossterm']");
} else {
  $nodes = $xpath->query("//em[@class='glossterm']");
}
//look at nodes here
peter at softcoded dot com 03-May-2017 04:46
Using XPath expressions can save a lot of programming
and allow you to home in on only the nodes you want.
Suppose you want to delete all empty <p> tags.
If you create a query using the following XPath expression,
you can find <p> tags that do not have any text
(other than spaces), any attributes,
any children or comments:

$expression = "//p[not(@*)
   and not(*)
   and not(./comment())
   and normalize-space(text())='']";

This expression will only find para tags that look like:

<p>[any number of spaces]</p>
<p></p>

Imagine the code you would have to add if you used
DOMDocument::getElementsByTagName("p") instead.
archimedix32783262 at mailinator dot com 03-Sep-2014 12:03
Note that evaluate() will use the same encoding as the XML document.

So if you have a UTF-16 XML, you will have to query using UTF-16 strings.

You can use iconv() to convert from your code's encoding to the target encoding for better legibility.
dhz 05-Jan-2011 10:47
I just spent far too much time chasing this one....

When running an xpath query on a table be careful about table internal nodes (ie: <tr></tr>, and <td></td>).  If the master <table> tag is missing, then query() (and likely evaluate() also) will return unexpected results.

I had a DOMNode with a structure like this:

<td>
    <table></table>
    <table>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
</td>

Upon which I was trying to do a relative query (ie: <?php $xpath_obj->query('my/x/path', $relative_node); ?>).

But because of the lone outer <td></td> tags, the inner tags were being invalidated, while the nodes were still recognized.  Meaning that the following query would work:

<?php $xpath_obj->query('*[2]/*[*[2]]', $relative_node); ?>

But when replacing any of the "*" tokens with the corresponding (and valid) "table", "tr", or "td" tokens the query would inexplicably break.
david at lionhead dot nl 11-Aug-2009 06:33
When using DOMXPath and having a default namespace. Consider using an intermediate function to add the default namespace to all queries:

<?php
// The default namespace: x:xmlns="http://..."
$path="/Book/Title";
$path=preg_replace("\/([a-zA-Z])","/x:$1",$path);

// Result: /x:Book/x:Title
?>
Mark Omohundro, ajamyajax dot com 14-Dec-2008 09:15
<?php
// to retrieve selected html data, try these DomXPath examples:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);

// example 1: for everything with an id
//$elements = $xpath->query("//*[@id]");

// example 2: for node data in a selected id
//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");

// example 3: same as above with wildcard
$elements = $xpath->query("*/div[@id='yourTagIdHere']");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>


Creates a new DOMXPath object

  • ? DOMXPath
  • DOMXPath::evaluate ?
  • PHP Manual
  • DOMXPath
  • Creates a new DOMXPath object

DOMXPath::__construct

(PHP 5, PHP 7)

DOMXPath::__construct — Creates a new DOMXPath object

说明

public DOMXPath::__construct ( DOMDocument $document , bool $registerNodeNS = true )

Creates a new DOMXPath object.

参数

document

The DOMDocument associated with the DOMXPath.

User Contributed Notes

thsoft at vipmail dot hu 04-Jul-2007 04:57
As of PHP 5.2.0, DOMXPath object implements XPath 1.0.
Saulo Vallory 26-Jun-2007 03:23
The DOMXPath object doesn't create a reference to the document. If you load a new xml using either load, loadXML or loadHTML functions the DOMXPath object will still query and evaluate over the source in the DOMDocument when it was created.


Evaluates the given XPath expression and returns a typed result if possible

  • ? DOMXPath::__construct
  • DOMXPath::query ?
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::evaluate

(PHP 5 >= 5.1.0, PHP 7)

DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible

说明

public DOMXPath::evaluate ( string $expression , DOMNode|null $contextNode = null , bool $registerNodeNS = true ) : mixed

Executes the given XPath expression and returns a typed result if possible.

参数

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

返回值

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

If the expression is malformed or the contextNode is invalid, DOMXPath::evaluate() returns false.

范例

Example #1 Getting the count of all the english books

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";

?>

以上例程会输出：

There are 2 english books

参见

  • DOMXPath::query() - Evaluates the given XPath expression

User Contributed Notes

danny at webdevelopers dot eu 28-Jan-2020 11:36
The only way how to distinguish FALSE returned value from syntax error FALSE is to re-run the XPath expression wrapped in string() function. If must return empty string. If it returns FALSE again then it is an error.

<?php

        $ret=$this->xp->evaluate($eval, $context);

        // Error detection: DOMXPath::evaluate() returns FALSE on error
        // so does DOMXPath::evaluate("boolean(/nothing)")
        // @workaround webdevelopers.eu
        if ($ret === false && $this->xp->evaluate("string($eval)", $context) === false) {
            throw new Exception("Invalid XPath expression ".json_encode($eval), 3491);
        }
?>
aazaharov81 at gmail dot com 14-Jan-2015 12:48
To query DOMNodes by their HTML classes, use such snippet
<?php

// CssClassXPathSelector
function ccxs($class) {
    return '[contains(concat(" ", normalize-space(@class), " "), " ' . $class . ' ")]';
}

 // then just
 $domitems = $this->xpath("//*[@id='searchResultsRows']//a" . ccxs('listing_row'));
?>
daniel at danielnorton dot com 25-Jun-2011 09:56
Note that this method does not provide any means to distinguish between a successful result that returns FALSE and an error.

For example, this will succeed and return FALSE:

<?php $xpath->evaluate("1 = 0"); ?>

One workaround when you know you are expecting a Boolean is to wrap the result with string(). e.g.

<?php $xpath->evaluate("string(1 = 0)"); ?>

This will return a string "false" on success, or the Boolean FALSE on error.
Damien Bezborodov 28-Mar-2011 06:13
If your expression returns a node set, you will get a DOMNodeList instead of a typed result. Instead, try modifying your expression from "//node[1]" to "string(//node[1])".
yuriucsal at NOSPAM dot yahoo dot com dot br 06-Mar-2005 12:55
this class can substitute the method evaluate while it is not validated. Made for Yuri Bastos and Jo?o Gilberto Magalh?es.

<?php

    class XPtahQuery
    {
        // function returns a DOMNodeList from a relative xPath
        public static function selectNodes($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNodeList = $domXPath->query($xPathQueryFull);

                return $rNodeList;
        }
        // function returns a DOMNode from a xPath from other DOMNode
        public static function selectSingleNode($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNode = $domXPath->query($xPathQueryFull)->item(0);

                return $rNode;
        }
        //utilitaries functions off selectSingleNode
        private function getNodePos($pNode, $nodeName)
        {
            if($pNode == null)
                {
                        return 0;
            }
            else
            {
                $var = 0;
                    if ($pNode->previousSibling != null)
                    {
                    if ($pNode->previousSibling->nodeName == $nodeName)
                    {
                        $var = 1;
                    }
                    }
                    return self::getNodePos($pNode->previousSibling, $nodeName) + $var;
            }
        }
        //utilitaries functions off selectSingleNode
        private function getFullXpath($pNode)
        {
            if($pNode == null)
                {
                        return "";
            }
            else
            {

                return self::getFullXpath($pNode->parentNode) . "/" . $pNode->nodeName . "[" .strval(self::getNodePos($pNode, $pNode->nodeName)+1) . "]";//+1 to get the real xPath index

            }
        }
    }
?>


Evaluates the given XPath expression

  • ? DOMXPath::evaluate
  • DOMXPath::registerNamespace ?
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression

DOMXPath::query

(PHP 5, PHP 7)

DOMXPath::query — Evaluates the given XPath expression

说明

public DOMXPath::query ( string $expression , DOMNode|null $contextNode = null , bool $registerNodeNS = true ) : mixed

Executes the given XPath expression.

参数

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

返回值

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.

If the expression is malformed or the contextNode is invalid, DOMXPath::query() returns false.

范例

Example #1 Getting all the english books

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// We start from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

以上例程会输出：

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

We can also use the contextNode parameter to shorten our expression:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

参见

  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

User Contributed Notes

chris dot russo99 at gmail dot com 17-Aug-2016 03:58
If you can't find a solution for PHP XPATH case sensitivity, you can always try this approach:

http://fsockopen.com/php-programming/your-final-stop-for-php-xpath-case-insensitive

Instead of inserting PHP functions into a XPATH object, convert the XPATH object into an Array(), and then use any PHP function, the regular way.
ikmahesh at cdac dot in 08-Jul-2015 09:29
The parameters for $xPath->query() method is case sensitive.
It matches IDs exact words.
RiKdnUa at mail dot ru 17-Sep-2013 04:26
Пример XPath запроса к XML документу. XML документ содержить элементы с именами из НЕлатинских символов (кириллица). При использовании в XPath запросе предиката, функция DOMXPath::query() выдает предупреждение и запрос не работает. Чтобы запрос работал, надо явно указывать ось. Файл этого примера должен быть в кодировке WINDOWS-1251. Тестировал в PHP 5.2.9-2 и PHP 5.2.17

Example XPath-query to the XML-document. XML-document contains an elements with the names of non-Latin characters (cyrillic). When used predicate in XPath-query, function DOMXPath::query() gives a warning and query does not work. In order to earned the query, it is necessary to explicitly specify the axis. The file of this example is to be in the encoding WINDOWS-1251. Tested in PHP 5.2.9-2 and PHP 5.2.17
<?php
ini_set("display_errors","on");
error_reporting(-1);
function utf8encode($str){return iconv('WINDOWS-1251', 'UTF-8', $str);}
$xml="<?xml version='1.0' encoding='WINDOWS-1251'?>
<часть>
<ссылка href='yandex.com'>Яндекс</ссылка>
<ссылка href='rik.dn.ua/fotopan.php'>г.Донецк</ссылка>
</часть>
";
$document=new domDocument();
$document->preserveWhiteSpace=false;
$document->loadXML($xml);
$domxpath=new domXpath($document);
$list=$domxpath->query(utf8encode('/child::часть/child::ссылка'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/часть/ссылка'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/child::часть/child::ссылка[position()=1]'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/часть/ссылка[1]'));//Warning: DOMXPath::query() [domxpath.query]: Invalid expression in ...
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/часть/ссылка[position()=1]'));//Warning: DOMXPath::query() [domxpath.query]: Invalid expression in ...
echo '$list->length='.$list->length."\n<br/>\n";
?>
info at syncgw dot com 22-Sep-2011 09:05
A warning to all PHP programmer using this function PHP 5.0.0.0: We needed an equivalent to upper-case() function (is not available in XPath 1.0).

XML-Document:

<Rec>
<SourceRef>./c:calendar2</SourceRef>
<SourceRef>./c:calendar</SourceRef>
</Rec>

using

query('//DataStore[translate(SourceRef,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ")="./C:CALENDAR"]/.')

returns ZERO matches.

If you change XML-Source to

<Rec>
<SourceRef>./c:calendar</SourceRef>
<SourceRef>./c:calendar2</SourceRef>
</Rec>

everything works fine
yuriscom at gmail dot com 07-Sep-2011 10:29
I hope it will be helpful for someone:

I spent some time to solve the problem when you query a string with quotes inside.

Suppose you have:
$parameter = "aaa \"bbb\"";
$domxpath->query("//path[text()=\"".$parameter."\""];

In versions > 5.3.0 there is registerPhpFunctions where you can put an addslashes. But in older version you cannot do it in simple way.

So the solution is to use a concat function. So when you have a substring with " inside, wrap it with '. And when you have a substring with ', then wrap with in ".

The code is:

<?php
$dom = new DOMDocument;
$dom->loadXML("<name>'bla' \"bla\" bla</name>");
$xpath = new DOMXPath($dom);
$nodeList = $xpath->query("//name[text()=concat(\"'bla' \" ,'\"bla\"' ,\" bla\")]");
?>

Below is the function that receives a string and returns a concat pattern for the xpath query.

<?php
    function getPattern_MQ($pattern) {
        // initiating an array of substrings
        $ar = array();
        // points to the current position in a string
        $offset = 0;
        $strlen = strlen($pattern);
        while (true) {
            // find a position of quotes
            $qPos = strpos($pattern, "\"", $offset);

            if (!$qPos) {
                // no more quotes
                $leftOver = $offset - $strlen;
                if ($leftOver < 0) {
                    $string = substr($pattern, $leftOver);
                    $ar[] = "\"" . $string . "\"";
                }
                break;
            }
            // add the whole substring before the quotes into the array
            $ar[] = "\"" . substr($pattern, $offset, ($qPos - $offset)) . "\"";
            // add the quotes wrapped with single quot
            $ar[] = "'" . substr($pattern, $qPos, 1) . "'";
            $offset = $qPos + 1;
        }
        // join the array to get: concat("aaa",'"',"bbb",'"');
        $pattern = "concat(''," . join(",", $dynamicPatternsAr) . ")";
        return $pattern;
    }
?>
chris AT cmbuckley DOT co DOT uk 14-Apr-2011 07:31
To help with the problem where the default namespace is not registered with the DOMXPath object, you can use the following replacement to update your paths accordingly:

<?php

$xml = <<<EOS
<root xmlns="urn:test">
    <foo>bar</foo>
</root>
EOS;

$expression = '//foo';
$prefix = 'fakeprefix';

$doc = new DOMDocument();
$doc->loadXML($xml);

$context = $doc->documentElement; // or whichever element you choose
$xpath = new DOMXPath($doc);

// register namespace as below, and apply a regex to the expression
if (null !== $context->namespaceURI) {
    $xpath->registerNamespace($prefix, $context->namespaceURI);
    $expression = preg_replace('#(::|/\s*|\A)(?![/@].+?|[a-z\-]+::)#', '$1' . $prefix . ':$2', $expression);
    var_dump($expression); // string(16) "//fakeprefix:foo"
}

$foo = $xpath->query($expression, $context)->item(0);
var_dump($doc->saveXML($foo)); // string(14) "<foo>bar</foo>"

?>
kkez at example dot com 03-Sep-2010 07:51
If the query() function seems to ignore your $contextnode, and instead returns all the tags in the document, try to use a relative path (use a . in front of the query):

<?php
    $xml = "<?xml version='1.0' encoding='UTF-8'?>
        <test>
            <tag1>
                <uselesstag>
                    <tag2>test</tag2>
                </uselesstag>
            </tag1>
            <tag2>test2</tag2>
        </test>";

    $dom = new DomDocument();
    $dom->loadXML($xml);
    $xpath = new DomXPath($dom);

    $tag1 = $dom->getElementsByTagName("tag1")->item(0);

    echo $xpath->query("//tag2")->length; //output 2 -> correct
    echo $xpath->query("//tag2", $tag1)->length; //output 2 -> wrong, the query is not relative
    echo $xpath->query(".//tag2", $tag1)->length; //output 1 -> correct (note the dot in front of //)
?>

See that i couldn't use $xpath->query("tag2", $tag1) as per the documentation, since "tag2" is not a direct child of "tag1".
I don't know why this note was deleted, i just tested it and it's correct.
It's not a bug, it's simply not written in the documentation.
Anonymous 27-Nov-2009 12:26
I found this useful for building page templates

<?php
$xsl = new DOMDocument;
$xsl->load('layout.xsl');

// Set the <xsl:include> href attribute, the inner stylesheet to include in this layout
$xpath = new DomXPath($xsl);
$res = $xpath->query('//xsl:include');
$res->item(0)->setAttribute('href','page.xsl');
$xsl->save('media/xsl/layout.xsl');
?>
Niklas 27-Aug-2008 02:36
For XPath escaping use the following method (of course it could be more efficient).
<?php
public function xpathescape($string)
{
$result = 'concat(';

for($i=0, $j=strlen($string); $i<$j; ++$i)
{
if($i > 0)
$result .= ",";

if($string[$i] == '\'')
$result .= "\"".$string[$i]."\"";
else
$result .= '\''.$string[$i].'\'';
}

$result .= ')';

return $result;
}
?>

Use it this way:
<php
$xpath->query('//example[sub='.xpathescape($acomplexstring).']');

?>
adam dot prall at thinkingman dot com 19-Jul-2008 09:01
If you're wondering, like I was, why your XPath queries are not returning any of the new DOMElements you create in your (X)HTML documents, and only the ones originally loaded in with (for example) loadXML(), this is why; if you're doing things right, you have registered the nameSpace 'html' after creating your DOMXPath object thus:

<?php

class XPathQueryLength {
     private $nameSpace = '';
     function __construct(DOMDocument $doc) {
          $this->xpath = new DOMXPath($this->doc);
          $this->xpath->registerNamespace(
                 'html','http://www.w3.org/1999/xhtml' );
     }
     function queryLength($query) {
          return $this->xpath->query($query)->length;
     }
}

?>

...but don't forget that when adding new elements to the above DOMDocument $doc, to use createElementNS() instead of createElement(), otherwise you'll have this problem:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElement('p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 0

print $xPath->queryLength('//p');

output: 1

?>

So do this instead:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElementNS('http://www.w3.org/1999/xhtml','p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 2

print $xPath->queryLength('//p');

output: 0

?>

The resulting XHTML file from both example scripts looks much like this:

<html>
  <head></head>
  <body>
     <p>This is a hardcoded paragraph.</p>
     <p>This is a new paragraph!</p>
  </body>
</html>

...so you would think that a paragraph is a paragraph is a paragraph, since you never see the prefix, as in "<html:p>This is a new paragraph!</html:p>".

This may seem glaringly obvious, but I was writing a class that converts CSS queries into XPath queries, and the fact that a namespace had been registered was rather buried in the code.

We love the DOM, the DOM is good to us.
Nibinaear 03-Mar-2008 06:15
I've searched the entire web looking for a way to update / modify/ change/ alter the elements of an xml file and found NOTHING!

So here it is, the defninitive way to "Change XML elements with PHP" rather than adding / appending new ones. This uses XPATH:

<?php

// Create a DOMDocument instance
$xml = new DOMDocument;

// Ignore whitespace between nodes (default: true)
$xml->preserveWhiteSpace = false;

$file='about.xml';

// Load the XML data source
$xml->Load($file);

$xpath = new DOMXPath($xml);

$query='/regions/branch';

$entries = $xpath->query($query);

foreach ($entries as $entry)
{
  $entry->firstChild->nodeValue="like this!";
  echo $entry->firstChild->nodeValue;
}

$xml->save($file);

?>
ondrej dot fischer at 4internet dot cz 25-Oct-2007 06:46
Unfortunately PHP's DOM extension doesn't support use of:
<?xml-stylesheet type="text/xsl" ... ?>
processing instruction.
Here is an example, how to implement it using XPath query and extending DOMDocument by a method output().

<?php

// This simple function adds missing direct usage of anonymous instances
// in PHP5's reference model
function a($var) {
   return $var;
}

// Extended DOMDocument class
class MyDOMDocument extends DOMDocument
{

   public function output()
   {
      $stylesheets = array();
      $PIs = a(new DOMXPath($this))
                  ->query('/processing-instruction("xml-stylesheet")');

      foreach($PIs as $PI)
      {
         // This might be implemented cleaner by regular parsing
         // of DOMProcessingInstruction::data property
         if(ereg('type *= *"text/xsl" +href *= *"([^"]+)"', $PI->data, $mem))
         {
            // Here should be verified, that XSL file exists.
            a($stylesheets[] = new DOMDocument())->load($mem[1]);
         }
      }

      if($stylesheets)
      {
         $processor = new XSLTProcessor();
         foreach($stylesheets as $stylesheet)
            $processor->importStylesheet($stylesheet);
         return $processor->transformToDoc($this);
      }
      // If no stylesheet instructions present, return self directly
      else return $this;

   }
}

?>

Usage:

<?php

$document = new MyDOMDocument();
$document->load('my.xml');
echo $document->output()->saveXML();

?>

With following file my.xml:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="my.xsl" ?>
<my-root />

and existing file my.xsl that code will transform the xml file using my.xsl and output the result.
jbarnett at flowershopnetwork dot com 11-Sep-2007 01:46
The order of nodes in the return value is not guaranteed.

When my code was on an old server, the returned DOMNodeList was in document order.  On the new server, the returned DOMNodeList is in a consistent order, but it is not in document order.

PHP passes this function call off to the xmlXPathEvalExpression() function in libxml.  That function in libxml only accepts two arguments - the same two this PHP function accepts.  There must have been a change in the libxml version from the old server to the new server, and that libxml behaves differently.

This would be okay if PHP had a way to compare nodes so I can resort the nodes manually, but there is not.

So, there is no guaranteed way to get an ordered list of nodes like DOM 3 XPath provides.
Hayley Watson 12-Aug-2007 05:43
Note that if your DOMDocument was loaded from HTML, where element and attribute names are case-insensitive, the DOM parser converts them all to lower-case, so your XPath queries will have to as well; '//A/@HREF' won't find anything even if the original HTML contained "<A HREF='example.com'>".
nicolas_rainardNOSPAM at yahoo dot fr 10-Jul-2007 02:04
Please note that what clochix says is valid for *any* document which has a default namespace (as it is the case for XHTML).

This document :

<?xml version="1.0" encoding="UTF-8" ?>

<root xmlns="http://www.exemple.org/namespace">

    <element id="1">
    ...
    </element>

    <element id="2">
    ...
    </element>

</element>

must be accessed this way :

$document = new DOMDocument();
$document->load('document.xml');

$xpath = new DOMXPath($document);
$xpath->registerNameSpace('fakeprefix', 'http://www.exemple.org/namespace');

$elements = $xpath->query('//fakeprefix:element');

Of course, there is no prefix in the original document, but the DOMXPath class *needs* one, whatever it is, if you use a default namespace. It *doesn't work* if you specify an empty prefix like this :

$xpath->registerNameSpace('', 'http://www.exemple.org/namespace');

Hope this help to spare some time...
clochix at clochix dot net 01-Mar-2007 04:05
If you want to perform queries on XHTML documents, you must fix a default namespace:

<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = true;
$doc->resolveExternals = true; // for character entities
$doc->load("http://www.w3.org/");
$xpath = new DOMXPath($doc);
// won't work
$entries = $xpath->query("//div");
// you should use :
$xpath->registerNamespace("html", "http://www.w3.org/1999/xhtml");
$entries = $xpath->query("//html:div");
?>
jakob dot voss at nichtich dot de 14-Nov-2005 12:33
You can transform the result nodes into new DOMDocument objects this way:

<?php
$result = $xpath->query($query);
$resultNode = $result->item(0);
$newDom = new DOMDocument;
$newDom->appendChild($newDom->importNode($resultNode,1));

print "<pre>" . htmlspecialchars($newDom->saveXML()) . "</pre>";
?>
Eric Hanson 12-Jul-2005 05:40
Two great XPath references follow.

XPath in Five Paragraphs (finally!):
http://www.rpbourret.com/xml/XPathIn5.htm

The w3c spec actually has a bunch of helpful examples:
http://www.w3.org/TR/xpath#location-paths


Registers the namespace with the DOMXPath object

  • ? DOMXPath::query
  • DOMXPath::registerPhpFunctions ?
  • PHP Manual
  • DOMXPath
  • Registers the namespace with the DOMXPath object

DOMXPath::registerNamespace

(PHP 5, PHP 7)

DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object

说明

public DOMXPath::registerNamespace ( string $prefix , string $namespace ) : bool

Registers the namespace and prefix with the DOMXPath object.

参数

prefix

The prefix.

namespace

The URI of the namespace.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

igor dot pellegrini at diespam-berlinonline dot de 10-Mar-2015 07:32
The documentation is not really detailed.
Probably someone is also interested in the possibility of unregistering the namespace.

Worths to note that the original libxml function "xmlXPathRegisterNs()"

* Does NOT accept NULL or empty string for the argument "$prefix".

   and

* Unregisters the namespace if the "$namespaceURI" argument is NULL.

Here the documentation:
http://xmlsoft.org/html/libxml-xpathInternals.html#xmlXPathRegisterNs
xmedeko at gmail dot com 20-Sep-2011 04:58
A general way to register the root default namespace:

<?php
$xml = new DomDocument();
$xml->load('data.xml');
$xpath = new DOMXPath($xml);
$rootNamespace = $xml->lookupNamespaceUri($xml->namespaceURI);
$xpath->registerNamespace('x', $rootNamespace);
?>

And then just query:

<?php $elementList = $xpath->query('//x:items/x:name'); ?>
dulao5 at gmail dot com 16-Jun-2009 12:01
The following code can work for XML default namespace.
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:other="http://other.w3.org/other" >
        <id>uYG7-sPwjFg</id>
        <published>2009-05-17T18:29:31.000Z</published>
</entry>
EOT;

$doc = new DOMDocument;
$doc->loadXML($xml);
$xpath =  DOMXPath($doc);

$xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");

$xpath_str = '//atom:entry/atom:published/text()';

$entries = $xpath->evaluate($xpath_str);

print $entries->item(0)->nodeValue ."\n";

?>
agent009 31-Mar-2009 04:55
Ok, here's a function that extends XPath syntax with the following special characters:

~ inserts default namespace prefix if defined

# shorthand for text()

% shorthand for comment()

$ shorthand for node()

?* shorthand for processing-instruction()

?foo shorthand for processing-instruction("foo")

? shorthand for processing-instruction("")

^ escapes following character (with literal or SGML entity as needed)

All of the above except ^ are ignored within quoted strings

<?php
function extendXPath($str, $defns = NULL) {
   $quote = false;
   $map = array(
      '~' => isset($defns) ? "$defns:" : '',
      '#' => 'text()',
      '%' => 'comment()',
      '$' => 'node()'
   );
   $out = '';

   for ($i = 0, $len = strlen($str); $i < $len; $i++) {
      $c = $str[$i];
      if (!$quote && array_key_exists($c, $map)) {
         $out .= $map[$c];
      } else switch ($c) {
         case '^':
            $out .= htmlspecialchars($str[++$i], ENT_QUOTES);
            break;
         case '?':
            if ($quote) {
               $out .= $c;
            } elseif ($str[$i + 1] == '*') {
               $out .= 'processing-instruction()';
               $i++;
            } else {
               preg_match('/^\w+/', substr($str, $i + 1), $matches);
               $out .= 'processing-instruction("'.$matches[0].'")';
               $i += strlen($matches[0]);
            };
            break;
         case '"':
            $quote = !$quote;
         default:
            $out .= $c;
      };
   };

   return $out;
}
?>
cameron kellough 14-Apr-2007 10:33
This is called prefix mapping and it is necessary to use xpath to handle documents which have default namespaces. //root/item will search for items with no namespace, not items with the namespace described as the default in the xmlns declaration.  This problem is maddening as it just looks on the surface like xpath isn't working.
spam at spam dot spam 31-Mar-2005 12:46
It is mentioned in a few places on the web, but it wasn't mentioned here. You need to use this function to set up a prefix for the default namespace of a document.

For instance, if you are trying to parse a Microsoft Spreadsheet XML file, which has the default namespace of "urn:schemas-microsoft-com:office:spreadsheet":

$doc = DOMDocument::load("my_spreadsheet.xml);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace("m",
        "urn:schemas-microsoft-com:office:spreadsheet");
$query = '/m:Workbook/m:Worksheet[1]/m:Table';
$result = $xpath->query($query, $doc);

You can use anything in place of the 'm', but you have to specify something! Just asking for "/Workbook/Worksheet/Table" doesn't work.


Register PHP functions as XPath functions

  • ? DOMXPath::registerNamespace
  • DOM 函数 ?
  • PHP Manual
  • DOMXPath
  • Register PHP functions as XPath functions

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0, PHP 7)

DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

说明

public DOMXPath::registerPhpFunctions ( string|array|null $restrict = null ) : void

This method enables the ability to use PHP functions within XPath expressions.

参数

restrict

Use this parameter to only allow certain functions to be called from XPath.

This parameter can be either a string (a function name) or an array of function names.

返回值

没有返回值。

范例

The following examples use book.xml which contains the following:

Example #1 book.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
 <book>
  <title>PHP Basics</title>
  <author>Jim Smith</author>
  <author>Jane Smith</author>
 </book>
 <book>
  <title>PHP Secrets</title>
  <author>Jenny Smythe</author>
 </book>
 <book>
  <title>XML basics</title>
  <author>Joe Black</author>
 </book>
</books>

Example #2 DOMXPath::registerPHPFunctions() with php:functionString

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();

// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "Found {$nodes->length} books starting with 'PHP':\n";
foreach ($nodes as $node) {
    $title  = $node->getElementsByTagName("title")->item(0)->nodeValue;
    $author = $node->getElementsByTagName("author")->item(0)->nodeValue;
    echo "$title by $author\n";
}

?>

以上例程的输出类似于：

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Example #3 DOMXPath::registerPHPFunctions() with php:function

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
    // Return true if more than one author
    return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Books with multiple authors:\n";
foreach ($books as $book) {
    echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

以上例程的输出类似于：

Books with multiple authors:
PHP Basics

参见

  • DOMXPath::registerNamespace() - Registers the namespace with the DOMXPath object
  • DOMXPath::query() - Evaluates the given XPath expression
  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

User Contributed Notes

There are no user contributed notes for this page.


DOM 函数

Table of Contents

  • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

User Contributed Notes

There are no user contributed notes for this page.


Gets a DOMElement object from a SimpleXMLElement object

  • ? DOM 函数
  • libxml ?
  • PHP Manual
  • DOM 函数
  • Gets a DOMElement object from a SimpleXMLElement object

dom_import_simplexml

(PHP 5, PHP 7)

dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

说明

dom_import_simplexml ( object $node ) : DOMElement|null

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

参数

node

The SimpleXMLElement node.

返回值

The DOMElement node added or false if any errors occur.

范例

Example #1 Import SimpleXML into DOM with dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
    echo 'Error while parsing the document';
    exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Error while converting XML';
    exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

参见

  • simplexml_import_dom() - Get a SimpleXMLElement object from a DOM node

User Contributed Notes

h4ss4n3 at hyj4z1 dot me 08-Sep-2020 08:08
//No need to initiate, import and append on example#1

(...)
$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Erreur lors de la conversion du XML';
    exit;
}

//$dom = new DOMDocument('1.0');
//$dom_sxe = $dom->importNode($dom_sxe, true);
//$dom_sxe = $dom->appendChild($dom_sxe);

//use ownerDocument propertie
echo $dom->ownerDocument->saveXML();

?>
biniou at yopmail dot com 20-May-2016 09:58
Very useful to add a CDATA node with SimpleXMLElement (use it like addChild) :

<?php
class My_SimpleXMLElement extends SimpleXMLElement {

    public function addChildWithCData($name, $value = NULL) {
        $new_child = $this->addChild($name);

        $node = dom_import_simplexml($new_child);
        $no = $node->ownerDocument;
        $node->appendChild($no->createCDATASection($value));

        return $new_child;
    }
}
Jeff M 06-Mar-2009 01:09
SimpleXML is an 'Object Mapping XML API'. It is not DOM, per se. SimpleXML converts the XML elements into PHP's native data types.

The dom_import_simplexml and simplexml_import_dom functions do *not* create separate copies of the original object. You are free to use the methods of either or both interchangeably, since the underlying instance is the same.

<?php
    // initialize a simplexml object
    $sxe = simplexml_load_string('<root/>');

    // get a dom interface on the simplexml object
    $dom = dom_import_simplexml($sxe);

    // dom adds a new element under the root
    $element = $dom->appendChild(new DOMElement('dom_element'));

    // dom adds an attribute on the new element
    $element->setAttribute('creator', 'dom');

    // simplexml adds an attribute on the dom element
    $sxe->dom_element['sxe_attribute'] = 'added by simplexml';

    // simplexml adds a new element under the root
    $element = $sxe->addChild('sxe_element');

    // simplexml adds an attribute on the new element
    $element['creator'] = 'simplexml';

    // dom finds the simplexml element (via DOMNodeList->index)
    $element = $dom->getElementsByTagName('sxe_element')->item(0);

    // dom adds an attribute on the simplexml element
    $element->setAttribute('dom_attribute', 'added by dom');

    echo ('<pre>');
    print_r($sxe);
    echo ('</pre>');
?>

Outputs:

SimpleXMLElement Object
(
    [dom_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => dom
                    [sxe_attribute] => added by simplexml
                )

        )

    [sxe_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => simplexml
                    [dom_attribute] => added by dom
                )

        )

)

What this illustrates is that both interfaces are operating on the same underlying object instance. Also, when you dom_import_simplexml, you can create and add new elements without reference to an ownerDocument (or documentElement).

So passing a SimpleXMLElement to another method does not mean the recipient is limited to using SimpleXML methods.

Hey Presto! Your telescope has become a pair of binoculars!
crescentfreshpot at yahoo dot com 12-Dec-2007 12:22
justinpatrin at php dot net:
> To get a proper DOM document (which you need to do most things) you need...

No you don't. Just do:
<?php
$dom = dom_import_simplexml($xml)->ownerDocument;
?>
justinpatrin at php dot net 01-Jun-2006 09:44
I've found that newer versions of PHP5 require some special syntax in order to properly convert between SimpleXML and DOM. It's not as easy as calling dom_import_simplexml() with a SimpleXML node. To get a proper DOM document (which you need to do most things) you need:
<?php
//$xml is a SimpleXML instance
$domnode = dom_import_simplexml($xml);
$dom = new DOMDocument();
$domnode = $dom->importNode($domnode, true);
$dom->appendChild($domnode);
?>

Switching back, though, is, well...simple.

<?php
//$dom is a DOMDocument instance
$xml = simplexml_import_dom($dom);
?>


libxml

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • libXMLError — The libXMLError class
  • libxml 函数
    • libxml_clear_errors — Clear libxml error buffer
    • libxml_disable_entity_loader — Disable the ability to load external entities
    • libxml_get_errors — Retrieve array of errors
    • libxml_get_last_error — Retrieve last error from libxml
    • libxml_set_external_entity_loader — Changes the default external entity loader
    • libxml_set_streams_context — Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

User Contributed Notes

There are no user contributed notes for this page.


简介

These functions/constants are available as of PHP 5.1.0, and the following core extensions rely on this libxml extension: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XML, XMLReader, XMLRPC 和 XMLWriter.

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires » libxml >= 2.6.0.

User Contributed Notes

There are no user contributed notes for this page.


安装

The libxml extension is enabled by default, although it may be disabled with --disable-libxml.

The optional --with-libxml-dir directive is used to specify the location of libxml on the system that PHP is being compiled on, otherwise only the default locations are scanned. The configure process checks for libxml (specifically, xml2-config) in the following order:

  1. The location ([DIR]) specified with --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

If configure cannot find xml2-config in the directory specified by --with-libxml-dir, then it'll continue on and check the default locations.

User Contributed Notes

fred5 at no dot spam dot co dot za 31-Jul-2014 10:29
(I tried to enter a bug but the PHP version selection drop down isn't working so I have entered here)

This documentation is very confusing as it refers to xml2-config as a directory and file interchangeably (it is a file) ...so I'm not clear whether to use the containing directory or the actual file in the switch


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

LIBXML_BIGLINES (int)
Allows line numbers greater than 65535 to be reported correctly.

Note:

Only available as of PHP 7.0.0 with Libxml >= 2.9.0

LIBXML_COMPACT (int)
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.

Note:

Only available in Libxml >= 2.6.21

LIBXML_DTDATTR (int)
Default DTD attributes
LIBXML_DTDLOAD (int)
Load the external subset
LIBXML_DTDVALID (int)
Validate with the DTD
LIBXML_HTML_NOIMPLIED (int)
Sets HTML_PARSE_NOIMPLIED flag, which turns off the automatic adding of implied html/body... elements.

Note:

Only available in Libxml >= 2.7.7 (as of PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (int)
Sets HTML_PARSE_NODEFDTD flag, which prevents a default doctype being added when one is not found.

Note:

Only available in Libxml >= 2.7.8 (as of PHP >= 5.4.0)

LIBXML_NOBLANKS (int)
Remove blank nodes
LIBXML_NOCDATA (int)
Merge CDATA as text nodes
LIBXML_NOEMPTYTAG (int)
Expand empty tags (e.g. <br/> to <br></br>)

Note:

This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.

LIBXML_NOENT (int)
Substitute entities
Caution

Enabling entity substitution may facilitate XML External Entity (XXE) attacks.

LIBXML_NOERROR (int)
Suppress error reports
LIBXML_NONET (int)
Disable network access when loading documents
LIBXML_NOWARNING (int)
Suppress warning reports
LIBXML_NOXMLDECL (int)
Drop the XML declaration when saving a document

Note:

Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (int)
Remove redundant namespace declarations
LIBXML_PARSEHUGE (int)
Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document or the entity recursion, as well as limits of the size of text nodes.

Note:

Only available in Libxml >= 2.7.0 (as of PHP >= 5.3.2 and PHP >= 5.2.12)

LIBXML_PEDANTIC (int)
Sets XML_PARSE_PEDANTIC flag, which enables pedantic error reporting.

Note:

Available as of PHP >= 5.4.0

LIBXML_XINCLUDE (int)
Implement XInclude substitution
LIBXML_ERR_ERROR (int)
A recoverable error
LIBXML_ERR_FATAL (int)
A fatal error
LIBXML_ERR_NONE (int)
No errors
LIBXML_ERR_WARNING (int)
A simple warning
LIBXML_VERSION (int)
libxml version like 20605 or 20617
LIBXML_DOTTED_VERSION (string)
libxml version like 2.6.5 or 2.6.17
LIBXML_SCHEMA_CREATE (int)
Create default/fixed value nodes during XSD schema validation

Note:

Only available in Libxml >= 2.6.14 (as of PHP >= 5.5.2)

User Contributed Notes

vetalstar at mail dot ru 16-Nov-2017 12:26
LIBXML_DOTTED_VERSION option doesn't work.
libxml version: 2.9.4

<?php

echo LIBXML_DOTTED_VERSION;
$xml = new SimpleXMLElement('<fasa_request id="1234567"/>', LIBXML_NOXMLDECL);

?>
@oneseventeen 05-Feb-2011 11:51
When inserting XML DOM Elements inside existing XML DOM Elements that I loaded from an XML file using the following code, none of my new elements were formatted correctly, they just showed up on one line:

<?php
$dom = DOMDocument::load('file.xml');
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks normal but the new nodes are all on one line.
?>

I found I could pass LIBXML_NOBLANKS to the load method and it would reformat the whole document, including my added stuff:
<?php
$dom = DOMDocument::load('file.xml', LIBXML_NOBLANKS);
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks newly formatted, including new nodes
?>

Hope this helps, took me hours of trial and error to figure this out!
zachatwork at gmail dot com 09-Feb-2010 11:30
Note: The LIBXML_NOXMLDECL constant is defined in this library but is not supported by DOMDocument (yet).

See also: http://bugs.php.net/bug.php?id=47137

<?php

print "PHP_VERSION:      ".PHP_VERSION."\n";
print "LIBXML_VERSION:   ".LIBXML_VERSION."\n";
print "LIBXML_NOXMLDECL: ".LIBXML_NOXMLDECL."\n";

$dom = new DomDocument();
$dom->loadXML("<foo />");

# This should work but doesn't.

print "DOMDocument doesn't honor LIBXML_NOXMLDECL:\n";
print $dom->saveXML(null,LIBXML_NOXMLDECL);

# This works, and will still work after the above is fixed.

print "Forwards compatible workaround:\n";
$lines = explode("\n", $dom->saveXML(null, LIBXML_NOXMLDECL), 2);
if(!preg_match('/^\<\?xml/', $lines[0]))
    print $lines[0];
print $lines[1];

?>

PHP_VERSION:      5.3.1-0.dotdeb.1
LIBXML_VERSION:   20632
LIBXML_NOXMLDECL: 2
DOMDocument doesn't honor LIBXML_NOXMLDECL:
<?xml version="1.0"?>
<foo/>
Forwards compatible workaround:
<foo/>


The libXMLError class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

类摘要

libXMLError {
/* 属性 */
public int $level ;
public int $code ;
public int $column ;
public string $message ;
public string $file ;
public int $line ;
}

属性

level

the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)

code

The error's code.

column

The column where the error occurred.

Note:

This property isn't entirely implemented in libxml and therefore 0 is often returned.

message

The error message, if any.

file

The filename, or empty if the XML was loaded from a string.

line

The line where the error occurred.

User Contributed Notes

There are no user contributed notes for this page.


libxml 函数

Table of Contents

  • libxml_clear_errors — Clear libxml error buffer
  • libxml_disable_entity_loader — Disable the ability to load external entities
  • libxml_get_errors — Retrieve array of errors
  • libxml_get_last_error — Retrieve last error from libxml
  • libxml_set_external_entity_loader — Changes the default external entity loader
  • libxml_set_streams_context — Set the streams context for the next libxml document load or write
  • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

User Contributed Notes

There are no user contributed notes for this page.


Clear libxml error buffer

  • ? libxml 函数
  • libxml_disable_entity_loader ?
  • PHP Manual
  • libxml 函数
  • Clear libxml error buffer

libxml_clear_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_clear_errors — Clear libxml error buffer

说明

libxml_clear_errors ( ) : void

libxml_clear_errors() clears the libxml error buffer.

返回值

没有返回值。

参见

  • libxml_get_errors() - Retrieve array of errors
  • libxml_get_last_error() - Retrieve last error from libxml

User Contributed Notes

There are no user contributed notes for this page.


Disable the ability to load external entities

  • ? libxml_clear_errors
  • libxml_get_errors ?
  • PHP Manual
  • libxml 函数
  • Disable the ability to load external entities

libxml_disable_entity_loader

(PHP 5 >= 5.2.11, PHP 7, PHP 8)

libxml_disable_entity_loader — Disable the ability to load external entities

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

libxml_disable_entity_loader ( bool $disable = true ) : bool

Disable/enable the ability to load external entities. Note that disabling the loading of external entities may cause general issues with loading XML documents. However, as of libxml 2.9.0 entity substitution is disabled by default, so there is no need to disable the loading of external entities, unless there is the need to resolve internal entity references with LIBXML_NOENT. Generally, it is preferable to use libxml_set_external_entity_loader() to suppress loading of external entities.

参数

disable

Disable (true) or enable (false) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

返回值

Returns the previous value.

参见

  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • libxml_set_external_entity_loader() - Changes the default external entity loader
  • The LIBXML_NONET constant

User Contributed Notes

suconghou at gmail dot com 07-Jan-2021 10:27
In PHP 8.0 and later, PHP uses libxml versions from 2.9.0, libxml_disable_entity_loader is deprecated.
so it is now safe to remove all `libxml_disable_entity_loader` calls on php8

if you want Backwards Compatibility

use this snippet

if (\PHP_VERSION_ID < 80000) {
    libxml_disable_entity_loader(true);
}
vavra at 602 dot cz 04-Jan-2018 09:48
If is called
libxml_disable_entity_loader(true);

, it causes that new SoapClient(.) fails with

SOAP-ERROR: Parsing WSDL: Couldn't load from 'D:\path/dm_operations.wsdl' : failed to load external entity "D:\path/dm_operations.wsdl

because this wsdl imports a xsd as an another external file.
Tested on php 7.1.12, win x64.
brendan at bloodbone dot ws 25-Mar-2014 10:23
This also seems to have an impact on <xsl:import /> statements if this is applied when loading XSLT for the XSLTProcessor class.
phofstetter at sensational dot ch 27-Jan-2014 04:36
Be mindful that this also disables url loading in simplexml_load_file() and likely other libxml based functions that deal with URLs
daschtour at me dot com 25-Dec-2013 11:56
This function was reported to be not thread safe. So this might affect php-scripts on the same server.
simonsimcity 29-Feb-2012 06:23
Using this function you can prevent a vulnerable to Local and Remote File Inclusion attacks.

You'll see it in an example where I load and validate the following string:

<!DOCTYPE scan [<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=/etc/passwd">]>
<scan>&test;</scan>

One way to prevent that the file in given back is to set this value to 0.
Please take a closer look at the release of symfony 2.0.11


Retrieve array of errors

  • ? libxml_disable_entity_loader
  • libxml_get_last_error ?
  • PHP Manual
  • libxml 函数
  • Retrieve array of errors

libxml_get_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_get_errors — Retrieve array of errors

说明

libxml_get_errors ( ) : array

Retrieve array of errors.

返回值

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

范例

Example #1 A libxml_get_errors() example

This example demonstrates how to build a simple libxml error handler.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <titles>PHP: Behind the Parser</title>
 </movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if ($doc === false) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
    $return  = $xml[$error->line - 1] . "\n";
    $return .= str_repeat('-', $error->column) . "^\n";

    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "Warning $error->code: ";
            break;
         case LIBXML_ERR_ERROR:
            $return .= "Error $error->code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "Fatal Error $error->code: ";
            break;
    }

    $return .= trim($error->message) .
               "\n  Line: $error->line" .
               "\n  Column: $error->column";

    if ($error->file) {
        $return .= "\n  File: $error->file";
    }

    return "$return\n\n--------------------------------------------\n\n";
}

?>

以上例程会输出：

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

参见

  • libxml_get_last_error() - Retrieve last error from libxml
  • libxml_clear_errors() - Clear libxml error buffer

User Contributed Notes

lech 29-Jul-2017 12:12
Please beware that the column property seems almost always to be invalid. I thought it only occurred when the line in question was long (and I was just about to submit a bug report with an example), however, at the time of posting, you can even see the problem in the example provided on this page: line 4 does not even have 46 characters. Where the XML line is long, the difference can be very large.

This property comes from the libxml extension, so in any case I don't think this is a PHP bug, however it is worth knowing that the value might be totally unreliable to save some confusion.

The PHP documentation page for the libXMLError class gives some indication, stating:

"This property isn't entirely implemented in libxml and therefore 0 is often returned."

(My libxml version: 2.9.1)


Retrieve last error from libxml

  • ? libxml_get_errors
  • libxml_set_external_entity_loader ?
  • PHP Manual
  • libxml 函数
  • Retrieve last error from libxml

libxml_get_last_error

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_get_last_error — Retrieve last error from libxml

说明

libxml_get_last_error ( ) : LibXMLError|false

Retrieve last error from libxml.

返回值

Returns a LibXMLError object if there is any error in the buffer, false otherwise.

参见

  • libxml_get_errors() - Retrieve array of errors
  • libxml_clear_errors() - Clear libxml error buffer

User Contributed Notes

There are no user contributed notes for this page.


Changes the default external entity loader

  • ? libxml_get_last_error
  • libxml_set_streams_context ?
  • PHP Manual
  • libxml 函数
  • Changes the default external entity loader

libxml_set_external_entity_loader

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

libxml_set_external_entity_loader — Changes the default external entity loader

说明

libxml_set_external_entity_loader ( callable|null $resolver_function ) : bool

Changes the default external entity loader. This can be used to suppress the expansion of arbitrary external entities to avoid XXE attacks, even when LIBXML_NOENT has been set for the respective operation, and is usually preferable over calling libxml_disable_entity_loader().

参数

resolver_function

A callable with the following signature:

resolver ( string $public_id , string $system_id , array $context ) : resource|string|null
public_id
The public ID.
system_id
The system ID.
context
An array with the four elements "directory", "intSubName", "extSubURI" and "extSubSystem".
This callable should return a 资源(resource), a string from which a resource can be opened. If null is returned, the entity reference resolution will fail.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 libxml_set_external_entity_loader() example

<?php
$xml = <<<XML
<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar">
<foo>bar</foo>
XML;

$dtd = <<<DTD
<!ELEMENT foo (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
    function ($public, $system, $context) use($dtd) {
        var_dump($public);
        var_dump($system);
        var_dump($context);
        $f = fopen("php://temp", "r+");
        fwrite($f, $dtd);
        rewind($f);
        return $f;
    }
);

$dd = new DOMDocument;
$r  = $dd->loadXML($xml);

var_dump($dd->validate());
?>

以上例程会输出：

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

参见

  • libxml_disable_entity_loader() - Disable the ability to load external entities

User Contributed Notes

There are no user contributed notes for this page.


Set the streams context for the next libxml document load or write

  • ? libxml_set_external_entity_loader
  • libxml_use_internal_errors ?
  • PHP Manual
  • libxml 函数
  • Set the streams context for the next libxml document load or write

libxml_set_streams_context

(PHP 5, PHP 7, PHP 8)

libxml_set_streams_context — Set the streams context for the next libxml document load or write

说明

libxml_set_streams_context ( resource $context ) : void

Sets the streams context for the next libxml document load or write.

参数

context

The stream context resource (created with stream_context_create())

返回值

没有返回值。

范例

Example #1 A libxml_set_streams_context() example

<?php

$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

参见

  • stream_context_create() - 创建资源流上下文

User Contributed Notes

There are no user contributed notes for this page.


Disable libxml errors and allow user to fetch error information as needed

  • ? libxml_set_streams_context
  • SimpleXML ?
  • PHP Manual
  • libxml 函数
  • Disable libxml errors and allow user to fetch error information as needed

libxml_use_internal_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

说明

libxml_use_internal_errors ( bool|null $use_errors = null ) : bool

libxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.

参数

use_errors

Enable (true) user error handling or disable (false) user error handling. Disabling will also clear any existing libxml errors.

返回值

This function returns the previous value of use_errors.

更新日志

版本 | 说明
8.0.0 | use_errors is nullable now. Previously, its default was false.

范例

Example #1 A libxml_use_internal_errors() example

This example demonstrates the basic usage of libxml errors and the value returned by this function.

<?php

// enable user error handling
var_dump(libxml_use_internal_errors(true));

// load the document
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
    foreach (libxml_get_errors() as $error) {
        // handle errors here
    }

    libxml_clear_errors();
}

?>

以上例程会输出：

bool(false)

参见

  • libxml_clear_errors() - Clear libxml error buffer
  • libxml_get_errors() - Retrieve array of errors

User Contributed Notes

marcovtwout 07-May-2013 01:05
When using libxml_use_internal_errors(true), and perform a possibly memory intensive operation like simplexml_load_string() next, you might end up with a blank screen and no php error logged because the error message been suppressed.
james at dunmore dot me dot uk 21-Aug-2008 03:03
We use a custom error handler using  set_error_handler()  I found that after I call

libxml_use_internal_errors(false);

It resets my error_handler - not sure if this is a bug or not, I will report it as a bug - however, I needed to repeat my call to set_error_handler

(did confuse me for a while)
B Crawford 03-Oct-2007 06:22
When using this funtion, be sure to clear your internal error buffer. If you dn't and you are using this in a long running process, you may find that all your memory is used up.


SimpleXML

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
    • Basic SimpleXML usage
    • Dealing with XML errors
  • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild — Adds a child element to the XML node
    • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes — Identifies an element's attributes
    • SimpleXMLElement::children — Finds children of given node
    • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
    • SimpleXMLElement::count — Counts the children of an element
    • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
    • SimpleXMLElement::getName — Gets the name of the XML element
    • SimpleXMLElement::getNamespaces — Returns namespaces used in document
    • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::saveXML — 别名 SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • SimpleXMLElement::xpath — Runs XPath query on XML data
  • SimpleXMLIterator — The SimpleXMLIterator class
    • SimpleXMLIterator::current — Returns the current element
    • SimpleXMLIterator::getChildren — Returns the sub-elements of the current element
    • SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements
    • SimpleXMLIterator::key — Return current key
    • SimpleXMLIterator::next — Move to next element
    • SimpleXMLIterator::rewind — Rewind to the first element
    • SimpleXMLIterator::valid — Check whether the current element is valid
  • SimpleXML 函数
    • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
    • simplexml_load_file — Interprets an XML file into an object
    • simplexml_load_string — Interprets a string of XML into an object

User Contributed Notes

Anonymous 25-Dec-2019 09:10
<?php
function array_to_xml( $array, $xml = null ) {
  if ( is_array( $array ) ) {
    foreach( $array as $key => $value ) {
      if ( is_int( $key ) ) {
        if ( $key == 0 ) {
          $node = $xml;
        } else {
          $parent = $xml->xpath( ".." )[0];
          $node = $parent->addChild( $xml->getName() );
        }
      } else {
        $node = $xml->addChild( $key );
      }
      array_to_xml( $value, $node );
    }
  } else {
    $xml[0] = $array;
  }
}

$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><root></root>" );

array_to_xml( $array, $xml );
echo $xml->asXML();
?>
charles dot a dot dacosta at gmail dot com 15-Nov-2016 09:49
I had to do the following to catch the fact that my simplexml_load_string call was not working right (it was returning empty objects).

$statistik = simplexml_load_string($record,"SimpleXMLElement",LIBXML_NSCLEAN,$ns,TRUE);

    if (($statistik === FALSE) or ($statistik === NULL) or empty($statistik))
    {
        echo "$ctr) STATISTIK ERROR---\n";
        var_dump($statistik);
        echo "\n\n";
        echo "Failed loading XML\n";
        foreach(libxml_get_errors() as $error)
        {
            echo "\n", $error->message;
        }
        die();
    }

before I put the check for "empty()" I was not catching the error.
oleg at mastak dot fi 30-Mar-2016 09:57
Two lines xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$array = (array) $xml;

?>
Serge 26-Feb-2015 10:58
XML data values should not contain "&" and that need to be replaced by html-entity "&amp;"

You can use this code to replace lonely "&" to "&amp;":

<?php
$sText = preg_replace('#&(?![a-z]{1,6};)#i', '&amp;', $sText);
?>

This will replace just "&" into "&amp;" but dont touches other html-entities like "&nbsp;", "&lt;" etc and, of course, "&amp;".

P.S. In regexp max length is 6 becouse I found that is the maximum length of possible html entity using this code:
<?php
max(array_map('strlen', array_values(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5)))) - 2
?>
minus two is for first "&" and last ";" in an any html entity.
Tim Adam Perez 23-Jan-2014 08:22
XML to Array in a single line:
$array = (array) simplexml_load_string($xml);

Enjoy!
maikel at yuluma dot com 17-Oct-2013 09:02
In reply to  soloman at textgrid dot com,

2 line XML2Array:

$xml = simplexml_load_string($file);
$array = (array)$xml;
dkrnl at yandex dot ru 30-Sep-2013 02:57
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php

<?php

/**
 * Simple XML Reader
 *
 * @license Public Domain
 * @author Dmitry Pyatkov(aka dkrnl) <dkrnl@yandex.ru>
 * @url http://github.com/dkrnl/SimpleXMLReader
 */
class SimpleXMLReader extends XMLReader
{

    /**
     * Callbacks
     *
     * @var array
     */
    protected $callback = array();

    /**
     * Add node callback
     *
     * @param  string   $name
     * @param  callback $callback
     * @param  integer  $nodeType
     * @return SimpleXMLReader
     */
    public function registerCallback($name, $callback, $nodeType = XMLREADER::ELEMENT)
    {
        if (isset($this->callback[$nodeType][$name])) {
            throw new Exception("Already exists callback $name($nodeType).");
        }
        if (!is_callable($callback)) {
            throw new Exception("Already exists parser callback $name($nodeType).");
        }
        $this->callback[$nodeType][$name] = $callback;
        return $this;
    }

    /**
     * Remove node callback
     *
     * @param  string  $name
     * @param  integer $nodeType
     * @return SimpleXMLReader
     */
    public function unRegisterCallback($name, $nodeType = XMLREADER::ELEMENT)
    {
        if (!isset($this->callback[$nodeType][$name])) {
            throw new Exception("Unknow parser callback $name($nodeType).");
        }
        unset($this->callback[$nodeType][$name]);
        return $this;
    }

    /**
     * Run parser
     *
     * @return void
     */
    public function parse()
    {
        if (empty($this->callback)) {
            throw new Exception("Empty parser callback.");
        }
        $continue = true;
        while ($continue && $this->read()) {
            if (isset($this->callback[$this->nodeType][$this->name])) {
                $continue = call_user_func($this->callback[$this->nodeType][$this->name], $this);
            }
        }
    }

    /**
     * Run XPath query on current node
     *
     * @param  string $path
     * @param  string $version
     * @param  string $encoding
     * @return array(SimpleXMLElement)
     */
    public function expandXpath($path, $version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->xpath($path);
    }

    /**
     * Expand current node to string
     *
     * @param  string $version
     * @param  string $encoding
     * @return SimpleXMLElement
     */
    public function expandString($version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->asXML();
    }

    /**
     * Expand current node to SimpleXMLElement
     *
     * @param  string $version
     * @param  string $encoding
     * @param  string $className
     * @return SimpleXMLElement
     */
    public function expandSimpleXml($version = "1.0", $encoding = "UTF-8", $className = null)
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return simplexml_import_dom($node, $className);
    }

    /**
     * Expand current node to DomDocument
     *
     * @param  string $version
     * @param  string $encoding
     * @return DomDocument
     */
    public function expandDomDocument($version = "1.0", $encoding = "UTF-8")
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return $document;
    }

}
?>
whyme 28-Dec-2012 09:55
Simple means simple.  If you know the structure and just want the value of a tag:

<?php
$xml = simplexml_load_file($xmlfile);
print $xml->City->Street->Address->HouseColor;
?>

Warning, numbers can come out as strings, empty elements like <HouseColor></HouseColor> come out as array(0)
Laurent Vervisch 24-Jun-2012 10:57
Here is an example of an easy mapping between xml and classes defined by user.

<?php
class XmlClass extends SimpleXMLElement
{
    /**
     * Returns this object as an instance of the given class.
     */
    public function asInstanceOf($class_name)
    {
        // should check that class_name is valid

        return simplexml_import_dom(dom_import_simplexml($this), $class_name);
    }

    public function __call($name, array $arguments)
    {
        echo "magic __call called for method $name on instance of ".get_class()."\n";

        // class could be mapped according $this->getName()
        $class_name = 'Test';

        $instance = $this->asInstanceOf($class_name);
        return call_user_func_array(array($instance, $name), $arguments);
    }
}

class Test extends XmlClass
{
    public function setValue($string)
    {
        $this->{0} = $string;
    }
}

$xml = new XmlClass('<example><test/></example>');
$test = $xml->test->asInstanceOf('Test');
echo get_class($xml->test), "\n";
echo get_class($test), "\n";

$test->setValue('value set directly by instance of Test');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";

$xml->test->setValue('value set by instance of XmlClass and magic __call');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";
?>

XmlClass
Test
value set directly by instance of Test
value set directly by instance of Test
magic __call called for method setValue on instance of XmlClass
value set by instance of XmlClass and magic __call
value set by instance of XmlClass and magic __call
xaviered at gmail dot com 17-May-2012 07:00
Here is a recursive function that will convert a given SimpleXMLElement object into an array, preserving namespaces and attributes.

<?php
function xmlObjToArr($obj) {
        $namespace = $obj->getDocNamespaces(true);
        $namespace[NULL] = NULL;

        $children = array();
        $attributes = array();
        $name = strtolower((string)$obj->getName());

        $text = trim((string)$obj);
        if( strlen($text) <= 0 ) {
            $text = NULL;
        }

        // get info for all namespaces
        if(is_object($obj)) {
            foreach( $namespace as $ns=>$nsUrl ) {
                // atributes
                $objAttributes = $obj->attributes($ns, true);
                foreach( $objAttributes as $attributeName => $attributeValue ) {
                    $attribName = strtolower(trim((string)$attributeName));
                    $attribVal = trim((string)$attributeValue);
                    if (!empty($ns)) {
                        $attribName = $ns . ':' . $attribName;
                    }
                    $attributes[$attribName] = $attribVal;
                }

                // children
                $objChildren = $obj->children($ns, true);
                foreach( $objChildren as $childName=>$child ) {
                    $childName = strtolower((string)$childName);
                    if( !empty($ns) ) {
                        $childName = $ns.':'.$childName;
                    }
                    $children[$childName][] = xmlObjToArr($child);
                }
            }
        }

        return array(
            'name'=>$name,
            'text'=>$text,
            'attributes'=>$attributes,
            'children'=>$children
        );
    }
?>
thedoc8786 at gmail dot com 23-Mar-2012 07:42
FAIL! This function works better than the one I posted below:

<?php
    function toArray($xml) {
        $array = json_decode(json_encode($xml), TRUE);

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( empty($value) ) $array[$key] = NULL;
            elseif ( is_array($value) ) $array[$key] = toArray($value);
        }

        return $array;
    }
thedoc8786 at gmail dot com 23-Mar-2012 04:19
I know it is over-done, but the following is a super-short example of a XML to Array conversion function (recursive):

<?php
    function toArray(SimpleXMLElement $xml) {
        $array = (array)$xml;

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( $value instanceof SimpleXMLElement ) {
                $array[$key] = empty($value) ? NULL : toArray($value);
            }
        }
        return $array;
    }
xananax at yelostudio dot com 07-Sep-2011 06:25
None of the XML2Array functions that I found satisfied me completely; Their results did not always fit the project I was working on, and I found none that would account for repeating XML elements (such as
<fields><field/><field/><field/></fields>)
So I rolled out my own; hope it helps someone.
<?php
/**
 * Converts a simpleXML element into an array. Preserves attributes.<br/>
 * You can choose to get your elements either flattened, or stored in a custom
 * index that you define.<br/>
 * For example, for a given element
 * <code>
 * <field name="someName" type="someType"/>
 * </code>
 * <br>
 * if you choose to flatten attributes, you would get:
 * <code>
 * $array['field']['name'] = 'someName';
 * $array['field']['type'] = 'someType';
 * </code>
 * If you choose not to flatten, you get:
 * <code>
 * $array['field']['@attributes']['name'] = 'someName';
 * </code>
 * <br>__________________________________________________________<br>
 * Repeating fields are stored in indexed arrays. so for a markup such as:
 * <code>
 * <parent>
 *     <child>a</child>
 *     <child>b</child>
 *     <child>c</child>
 * ...
 * </code>
 * you array would be:
 * <code>
 * $array['parent']['child'][0] = 'a';
 * $array['parent']['child'][1] = 'b';
 * ...And so on.
 * </code>
 * @param simpleXMLElement    $xml            the XML to convert
 * @param boolean|string    $attributesKey    if you pass TRUE, all values will be
 *                                            stored under an '@attributes' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $childrenKey    if you pass TRUE, all values will be
 *                                            stored under an '@children' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $valueKey        if you pass TRUE, all values will be
 *                                            stored under an '@values' index. Note
 *                                            that you can also pass a string to
 *                                            change the default index.<br/>
 *                                            defaults to null.
 * @return array the resulting array.
 */
function simpleXMLToArray(SimpleXMLElement $xml,$attributesKey=null,$childrenKey=null,$valueKey=null){

    if($childrenKey && !is_string($childrenKey)){$childrenKey = '@children';}
    if($attributesKey && !is_string($attributesKey)){$attributesKey = '@attributes';}
    if($valueKey && !is_string($valueKey)){$valueKey = '@values';}

    $return = array();
    $name = $xml->getName();
    $_value = trim((string)$xml);
    if(!strlen($_value)){$_value = null;};

    if($_value!==null){
        if($valueKey){$return[$valueKey] = $_value;}
        else{$return = $_value;}
    }

    $children = array();
    $first = true;
    foreach($xml->children() as $elementName => $child){
        $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
        if(isset($children[$elementName])){
            if(is_array($children[$elementName])){
                if($first){
                    $temp = $children[$elementName];
                    unset($children[$elementName]);
                    $children[$elementName][] = $temp;
                    $first=false;
                }
                $children[$elementName][] = $value;
            }else{
                $children[$elementName] = array($children[$elementName],$value);
            }
        }
        else{
            $children[$elementName] = $value;
        }
    }
    if($children){
        if($childrenKey){$return[$childrenKey] = $children;}
        else{$return = array_merge($return,$children);}
    }

    $attributes = array();
    foreach($xml->attributes() as $name=>$value){
        $attributes[$name] = trim($value);
    }
    if($attributes){
        if($attributesKey){$return[$attributesKey] = $attributes;}
        else{$return = array_merge($return, $attributes);}
    }

    return $return;
}
?>
soloman at textgrid dot com 09-Aug-2011 05:06
Three line xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

?>

Ta da!
streaver91 at gmail dot com 04-May-2011 08:49
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different.

I think the array structure developed by svdmeer can fit for XML, and fits well.

here is an example array converted from an xml file:
array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@text"=>"some text",
)

or if it has childrens, that can be:

array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@items"=>array(
    0=>array(
        "@tag"=>"name","@text"=>"some text"
    )
)

Also, I wrote a function that can change that array back to XML.

<?php
function array2XML($arr,$root) {
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>");
$f = create_function('$f,$c,$a','
        foreach($a as $v) {
            if(isset($v["@text"])) {
                $ch = $c->addChild($v["@tag"],$v["@text"]);
            } else {
                $ch = $c->addChild($v["@tag"]);
                if(isset($v["@items"])) {
                    $f($f,$ch,$v["@items"]);
                }
            }
            if(isset($v["@attr"])) {
                foreach($v["@attr"] as $attr => $val) {
                    $ch->addAttribute($attr,$val);
                }
            }
        }');
$f($f,$xml,$arr);
return $xml->asXML();
}
?>
phil at dier dot us 19-Jan-2011 11:37
Here's a function I came up with to convert an associative array to XML.  Works for multidimensional arrays as well.

<?php
function assocArrayToXML($root_element_name,$ar)
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    $ch=$c->addChild($k);
                    $f($f,$ch,$v);
                } else {
                    $c->addChild($k,$v);
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}
?>
philipp at strazny dot com 23-Nov-2010 05:33
Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn't know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.

<?php
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
    $children = array();
    if ($xml instanceof SimpleXMLElement) {
        $children = $xml->children();
        if ($root){ // we're at root
            $path .= '/'.$xml->getName();
        }
    }
    if ( count($children) == 0 ){
        $return[$path] = (string)$xml;
        return;
    }
    $seen=array();
    foreach ($children as $child => $value) {
        $childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
        if ( !isset($seen[$childname])){
            $seen[$childname]=0;
        }
        $seen[$childname]++;
        XMLToArrayFlat($value, $return, $path.'/'.$child.'['.$seen[$childname].']');
    }
}
?>

Use like this:

<?php
$xml = simplexml_load_string(...some xml string...);
$xmlarray = array(); // this will hold the flattened data
XMLToArrayFlat($xml, $xmlarray, '', true);
?>

You can also pull multiple files in one array:

<?php
foreach($files as $file){
    $xml = simplexml_load_file($file);
    XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
?>
The respective filename/path is thus prefixed to each key.
kristof at viewranger dot com 18-Nov-2010 05:14
If you tried to load an XML file with this, but the CDATA parts were not loaded for some reason, is because you should do it this way:

$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);

This converts CDATA to String in the returning object.
sherwinterunez at yahoo dot com 01-Sep-2010 11:15
<?php

// Sherwin R. Terunez
//
// This is my own version of XML Object to Array
//

function amstore_xmlobj2array($obj, $level=0) {

    $items = array();

    if(!is_object($obj)) return $items;

    $child = (array)$obj;

    if(sizeof($child)>1) {
        foreach($child as $aa=>$bb) {
            if(is_array($bb)) {
                foreach($bb as $ee=>$ff) {
                    if(!is_object($ff)) {
                        $items[$aa][$ee] = $ff;
                    } else
                    if(get_class($ff)=='SimpleXMLElement') {
                        $items[$aa][$ee] = amstore_xmlobj2array($ff,$level+1);
                    }
                }
            } else
            if(!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(get_class($bb)=='SimpleXMLElement') {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            }
        }
    } else
    if(sizeof($child)>0) {
        foreach($child as $aa=>$bb) {
            if(!is_array($bb)&&!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(is_object($bb)) {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            } else {
                foreach($bb as $cc=>$dd) {
                    if(!is_object($dd)) {
                        $items[$obj->getName()][$cc] = $dd;
                    } else
                    if(get_class($dd)=='SimpleXMLElement') {
                        $items[$obj->getName()][$cc] = amstore_xmlobj2array($dd,$level+1);
                    }
                }
            }
        }
    }

    return $items;
}

?>
michael dot allen at emp dot shentel dot com 15-Apr-2010 11:06
Here is a very robust SimpleXML parser.  Can be used to load files, strings, or DOM into SimpleXML, or can be used to perform the reverse when handed SimpleXML.

<?php
/**
 * XMLParser Class File
 *
 * This class loads an XML document into a SimpleXMLElement that can
 * be processed by the calling application.  This accepts xml strings,
 * files, and DOM objects.  It can also perform the reverse, converting
 * an SimpleXMLElement back into a string, file, or DOM object.
 */
class XMLParser {
    /**
     * While parsing, parse the supplied XML document.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML document file.
     *
     * @param string $doc the xml document location path
     * @return object
     */
    public static function loadFile($doc) {
        if (file_exists($doc)) {
            return simplexml_load_file($doc);
        } else {
            throw new Exception ("Unable to load the xml file " .
                                 "using: \"$doc\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML string.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML string.
     *
     * @param string $string the xml document string
     * @return object
     */
    public static function loadString($string) {
        if (isset($string)) {
            return simplexml_load_string($string);
        } else {
            throw new Exception ("Unable to load the xml string " .
                                 "using: \"$string\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML DOM node.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML DOM node.
     *
     * @param object $dom the xml DOM node
     * @return object
     */
    public static function loadDOM($dom) {
        if (isset($dom)) {
            return simplexml_import_dom($dom);
        } else {
            throw new Exception ("Unable to load the xml DOM node " .
                                 "using: \"$dom\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the SimpleXMLElement.
     *
     * Sets up a XML file, string, or DOM object based on success of
     * parsing the XML DOM node.
     *
     * @param object $path the xml document location path
     * @param string $type the return type (string, file, dom)
     * @param object $simplexml the simple xml element
     * @return mixed
     */
    public static function loadSXML($simplexml, $type, $path) {
        if (isset($simplexml) && isset($type)) {
        switch ($type) {
            case 'string':
                return $simplexml->asXML();
            break;
            case 'file':
                if (isset($path)) {
                    return $simplexml->asXML($path);
                } else {
                    throw new Exception ("Unable to create the XML file. Path is missing or" .
                                         "is invalid: \"$path\"", E_USER_ERROR);
                }
            break;
            case 'dom':
                return dom_import_simplexml($simplexml);
            break;
        }
        } else {
            throw new Exception ("Unable to load the simple XML element " .
                                 "using: \"$simplexml\"", E_USER_ERROR);
        }
    }
}
?>
emmanuel 17-Feb-2010 10:21
dynamic sql in php using xml:

test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<sql>
    <statement>
        SELECT * FROM USERS
        <call criteria="byId">WHERE id = %d</call>
        <call criteria="byUsername">WHERE username = "%s"</call>;
    </statement>
</sql>

index.php:
<?php
function callMe($param) {
    $search = array('byUsername' => 'dynsql');

    if (isset($search[$param[1]])) {
        return sprintf($param[2], $search[$param[1]]);
    }

    return "";
}

$xml = simplexml_load_file("test.xml");
$string = $xml->statement->asXML();
$string = preg_replace_callback('/<call criteria="(\w+)">(.*?)<\/call>/', 'callMe', $string);
$node = simplexml_load_string($string);
echo $node;
?>

obviously, this example can be improved [in your own code.]
mahmutta at gmail dot com 20-Jan-2010 12:58
while using simple xml and get double or float int value from xml object for using math operations (+ * - / ) some errors happens on the operation, this is because of simple xml returns everythings to objects.
exmple;

<?php

$name = "somestring";
$size = 11.45;
$xml = '
<xml>
 <name>somestring</name>
 <size>11.45</size>
</xml>';

$xmlget = simplexml_load_string($xml)

echo $xml->size*2;    // 20  its false
// ($xml->size is an object (int)11 and  (45) )

// this is true
echo $size*2;            // 22.90
echo (float)$size*2;   // 22.90
?>
antoine dot rabanes at gmail dot com 16-Oct-2009 07:22
if for some reasons you need the string value instead of the simpleXML Object you can cast the return value as a string.

exemple:

<?php
$all_api_call = simplexml_load_file($url);
$all_api = array();
$all_api = $all_api_call->result;
$list_all_api_name = array();
$i = 0;
foreach ($all_api->children() as $funcky_function)
{
    $string_tmp = (string )$funcky_function->function;
    $list_all_api_name[$i++] = $putain;
}
?>

...
walter 12-Jun-2009 07:58
Working fix for the infamous SimpleXML + memcache bug.

Improves code at http://tinyurl.com/bmoon-simplexml to actually work for arbitrary-depth structures.  (Because neither the function nor the json_decode(json_encode($obj)) hack listed there worked for me.)

There's probably some superfluous code in here that could be improved on -- but it works!

<?php
 # convert a structure that may include objects to a pure
 # array-based structure (that can be stored in memcache)
 #  ... includes support for simplexml!
 # (nb: may have problems with infinite recursive structs)
 function enforce_array($obj) {
  $array = (array)$obj;
  if(empty($array)) {
   $array = '';
  }
  else {
   foreach($array as $key=>$value) {
    if(!is_scalar($value)) {
     if(is_a($value,'SimpleXMLElement')) {
      $tmp = memcache_objects_to_array($value);
      if(!is_array($tmp)) {
       $tmp = ''.$value;
      }
      $array[$key] = $tmp;
     }
     else {
      $array[$key] = enforce_array($value);
     }
    }
    else {
     $array[$key] = $value;
    }
   }
  }
  return $array;
 }
?>
mail at kleineedv dot de 28-Apr-2009 12:37
I had a problem with simplexml reading nodes from an xml file. It always return an SimpleXML-Object but not the text inside the node.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <Id>123</Id>
</Test>

Reading this xml into a variable called $xml and then doing the following
<?php
$myId = $xml->Id;
?>
Did not return 123 in $myId, but instead I got a SimpleXMLElement Object.

The solution is simple, when you know it. Use explicit string conversion.
<?php
$myId = (string)$xml->Id;
?>
oscargodson at gmail dot com 25-Jan-2009 03:05
To add to what others have said, you can't directly put a $_GET or $_POST value into a variable then into an attribute using SimpleXML. You must first convert it to an integer.

This will NOT work

<?php
      $page_id = $_GET['id'];
      echo $xml->page[$page_id]
?>

You will get something like:
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/mysite/index.php on line 10

However, this WILL work and is much simpler then using (string) or other methods.
<?php
   $page_id = intval($_GET['id']);
   echo $xml->page[$page_id]
?>
bxt at die-optimisten dot net 26-Nov-2008 07:47
Addition to QLeap's post:
SimpleXML will return a reference to an object containing the node value and you can't use references in session variables as there is no feasible way to restore a reference to another variable.

This won't work too:
$val=$this->xml->node->attributes()->name;
echo $array[$val]; // will cause a warning because of the wrong index type.

You have to convert/cast to a String first:
echo $array[(string)$val];

This will work as expected, because converting will call the __toString() method. Therefor echo works too:
echo $val; // will display the name
QLeap 18-Nov-2008 02:27
Storing SimpleXMLElement values in $_SESSION does not work. Saving the results as an object or individual elements of the object will result in the dreaded "Warning: session_start() [function.session-start]: Node no longer exists" error.

For example, this does not work:

    $xml  = new SimpleXMLElement($page);
    $country  = $xml->Response->Placemark->AddressDetails->Country->CountryNameCode;
    $_SESSION['country'] = $country;

This will work:

    $_SESSION['country'] = (string) $country;
gwhitescarver at yahoo dot com 11-Sep-2008 01:02
Moving some code from a PHP 5.2.6 / Windows environment to a 5.2.0 / Linux environment, I somehow lost access to a plain text node within a SimpleXML Object.  On a var_dump of $xml_node, a [0] element was shown as the string '12'.  However, $xml_node[0] was evaluating NULL in 5.2.0.  You can see below the code change I made, pulling my data out of the raw XML with a regular expression.  Hope this is useful to someone.

//In some versions of PHP it seems we cannot access the [0] element of a SimpleXML Object.  Doesn't work in 5.2.0:
//$count = $xml_node[0];
//grab the raw XML:
$count = ($xml_node->asXML());
//pull out the number between the closing and opening brace of the xml:
$count = preg_replace('/.*>(\d*)<.*/', '$1', $count);
charlie at blankcanvasstudios dot com 14-Aug-2008 11:21
Optimizing aalaap at gmail dot com's php

<?php
function is_rss($feedxml) {
    @$feed = simplexml_load_string($feedxml);

    return ($feed->channel->item)?true:false;
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);
    ($feed->entry):true:false;
}
?>
aalaap at gmail dot com 30-Jun-2008 06:58
Here are two quick and dirty functions that use SimpleXML to detect if a feed xml is RSS or ATOM:

<?php
function is_rss($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->channel->item) {
        return true;
    } else {
        return false;
    }
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->entry) {
        return true;
    } else {
        return false;
    }
}
?>

The functions take in the full text feed (retrieved via cURL, for example) and return a true or a false based on the result.


简介

SimpleXML 扩展提供了一个非常简单和易于使用的工具集，能将 XML 转换成一个带有一般属性选择器和数组迭代器的对象。

User Contributed Notes

There are no user contributed notes for this page.


需求

此扩展需要 libxml PHP 扩展。这表示需要使用 --with-libxml，或在 PHP 7.4 之前的版本中使用 --enable-libxml， 尽管这将隐式完成因为 libxml 是缺省开启的。

The SimpleXML extension requires PHP 5.

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-simplexml

Note: Before PHP 5.1.2, --enable-simplexml is required to enable this extension.

User Contributed Notes

Rapitharian at hotmail dot com 24-Apr-2019 08:39
To install on CentOS and Redhat, run: sudo yum -y install php-xml
ottakar at freezed dot me 19-Dec-2017 09:31
This XML module is not provided on a default php (v7) install on Debian GNU/Linux stretch (9.3)
Add it with: sudo apt-get install php-xml
shashank at shankee dot com 31-May-2017 09:44
Installing simpleXml using composer:

"composer require ext-simplexml"

The extension is enabled by default in most distros. You can check the list of php modules using:

"php -m"
morel dot josh at hotmail dot com 17-Dec-2016 12:09
For Linux Ubuntu using PHP 7:
sudo apt-get install php7.0-xml


范例

Table of Contents

  • Basic SimpleXML usage
  • Dealing with XML errors

User Contributed Notes

Juan Herrera 19-Dec-2009 12:49
When using simplexml to access a element the returned object may be a SimpleXMLElement instead of a string.

Example:

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
    <cmd>login</cmd>
    <login>Richard</login>
</document>
XML;

$xml = simplexml_load_string($string);
print_r($xml);
$login = $xml->login;
print_r($login);
$login = (string) $xml->login;
print_r($login);
?>

Expected result:
----------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
Richard
Richard

Actual result:
--------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
SimpleXMLElement Object
(
    [0] => Richard
)
Richard

But this is an intended behavior. See http://bugs.php.net/bug.php?id=29500
info at accountr dot eu 05-May-2009 08:35
Instead of using  <?php eval($code) ?>

you can use this method,

<?php

$node = "node";

$XML = simplexml_load_file($file);

$text = (string)$XML->nodes->{$node}; // works
// or
$text2 = (string)$XML->{$node}->child; // also works fine

?>

I think it is much more easier instead of eval().
Kari P. 15-Aug-2008 02:17
To take care of proper error checking, one must use try-catch blocks:

<?php
try {
  $sxe = new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>

To get rid of warnings, use @ in front of new:

<?php
try {
  $sxe = @new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>
mike at mike-griffiths dot co dot uk 18-Apr-2008 09:11
It is important that you select the correct method of loading the XML in depending on the format of your XML file.

If you use the wrong function to load it in you will get some strange errors.


Basic SimpleXML usage

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Example #1 Include file example.php with XML string

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Example #2 Getting <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

以上例程会输出：

   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

Example #3 Getting <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

以上例程会输出：

PHP solves all my web problems

Example #4 Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
   echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

以上例程会输出：

Ms. Coder played by Onlivia Actora
Mr. Coder played by El Actór

Note:

Properties ($movies->movie in previous example) are not arrays. They are iterable and accessible objects.

Example #5 Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
    switch((string) $rating['type']) { // Get attributes as element indices
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?>

以上例程会输出：

7 thumbs up5 stars

Example #6 Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
    print 'My favorite movie.';
}

echo htmlentities((string) $movies->movie->title);
?>

以上例程会输出：

My favorite movie.PHP: Behind the Parser

Example #7 Comparing Two Elements

Two SimpleXMLElements are considered different even if they point to the same element since PHP 5.2.0.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2); // false since PHP 5.2.0
?>

以上例程会输出：

bool(false)

Example #8 Using XPath

SimpleXML includes built-in XPath support. To find all <character> elements:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
    echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

以上例程会输出：

Ms. Coder played by Onlivia Actora
Mr. Coder played by El Actór

Example #9 Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

以上例程会输出：

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Miss Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>

Example #10 Adding elements and attributes

Since PHP 5.1.3, SimpleXML has had the ability to easily add children and attributes.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

以上例程会输出：

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  <character><name>Mr. Parser</name><actor>John Doe</actor></character></characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 <rating type="mpaa">PG</rating></movie>
</movies>

Example #11 DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

以上例程会输出：

blah

User Contributed Notes

dianarusu21 at gmail dot com 20-Oct-2017 09:16
Quick start with xml.

//PHP file:
<?php
$xml = simplexml_load_file("simpleXml.xml");

foreach ($xml as $key => $value) {
  foreach ($value as $key => $value) {
    echo $key.": ".$value."</br>";
  }
}
?>

//XML file:
<?xml version="1.0" encoding="UTF-8"?>
<locations>
  <country>
    <name>Romania</name>
    <capital>Bucharest</capital>
    <language>Romanian</language>
  </country>
  <country>
    <name>Frace</name>
    <capital>Paris</capital>
    <language>France</language>
  </country>
  <country>
    <name>Spain</name>
    <capital>Madrid</capital>
    <language>Spanish</language>
  </country>
</locations>

//Output:
// name: Romania
// capital: Bucharest
// language: Romanian
// name: Frace
// capital: Paris
// language: France
// name: Spain
// capital: Madrid
// language: Spanish

NOTE: You don't need to include the xml file in the php file..
Anonymous 22-Aug-2017 12:35
If your xml string contains booleans encoded with "0" and "1", you will run into problems when you cast the element directly to bool:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<values>
    <truevalue>1</truevalue>
    <falsevalue>0</falsevalue>
</values>
XML;
$values = new SimpleXMLElement($xmlstr);
$truevalue = (bool)$values->truevalue; // true
$falsevalue = (bool)$values->falsevalue; // also true!!!

Instead you need to cast to string or int first:

$truevalue = (bool)(int)$values->truevalue; // true
$falsevalue = (bool)(int)$values->falsevalue; // false
rowan dot collins at gmail dot com 04-Jun-2015 06:58
There is a common "trick" often proposed to convert a SimpleXML object to an array, by running it through json_encode() and then json_decode(). I'd like to explain why this is a bad idea.

Most simply, because the whole point of SimpleXML is to be easier to use and more powerful than a plain array. For instance, you can write <?php $foo->bar->baz['bing'] ?> and it means the same thing as <?php $foo->bar[0]->baz[0]['bing'] ?>, regardless of how many bar or baz elements there are in the XML; and if you write <?php (string)$foo->bar[0]->baz[0] ?> you get all the string content of that node - including CDATA sections - regardless of whether it also has child elements or attributes. You also have access to namespace information, the ability to make simple edits to the XML, and even the ability to "import" into a DOM object, for much more powerful manipulation. All of this is lost by turning the object into an array rather than reading understanding the examples on this page.

Additionally, because it is not designed for this purpose, the conversion to JSON and back will actually lose information in some situations. For instance, any elements or attributes in a namespace will simply be discarded, and any text content will be discarded if an element also has children or attributes. Sometimes, this won't matter, but if you get in the habit of converting everything to arrays, it's going to sting you eventually.

Of course, you could write a smarter conversion, which didn't have these limitations, but at that point, you are getting no value out of SimpleXML at all, and should just use the lower level XML Parser functions, or the XMLReader class, to create your structure. You still won't have the extra convenience functionality of SimpleXML, but that's your loss.
mymymymy at mymymymy dot com 02-Jan-2015 09:41
$children = $xml->children();
var_dump($children[0]["@attributes"]);//"NULL"
var_dump($children[0]);//(2) ["@attributes"]=>array(1) {['x']=> string(1) '2'}

no faithfully (not true)
------
example:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [name] => USA
        )
)

print_r($xml->country->attributes()->name);
show:
 SimpleXMLElement Object
(
    [0] => USA
)

print_r((string)$xml->country->attributes()->name);
show:
USA
RiKdnUA at mail dot ru 02-Dec-2013 09:40
Если кодировка XML-документа отличается от UTF-8, объявление кодировки должно следовать сразу после version='...' и перед standalone='...'. Это требование стандарта XML.

If encoding XML-document differs from UTF-8. Encoding declaration should follow immediately after the version = '...' and before standalone = '...'. This requirement is standard XML.

<?xml version='1.0' encoding='windows-1251' standalone='yes'?>
Ok
<?xml version='1.0' standalone='yes' encoding='windows-1251'?>
<body>Русский язык. Russian language</body>
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in...
eng dot emad_2010 at yahoo dot com 08-Oct-2013 11:46
Example #  DOM Interoperability ??????? ??????
PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML  .
The simplexml_import_dom() function returns a SimpleXMLElement object from a DOM node.
DOM         object

<?php
//create DOM  document $dom that contain XML
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}
//convert DOM document $dom to object $books
$books = simplexml_import_dom($dom);

//access object $books
echo $books->book[0]->title;
?>
jishcem at gmail dot com 12-Mar-2013 07:31
For me it was easier to use arrays than objects,

So, I used this code,

$xml = simplexml_load_file('xml_file.xml');

$json_string = json_encode($xml);

$result_array = json_decode($json_string, TRUE);

Hope it would help someone
gkokmdam at zonnet dot nl 23-Feb-2011 01:54
A quick tip on xpath queries and default namespaces. It looks like the XML-system behind SimpleXML has the same workings as I believe the XML-system .NET uses: when one needs to address something in the default namespace, one will have to declare the namespace using registerXPathNamespace and then use its prefix to address the otherwise in the default namespace living element.

<?php
$string = <<<XML
<?xml version='1.0'?>
<document xmlns="http://www.w3.org/2005/Atom">
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("def", "http://www.w3.org/2005/Atom");

$nodes = $xml->xpath("//def:document/def:title");

?>
kdos 31-Jan-2011 05:32
Using stuff like: is_object($xml->module->admin) to check if there actually is a node called "admin", doesn't seem to work as expected, since simplexml always returns an object- in that case an empty one  - even if a particular node does not exist.
For me good old empty() function seems to work just fine in such cases.

Cheers
Max K. 20-Jun-2010 02:38
From the README file:

SimpleXML is meant to be an easy way to access XML data.

SimpleXML objects follow four basic rules:

1) properties denote element iterators
2) numeric indices denote elements
3) non numeric indices denote attributes
4) string conversion allows to access TEXT data

When iterating properties then the extension always iterates over
all nodes with that element name. Thus method children() must be
called to iterate over subnodes. But also doing the following:
foreach ($obj->node_name as $elem) {
  // do something with $elem
}
always results in iteration of 'node_name' elements. So no further
check is needed to distinguish the number of nodes of that type.

When an elements TEXT data is being accessed through a property
then the result does not include the TEXT data of subelements.

Known issues
============

Due to engine problems it is currently not possible to access
a subelement by index 0: $object->property[0].
ie dot raymond at gmail dot com 01-Apr-2010 03:07
If you need to output valid xml in your response, don't forget to set your header content type to xml in addition to echoing out the result of asXML():

<?php

$xml=simplexml_load_file('...');
...
...xml stuff
...

//output xml in your response:
header('Content-Type: text/xml');
echo $xml->asXML();
?>
php at keith tyler dot com 23-Dec-2009 12:57
[Editor's Note: The SimpleXMLIterator class, however, does implement these methods.]

While SimpleXMLElement claims to be iterable, it does not seem to implement the standard Iterator interface functions like ::next and ::reset properly. Therefore while foreach() works, functions like next(), current(), or each() don't seem to work as you would expect -- the pointer never seems to move or keeps getting reset.
bjorn at xQmail dot eu 31-Aug-2009 07:48
If you're not sure the XML will be valid you'd better use:

<?php
$xmlObject = simplexml_load_string($xml);
// or
$xmlObject = simplexml_load_file(xml);
?>

Both of these return a SimpleXMLElement Object or a libXMLError Object.
radams at circlepix com 24-Apr-2009 10:52
To test whether an element exists:

<?php

    $xml = <<<EOT
<?xml version='1.0' standalone='yes'?>
<root>
    <test1></test1>
    <test2 />
    <test4> </test4>
</root>
EOT;

    $xmlDoc = new SimpleXMLElement($xml);

echo "Test1: \n";
var_dump($xmlDoc->test1);
echo "\n(" . (bool)$xmlDoc->test1 . ")";
echo "\n\n";

echo "Test2: \n";
var_dump($xmlDoc->test2);
echo "\n(" . (bool)$xmlDoc->test2 . ")";
echo "\n\n";

echo "Test3: \n";
var_dump($xmlDoc->test3);
echo "\n(" . (bool)$xmlDoc->test3 . ")";
echo "\n\n";

echo "Test4: \n";
var_dump($xmlDoc->test4);
echo "\n(" . (bool)$xmlDoc->test4 . ")";
echo "\n\n";

?>

The var_dumps for test1, test2, and test3 are identical, but the (bool) test gives a '1' for test1 and test2, and a '' for test3.


Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLError object, returned by libxml_get_errors(), contains several properties including the message, line and column (position) of the error.

Example #1 Loading broken XML string

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}
?>

以上例程会输出：

Failed loading XML
    Blank needed here
    parsing XML declaration: '?>' expected
    Opening and ending tag mismatch: xml line 1 and broken
    Premature end of data in tag broken line 1

参见

  • libxml_use_internal_errors()
  • libxml_get_errors()
  • libXMLError

User Contributed Notes

1337 at netapp dot com 04-Sep-2015 02:21
If you need to process the content of your broken XML-doc you might find this interesting. It has blown past a few simple corruptions for me.
http://php.net/manual/en/class.domdocument.php#domdocument.props.recover
tuxedobob 11-Sep-2014 09:29
Now that the /e modifier is considered deprecated in preg_replace, you can use a negative lookahead to replace unescaped ampersands with &amp; without throwing warnings:

$str = preg_replace('/&(?!;{6})/', '&amp;', $str);

You probably should have been doing this before /e was deprecated, actually.
openbip at gmail dot com 25-Feb-2010 08:20
Note that "if (! $sxe) {" may give you a false-negative if the XML document was empty (e.g. "<root />").  In that case, $sxe will be:

object(SimpleXMLElement)#1 (0) {
}

which will evaluate to false, even though nothing technically went wrong.

Consider instead: "if ($sxe === false) {"
Jacob Tabak 15-Feb-2010 01:17
If you are trying to load an XML string with some escaped and some unescaped ampersands, you can pre-parse the string to ecsape the unescaped ampersands without modifying the already escaped ones:
<?php
$s = preg_replace('/&[^; ]{0,6}.?/e', "((substr('\\0',-1) == ';') ? '\\0' : '&amp;'.substr('\\0',1))", $s);
?>


The SimpleXMLElement class

(PHP 5, PHP 7, PHP 8)

简介

Represents an element in an XML document.

类摘要

SimpleXMLElement implements Traversable {
/* 方法 */
final public __construct ( string $data , int $options = 0 , bool $data_is_url = false , string $ns = "" , bool $is_prefix = false )
public addAttribute ( string $name , string $value = ? , string $namespace = ? ) : void
public addChild ( string $name , string $value = ? , string $namespace = ? ) : SimpleXMLElement
public asXML ( string $filename = ? ) : mixed
public attributes ( string $ns = null , bool $is_prefix = false ) : SimpleXMLElement
public children ( string $ns = ? , bool $is_prefix = false ) : SimpleXMLElement
public count ( ) : int
public getDocNamespaces ( bool $recursive = false , bool $from_root = true ) : array
public getName ( ) : string
public getNamespaces ( bool $recursive = false ) : array
public registerXPathNamespace ( string $prefix , string $ns ) : bool
public __toString ( ) : string
public xpath ( string $path ) : array
}

Table of Contents

  • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
  • SimpleXMLElement::addChild — Adds a child element to the XML node
  • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
  • SimpleXMLElement::attributes — Identifies an element's attributes
  • SimpleXMLElement::children — Finds children of given node
  • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
  • SimpleXMLElement::count — Counts the children of an element
  • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
  • SimpleXMLElement::getName — Gets the name of the XML element
  • SimpleXMLElement::getNamespaces — Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::saveXML — 别名 SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • SimpleXMLElement::xpath — Runs XPath query on XML data

User Contributed Notes

Patanjali 15-Oct-2020 02:20
Further to rmirabelle's comment, to compare two SimpleXML elements, do the comparison between the objects returned by the dom_import_simplexml function, as per:

<?php
if(dom_import_simplexml($simplexml_element_1)===dom_import_simplexml($simplexml_element_2)){
  ...
 }
?>

You must ensure that both are SimpleXML elements before conversion to DOM objects.
guilhermeasn at yahoo dot com dot br 15-Jan-2020 08:09
Class with a method to transform array or object to XML:

class MakeXML {

    public static function array_obj_to_xml($data, \SimpleXMLElement &$xmlObj) {
        foreach((array) $data as $key => $value) {
            if(is_numeric($key)) {
                $key = "n" . $key;
            }
            if(is_array($value) or is_object($value)) {
                $subnode = $xmlObj->addChild($key);
                self::array_obj_to_xml($value, $subnode);
            } else {
                $xmlObj->addChild($key, htmlspecialchars($value));
            }
        }
    }

}

Example:

$object = new \stdClass();
$object->example = "Try this class";

$objxml = new \SimpleXMLElement('<API/>');
MakeXML::array_obj_to_xml($objxml, $objxml);
echo $objxml->asXML();
Budu 13-May-2018 07:17
public function crearXml(){
        $pruebaXml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<Root></Root>
XML;
$example = new SimpleXMLElement($pruebaXml); //Crea un nuevo objeto SimpleXMLElement
        $example->addAttribute('id', '1');//A?ade un elemento hijo al nodo XML

        while( $nodo = $this->iteraciones->iterate()){
            $nodos = $example->addChild('Nodo');
            $nodos->addAttribute('id',$nodo->getId());
            $acierto = $nodos->addChild('nuevoHijo', $nodo->getX());
        }
        $miFichero = $example->asXML();//Retorna un string XML correcto basado en un elemento SimpleXML
        $miArchivo = fopen("xml/example.xml", "w+");//Abre un fichero o un URL
        fwrite($miArchivo, $miFichero);//Escritura archivo
    }
CameronXie 11-Dec-2017 10:48
Map xml to array (with attributes)

<?php declare(strict_types=1);

/**
 * @param SimpleXMLElement $xml
 * @return array
 */
function xmlToArray(SimpleXMLElement $xml): array
{
    $parser = function (SimpleXMLElement $xml, array $collection = []) use (&$parser) {
        $nodes = $xml->children();
        $attributes = $xml->attributes();

        if (0 !== count($attributes)) {
            foreach ($attributes as $attrName => $attrValue) {
                $collection['attributes'][$attrName] = strval($attrValue);
            }
        }

        if (0 === $nodes->count()) {
            $collection['value'] = strval($xml);
            return $collection;
        }

        foreach ($nodes as $nodeName => $nodeValue) {
            if (count($nodeValue->xpath('../' . $nodeName)) < 2) {
                $collection[$nodeName] = $parser($nodeValue);
                continue;
            }

            $collection[$nodeName][] = $parser($nodeValue);
        }

        return $collection;
    };

    return [
        $xml->getName() => $parser($xml)
    ];
}
kurtbr at gmail dot com 31-May-2017 02:58
Here is a helper class to convert a PHP array to XML
You would call it doing the following:

<?php
$xml = new Xml();
$xml-> generateXmlFromArray($array, 'entities', 'entity');
?>

<?php
class Xml
{
    public function getXmlFromArray($value, \SimpleXMLElement &$xmlElement, $entity, $starting = null)
    {

        $handleValue = function($value){
            if(is_string($value)){
                $value = htmlspecialchars($value);
            }
            return $value;
        };
        $addChild = function($name, $value, &$subNode = null)use(&$xmlElement, $handleValue, $entity){
            if(is_array($value)){
                if(!$subNode instanceof \SimpleXMLElement){
                    $currentKey = key($value);
                    $initialValue = null;
                    if(is_numeric($currentKey)){
                        if(!is_array($value[$currentKey])){
                            $initialValue = $value[$currentKey];
                            unset($value[$currentKey]);
                        }
                    }
                    $subNode = $xmlElement->addChild($name, $initialValue);
                }
                $this->getXmlFromArray($handleValue($value), $subNode, $name);
            } else {
                $xmlElement->addChild($name, $handleValue($value));
            }
        };

        if(is_array($value))
        {
            if(is_numeric(key($value))){
                $setSubNodePrimitiveValue = function($value)use(&$xmlElement, $entity, $handleValue){
                    $value = $handleValue($value);
                    $children = $xmlElement->children();
                    $children[] = $value;
                };
                foreach ($value as $item)
                {
                    if(!is_array($item)){
                        $setSubNodePrimitiveValue($item);
                    } else {
                        if($starting === true){
                            $addChild($entity, $item);
                        } else {
                            $addChild($entity, $item, $xmlElement);
                        }
                    }
                }
            } else {
                foreach ($value as $subEntity => $subEntityItem)
                {
                    $addChild($subEntity, $subEntityItem);
                }
            }
        } else {
            $xmlElement->addChild($entity, $handleValue($value));
        }
    }

    /**
     * @param array $array
     * @param string $openingTag
     * @param string $entity
     * @param string $nameSpace
     * @param bool $isPrefixed
     * @return \SimpleXMLElement
     */
    public function generateXmlFromArray(array $array, string $openingTag, string $entity, $nameSpace = '', $isPrefixed = false)
    {
        $xmlString = '<'.$openingTag.'></'.$openingTag.'>';
        $xml = new \SimpleXMLElement($xmlString, LIBXML_NOERROR, false, $nameSpace, $isPrefixed);
        $this->getXmlFromArray($array, $xml, $entity, true);
        return $xml;
    }

    /**
     * @param string $xml
     * @return bool
     */
    public function validateXml(string $xml)
    {
        $dom = new \DOMDocument();
        $dom->loadXML($xml);
        return $dom->validate();
    }

    public function loadXmlPathAsArray(string $xmlPath)
    {
        $xml   = simplexml_load_file($xmlPath);
        $array = json_decode(json_encode($xml), TRUE);
        return (array)$array;
    }

    /**
     * @param string $xmlString
     * @return array
     */
    public function loadXmlStringAsArray(string $xmlString)
    {
        $array = (array) @simplexml_load_string($xmlString);
        if(!$array){
            $array = (array) @json_decode($xmlString, true);
        } else{
            $array = (array)@json_decode(json_encode($array), true);
        }
        return $array;
    }

    /**
     * @param string $xmlString
     * @return \SimpleXMLElement
     */
    public function loadXmlString(string $xmlString)
    {
        return @simplexml_load_string($xmlString);
    }
}
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:54
See previous two parts to get better understanding of how these tricks works. Example shown here refers to part two. (Sorry, length limitation)

3. Tricks
<?php
        // The real profit is in combination of property and array accesses and unset($someNode->{0}) trick -
        // it allows you to remove whatever node you want:
        unset($rootNode->{'div'}[2]);   // remove node with * mark (text*)

        // Another trick is removing child node using child node object
        $newChildNode = $rootNode->addChild('div','text**');    // Create
        unset($newChildNode->{0});      // Remove, node removed from parent object too!

        echo "--2--\n".$rootNode->asXML();
        /*
        <xml_root>complex node
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
                <div>text</div>
                <div>text</div>
                <div>text</div>
        </xml_root>
        */
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:48
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

2. How child nodes works (understanding)
<?php
        echo "Exercise 2 \n";

        $rootNode = new SimpleXMLElement('<xml_root>complex node</xml_root>');  // Create root node
        $childNode1 = $rootNode->addChild('type_one','node 1');                 // Create child node 1 with name 'type_one'
        $childNode2 = new SimpleXMLElement('<type_one>node 2</type_one>');      // Create child node 2 with name 'type_one'
        $childNode3 = new SimpleXMLElement('<type_two>node 3</type_two>');      // Create child node 3 with name 'type_two' (different!)
        // Now $rootNode has only one children because other child nodes was created separately
        // Lets paste child node to root node
        echo $childNode1;

        $rootNode->{'type_one'} = $childNode2;      // Note that the property name is 'type_one'
        $rootNode->{'type_two'} = $childNode3;      // Note that the property name is 'type_two'
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            string(6) "node 2"
            ["type_two"]=>
            string(6) "node 3"
        }
        */
        // We see that "node 1" disappeared, that's because assigning one node to some property of another in not a magic.
        // To be clear, the real calls looks like:
        $rootNode->{'type_one'}[0] = (string) $childNode2;
        $rootNode->{'type_two'}[0] = (string) $childNode3;
        // Explanation:
        // A: (string)
        // It means that you can't assign node itself, only its string representation because assigned node will be casted to string anyway.
        // It also means that tag name of assigned node doesn't matter - its name will be whatever name you specified in {} braces.
        // B: [0]
        // The array access operator ([0]) means that each tag name (type_one and type_two) has its own collection with integer indexes.
        // If you want to add another tag with same name, you should increment index:
        $rootNode->{'type_one'}[1] = $childNode2;
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(6) "node 2"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 1. The value of $childNode1 has been changed to "node 1" - that's because the child node, returned from addChild() method
        // is referenced with parent node. If you change its content in one side - it changes in other side too:
        $childNode1->{0} = 'renewed node 1';
        // But it won't happen with $childNode2 - it is single and has no reference with parent node:
        $childNode2->{0} = 'renewed node 2';
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(14) "renewed node 1"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 2. When you added child nodes, the parent node's string content is still alive, var_dump doesn't show it,
        // but you can see through echoing XML:
        echo "--1--\n".$rootNode->asXML();
        /*
        <xml_root>complex node <--------- here!
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
        </xml_root>
        */
        // See 'complex node'? Bad news that you can't change string content anymore, if we try to call `$rootNode->{0} = 'something'` -
        // it overrides all content - both string and child nodes! I don't know how to write to string content only in that case.
        // But still you can read string content and remove entire node as described above.

        // So the following statements gives same result, except $result variable value:
        $someNode = new SimpleXMLElement('<div>text</div>');
        $result = $rootNode->addChild('div','text');                    // $result is SimpleXMLElement
        $result = $rootNode->addChild($someNode->getName(),$someNode);  // $result is SimpleXMLElement
        $result = $rootNode->{'div'}[] = 'text*';                       // $result is string 'text*'
        $result = $rootNode->{$someNode->getName()}[] = $someNode;      // $result is string 'text'
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:45
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

1. How to work with single node and its value (basics)
<?php
        echo "Exercise 1 \n";
        // Create
        $someNode = new SimpleXMLElement('<xml_root>simple node</xml_root>');
        // Read
        echo $someNode->{0} ."\n";      // Echoes "simple node"
        echo $someNode ."\n";           // Echoes "simple node", might be used for read case too
        // Edit
        $someNode->{0} = 'new value';
        echo $someNode->{0} ."\n";      // Echoes "new value", value is changed!
        // Remove
        unset($someNode->{0});

        // Don't touch this node anymore otherwise it will throw a warning:
        // "Warning:  SimpleXMLElement::asXML(): Node no longer exists in <...> on line <...>"
        // echo $someNode ."\n";      // Throws the warning

        // Recap: property access to zero property ($someNode->{0}) is the way to read and edit string content of the node AND
        // to remove the node itself
?>
frame at dynamiccreated dot de 14-Jun-2013 01:36
Important note I miss here in the documentation:

SimpleXML supports Array/Iteration-Methods. Therefore it is possible to

add attributes
edit attributes
remove attributes

add nodes
edit nodes
remove nodes

This is the reason why SimpleXML provides only add-methods not deleting- or editing-methods. We also need this methods because SimpleXML acts as a normal class and
new member will not converted to a new node.

Deleting a node seems not to be possible within a foreach-loop. The reason is simple. To do that we need a valid key, but the Iterator only gives us a "understandable feedback" on which node we are working on: the tag name.

So this will not work:

<?php
foreach($doc->seg as $key => $seg)
{
    if((string)$seg['id'] === 'whatever')
    {
        unset($seg); // only clears local copy
        unset($seg[$key]); // wrong index "seg"
    }
}
?>

But this, eg. will work:
<?php
unset($doc->seg[2]);
?>

In case of doubt always do a print_r/var_dump(). It nicely shows the real linked indexes.
Yukull 15-Feb-2013 01:59
xml to object conversion function :
<?php
/**
    @param:
        $xml: SimpleXMLElement
        $force: set to true to always create 'text', 'attribute', and 'children' even if empty
    @return
        object with attributs:
            (string) name: XML tag name
            (string) text: text content of the attribut name
            (array) attributes: array witch keys are attribute key and values are attribute value
            (array) children: array of objects made with xml2obj() on each child
**/
function xml2obj($xml,$force = false){

    $obj = new StdClass();

    $obj->name = $xml->getName();

    $text = trim((string)$xml);
    $attributes = array();
    $children = array();

    foreach($xml->attributes() as $k => $v){
        $attributes[$k]  = (string)$v;
    }

    foreach($xml->children() as $k => $v){
        $children[] = xml2obj($v,$force);
    }

    if($force or $text !== '')
        $obj->text = $text;

    if($force or count($attributes) > 0)
        $obj->attributes = $attributes;

    if($force or count($children) > 0)
        $obj->children = $children;

    return $obj;
}
?>
heaver 31-May-2012 07:33
XML to JSON conversion without '@attributes'
<?php
function XML2JSON($xml) {

        function normalizeSimpleXML($obj, &$result) {
            $data = $obj;
            if (is_object($data)) {
                $data = get_object_vars($data);
            }
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $res = null;
                    normalizeSimpleXML($value, $res);
                    if (($key == '@attributes') && ($key)) {
                        $result = $res;
                    } else {
                        $result[$key] = $res;
                    }
                }
            } else {
                $result = $data;
            }
        }
        normalizeSimpleXML(simplexml_load_string($xml), $result);
        return json_encode($result);
    }
?>
demian dot katz at villanova dot edu 29-Mar-2012 05:50
Here is a more namespace-aware version of the earlier function for attaching one SimpleXMLElement to another.  I'm sure it could still be further improved (right now it generates some redundant xmlns definitions), but it seems to be working well enough for my purposes so far.

function SimpleXMLElement_append($parent, $child)
{
    // get all namespaces for document
    $namespaces = $child->getNamespaces(true);

    // check if there is a default namespace for the current node
    $currentNs = $child->getNamespaces();
    $defaultNs = count($currentNs) > 0 ? current($currentNs) : null;
    $prefix = (count($currentNs) > 0) ? current(array_keys($currentNs)) : '';
    $childName = strlen($prefix) > 1
        ? $prefix . ':' . $child->getName() : $child->getName();

    // check if the value is string value / data
    if (trim((string) $child) == '') {
        $element = $parent->addChild($childName, null, $defaultNs);
    } else {
        $element = $parent->addChild(
            $childName, htmlspecialchars((string)$child), $defaultNs
        );
    }

    foreach ($child->attributes() as $attKey => $attValue) {
        $element->addAttribute($attKey, $attValue);
    }
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->attributes($nsurl) as $attKey => $attValue) {
            $element->addAttribute($nskey . ':' . $attKey, $attValue, $nsurl);
        }
    }

    // add children -- try with namespaces first, but default to all children
    // if no namespaced children are found.
    $children = 0;
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->children($nsurl) as $currChild) {
            SimpleXMLElement_append($element, $currChild);
            $children++;
        }
    }
    if ($children == 0) {
        foreach ($child->children() as $currChild) {
            SimpleXMLElement_append($element, $currChild);
        }
    }
}
saganmarketing.com 12-Mar-2012 12:27
Parsing an invalid XML string through SimpleXML causes the script to crash completely (usually) therefore it is best to make sure the XML is valid before parsing with something like this:

// Must be tested with ===, as in if(isXML($xml) === true){}
// Returns the error message on improper XML
function isXML($xml){
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();

    if(empty($errors)){
        return true;
    }

    $error = $errors[0];
    if($error->level < 3){
        return true;
    }

    $explodedxml = explode("r", $xml);
    $badxml = $explodedxml[($error->line)-1];

    $message = $error->message . ' at line ' . $error->line . '. Bad XML: ' . htmlentities($badxml);
    return $message;
}
Anonymous 14-Nov-2011 12:34
Warning to anyone trying to parse XML with a key name that includes a hyphen ie.)
<subscribe>
    <callback-url>example url</callback-url>
</subscribe>

In order to access the callback-url you will need to do something like the following:
<?php
$xml = simplexml_load_string($input);
$callback = $xml->{"callback-url"};
?>
If you attempt to do it without the curly braces and quotes you will find out that you are returned a 0 instead of what you want.
juanfhj at gmail dot spam dot me dot not dot com 13-Aug-2011 11:01
To access the underlying element as a string, it's necessary to make the cast $x = (string)$my_xml_element.
dans at dansheps dot com 22-Apr-2011 12:06
I created a little function to parse the simple XML into a structure which is easier to iterate(I believe anyways) than the simpleXML node structure.

<?php
function parseSimpleXML($xmldata)
    {
        $childNames = array();
        $children = array();

        if( $xmldata->count() !== 0 )
        {
            foreach( $xmldata->children() AS $child )
            {
                $name = $child->getName();

                if( !isset($childNames[$name]) )
                {
                    $childNames[$name] = 0;
                }

                $childNames[$name]++;
                $children[$name][] = $this->parseSimpleXML($child);
            }
        }

        $returndata = new XMLNode();
        if( $xmldata->attributes()->count() > 0 )
        {
            $returndata->{'@attributes'} = new XMLAttribute();
            foreach( $xmldata->attributes() AS $name => $attrib )
            {
                $returndata->{'@attributes'}->{$name} = (string)$attrib;
            }
        }

        if( count($childNames) > 0 )
        {
            foreach( $childNames AS $name => $count )
            {
                if( $count === 1 )
                {
                    $returndata->{$name} = $children[$name][0];
                }
                else
                {
                    $returndata->{$name} = new XMLMultiNode();
                    $counter = 0;
                    foreach( $children[$name] AS $data )
                    {
                        $returndata->{$name}->{$counter} = $data;
                        $counter++;
                    }
                }
            }
        }
        else
        {
            if( (string)$xmldata !== '' )
            {
                $returndata->{'@innerXML'} = (string)$xmldata;
            }
        }
        return $returndata;
    }
?>
ms dot n at 163 dot com 11-Feb-2011 10:50
Adds a new function for SimpleXMLElement class, in order to output HTML code.

<?php
class CeiXML extends SimpleXMLElement{
public function asHTML(){
$ele=dom_import_simplexml($this);
$dom = new DOMDocument('1.0', 'utf-8');
$element=$dom->importNode($ele,true);
$dom->appendChild($element);
return $dom->saveHTML();
}
}
?>
Pavel Musil pavel dot musil at gmail dot com 10-Feb-2011 03:18
Simple recursive function to append XML object into SimpleXMLElement node:

<?php
// root: parent element - SimpleXMLElement instance
// append: XML object from simplexml_load_string

function xml_join($root, $append) {
    if ($append) {
        if (strlen(trim((string) $append))==0) {
            $xml = $root->addChild($append->getName());
            foreach($append->children() as $child) {
                xml_join($xml, $child);
            }
        } else {
            $xml = $root->addChild($append->getName(), (string) $append);
        }
        foreach($append->attributes() as $n => $v) {
            $xml->addAttribute($n, $v);
        }
    }
}

$xml_append = simplexml_load_string('<data><items><item id="1">value</item></items></data>');
$xml_root = new SimpleXMLElement('<result></result>');

$cxml = $xml_root->addChild('clone');
xml_join($cxml, $xml_append->items->item[0]);

print $xml_root->asXML();
?>

Result:
<?xml version="1.0"?>
<result>
    <clone>
        <item id="1">
            value
        </item>
    </clone>
</result>
rmirabelle 08-Nov-2010 09:42
To further previous comments and drive the point home:

What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE,  (specifically a libxml resource).

That's why you can't store a SimpleXMLElement to $_SESSION or perform straight comparison operations on node values without first casting them to some type of object.  $_SESSION expects to store 'an object' and comparison operators expect to compare 2 'objects' and SimpleXMLElements are not objects.

When you echo or print a node's value, PHP converts the value (a resource) into a string object for you.  It's a time saver for sure, but can fool you into thinking that your SimpleXMLElement is an object.

Hope this helps clarify
joshduck at gmail dot com 28-Sep-2010 05:00
You should cast elements to a float (or even string) if you plan on using them in addition, multiplication, etc. If you don't then PHP will incorrectly treat the node values as an integer.

<?php
$obj = new SimpleXMLElement('<root>
    <a>1.9</a>
    <b>1.9</b>
</root>');

var_dump($obj->a + $obj->b);
var_dump((float)$obj->a + (float)$obj->b);
var_dump((string)$obj->a + (string)$obj->b);
?>

The first line gives: int(2)
The second and third give the expected result: float(3.8)
francs at seznam dot cz 23-Sep-2010 05:28
Be aware when you trying to cast some attribute to boolean.

(boolean)$xml->attributes()->someAtt;

returns TRUE if attribute is array([0] => 0);

use (boolean)(int) instead.
kweij at lsg dot nl 26-Jul-2010 04:47
I'm using SimpleXML for, ofcourse, it's simplicity, however I did wanted to manipulate the xml and combining one SimpleXMLElement with any other, so I wrote this function to add a SimpleXMLElement-child.

<?php
function SimpleXMLElement_append($key, $value) {
    // check class
    if ((get_class($key) == 'SimpleXMLElement') && (get_class($value) == 'SimpleXMLElement')) {
        // check if the value is string value / data
        if (trim((string) $value) == '') {
            // add element and attributes
            $element = $key->addChild($value->getName());
            foreach ($value->attributes() as $attKey => $attValue) {
                $element->addAttribute($attKey, $attValue);
            }
            // add children
            foreach ($value->children() as $child) {
                SimpleXMLElement_append($element, $child);
            }
        } else {
            // set the value of this item
            $element = $key->addChild($value->getName(), trim((string) $value));
        }
    } else {
        // throw an error
        throw new Exception('Wrong type of input parameters, expected SimpleXMLElement');
    }
}
?>

I'd recommend SimpleXMLElement to extend it's addChild() function with the functionalitity above.
cherubangel at gmail dot com 02-Jul-2010 04:28
Note that changing attributes from within a foreach loop, especially namespaced attributes, can be very tricky.

For example, when trying to change the value of an existing xlink:href attribute:
<?php
foreach($xmlelement -> attributes('xlink', true) as $attribute => $attribvalue){
    $attribvalue[0] = 'value'; // Throws an error
    $attribvalue = 'value'; // Does not change your XML
    $xmlelement -> addAttribute($attribute, 'value', 'http://www.w3.org/1999/xlink'); // Adds an attribute, does not change existing one.
    $xmlelement[$attribute] = 'value'; // Adds an attribute, does not change existing one.
}
?>

Instead, you should access the array returned by the attributes() function directly, like this:
<?php
    $xmlelement -> attributes('xlink', true) -> href = 'value'; // Works!
?>
php at keith tyler dot com 19-Feb-2010 06:23
The root node element of your input XML string is not retrievable as a property.

<?php
$xml="<foo>bar</foo>";
$sxe=new SimpleXMLElement($xml);
print $sxe->foo;
?>

prints nothing. You can only get to the root element via the array index method ($sxe[0]).

Also, you may not have two (or more) root elements -- that is apparently not well-formed XML.

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement($xml);
?>

throws an exception. A Q&D is to append an arbitraty root node structure to both ends of the input:

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement("<z>".$xml."</z>");
?>

Doing this also solves the above problem of root node property accessibility. (It may not work if your XML string includes a declaration.)
triplepoint at gmail dot com 19-Dec-2009 04:19
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating it as if it were a full document).
<?php
class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addProcessingInstruction( $name, $value )
    {
        // Create a DomElement from this simpleXML object
        $dom_sxe = dom_import_simplexml($this);

        // Create a handle to the owner doc of this xml
        $dom_parent = $dom_sxe->ownerDocument;

        // Find the topmost element of the domDocument
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);

        // Add the processing instruction before the topmost element
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}
?>

For example, if you had a simpleXMLElement_Plus object made out of the xml fragment:
<xml><content /></xml>

And you needed the output to be:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>
<xml><content/></xml>

you could do (using the class above):
<?php
$xml = new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/xsl.xsl"');
echo $xml->asXML();
?>
ivandosreisandrade at gmail dot com 19-Nov-2009 06:55
Hello,

here goes my contribution for those whom are struggling to understand how SimpleXMLElement works.

After some time trying to figure out how this works, I've came up to this small example:

<?php
    $xmlstr = "<?xml version='1.0' ?>\n".
              // optionally you can specify a xml-stylesheet for presenting the results. just uncoment the following line and change the stylesheet name.
              /* "<?xml-stylesheet type='text/xsl' href='xml_style.xsl' ?>\n". */
              "<book></book>";

    // create the SimpleXMLElement object with an empty <book> element
    $xml = new SimpleXMLElement($xmlstr);

    // add some child nodes
    $xml->addChild("title", "Title of my book");
    $xml->addChild("abstract", "My book is about learning to work with SimpleXMLElement");

    // add some more child nodes
    $chapter1 = $xml->addChild("chapter_1");
    // add an attribute to child chapter_1
    $chapter1->addAttribute("chapter_title", "Introduction to my book");

    $chapter2 = $xml->addChild("chapter_2");
    $chapter2->addAttribute("chapter_title", "Development of my book");

    $chapter3 = $xml->addChild("chapter_3");
    $chapter3->addAttribute("chapter_title", "Another chapter of my book");

    $conclusion = $xml->addChild("conclusion", "The ending of my book");

    // insert the header to tell the browser how to read the document
    header("Content-type: text/xml");
    // print the SimpleXMLElement as a XML well-formed string
    echo $xml->asXML();
?>

With this script you can just copy-paste and try to understand how it works.
I hope it can help somebody :)
brett at brettbrewer dot com 27-Oct-2009 04:53
Figuring out how to access the properties of a SimpleXmlElement object was a little tricky for me. In particular, it took a while to discover that I needed to cast my SimpleXmlElement properties to be of type "string" to print them or do comparisons on them. For instance, assuming you already have a string of xml in $xmlstr...

<?php
$sxml= new SimpleXmlElement($xmlstr);

if ((string) $sxml->property== "somevalue") {
    echo (string) $sxml->property;
}
?>
The properties of a SimpleXmlElement object are objects themselves, so you need to put "(string)" before them, which casts their values to a string instead of an object. I assume if you were doing a numeric comparison you'd want to cast to an (int) or something numeric instead.


Adds an attribute to the SimpleXML element

  • ? SimpleXMLElement
  • SimpleXMLElement::addChild ?
  • PHP Manual
  • SimpleXMLElement
  • Adds an attribute to the SimpleXML element

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element

说明

public SimpleXMLElement::addAttribute ( string $name , string $value = ? , string $namespace = ? ) : void

Adds an attribute to the SimpleXML element.

参数

name

The name of the attribute to add.

value

The value of the attribute.

namespace

If specified, the namespace to which the attribute belongs.

返回值

没有返回值。

范例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

以上例程的输出类似于：

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

参见

  • SimpleXMLElement::addChild() - Adds a child element to the XML node
  • Basic SimpleXML usage

User Contributed Notes

Patanjali 10-Apr-2016 10:37
You cannot use this to update an existing attribute's value.

Instead, get a DOM version of the SimpleXMLElement and use setAttribute, as per:

$XML = '<element a="aa">Text</element>';
$snode = new simple_xml_element($XML);

$dnode = dom_import_simplexml($snode);
$dnode->setAttribute('a', 'bb');

Resulting XML for the node is:
<element a="bb">Text</element>
p.servus 18-Nov-2011 05:42
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml = new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo $xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
sarlak 07-May-2011 07:49
You can access a node child with his name this way :

<?php
$root = new SimpleXMLElement($filePath);
echo $root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
booleer at yahoo dot it 16-Dec-2010 09:44
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo $xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>


Adds a child element to the XML node

  • ? SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML ?
  • PHP Manual
  • SimpleXMLElement
  • Adds a child element to the XML node

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addChild — Adds a child element to the XML node

说明

public SimpleXMLElement::addChild ( string $name , string $value = ? , string $namespace = ? ) : SimpleXMLElement

Adds a child element to the node and returns a SimpleXMLElement of the child.

参数

name

The name of the child element to add.

value

If specified, the value of the child element.

namespace

If specified, the namespace to which the child element belongs.

返回值

The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

范例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

以上例程的输出类似于：

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

参见

  • SimpleXMLElement::addAttribute() - Adds an attribute to the SimpleXML element
  • Basic SimpleXML usage

User Contributed Notes

nwarap 07-Nov-2017 02:46
Want to continue the ampersand (&) chain problem.

Sometimes, you would want to assign  (=) addChild.
This trick will helps you to do this.

<?php
$webOrders = new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

OUTPUT would be:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
    <WebOrder>
        <Product price="19.99" qty="2">T&amp;M</Product>
    </WebOrder>
</WebOrders>
johninen at gmail dot com 14-Sep-2015 01:27
In the docs for google sitemaps it is required an element for mobile sitemaps that looks like this: <mobile:mobile/>

I used some time to figure out how to make it, but it is quite simple when understood.

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//Create root element
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//Add required children
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

For this to work properly the attribute xmlns:mobile must be set in the root node, and then used as namespace(third argument) when creating the mobile:mobile child with null as value.
thallisphp at gmail dot com 07-May-2014 07:35
<?php
class MySimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     *
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string)$append)) == 0) {
                $xml = $this->addChild($append->getName());
            } else {
                $xml = $this->addChild($append->getName(), (string)$append);
            }

            foreach ($append->children() as $child) {
                $xml->appendXML($child);
            }

            foreach ($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
frosty dot z at freesbee dot fr 16-May-2013 02:31
To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."

To work around that problem, you can use direct property assignment such as :

<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value &lt; &gt; &amp;</value>
?>

instead of doing :

<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value &lt; &gt; &</value> (invalid XML)
?>

See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

HTH
passerbyxp at gmail dot com 27-Mar-2013 03:59
Be aware that simply because you can <?php $dom->addChild();?> doesn't mean your XML is valid under simple XML itself:

<?php
$dom=simplexml_load_string("<test></test>");
$dom->addChild("3D","1,2,3");
$xml=$dom->asXML();
echo $xml;
/* echos:
<?xml version="1.0"?>
<test><3D>1,2,3</3D></test>
*/

$dom=simplexml_load_string($xml);
/*
generates a whole lots of warnings,
and refuses to create an object.
*/
?>

Same in PHP 5.3 and 5.4
ivan dot kakurov at gmail dot com 13-Jan-2013 04:09
Here's my solution for creating XML from Multidimensional Array.
<?php
//DATA
        $xmlDAta = array(
            array(
                "name"  => "nameVal",
                "value" => "valVal",
                "css"   => "cssVal"
            ),
            array(
                "name"  => "name1Val",
                "value" => "val1Val",
                "css"   => "css1Val"
            ),
            "tname" => array(
                array(
                    "iTname"   => "iTname",
                    "iTname2"  => "iTname1",
                    "iTname2"  => "iTname2",
                    "iTbname3" => array(
                        "iiTbname"  => "tbName",
                        "iiTbname1" => "tbName1",
                    ),
                ),
            ),
            "tdata" => "otheerDAta"
        );

   /**
     * Create XML using string or array
     *
     * @param mixed $data input data
     * @param SimpleXMLElement $xml
     * @param string $child name of first level child
     *
     * @return adding Xml formated data into SimpleXmlElement
     */

function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
    {

        foreach($data as $key => $val) {
            if(is_array($val)) {

                if(is_numeric($key)) {
                    $node  = $xml->addChild($child);
                    $nodes = $node->getName($child);
                } else {

                    $node  = $xml->addChild($key);
                    $nodes = $node->getName($key);
                }

                $node->addChild($nodes, self::data2Xml($val, $node));
            } else {
                $xml->addChild($key, $val);
            }
        }

    }

//Use

        $xml    = new SimpleXMLElement("<root/>");
        Util::data2XML($xmlDAta, $xml, "Items");

?>
jerikojerk 31-Jul-2011 07:32
If you're looking for a way to append children you may be interested in this:

<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');

$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
    var_dump($foo);
}

?>
alex dot feraud at gmail dot com 16-Jun-2011 02:52
Here is a class with more functions for SimpleXMLElement :

<?php
/**
 *
 * Extension for SimpleXMLElement
 * @author Alexandre FERAUD
 *
 */
class ExSimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
  private function addCData($cdata_text)
  {
   $node= dom_import_simplexml($this);
   $no = $node->ownerDocument;
   $node->appendChild($no->createCDATASection($cdata_text));
  }

  /**
   * Create a child with CDATA value
   * @param string $name The name of the child element to add.
   * @param string $cdata_text The CDATA value of the child element.
   */
    public function addChildCData($name,$cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string) $append))==0) {
                $xml = $this->addChild($append->getName());
                foreach($append->children() as $child) {
                    $xml->appendXML($child);
                }
            } else {
                $xml = $this->addChild($append->getName(), (string) $append);
            }
            foreach($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
Volker Grabsch 21-Apr-2011 06:17
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
felipenmoura at gmail dot com 11-Apr-2011 06:06
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
    $xml= new SimpleXMLElement('<root></root>');
    $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
    $son= $xml->father->addChild('son'); // uses the first father tag
    $son['name']= 'first son';
    $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
    $otherSon['name']= 'second son';

    echo htmlentities($xml->asXML());
?>

The result will be
<root>
    <father>
        <son name='first son' />
        <son name='second son' />
    </father>
</root>

So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.


Return a well-formed XML string based on SimpleXML element

  • ? SimpleXMLElement::addChild
  • SimpleXMLElement::attributes ?
  • PHP Manual
  • SimpleXMLElement
  • Return a well-formed XML string based on SimpleXML element

SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element

说明

public SimpleXMLElement::asXML ( string $filename = ? ) : mixed

The asXML method formats the parent object's data in XML version 1.0.

参数

filename

If specified, the function writes the data to the file rather than returning it.

返回值

If the filename isn't specified, this function returns a string on success and false on error. If the parameter is specified, it returns true if the file was written successfully and false otherwise.

范例

Example #1 Get XML

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

以上例程会输出：

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

asXML also works on Xpath results:

Example #2 Using asXML() on SimpleXMLElement::xpath() results

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
    echo $node->asXML();
}
?>

以上例程会输出：

<c>text</c><c>stuff</c>

参见

  • SimpleXMLElement::__toString() - Returns the string content
  • Basic SimpleXML usage

User Contributed Notes

andreas dot theissen at t-online dot de 27-Oct-2012 12:37
To prevent asXML from encoding vowels unwantedly, simply use an approriate XML header with encoding in advance.

If you do so, asXML will happily leave your vowels (and the header) entirely untouched.

<?php

$xmlstr =
'<?xml version="1.0" encoding="UTF-8"?>
<keys>
  <key lang="en">&lt;Insert&gt;</key>
  <key lang="de">&lt;Einfügen&gt;</key>
</keys>';

$sxe = new SimpleXMLElement($xmlstr);

$output = $sxe->asXML();

?>

$xmlstr and $output are identical now.

The subsequent use of html_entity_decode() (as proposed in the very beginning in another post) has several drawbacks:

1. It is slow
2. It is expensive
3. If there are already encoded arrow brackets or double quotes in your source for instance (as shown in the above example), markup will be broken.
oleg dot pavlin at gmail dot com 10-Jan-2012 04:17
Function asXML decodes special chars like ?, ? and others to &#xE6;, &#xF8;

To get normal output use without quoting:

$xml = html_entity_decode($xml, ENT_NOQUOTES, 'UTF-8');
jcr at di dot uminho dot pt 25-Jan-2011 02:32
Code snippet to load a XML document, increment an attribute and store it again.
My XML looks like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<doctypes counter="16">
    <doctype id="d1">
        <name>Carta</name>
        <acro>CA</acro>
    </doctype>
...
</doctypes>

I want to retrieve the counter attribute, increment it, and store the new document at the end:

<?php
  $document = simplexml_load_file("mydoc.xml");
  $cont = (integer) $document['counter'];
  $document['counter'] = $cont+1;
  $document->asXML("mydoc.xml");
?>


Identifies an element's attributes

  • ? SimpleXMLElement::asXML
  • SimpleXMLElement::children ?
  • PHP Manual
  • SimpleXMLElement
  • Identifies an element's attributes

SimpleXMLElement::attributes

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::attributes — Identifies an element's attributes

说明

public SimpleXMLElement::attributes ( string $ns = null , bool $is_prefix = false ) : SimpleXMLElement

This function provides the attributes and values defined within an xml tag.

Note: SimpleXML 建起了一个给大多数方法添加迭代属性的规则。不能通过使用 var_dump() 或任何可检查对象的其它东西来查看。

参数

ns

An optional namespace for the retrieved attributes

is_prefix

Default to false

返回值

Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.

Returns null if called on a SimpleXMLElement object that already represents an attribute and not a tag.

更新日志

版本 | 说明
5.2.0 | The optional parameter is_prefix was added.

范例

Example #1 Interpret an XML string

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

以上例程会输出：

name="one"
game="lonely"

参见

  • Basic SimpleXML usage

User Contributed Notes

jurchiks101 at gmail dot com 23-May-2018 12:38
An undocumented way - and, IMO, a hack - of getting an element's value OR attributes
(but not both) without type-casting is to use the function `current()`:

<?php
$xml = new SimpleXMLElement(<<<'XML'
<foo>
    <bar>1</bar>
    <baz name="baz" />
    <qux name="qux">3</qux>
</foo>
XML
);

var_dump([
    'bar' => [
        $xml->bar,
        current($xml->bar),
    ],
    'baz' => [
        $xml->baz->attributes(),
        current($xml->baz->attributes()),
    ],
    'qux' => [
        // won't work here correctly
        $xml->qux,
        current($xml->qux),
        $xml->qux->attributes(),
        current($xml->qux->attributes()),
    ],
]);
?>

Results in the following output (re-formatted to shorten it):
```
array(3) {
  'bar' => array(2) {
    [0] => class SimpleXMLElement#2 (1) {
      public ${0} => string(1) "1"
    }
    [1] => string(1) "1"
  }
  'baz' => array(2) {
    [0] => class SimpleXMLElement#5 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [1] => array(1) {
      'name' => string(3) "baz"
    }
  }
  'qux' => array(4) {
    [0] => class SimpleXMLElement#6 (2) {
      public $@attributes => array(1) {
        ...
      }
      public ${0} => string(1) "3"
    }
    [1] => array(1) {
      'name' => string(3) "qux"
    }
    [2] => class SimpleXMLElement#7 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [3] => array(1) {
      'name' => string(3) "qux"
    }
  }
}
```

This apparently reads the element as an array and just returns the value of the first property, whether it be the attributes or the value. As seen in the third example, this is unreliable, especially if you're parsing XML from an outside source that may or may not have attributes on an element that you want the value of.

I certainly do NOT advise anyone to use this since it is undocumented and it is just a coincidence that it works, so it might break in the future without prior notice.
andy dot locologic+101 at gmail dot com 14-Aug-2015 10:00
Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see http://php.net/manual/en/function.iterator-to-array.php):

<?php
      $x = new SimpleXMLElement('<div class="myclass" id="myid"/>');
      $attributes = iterator_to_array($x->attributes());
?>
zevnikrok 18-Dec-2014 11:01
If you wish to get attributes as an associative array of key value pairs, you don't need to iterate through them, you can get it with this one liner:

  reset($element->attributes())
webfelipemaia at gmail dot com 07-Sep-2013 05:11
Use attributes to display when it meets certain condition defined attribute / value in xml tags.

Use atributos para exibir quando atende determinada condi??o definida atributo / valor em tags XML.

Consider the following example:
Considere o seguinte exemplo:

(file.xml)

<?xml version="1.0" encoding="UTF-8"?>

<list>
    <item type="Language">
        <name>PHP</name>
        <link>www.php.net</link>
    </item>
    <item type="Database">
        <name>Java</name>
        <link>www.oracle.com/br/technologies/java/?</link>
    </item>
</list>

Checks if the attribute value equals "Language", if equal prints everything that is related to "Language".

Verifica se o valor do atributo é igual a "Language", se for, imprime tudo o que for relativo ao mesmo.

<?php

$xml = simplexml_load_file("file.xml");

foreach($xml->children() as $child) {

        $role = $child->attributes();

        foreach($child as $key => $value) {

            if($role == "Language")
            echo("[".$key ."] ".$value . "<br />");

        }
}
?>

output:
saída:

[name] PHP
[link] www.php.net
adrian at foeder dot de 14-Jun-2013 10:15
in order to get a possibly present xml:space attribute, use the following construct:

<?php
$simpleXmlElement->element->attributes('http://www.w3.org/XML/1998/namespace')->space;
?>

This will, for example, return 'preserve' if set.

Just passing by 'xml' as namespace argument of the attribute() method didn't work out for me. Passing by the complete namespace URI works also if it is not explicitly defined in the underlying XML document.

Also, $simpleXmlElement->getNamespaces() does not return anything of use.
totalwipeout at gmail dot com 08-Nov-2012 05:21
Tip to get a real array of all attributes of a node (not SimpleXML's object acting like an array)

<?php
//- $node is a SimpleXMLElement object

$atts_object = $node->attributes(); //- get all attributes, this is not a real array
$atts_array = (array) $atts_object; //- typecast to an array

//- grab the value of '@attributes' key, which contains the array your after
$atts_array = $atts_array['@attributes'];

var_dump($atts_object); //- outputs object(SimpleXMLElement)[19]
                        //-             public '@attributes' => ...

var_dump($atts_array); //- outputs array (size=11) ...

?>
Hope this helps!
chris at chlab dot ch 23-Mar-2012 10:16
Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Table Foo="Bar" ss:ExpandedColumnCount="7">
 </Table>
</Workbook>
XML;

$sxml = new SimpleXMLElement($xml);

/**
 * Access attribute of default namespace
 */
var_dump((string) $sxml->Table[0]['Foo']);
// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */
var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);
// outputs: 0

var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);
// outputs: '7'
?>
Andrei 16-May-2011 04:46
Reading the attributes of the root element with name space prefixes as in an Atom feed

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;Ck4EQXYzeCp7ImA9WhZWFE4.&quot;">

<?php
$xml =  @simplexml_load_file($feed);
$att_gd = $xml->attributes("gd",1);
$Etag = $att_gd["etag"];
?>
sarlak 27-Apr-2011 01:12
<?php
$att = 'attribueName';

// You can access an element's attribute just like this :
$attribute = $element->attributes()->$att;

// This will save the value of the attribute, and not the objet
$attribute = (string)$element->attributes()->$att;

// You also can edit it this way :
$element->attributes()->$att = 'New value of the attribute';
?>
leap 02-Apr-2011 09:07
If you want to save the value of an attribute into an array, typecast it to a string.

<?php
// stores an xml-element-object
$dataStore['value'] = $attributes->myValue

// stores the value of the attribute
$dataStore['value'] = (string)$attributes->myValue
?>
alan at performantsystems dot com 23-May-2010 10:26
So lets say you have database type data in an XML string called $xmlstring with the key or item ID as an XML Attribute and all content data as regular XML Elements, as above. SimpleXML processes the Attributes as an array, so we can play along and push the Attributes into an array. Then we can get the value of any specific Attribute we want by addressing it by name, such as "ID".

Considering this data:

<?xml version="1.0" encoding="utf-8"?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company>Digital Showcase</Company>
   </item>
</data>

Example of listing both the ID Attribute and Company Element values:

<?php
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node) {
        $arr = $node->attributes();   // returns an array
        print ("ID=".$arr["ID"]);     // get the value of this attribute
        print ("  Company=".$node->Company);
        print ("<p><hr>");
}
?>
Xeoncross 10-Apr-2010 07:46
It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

<?php
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 55555
        )

    [text] => "hello world"
)
?>

Then using a function

<?php
function xml_attribute($object, $attribute)
{
    if(isset($object[$attribute]))
        return (string) $object[$attribute];
}
?>

I can get the "id" like this

<?php
print xml_attribute($xml, 'id'); //prints "55555"
?>
gillllberg at gmail dot com 04-Nov-2009 02:21
To get an attribute in the node, use node->attributes()->attributeName
skerr at mojavi dot org 09-Dec-2004 10:55
You can also access the node as an array to get attributes:

<?php

$xml = simplexml_load_file('file.xml');

echo 'Attribute: ' . $xml['attribute'];

?>
inge at elektronaut dot no 26-May-2004 10:53
here's a simple function to get an attribute by name, based on the example

<?php
function findAttribute($object, $attribute) {
  foreach($object->attributes() as $a => $b) {
    if ($a == $attribute) {
      $return = $b;
    }
  }
  if($return) {
    return $return;
  }
}
?>


Finds children of given node

  • ? SimpleXMLElement::attributes
  • SimpleXMLElement::__construct ?
  • PHP Manual
  • SimpleXMLElement
  • Finds children of given node

SimpleXMLElement::children

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::children — Finds children of given node

说明

public SimpleXMLElement::children ( string $ns = ? , bool $is_prefix = false ) : SimpleXMLElement

This method finds the children of an element. The result follows normal iteration rules.

Note: SimpleXML 建起了一个给大多数方法添加迭代属性的规则。不能通过使用 var_dump() 或任何可检查对象的其它东西来查看。

参数

ns

An XML namespace.

is_prefix

If is_prefix is true, ns will be regarded as a prefix. If false, ns will be regarded as a namespace URL.

返回值

Returns a SimpleXMLElement element, whether the node has children or not.

范例

Example #1 Traversing a children() pseudo-array

<?php
$xml = new SimpleXMLElement(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

foreach ($xml->children() as $second_gen) {
    echo ' The person begot a ' . $second_gen['role'];

    foreach ($second_gen->children() as $third_gen) {
        echo ' who begot a ' . $third_gen['role'] . ';';

        foreach ($third_gen->children() as $fourth_gen) {
            echo ' and that ' . $third_gen['role'] .
                ' begot a ' . $fourth_gen['role'];
        }
    }
}
?>

以上例程会输出：

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Example #2 Using namespaces

<?php
$xml = '<example xmlns:foo="my.foo.urn">
  <foo:a>Apple</foo:a>
  <foo:b>Banana</foo:b>
  <c>Cherry</c>
</example>';

$sxe = new SimpleXMLElement($xml);

$kids = $sxe->children('foo');
var_dump(count($kids));

$kids = $sxe->children('foo', TRUE);
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn');
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn', TRUE);
var_dump(count($kids));

$kids = $sxe->children();
var_dump(count($kids));
?>
int(0)
int(2)
int(2)
int(0)
int(1)

注释

SimpleXMLElement::children() returns a node object no matter if the current node has children or not. Use count() on the return value to see if there are any children. As of PHP 5.3.0, SimpleXMLElement::count() may be used instead.

参见

  • SimpleXMLElement::count() - Counts the children of an element
  • count() - 计算数组中的单元数目，或对象中的属性个数

User Contributed Notes

boan dot web at outlook dot com 15-Mar-2019 07:09
SimpleXMLElement::children can return null in this case:

<?php
$xml = '
<root attr="Hello"/>
';

$sxe = new SimpleXMLElement($xml);

$sxe_xpath = $sxe->xpath('/root/@attr')[0];

$children = $sxe_xpath->children();

var_export($children); // Is null
?>
thetazzbot at gmail dot com 08-Sep-2011 06:56
Ok so say you have this xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE nitf
PUBLIC "-//IPTC-NAA//DTD NITF 3.1//EN"
       "http://www.nitf.org/site/nitf-documentation/nitf-3-1.dtd">
<nitf>
  <head>
    <docdata management-status="embargoed">
      <!--data/2011/08/23/parties/doc4e53aa5783cca930694817.txt-->
      <doc-id id-string="doc4e53aa5783cca930694817"/>
      <date.release norm="20110823T000000"/>
      <key-list/>
    </docdata>
    <pubdata type="web" position.section="parties" position.sequence="0"/>
  </head>

-- snip --

If you need to access the nodes named "like.this" such as the date.release above, here is how I did it:

$xml = new SimpleXMLElement($xhtml);
 echo (string)$xml->head->docdata->{"date.release"}["norm"];

Took me a while to figure that one out ;)
coldshine1 at rambler dot ru 10-Dec-2010 02:37
This is my recursive simple function to parse XML with attributes.

<?php
function ParseXML($node, &$parent=array(), $only_child=true) {

        //Current node name
        $node_name = $node->getName();

        //Let's count children
        $only_child = true;
        if($node->count() > 1 ) $only_child = false;

        //If there is no child, then there may be text data
        if($only_child){
            $content="$node";
            if (strlen($content)>0) $parent['content']=$content;
        }

        //Get attributes of current node
        foreach ($node->attributes() as $k=>$v) {
            $parent['@attributes'][$k]="$v";
        }

        //Get children
        $count = 0;
        foreach ($node->children() as $child_name=>$child_node) {
            if(!$only_child) //If there are siblings then we'll add node to the end of the array
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name][$count], $only_child);
            else
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name], $only_child);
            $count++;
        }

        return $parent;
        //(c) c01d[s]h!nE 10.12.2010
    }

?>
Anonymous 26-Oct-2010 05:19
Here's my xml-to-array routine. Unlike many of the other comments here, this one takes namespaces into account.

<?php

class XmlArray {

  public function load_dom ($xml) {
    $node=simplexml_import_dom($xml);
    return $this->add_node($node);
  }

  public function load_string ($s) {
    $node=simplexml_load_string($s);
    return $this->add_node($node);
  }

  private function add_node ($node, &$parent=null, $namespace='', $recursive=false) {

    $namespaces = $node->getNameSpaces(true);
    $content="$node";

    $r['name']=$node->getName();
    if (!$recursive) {
      $tmp=array_keys($node->getNameSpaces(false));
      $r['namespace']=$tmp[0];
      $r['namespaces']=$namespaces;
    }
    if ($namespace) $r['namespace']=$namespace;
    if ($content) $r['content']=$content;

    foreach ($namespaces as $pre=>$ns) {
      foreach ($node->children($ns) as $k=>$v) {
        $this->add_node($v, $r['children'], $pre, true);
      }
      foreach ($node->attributes($ns) as $k=>$v) {
        $r['attributes'][$k]="$pre:$v";
      }
    }
    foreach ($node->children() as $k=>$v) {
      $this->add_node($v, $r['children'], '', true);
    }
    foreach ($node->attributes() as $k=>$v) {
      $r['attributes'][$k]="$v";
    }

    $parent[]=&$r;
    return $parent[0];

  }

}

?>
mrdaniellee at live dot com 10-Jan-2010 09:11
use this If you want to view the HTML as well as data.

normal dumps display the parsed versions of HTML.
This code displays the HTML as Text in a Text Area, and also display all other a data along side as an array

perfect for debugging (xml with html).

Try This Code:

<?php
$xml  = simplexml_load_file($url);

function xml2array_parse($xml){
     foreach ($xml->children() as $parent => $child){
         $return["$parent"] = xml2array_parse($child)?xml2array_parse($child):"$child";
     }
     return $return;
 }

 print "<pre><textarea style=\"width:200%;height:100%;\">";
 print_r(xml2array_parse($xml));
 print "</textarea></pre>";
?>
rodmen at gmail dot com 21-May-2009 08:32
Transform xml to array php

<?php
function xml2phpArray($xml,$arr){
    $iter = 0;
        foreach($xml->children() as $b){
                $a = $b->getName();
                if(!$b->children()){
                        $arr[$a] = trim($b[0]);
                }
                else{
                        $arr[$a][$iter] = array();
                        $arr[$a][$iter] = xml2phpArray($b,$arr[$a][$iter]);
                }
        $iter++;
        }
        return $arr;
}

$Array = simplexml_load_string(file_get_contents('myfile.xml'));
print_r(xml2phpArray($Array,array()));
?>
Anonymous 06-Sep-2008 05:39
for XML namespaces such as <dc:creator> in RSS feeds use

<?php
    $xml = new SimpleXMLElement($string);
    $item = $xml->channel[0]->item[0];
    $dc = $item->children("http://purl.org/dc/elements/1.1/");
    echo $dc->creator;
?>
transglobe at gmx dot de 19-Mar-2008 02:37
I made a slightly differnt approch towards the RecurseXML function. Beeing hungry I had problems with the code, as it did just overwrite two <maincourse>s. So here is what I did:

<?php

$xml = new SimpleXMLElement(
'<meal>
   <type>Lunch</type>
   <time>12:30</time>
   <menu>
     <entree>salad</entree>
     <maincourse>
        <part>ships</part>
        <part>steak</part>
     </maincourse>
     <maincourse>
        <part>fisch</part>
        <part>rice</part>
     </maincourse>
     <maincourse>
        <part>wine</part>
        <part>cheese</part>
     </maincourse>
   </menu>
</meal>');

$vals = array();
RecurseXML($xml,$vals);

foreach($vals as $key=>$value)
  print("{$key} = {$value}<BR>\n");

function RecurseXML($xml,&$vals,$parent="") {

  $childs=0;
  $child_count=-1; # Not realy needed.
  $arr=array();
        foreach ($xml->children() as $key=>$value) {
                if (in_array($key,$arr)) {
                        $child_count++;
                } else {
                        $child_count=0;
                }
                $arr[]=$key;
                $k=($parent == "") ? "$key.$child_count" : "$parent.$key.$child_count";
                $childs=RecurseXML($value,$vals,$k);
                if ($childs==0) {
                        $vals[$k]= (string)$value;
                }
        }

  return $childs;
}

?>
Output is like this:
type.0 = Lunch
time.0 = 12:30
menu.0.entree.0 = salad
menu.0.maincourse.0.part.0 = ships
menu.0.maincourse.0.part.1 = steak
menu.0.maincourse.0 =
menu.0.maincourse.1.part.0 = fisch
menu.0.maincourse.1.part.1 = rice
menu.0.maincourse.1 =
menu.0.maincourse.2.part.0 = wine
menu.0.maincourse.2.part.1 = cheese
menu.0.maincourse.2 =
menu.0 =

(Not beautiful, but it solved my case...)
crescentfreshpot at yahoo dot com 10-Dec-2007 08:16
Just a warning that the iterable returned from children() contains the '@attributes' key, which is "invisible" during a foreach but can be seen if using a different construct, such as list()=each() or casting to an array before iterating w/ foreach.
aero 23-May-2007 08:07
Here's a simple, recursive, function to transform XML data into pseudo E4X syntax ie. root.child.value = foobar

<?php
error_reporting(E_ALL);

$xml = new SimpleXMLElement(
'<Patriarch>
   <name>Bill</name>
   <wife>
     <name>Vi</name>
   </wife>
   <son>
     <name>Bill</name>
   </son>
   <daughter>
     <name>Jeri</name>
     <husband>
       <name>Mark</name>
     </husband>
     <son>
       <name>Greg</name>
     </son>
     <son>
       <name>Tim</name>
     </son>
     <son>
       <name>Mark</name>
     </son>
     <son>
       <name>Josh</name>
         <wife>
           <name>Kristine</name>
         </wife>
         <son>
           <name>Blake</name>
         </son>
         <daughter>
           <name>Liah</name>
         </daughter>
     </son>
   </daughter>
</Patriarch>');

RecurseXML($xml);

function RecurseXML($xml,$parent="")
{
   $child_count = 0;
   foreach($xml as $key=>$value)
   {
      $child_count++;
      if(RecurseXML($value,$parent.".".$key) == 0)  // no childern, aka "leaf node"
      {
         print($parent . "." . (string)$key . " = " . (string)$value . "<BR>\n");
      }
   }
   return $child_count;
}

?>

The output....

.name = Bill
.wife.name = Vi
.son.name = Bill
.daughter.name = Jeri
.daughter.husband.name = Mark
.daughter.son.name = Greg
.daughter.son.name = Tim
.daughter.son.name = Mark
.daughter.son.name = Josh
.daughter.son.wife.name = Kristine
.daughter.son.son.name = Blake
.daughter.son.daughter.name = Liah
taylorbarstow at that google mail thingy 21-Apr-2006 07:38
Sometimes you actually want an array, not a pseudo array.   This is especially true when you aren't dealing with attributes (i.e., you just want the array of child nodes).

Do like this:

<?php
$children = $sxml->xpath('child::node()');
?>

The reason you might want this is to be able to use array functions like array_shift, array_pop, etc.  This is especially true when you are writing recursive functions.  Simplexml works really well in iterative programming, but if you try to implement recursion it gets ugly.
Sebastian 27-Oct-2005 03:45
Just a quick addition:

If you need to access a child node which contains a dash, you need to encapsulate it with {""}.

For example:
<?php
foreach ($domain->domain-listing as $product) {
}
?>

The example above doesn't work because of the dash. But instead you need to use:
<?php
foreach ($domain->{"domain-listing"} as $product) {
}
?>

At least for me the second example works perfectly fine.
no-one 31-May-2005 06:05
For anyone who hasn't read Sterling Hughe's article (http://www.zend.com/php5/articles/php5-simplexml.php):

<?php
$xml_document =<<<EOT
<?xml version="1.0"?>
<root xmlns:foo="http://example.com">
  <foo:bar>baz</foo:bar>
</root>
EOT;

$xml_document = simplexml_load_xml($xml_document);

$foo_ns_bar = $xml_document->children('http://example.com');

echo $foo_ns_bar->bar[0]; // prints 'baz'
?>
Andrew Rose (rose dot andrew at gmail dot com) 16-Mar-2005 04:48
The example below shows the basic use of depth-first recursion to span the xml tree.

This is coded for the command line, and it prints out the original sentance above and then the copy cat sentence it creates itself for comparison, which as you will see; this example is slightly off from, I'll leave it upto you to resolve this issue.

All in all I personaly think xml and recursion go hand in hand, so if you don't understand recursion but know xml and want to use php to manipulate xml you will need to learn about recursion at some point.

<?php
$xml = simplexml_load_string(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

function recurse($child)
 {
   foreach($child->children() as $children) {
     echo ' who begot a '.$children['role'];
     recurse($children);
   }
    return;
 }

foreach($xml->children() as $children) {
 echo 'The person begot a '.$children['role'];
  recurse($children, 0);
 echo '; ';
}

echo "\n";
echo 'The person begot a son who begot a daughter; The person begot a daughter who begot a son; and that son begot a son'."\n";

?>
zyxwvu at users dot sourceforge dot net 15-Feb-2004 10:32
File:

<category>
  <item>text</item>
  <bold>text</bold>
  <item>text</item>
  <item>text</item>
  <mark>text</mark>
  <bold>text</bold>
</category>

If you want to get also names of the tags, you can use this loop layout:

<?php
foreach($category -> children() as $name => $node){
  echo $name.'<br/>';
}
?>


Creates a new SimpleXMLElement object

  • ? SimpleXMLElement::children
  • SimpleXMLElement::count ?
  • PHP Manual
  • SimpleXMLElement
  • Creates a new SimpleXMLElement object

SimpleXMLElement::__construct

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::__construct — Creates a new SimpleXMLElement object

说明

final public SimpleXMLElement::__construct ( string $data , int $options = 0 , bool $data_is_url = false , string $ns = "" , bool $is_prefix = false )

Creates a new SimpleXMLElement object.

参数

data

A well-formed XML string or the path or URL to an XML document if data_is_url is true.

options

Optionally used to specify additional Libxml parameters, which affect reading of XML documents. Options which affect the output of XML documents (e.g. LIBXML_NOEMPTYTAG) are silently ignored.

Note:

It may be necessary to pass LIBXML_PARSEHUGE to be able to process deeply nested XML or very large text nodes.

data_is_url

By default, data_is_url is false. Use true to specify that data is a path or URL to an XML document instead of string data.

ns

Namespace prefix or URI.

is_prefix

true if ns is a prefix, false if it's a URI; defaults to false.

返回值

Returns a SimpleXMLElement object representing data.

错误／异常

Produces an E_WARNING error message for each error found in the XML data and additionally throws an Exception if the XML data could not be parsed.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

更新日志

版本 | 说明
5.2.0 | Added the ns and is_prefix parameters.
5.1.2 | Added the options and data_is_url parameters.

范例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Create a SimpleXMLElement object

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

以上例程会输出：

PHP: Behind the Parser

Example #2 Create a SimpleXMLElement object from a URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

参见

  • Basic SimpleXML usage
  • simplexml_load_string() - Interprets a string of XML into an object
  • simplexml_load_file() - Interprets an XML file into an object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed

User Contributed Notes

rowan dot collins at gmail dot com 22-Apr-2017 03:23
The manual doesn't really explain what the $ns argument (and the accompanying $is_prefix) are for.

What they do is similar to the ->children() method: they set the context of the returned object to that namespace, so that access via ->elementName and ['attributeName'] refer to elements and attributes in that namespace.

In particular, they do *not* change the namespaces which exist on the document.

See this example:

<?php
// This XML contains two elements called <child>
// One is in the namespace http://example.com, with local prefix 'ws'
// The other has no namespace (no prefix, and no default namespace declared)
$xml = '<ws:example xmlns:ws="http://example.com"><child>Not in namespace</child><ws:child>In example namespace</ws:child></ws:example>';

$sx0 = new SimpleXMLElement($xml, 0, false);
$sx1 = new SimpleXMLElement($xml, 0, false, 'http://example.com');
$sx2 = new SimpleXMLElement($xml, 0, false, 'ws', true);

echo "
    Without: {$sx0->child}
    By namespace: {$sx1->child}
    By prefix: {$sx2->child}
";
?>

Output:

 Without: Not in namespace
 By namespace: In example namespace
 By prefix: In example namespace
ahmad dot mayahi at gmail dot com 07-Jun-2016 09:36
You won't be able to load an XML file without root element:

//This will throw an exception
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>', null, false);

//Here is the solution
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>', null, false);
Phil Cross 01-Sep-2014 11:39
It's worth noting, that you need to typecast dynamic property names to string in order to retrieve there value, for example:

<?php
    $xml = new SimpleXMLElement('records.xml', 0, true);

    // This will work as expected because its a hard coded property value
    foreach($xml as $record){
        echo $record->id;    // Will output the ID fine
    }

    // Dynamic properties require typecasting to string
    $xml_field = 'id';
    foreach($xml as $record){

        // This will dump a SimpleXMLElement object
        var_dump($record->$xml_field);

        // This will output the value as expected
        echo (string)$record->$xml_field;
    }
?>
bertolini dot cedric at me dot com 16-Jun-2014 11:07
It's worth noting that the behavior of SimpleXmlElement::__construct is not exactly the same as simplexml_load_string, regarding libxml_use_internal_errors().

In my case,

<?php
libxml_use_internal_errors(true);
new \SimpleXmlElement($data);
?>

was still throwing error. But as soon as I switched to

<?php
libxml_use_internal_errors(true);
simplexml_load_string($data);
?>

everything worked fine and I stopped getting an error.
kumarldh at gmail dot com 22-Mar-2011 10:50
Using libxml_use_internal_errors() may suppress errors but Exception still requires decent handling. I used following code snippet.

<?php
libxml_use_internal_errors(true);
try{
    $xmlToObject = new SimpleXMLElement($notSoWellFormedXML);
} catch (Exception $e){
    echo 'Please try again later...';
    exit();
}
?>
uramihsayibok, gmail, com 16-Aug-2009 06:52
As I was filling out a bug report, I realized why (speculation here) the constructor is final: so that functions like simplexml_load_file and simplexml_load_string can work. I imagine the PHP-ized code looks something like

<?php

function simplexml_load_file($filename, $class_name = "SimpleXMLElement", $options = 0, $ns = "", $is_prefix = false) {
    return new $class_name($filename, $options, true, $ns, $is_prefix);
}

?>

If we were to use a different $class_name and change the constructor's definition these functions wouldn't work.

There's no easy, sensible solution that keeps simplexml_load_file and simplexml_load_string.
tudor at culise dot net 20-Nov-2007 03:35
This class is extendable, but it's too bad that its constructor cannot be overriden (PHP says it's a final method). Thus the class should be wrapped using the delegation principle rather that extended.


Counts the children of an element

  • ? SimpleXMLElement::__construct
  • SimpleXMLElement::getDocNamespaces ?
  • PHP Manual
  • SimpleXMLElement
  • Counts the children of an element

SimpleXMLElement::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SimpleXMLElement::count — Counts the children of an element

说明

public SimpleXMLElement::count ( ) : int

This method counts the number of children of an element.

返回值

Returns the number of elements of an element.

范例

Example #1 Counting the number of children

<?php
$xml = <<<EOF
<people>
 <person name="Person 1">
  <child/>
  <child/>
  <child/>
 </person>
 <person name="Person 2">
  <child/>
  <child/>
  <child/>
  <child/>
  <child/>
 </person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
    printf("%s has got %d children.\n", $person['name'], $person->count());
}
?>

以上例程会输出：

Person 1 has got 3 children.
Person 2 has got 5 children.

参见

  • SimpleXMLElement::children() - Finds children of given node

User Contributed Notes

daniel dot erni at focusedpublishing dot com 22-Mar-2011 08:37
Alternative code for PHP < 5.3:
<?php
$count = $node->count(); // PHP > 5.3
$count = count($node->children()); // PHP < 5.3
?>


Returns namespaces declared in document

  • ? SimpleXMLElement::count
  • SimpleXMLElement::getName ?
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces declared in document

SimpleXMLElement::getDocNamespaces

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document

说明

public SimpleXMLElement::getDocNamespaces ( bool $recursive = false , bool $from_root = true ) : array

Returns namespaces declared in document

参数

recursive

If specified, returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node.

from_root

Allows you to recursively check namespaces under a child node instead of from the root of the XML doc.

返回值

The getDocNamespaces method returns an array of namespace names with their associated URIs.

范例

Example #1 Get document namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces();
var_dump($namespaces);

?>

以上例程会输出：

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Example #2 Working with multiple namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person t:id="1">John Doe</p:person>
    <p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
        Susie Q. Public
    </p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

以上例程会输出：

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

参见

  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query

User Contributed Notes

There are no user contributed notes for this page.


Gets the name of the XML element

  • ? SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces ?
  • PHP Manual
  • SimpleXMLElement
  • Gets the name of the XML element

SimpleXMLElement::getName

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::getName — Gets the name of the XML element

说明

public SimpleXMLElement::getName ( ) : string

Gets the name of the XML element.

返回值

The getName method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.

范例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Get XML element names

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
    echo $child->getName() . "\n";
}

?>

以上例程会输出：

movies
movie

User Contributed Notes

There are no user contributed notes for this page.


Returns namespaces used in document

  • ? SimpleXMLElement::getName
  • SimpleXMLElement::registerXPathNamespace ?
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces used in document

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SimpleXMLElement::getNamespaces — Returns namespaces used in document

说明

public SimpleXMLElement::getNamespaces ( bool $recursive = false ) : array

Returns namespaces used in document

参数

recursive

If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

返回值

The getNamespaces method returns an array of namespace names with their associated URIs.

范例

Example #1 Get document namespaces in use

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

以上例程会输出：

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

参见

  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query

User Contributed Notes

thiago at osfeio dot com 29-Oct-2013 04:23
this article has more info : http://www.sitepoint.com/parsing-xml-with-simplexml/
harry at nospam dot thestorm dot plus dot com 17-Feb-2012 02:21
If the namespace is nested in the xml, then you will have to loop over the nodes.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
  <people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
      <items>
            <title>This is a test of namespaces and my patience</title>
            <p:person id="1">John Doe</p:person>
            <p:person id="2">Susie Q. Public</p:person>
            <p:person id="1">Fish Man</p:person>
      </items>
  </people>
XML;

$sxe = new SimpleXMLElement($xml);

foreach ($sxe as $out_ns)
{
    $ns = $out_ns->getNamespaces(true);

    $child = $out_ns->children($ns['p']);

    foreach ($child as $out)
    {
        echo $out . "<br />";
    }
}
?>
harry at nospam dot thestorm dot plus dot com 16-Feb-2012 12:50
To read a namespace node you have to use the children method.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$ns = $sxe->getNamespaces(true);

$child = $sxe->children($ns['p']);

foreach ($child->person as $out_ns)
{
    echo $out_ns;
}

?>


Creates a prefix/ns context for the next XPath query

  • ? SimpleXMLElement::getNamespaces
  • SimpleXMLElement::saveXML ?
  • PHP Manual
  • SimpleXMLElement
  • Creates a prefix/ns context for the next XPath query

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query

说明

public SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns ) : bool

Creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. registerXPathNamespace will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider.

参数

prefix

The namespace prefix to use in the XPath query for the namespace given in ns.

ns

The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using prefix will not return any results.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Setting a namespace prefix to use in an XPath query

<?php

$xml = <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
    <title>My Book</title>
    <chapter id="1">
        <chap:title>Chapter 1</chap:title>
        <para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
            In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
            Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
            ultricies id, mauris.</para>
    </chapter>
    <chapter id="2">
        <chap:title>Chapter 2</chap:title>
        <para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
            gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
            vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
            tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
    </chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach ($result as $title) {
  echo $title . "\n";
}

?>

以上例程会输出：

Chapter 1
Chapter 2

Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.

参见

  • SimpleXMLElement::xpath() - Runs XPath query on XML data
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document

User Contributed Notes

Lea Hayes 12-Jan-2011 09:56
Looks like you have to use registerXPathNamespace for each node when using XPath:

<?php
$xml = simplexml_load_file($filename);

$xml->registerXPathNamespace('test', 'http://example.com');

$shopping_element = $xml->xpath('test:shopping-list');

// Breaks with out the following line:

$shopping_element->registerXPathNamespace('test', 'http://example.com');

$fruit = $shopping_element->xpath('test:fruit');
?>


别名 SimpleXMLElement::asXML

  • ? SimpleXMLElement::registerXPathNamespace
  • SimpleXMLElement::__toString ?
  • PHP Manual
  • SimpleXMLElement
  • 别名 SimpleXMLElement::asXML

SimpleXMLElement::saveXML

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SimpleXMLElement::saveXML — 别名 SimpleXMLElement::asXML()

说明

此方法是该方法的别名： SimpleXMLElement::asXML()

User Contributed Notes

There are no user contributed notes for this page.


Returns the string content

  • ? SimpleXMLElement::saveXML
  • SimpleXMLElement::xpath ?
  • PHP Manual
  • SimpleXMLElement
  • Returns the string content

SimpleXMLElement::__toString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SimpleXMLElement::__toString — Returns the string content

说明

public SimpleXMLElement::__toString ( ) : string

Returns text content that is directly in this element. Does not return text content that is inside this element's children.

参数

此函数没有参数。

返回值

Returns the string content on success or an empty string on failure.

范例

Example #1 Get string content

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

以上例程会输出：

1 3

参见

  • SimpleXMLElement::asXML() - Return a well-formed XML string based on SimpleXML element

User Contributed Notes

mmj at example dot net 02-Oct-2017 03:22
__toString() is not intended to be called directly.

Instead, it defines what is returned when the object is cast to string, either explicitly with:

(string)$element

Or implicitly, when used in certain contexts which would cause a conversion to string.
Patanjali 27-Mar-2016 10:55
[Someone remove that other Patanjali's note, because it has errors! :-(]

For those for whom it may not be immediately obvious from the example, the echo is what is forcing __toString() to be used.

However, to assign the text of a node (but not its children) to a variable:

$XML = new SimpleXMLElement('<p>Hello<span> world</span>.<span> Good day!</span></p>');

$Text = $XML->__toString();

is effectively:
$Text = 'Hello.'; // The <span>s are ignored.

Either of:
$Text = $XML->span->__toString();
$Text = $XML->span[0]->__toString();

is effectively:
$Text = ' world'; // Only the first <span> is used.

$Text = $XML->span[1]->__toString();

is effectively:
$Text = ' Good day!'; // Only the second <span> is used.
Patanjali 27-Mar-2016 10:36
For those for whom it may not be immediately obvious from the example, to assign the text of a node (but not its children) to a variable:

$XML = new SimpleXMLElement('<p>Hello<span> world</span>.<span> Good day!</span></p>');

Either:
$Text = $XML;
$Text = $XML->__String();

is effectively:
$Text = 'Hello.'; // The <span>s are ignored.

Either of:
$Text = $XML->span;
$Text = $XML->span[0];

is effectively:
$Text = ' world'; // Only the first <span> is used.

$Text = $XML->span[1];

is effectively:
$Text = ' Good day!'; // Only the second <span> is used.


Runs XPath query on XML data

  • ? SimpleXMLElement::__toString
  • SimpleXMLIterator ?
  • PHP Manual
  • SimpleXMLElement
  • Runs XPath query on XML data

SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpath — Runs XPath query on XML data

说明

public SimpleXMLElement::xpath ( string $path ) : array

The xpath method searches the SimpleXML node for children matching the XPath path.

参数

path

An XPath path

返回值

Returns an array of SimpleXMLElement objects or false in case of an error.

范例

Example #1 Xpath

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

while(list( , $node) = each($result)) {
    echo 'b/c: ',$node,"\n";
}
?>

以上例程会输出：

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

参见

  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • Basic SimpleXML usage

User Contributed Notes

awoerl at contentserv dot com 31-Jan-2017 12:43
I tried to use string functions in the xpath statements I'm passing, like

$oXml->xpath('substring(/foo/bar/text(), 0, 4)');

But no matter which syntax I'm trying I never the string functions to work.

Is it possible, that the xpath method does not support function calls?
Alexis Peters 11-Oct-2016 09:11
If you want this behavior for an multidimensional array you can use this:

<?php
function apath(&$a, $path, $value = NULL) {
    $pathes = explode('/',$path);

    if(count($pathes) > 1) {
        $firstPart = array_shift($pathes);
        if(!isset($a[$firstPart])) {
            $a[$firstPart] = array();
        }
        return apath($a[$firstPart], implode('/', $pathes), $value);
    } else {
        if($value){
            $a[$path] = $value;
        } else {
            return $a[$path];
        }
    }
}

apath($a, 'user/name', array('prename' => 'foo', 'lastname' => 'bar'));

$a = array();
var_dump($a);
var_dump(apath($a, 'user/name/lastname'));

?>
Gives you this:

array(1) {
  ["user"]=>
  array(1) {
    ["name"]=>
    array(2) {
      ["prename"]=>
      string(5) "foo"
      ["lastname"]=>
      string(8) "bar"
    }
  }
}
string(8) "bar"
Anonymous 30-Jan-2015 05:30
As mentioned already xpath will fail is the default namespace 'xmlns' is used like in:

<?php

$xmlstring = $string = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <fileVersion appName="xl" />
</workbook>
XML;
?>

xpath cannot search through the xml without explicitly specifying a namespace.
There are 2 options :
1. rename the 'xmlns' into something else to trick xpath into believing that no default namespace is defined.
2. register a string as the default namespace and use that string in all your queries. Unfortunatly, an empty space will not work.
No other option currently exist until XPath2.0 becomes the default library.
leonjanzen at gmail dot com 19-Oct-2014 07:48
To run an xpath query on an XML document that has a namespace, the namespace must be registered with SimpleXMLElement::registerXPathNamespace() before running the query. If the XML document namespace does not include a prefix, you must make up an arbitrary one, and then use it in your query.

<?php
$strXml= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mydoc xmlns="http://www.url.com/myns">
    <message>Test message</message>
</mydoc>
XML;

$xmlDoc=new \SimpleXMLElement($strXml);

foreach($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
    if(strlen($strPrefix)==0) {
        $strPrefix="a"; //Assign an arbitrary namespace prefix.
    }
    $xmlDoc->registerXPathNamespace($strPrefix,$strNamespace);
}

print($xmlDoc->xpath("//a:message")[0]); //Use the arbitrary namespace prefix in the query.
?>

This will output:

Test message
BenjaminBeck at gmx dot de 13-Sep-2014 01:36
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $v = $row->xpath('./country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
yetihehe at yetihehe dot com 12-Jan-2011 02:21
Xpath actually knows which element is root regardless of element on which you execute it. Example:

<?php

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <b>
  <c>code</c>
 </b>
</a>
XML;

header('content-type: text/plain');

$xml = new SimpleXMLElement($string);

//relative to root
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: //c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: //c: ',$node,"\n";
}

echo "\n";

//relative to current element
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: .//c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: .//c: ',$node,"\n";
}

?>

Will return:
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code

b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code
stefan at efectos dot nl 09-Nov-2010 02:33
Having problems selecting information through xpath when there are namespaces in the XML?

Try this quick and dirty solution, but it works:

<?php
$objImageXml = new SimpleXMLElement($objImageXml->asXML());
?>
grummfy at gmail dot com 11-Feb-2010 04:08
On a xml that have namespace you need to do this before your xpath request (or empty array will be return) :

<?php
$string = str_replace('xmlns=', 'ns=', $string); //$string is a string that contains xml...
?>
DrupalFocus at earthlink dot net 02-Dec-2009 12:27
Looks like the relative path is relative to the SimpleXMLElement object that you call the Xpath() method on.  Basically chopping off the root element.

<?php
$string = <<<XML
<foo>
  <bar>
    <a>
     <b>
      <c>text</c>
      <c>stuff</c>
     </b>
     <d>
      <c>code</c>
     </d>
    </a>
  </bar>
</foo>
XML;

$xml = new SimpleXMLElement($string);
/* Search for children using 2nds level relative <bar><a><b><c> */
$result = $xml->xpath('a/b/c');
if ($result)
foreach($result as $node) {
    drupal_set_message(t('a/b/c: @node.', array('@node' => $node)));
}
else
  drupal_set_message(t('a/b/c: failed.'));

/* it relative to the SimpleXMLElement Search for 2nds level relative <bar><a><b><c> but where is foo */
$bar = $xml->bar;
$result = $bar->xpath('a/b/c');
foreach($result as $node) {
    drupal_set_message(t('bar->a/b/c: @node.', array('@node' => $node)));
}
?>

results in :
#
# a/b/c: failed.
# bar->a/b/c: text.
# bar->a/b/c: stuff.
behnam@zwnj 24-Sep-2009 01:34
Seems like this function cannot return the result of XPath string() [1] function.  For example if you query xpath("string(a/@b)") you will get bool(false) although the node "a" may have the attribute "b" set to a non-empty string.

[1] http://www.w3.org/TR/xpath#section-String-Functions
Anti Veeranna 17-Jun-2009 03:50
Whether it returns a false or empty array for a non-existing path seems to depend on libxml version.

I tried the following code:

<?php
$data = '<foo><bar></bar></foo>';
$xml = simplexml_load_string($data);
print gettype($xml->xpath('/first/second'));
?>

On a machine with libxml 2.6.16 and PHP 5.2.8 I got back boolean. On a different machine with libxml 2.7.3 and PHP 5.2.8/5.2.9 I got back empty array.

You can check the libxml version from command line by executing: php --ri libxml

or simply look at phpinfo() output
arealzone-czernobyl at yahoo dot de 11-Jun-2009 03:23
The simplest way to count nodes in a XML doc:

<?php
$xml = new SimpleXMLElement($xmlstr);

$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);

echo $nodeCount;
?>
anemik 02-Jul-2008 03:46
If you want to find easly all records satisfying some condition in XML data like

....
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
...

try example below

<?php

$xmlStr = file_get_contents('data/books.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find all book records with price higher than 40$
$res = $xml->xpath("book/price[.>'40']/parent::*");
print_r($res);

?>

You will see response like:
Array (
[0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => bk101
                )

            [author] => Gambardella, Matthew
            [title] => XML Developer's Guide
            [genre] => Computer
            [price] => 44.95
            [publish_date] => 2000-10-01
            [description] => An in-depth look at creating applications
      with XML.
        )
...
paul at pmtlogic dot com 18-Jun-2008 12:17
xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.

xml snippet:

<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>

The following code does not work:

<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");

foreach ( $result[0]->attributes() as $key => $val ) {
    print "<div class='coords'>$key: $val</div>\n";
}
?>

I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.

In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:

<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
canuemail at gmail dot com 05-May-2008 05:05
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
Hugh 18-Dec-2005 03:23
Note that this function does not ALWAYS return an array. It seems that if the specified path is not found in the document, it will return false. You need to check for the false value before using foreach, if you wish to avoid a warning (and often to handle errors or control program flow in this situation).
drewish at katherinehouse dot com 10-Jul-2005 06:16
xpath() can also be used to select elements by their attributes. For a good XPath reference check out: http://www.w3schools.com/xpath/xpath_syntax.asp

<?php
$string = <<<XML
<sizes>
    <size label="Square" width="75" height="75" />
    <size label="Thumbnail" width="100" height="62" />
    <size label="Small" width="112" height="69" />
    <size label="Large" width="112" height="69" />
</sizes>
XML;

$xml = simplexml_load_string($string);
$result = $xml->xpath("//size[@label='Large']");

// print the first (and only) member of the array
echo $result[0]->asXml();
?>

The script would print:
<size label="Large" width="112" height="69"/>


The SimpleXMLIterator class

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

简介

The SimpleXMLIterator provides recursive iteration over all nodes of a SimpleXMLElement object.

类摘要

SimpleXMLIterator extends SimpleXMLElement implements RecursiveIterator , Countable {
/* 方法 */
public current ( ) : mixed
public getChildren ( ) : SimpleXMLIterator
public hasChildren ( ) : bool
public key ( ) : mixed
public next ( ) : void
public rewind ( ) : void
public valid ( ) : bool
/* 继承的方法 */
final public SimpleXMLElement::__construct ( string $data , int $options = 0 , bool $data_is_url = false , string $ns = "" , bool $is_prefix = false )
public SimpleXMLElement::addAttribute ( string $name , string $value = ? , string $namespace = ? ) : void
public SimpleXMLElement::addChild ( string $name , string $value = ? , string $namespace = ? ) : SimpleXMLElement
public SimpleXMLElement::asXML ( string $filename = ? ) : mixed
public SimpleXMLElement::attributes ( string $ns = null , bool $is_prefix = false ) : SimpleXMLElement
public SimpleXMLElement::children ( string $ns = ? , bool $is_prefix = false ) : SimpleXMLElement
public SimpleXMLElement::count ( ) : int
public SimpleXMLElement::getDocNamespaces ( bool $recursive = false , bool $from_root = true ) : array
public SimpleXMLElement::getName ( ) : string
public SimpleXMLElement::getNamespaces ( bool $recursive = false ) : array
public SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns ) : bool
public SimpleXMLElement::__toString ( ) : string
public SimpleXMLElement::xpath ( string $path ) : array
}

Table of Contents

  • SimpleXMLIterator::current — Returns the current element
  • SimpleXMLIterator::getChildren — Returns the sub-elements of the current element
  • SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements
  • SimpleXMLIterator::key — Return current key
  • SimpleXMLIterator::next — Move to next element
  • SimpleXMLIterator::rewind — Rewind to the first element
  • SimpleXMLIterator::valid — Check whether the current element is valid

User Contributed Notes

prouchetvincent at free dot fr 10-Oct-2020 12:47
<?php
=======================================================
$index =
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <article id="8" visibility="true" filename="2020-10-08" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="7" visibility="true" filename="2020-10-07" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="6" visibility="true" filename="2020-10-02" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="5" visibility="true" filename="2020-09-30" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="4" visibility="true" filename="2020-09-26" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="3" visibility="true" filename="2020-09-22"     fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="2" visibility="true" filename="2020-09-20"     fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
        <article id="1" visibility="true" filename="hello world" fileExtension="xml">
            Hello World
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
</root>
====================================================================
?>
If you have to use an iterator to parse your XML
and need tu get an attribute of tags of this iterator then
use the fonction
->current()
of simpleXMLIterator on your object before
->attributes()->{attibute name}
<?php
$file="";
try{
     $index = new SimpleXMLIterator ( file_get_contents ( FILEDIRECTORY. 'index.xml' ) );}
catch(Exception $e) {whatever you want to do on error}}

for( $index->rewind(); $index->valid(); $index->next() ) {
    try {
          $file = file_get_contents(FILESDIRECTORY.$index->current()->attributes()->{'fileName'}. '.xml' );
    } catch (Exception $e) {whatever you want to do on error}
    $article = new Article ();
    $article->setXMLArticle ($file);
    array_push( $this->articles, $article );
    $file ="";
    }
}
?>
This exemple use a custom made Article object that itself parse the file given to him to initialise its properties .
Here we open a file (Yes I use constant for my directories)
make it a simpleXMLIterator and parse article elements to get the filename attribute to use it to open another XML file for data collection.
don't forget !!! In PHP Object created by new ClassName() are ALWAYS given by reference that is why new Article() in inside the loop and not outside
(yhea, I did that mistake)
XMLIterator are powerfull yet harder to understand in themselves but once passed that one point.
They are very more easier to use than plain arrays.
rukkykf at gmail dot com 16-Dec-2018 06:54
I think it's worth mentioning that you need to call the rewind() method on the SimpleXMLIterator object immediately after initialization before you can start doing any other operations on the object. An example:

<?php
$xml = new SimpleXMLIterator('file.xml', null, true);

// $x here will be set to null because the rewind() method has not been called
$x = $xml->current();

$xml->rewind();

// $x here will be set to the first element
$x = $xml->current();

?>
php-lover at live dot com 05-Oct-2015 09:50
Function to extract SimpleXMLElement data to array.

function extract($sxe = null) {
    if (!$sxe instanceOf SimpleXMLElement)
        return array();

    $extract = array();

    foreach ($sxe->children() as $key => $value) {
        if (array_key_exists($key, $extract)) {
            if (!isset($extract[$key][0])) {
                $tmp_extract = $extract[$key];
                $extract[$key] = array();
                $extract[$key][0] = $tmp_extract;
            } else
                $extract[$key] = (array) $extract[$key];
        }

        if ($value->count()) {
            if (isset($extract[$key]) && is_array($extract[$key]))
                $extract[$key][] = $this->extract($value);
            else
                $extract[$key] = $this->extract($value);
        } else {
            if (isset($extract[$key]) && is_array($extract[$key]))
                $extract[$key][] = empty(strval($value)) ? null : strval($value);
            else
                $extract[$key] = empty(strval($value)) ? null : strval($value);
        }
    }

    return $extract;
}
centy2010 at hotmail dot com 16-Jul-2014 03:22
I filled my database from an XML file about 1260 Kb.
I made my process less than a second. Simply by using SimpleXML.

I give you a little example of the usage to fill a database.
Given the table universe.
With 4 columns Coords, Planet_Name, Player_id, Moon_Size.

Now You have a XML file named universe.xml with this kind of data.
I enclose the data within php tags but it's a file :p
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<universe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -
xsi:noNamespaceSchemaLocation="http://s127-fr.ogame.gameforge.com/api/xsd/universe.xsd" -
timestamp="1405413350" serverId="fr127">
    <planet id="1" player="1" name="Arakis" coords="1:1:2">
        <moon id="2" name="Mond" size="4998"/>
    </planet>
    <planet id="33620176" player="100000" name="GameAdmin" coords="1:1:3"/>
    <planet id="33620179" player="100003" name="Heimatplanet" coords="1:1:1"/>
    <planet id="33620186" player="100004" name="OGame Team" coords="6:250:1"/>
    <planet id="33620242" player="100058" name="KnS" coords="9:1:6">
        <moon id="33668391" name="Lune" size="8831"/>
    </planet>
</universe>
EOT;
?>

Now how to bring these data in my 4 columns table :

<?php
$newfname = $path."Universe.XML";
$mydata = new SimpleXmlIterator($newfname, 0, true);
$myquery = "INSERT INTO `".$tablename."` (`coords`,`planet_name`, `player_id`, `moon_size`) VALUES ";
for ($mydata->rewind();$mydata->valid();$mydata->next()) {
    $myquery.= " ('".$mydata->current()->attributes()['coords']
_."','".utf8_decode($mydata->current()->attributes()['name'])
_."','".utf8_decode($mydata->current()->attributes()['player'])
_."','";
    if ($mydata->haschildren()) {
        $myquery.= $mydate->current()->children()->attributes()['size']."'),";
    } else {
        $myquery.= "'),";
    }
}
$myquery = rtrim($myquery, ",");
$datatosql = mysql_query($myquery);
?>
hezll at msn dot com 11-Apr-2013 04:34
Most of the time we need to convert the XML to array or JSON , but now I have to completed the requirement of converting XML to XPath which make our template easily geting the data from XML data source due to the Xpath mapping .Here is the function:

<?php

function sxiToXpath($sxi, $key = null, &$tmp = null)
{
    $keys_arr = array();
    //get the keys count array
    for ($sxi->rewind(); $sxi->valid(); $sxi->next())
    {
        $sk = $sxi->key();
        if (array_key_exists($sk, $keys_arr))
        {
            $keys_arr[$sk]+=1;
            $keys_arr[$sk] = $keys_arr[$sk];
        }
        else
        {
            $keys_arr[$sk] = 1;
        }
    }
    //create the xpath
    for ($sxi->rewind(); $sxi->valid(); $sxi->next())
    {
        $sk = $sxi->key();
        if (!isset($$sk))
        {
            $$sk = 1;
        }
        if ($keys_arr[$sk] >= 1)
        {
            $spk = $sk . '[' . $$sk . ']';
            $keys_arr[$sk] = $keys_arr[$sk] - 1;
            $$sk++;
        }
        else
        {
            $spk = $sk;
        }
        $kp = $key ? $key . '/' . $spk : '/' . $sxi->getName() . '/' . $spk;
        if ($sxi->hasChildren())
        {
            sxiToXpath($sxi->getChildren(), $kp, $tmp);
        }
        else
        {
            $tmp[$kp] = strval($sxi->current());
        }
        $at = $sxi->current()->attributes();
        if ($at)
        {
            $tmp_kp = $kp;
            foreach ($at as $k => $v)
            {
                $kp .= '/@' . $k;
                $tmp[$kp] = $v;
                $kp = $tmp_kp;
            }
        }
    }
    return $tmp;
}

function xmlToXpath($xml)
{
    $sxi = new SimpleXmlIterator($xml);
    return sxiToXpath($sxi);
}

/**
 *  How to use the function
 */
$xml = <<<EOT
<?xml version="1.0" encoding="utf8" ?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002" IDd="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company id='id_test'><g id='id_g'>glove</g></Company>
   </item>
    <item>
    </item>
</data>
EOT;

$rs = xmlToXpath($xml);
print_r($rs);

/**
 * the results may lkie this:
Array
(
    [/data/item[1]/Company[1]] => Navarro Corp.
    [/data/item[1]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30001
        )
    [/data/item[2]/Company[1]] => Performant Systems
    [/data/item[2]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30002
        )

    [/data/item[2]/@IDd] => SimpleXMLIterator Object
        (
            [0] => 30002
        )

    [/data/item[3]/Company[1]/g[1]] => glove
    [/data/item[3]/Company[1]/g[1]/@id] => SimpleXMLIterator Object
        (
            [0] => id_g
        )

    [/data/item[3]/Company[1]/@id] => SimpleXMLIterator Object
        (
            [0] => id_test
        )

    [/data/item[3]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30003
        )

    [/data/item[4]] =>

)
 */

echo "Total:" . count($rs);

echo "<hr>";
/* You can check the xpath result like this */
$xml = new SimpleXMLElement($xml);
foreach ($rs as $k => $v)
{
    echo "Xpath:" . $k . " |Value:" . $v . " ";
    var_dump($xml->xpath($k));
    echo "<br>";
}
ajnsit dot NOSPAM at gmail dot com 17-Mar-2011 10:14
Here's a simple function to convert an XML string to an array -

<?php
// PHP5.3 and above only
function parse($str) {
    $f = function($iter) {
      foreach($iter as $key=>$val)
        $arr[$key][] = ($iter->hasChildren())?
          call_user_func (__FUNCTION__, $val)
          : strval($val);
      return $arr;
    };
    return $f(new SimpleXmlIterator($str, null));
}
?>

PHP 5.2 and below do not have anonymous functions.
But you can create a helper function to achieve the same thing -

<?php
  function parse($str) {
    return parseHelper(new SimpleXmlIterator($str, null));
  }
  function parseHelper($iter) {
    foreach($iter as $key=>$val)
      $arr[$key][] = ($iter->hasChildren())?
        call_user_func (__FUNCTION__, $val)
        : strval($val);
    return $arr;
  }
?>

Using it is straightforward enough -

<?php

$xml = '
<movies>
  <movie>abcd</movie>
  <movie>efgh</movie>
  <movie>hijk</movie>
</movies>';
var_dump(parse($xml));

?>

This will output -

array
  'movie' =>
    array
      0 => string 'abcd' (length=4)
      1 => string 'efgh' (length=4)
      2 => string 'hijk' (length=4)
ratfactor at gmail dot com 19-Jul-2009 05:08
The documentation is a bit sparse for SimpleXmlIterator.  Here is an example showing the use of its methods. xml2Array and sxiToArray work together to convert an XML document to an associative array structure.

The contents of cats.xml:
======================================
<cats>
  <cat>
      <name>Jack</name>
      <age>2</age>
      <color>grey</color>
      <color>white</color>
  </cat>
  <cat>
      <name>Maxwell</name>
      <age>12</age>
      <color>orange</color>
      <color>black</color>
  </cat>
</cats>
======================================

<?php
function xml2array($fname){
  $sxi = new SimpleXmlIterator($fname, null, true);
  return sxiToArray($sxi);
}

function sxiToArray($sxi){
  $a = array();
  for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
    if(!array_key_exists($sxi->key(), $a)){
      $a[$sxi->key()] = array();
    }
    if($sxi->hasChildren()){
      $a[$sxi->key()][] = sxiToArray($sxi->current());
    }
    else{
      $a[$sxi->key()][] = strval($sxi->current());
    }
  }
  return $a;
}

// Read cats.xml and print the results:
$catArray = xml2array('cats.xml');
print_r($catArray);
?>

Results (reformatted a bit for compactness and clarity):
======================================
Array(
  [cat] => Array(
    [0] => Array(
      [name] => Array(  [0] => Jack    )
      [age] => Array(   [0] => 2       )
      [color] => Array( [0] => grey,
                        [1] => white   )
    )
    [1] => Array(
      [name] => Array(  [0] => Maxwell )
      [age] => Array(   [0] => 12      )
      [color] => Array( [0] => orange
                        [1] => black   )
    )
  )
)


Returns the current element

  • ? SimpleXMLIterator
  • SimpleXMLIterator::getChildren ?
  • PHP Manual
  • SimpleXMLIterator
  • Returns the current element

SimpleXMLIterator::current

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::current — Returns the current element

说明

public SimpleXMLIterator::current ( ) : mixed

This method returns the current element as a SimpleXMLIterator object or null.

参数

此函数没有参数。

返回值

Returns the current element as a SimpleXMLIterator object or null on failure.

范例

Example #1 Return the current element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>');
var_dump($xmlIterator->current());

$xmlIterator->rewind(); // rewind to first element
var_dump($xmlIterator->current());
?>

以上例程会输出：

NULL
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

参见

  • SimpleXMLIterator::key() - Return current key
  • SimpleXMLIterator::next() - Move to next element
  • SimpleXMLIterator::rewind() - Rewind to the first element
  • SimpleXMLIterator::valid() - Check whether the current element is valid
  • SimpleXMLElement

User Contributed Notes

bmafzallmahmud at gmail dot com 02-Dec-2017 05:51
<?php
$note=<<<XML
<note>
<to>Afzall</to>
<from>Hasan</from>
<heading>Reminder</heading>
<body>Don't forget your parents</body>
</note>
XML;

$xmlIterator = new SimpleXMLIterator($note);
var_dump($xmlIterator->current()); //out put : NULL
var_dump($xmlIterator->rewind()); //out put null
$xmlIterator->rewind(); //beacse of rewind to first element then show "$xmlIterator->current()""
var_dump($xmlIterator->current());
 //out put : object(SimpleXMLIterator)#2 (1) { [0]=> string(6) "Afzall" }
?>


Returns the sub-elements of the current element

  • ? SimpleXMLIterator::current
  • SimpleXMLIterator::hasChildren ?
  • PHP Manual
  • SimpleXMLIterator
  • Returns the sub-elements of the current element

SimpleXMLIterator::getChildren

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::getChildren — Returns the sub-elements of the current element

说明

public SimpleXMLIterator::getChildren ( ) : SimpleXMLIterator

This method returns a SimpleXMLIterator object containing sub-elements of the current SimpleXMLIterator element.

参数

此函数没有参数。

返回值

Returns a SimpleXMLIterator object containing the sub-elements of the current element.

范例

Example #1 Return the sub-elements of the current element

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Basics</title>
        <author>Jim Smith</author>
    </book>
    <book>XML basics</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator($xml);
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    foreach($xmlIterator->getChildren() as $name => $data) {
    echo "The $name is '$data' from the class " . get_class($data) . "\n";
    }
}
?>

以上例程会输出：

The title is 'PHP Basics' from the class SimpleXMLIterator
The author is 'Jim Smith' from the class SimpleXMLIterator

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the current element has sub elements

  • ? SimpleXMLIterator::getChildren
  • SimpleXMLIterator::key ?
  • PHP Manual
  • SimpleXMLIterator
  • Checks whether the current element has sub elements

SimpleXMLIterator::hasChildren

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements

说明

public SimpleXMLIterator::hasChildren ( ) : bool

This method checks whether the current SimpleXMLIterator element has sub-elements.

参数

此函数没有参数。

返回值

true if the current element has sub-elements, otherwise false

范例

Example #1 Check whether the current element has sub-elements

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Basics</title>
        <author>Jim Smith</author>
    </book>
    <book>XML basics</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator( $xml );
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    if($xmlIterator->hasChildren()) {
        var_dump($xmlIterator->current());
    }
}
?>

以上例程会输出：

object(SimpleXMLIterator)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}

User Contributed Notes

grummfy at gmail dot com 12-Feb-2010 01:01
Hello,

just a note for people like me who encounter the problems :

<?php
foreach($xmlIterator as $x)
{
    if($x->hasChildren())
    {
        //never reach
        echo 'x : ';
        var_dump($x->current());
    }
    if($xmlIterator->hasChildren())
    {
        echo 'iterator : ';
        var_dump($x->current()); //all time null
        var_dump($xmlIterator->current());
    }
}
?>


Return current key

  • ? SimpleXMLIterator::hasChildren
  • SimpleXMLIterator::next ?
  • PHP Manual
  • SimpleXMLIterator
  • Return current key

SimpleXMLIterator::key

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::key — Return current key

说明

public SimpleXMLIterator::key ( ) : mixed

This method gets the XML tag name of the current element.

参数

此函数没有参数。

返回值

Returns the XML tag name of the element referenced by the current SimpleXMLIterator object or false

范例

Example #1 Get the current XML tag key

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>');

echo var_dump($xmlIterator->key());
$xmlIterator->rewind(); // rewind to the first element
echo var_dump($xmlIterator->key());

?>

以上例程会输出：

bool(false)
string(4) "book"

User Contributed Notes

bmafzallmahmud at gmail dot com 01-Dec-2017 09:04
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;

$xmlIterator = new SimpleXMLIterator($note);
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
      echo "<pre>";
     echo var_dump($xmlIterator->key());

}
?>
out put :
string(2) "to"
string(4) "from"
string(7) "heading"
string(4) "body"


Move to next element

  • ? SimpleXMLIterator::key
  • SimpleXMLIterator::rewind ?
  • PHP Manual
  • SimpleXMLIterator
  • Move to next element

SimpleXMLIterator::next

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::next — Move to next element

说明

public SimpleXMLIterator::next ( ) : void

This method moves the SimpleXMLIterator to the next element.

参数

此函数没有参数。

返回值

没有返回值。

范例

Example #1 Move to the next element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Basics</book><book>XML basics</book></books>');
$xmlIterator->rewind(); // rewind to the first element
$xmlIterator->next();

var_dump($xmlIterator->current());
?>

以上例程会输出：

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

User Contributed Notes

bmafzallmahmud at gmail dot com 01-Dec-2017 09:39
<?php
$note=<<<XML
<note>
<to>Afzall</to>
<from>Sumon</from>
<heading>Reminder</heading>
<body>Don't forget go to kishorgong</body>
</note>
XML;

$xmlIterator = new SimpleXMLIterator($note);
$xmlIterator->rewind();
var_dump($xmlIterator->current());
$xmlIterator->next();
var_dump($xmlIterator->current());
$xmlIterator->next();
var_dump($xmlIterator->current());
?>
out put :
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(6) "Afzall"
}
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(5) "Sumon"
}
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(8) "Reminder"
}


Rewind to the first element

  • ? SimpleXMLIterator::next
  • SimpleXMLIterator::valid ?
  • PHP Manual
  • SimpleXMLIterator
  • Rewind to the first element

SimpleXMLIterator::rewind

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::rewind — Rewind to the first element

说明

public SimpleXMLIterator::rewind ( ) : void

This method rewinds the SimpleXMLIterator to the first element.

参数

此函数没有参数。

返回值

没有返回值。

范例

Example #1 Rewind to the first element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Basics</book><book>XML Basics</book></books>');
$xmlIterator->rewind();

var_dump($xmlIterator->current());
?>

以上例程会输出：

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element is valid

  • ? SimpleXMLIterator::rewind
  • SimpleXML 函数 ?
  • PHP Manual
  • SimpleXMLIterator
  • Check whether the current element is valid

SimpleXMLIterator::valid

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::valid — Check whether the current element is valid

说明

public SimpleXMLIterator::valid ( ) : bool

This method checks if the current element is valid after calls to SimpleXMLIterator::rewind() or SimpleXMLIterator::next().

参数

此函数没有参数。

返回值

Returns true if the current element is valid, otherwise false

范例

Example #1 Check whether the current element is valid

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>SQL Basics</book></books>');

$xmlIterator->rewind(); // rewind to the first element
echo var_dump($xmlIterator->valid()); // bool(true)

$xmlIterator->next(); // advance to the next element
echo var_dump($xmlIterator->valid()); // bool(false) because there is only one element
?>

User Contributed Notes

There are no user contributed notes for this page.


SimpleXML 函数

Table of Contents

  • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
  • simplexml_load_file — Interprets an XML file into an object
  • simplexml_load_string — Interprets a string of XML into an object

User Contributed Notes

Pyetro Costa [pyetrosafe at gmail dot com] 07-Dec-2018 08:48
After viewing the xml2array function of "http://www.php.net/manual/en/ref.simplexml.php#103617" and the "http://php.net/manual/en/ref.simplexml.php # 112038 "and still have made a change to convert empty tags to null ... I felt the need to work with the result as an object, keeping arrays like arrays. Arriving at this function:
<?php

    private function xml2Object($xmlObject, $out = null) {
        $out = (is_object($xmlObject) ? new \stdClass : array());
        foreach ((array) $xmlObject as $index => $node )
            if (is_array($out)) {
                $out[$index] = (is_object($node) || is_array($node)) ? (($node instanceof \SimpleXMLElement) && count((array) $node)==0 ? null : $this->xml2Object($node)) : $node;
            } else
                $out->{$index} = (is_object($node) || is_array($node)) ? (($node instanceof \SimpleXMLElement) && count((array) $node)==0 ? null : $this->xml2Object($node)) : $node;
        return $out;
    }
?>

And the results of function can be seen below:
<?php
    $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8" standalone="no"?><results><l1_elm1><l2_elm1>Some Text</l2_elm1><l2_elm2/></l1_elm1><l1_elm2><l2_elm1><l3_elm1>Array Index[0] - First property</l3_elm1><l3_elm2>Array Index[0] - Second property</l3_elm2><l3_elm3>Array Index[0] - Third property</l3_elm3></l2_elm1><l2_elm1><l3_elm1>Array Index[1] - First property</l3_elm1><l3_elm2>Array Index[1] - Second property</l3_elm2><l3_elm3>Array Index[1] - Third property</l3_elm3></l2_elm1></l1_elm2><l1_elm3/></results>');

    var_dump( $this->xml2Object($xml) );

    // var_dump xml2Object results
    object(stdClass)#339 (3) {
      ["l1_elm1"]=>object(stdClass)#344 (2) {
        ["l2_elm1"]=>string(9) "Some Text"
        ["l2_elm2"]=>NULL
      }
      ["l1_elm2"]=>object(stdClass)#347 (1) {
        ["l2_elm1"]=>array(2) {
          [0]=>object(stdClass)#348 (3) {
            ["l3_elm1"]=>string(31) "Array Index[0] - First property"
            ["l3_elm2"]=>string(32) "Array Index[0] - Second property"
            ["l3_elm3"]=>string(31) "Array Index[0] - Third property"
          }
          [1]=>object(stdClass)#349 (3) {
            ["l3_elm1"]=>string(31) "Array Index[1] - First property"
            ["l3_elm2"]=>string(32) "Array Index[1] - Second property"
            ["l3_elm3"]=>string(31) "Array Index[1] - Third property"
          }
        }
      }
      ["l1_elm3"]=>NULL
    }

    // VarDump Symphony xml2Object results something like
    object (#345) {
      +"l1_elm1": object (#339) {
        +"l2_elm1": "Some Text"
        +"l2_elm2": null
      }
      +"l1_elm2": object (#347) {
        +"l2_elm1": array(2) {
          [0] => object (#348) {
            +"l3_elm1": "Array Index[0] - First property"
            +"l3_elm2": "Array Index[0] - Second property"
            +"l3_elm3": "Array Index[0] - Third property"
          }
          [1] => object (#349) {
            +"l3_elm1": "Array Index[1] - First property"
            +"l3_elm2": "Array Index[1] - Second property"
            +"l3_elm3": "Array Index[1] - Third property"
          }
        ]
      }
      +"l1_elm3": null
    }
?>
Pyetro Costa [pyetrosafe at gmail dot com] 07-Dec-2018 02:55
This is just a new adjustment to the http://php.net/manual/en/ref.simplexml.php#112038 's function.

Adding the check by is_array has increased the conversion to lower levels by at least 3 levels, however empty Tags are converted to SimpleXMLElement class objects, adding a type and size check, convert these empty Tags to null.

See example:
<?php
    // The http://php.net/manual/en/ref.simplexml.php#112038 's function
    function xml2array($xmlObject, $out = array ()) {
        foreach ((array) $xmlObject as $index => $node )
            $out[$index] = (is_object($node) || is_array($node)) ? xml2array($node) : $node;
        return $out;
    }

    $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8" standalone="no"?><results><level1><l1_elm1><level2><l2_elm1>Some Text</l2_elm1><l2_elm2/></level2></l1_elm1><l1_elm2>Other String</l1_elm2><l1_elm3/></level1></results>');
    $XML2Array = xml2array($xml);
    var_dump($xml);
    var_dump($XML2Array);

    // The result is like bellow
    // simplexml_load_string results
    object(SimpleXMLElement)#227 (1) {
      ["level1"]=>object(SimpleXMLElement)#226 (3) {
        ["l1_elm1"]=>object(SimpleXMLElement)#236 (1) {
          ["level2"]=>object(SimpleXMLElement)#238 (2) {
            ["l2_elm1"]=>string(9) "Some Text"
            ["l2_elm2"]=>object(SimpleXMLElement)#239 (0) {}
          }
        }
        ["l1_elm2"]=>string(12) "Other String"
        ["l1_elm3"]=>object(SimpleXMLElement)#237 (0) {}
      }
    }

    // xml2array function results
    array(1) {
      ["level1"]=>array(3) {
        ["l1_elm1"]=>array(1) {
          ["level2"]=>array(2) {
            ["l2_elm1"]=>string(9) "Some Text"
            ["l2_elm2"]=>array(0) {}
          }
        }
        ["l1_elm2"]=>string(12) "Other String"
        ["l1_elm3"]=>array(0) {}
      }
    }
?>

Now, check node type and size, if node instanceof SimpleXMLElement and count == 0, set null to value (or empty string "" as you prefer);
<?php
    function xml2array($xmlObject, $out = array ()) {
        foreach ((array) $xmlObject as $index => $node )
            $out[$index] = (is_object($node) || is_array($node)) ? (($node instanceof \SimpleXMLElement) && count((array) $node)==0 ? null : xml2array($node)) : $node;
        return $out;
    }

    $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8" standalone="no"?><results><level1><l1_elm1><level2><l2_elm1>Some Text</l2_elm1><l2_elm2/></level2></l1_elm1><l1_elm2>Other String</l1_elm2><l1_elm3/></level1></results>');
    var_dump(xml2array($xml));

    // And now the result is like bellow
    array(1) {
      ["level1"]=>array(3) {
        ["l1_elm1"]=>array(1) {
          ["level2"]=>array(2) {
            ["l2_elm1"]=>string(9) "Some Text"
            ["l2_elm2"]=>NULL
          }
        }
        ["l1_elm2"]=>string(12) "Other String"
        ["l1_elm3"]=>NULL
      }
    }
?>
brandonkirsch at gmail dot com 09-Sep-2013 07:41
Contrary to other notes posted here, SimpleXML *DOES NOT* properly handle non-UTF8 encoded XML documents.

A proper "iso-8859-1" declared and encoded XML document will not parse with SimpleXML for PHP 5.2.17 or 5.5.1 when using extended characters (that is, byte values greater than 127)

DOMDocument, on the other hand, will correctly parse incoming iso-8859-1 XML documents and can also be used to perform character translation to UTF8:

$dom = new DOMDocument();

if($dom->loadXML($fileContents)){ // $fileContents is an XML document with iso-8859-1 encoding specified in the declaration
            $dom->encoding = 'utf-8'; // convert document encoding to UTF8
            return $dom->saveXML(); // return valid, utf8-encoded XML
William Fahria 15-Jul-2013 07:34
A simple implementation:
You can inform a direct XML in text format to the function.

function eoXML2Array($xmlContent, $out = array()){
    $xmlObject = is_object($xmlContent) ? $xmlContent : simplexml_load_string($xmlContent);
    foreach((array) $xmlObject as $index => $node)
        $out[$index] = ( is_object($node) || is_array($node) ) ? eoXML2Array( $node ) : $node;
    return $out;
}

Usage: $your_array = eoXML2Array(your xml text);
r dot m dot 0100101 at gmail dot com 25-Apr-2013 03:00
This is a slight adjustment to http://www.php.net/manual/en/ref.simplexml.php#103617 's function.
The function given by them would convert a simpleXML to an array but only at the highest level. Once you add the is_array check with the is_object it should convert each level to an array (well it did for me through 3 levels).

function simpleXmlObjectToArray ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) || is_array($node) )
        ? simpleXmlObjectToArray ( $node )
        : $node;

    return $out;
}
Happy Coding!
Eric 29-Jan-2013 03:00
If the SimpleXMLObject contains an array, adding is_array() allows the function to keep digging for Objects.

<?php
function xml2array ( $xmlObject, $out = array () )
{
        foreach ( (array) $xmlObject as $index => $node )
            $out[$index] = ( is_object ( $node ) ||  is_array ( $node ) ) ? xml2array ( $node ) : $node;

        return $out;
}
?>
thomas at guenneguez dot com 14-Dec-2011 02:36
Merge two xml only with SimpleXML :
Function corrected if note containe only value.

<?php
function mergeXML(&$base, $add)
{
    if ( $add->count() != 0 )
        $new = $base->addChild($add->getName());
    else
        $new = $base->addChild($add->getName(), $add);
    foreach ($add->attributes() as $a => $b)
    {
        $new->addAttribute($a, $b);
    }
    if ( $add->count() != 0 )
    {
        foreach ($add->children() as $child)
        {
            mergeXML($new, $child);
        }
    }
}
?>

Use : <?php mergeXML($xmlElement, simplexml_load_string($toMerge)) ?>
julien dot breiner at laposte dot net 09-Dec-2011 10:31
Merge two xml only with SimpleXML :

<?php
private function mergeXML(&$base, $add)
{
    $new = $base->addChild($add->getName());
    foreach ($add->attributes() as $a => $b) {
        $new[$a] = $b;
    }
    foreach ($add->children() as $child) {
        $this->mergeXML($new, $child);
    }
}?>

Use : <?php mergeXML($xmlElement, simplexml_load_string($toMerge)) ?>
k dot antczak at livedata dot pl 22-Apr-2011 01:08
A quick snippet which converts XML Object into array:

<?php
function xml2array ( $xmlObject, $out = array () )
{
        foreach ( (array) $xmlObject as $index => $node )
            $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

        return $out;
}
?>

Have fun! ;-)
help :-) @ theapotek :-) com 08-Apr-2011 12:54
If you are having trouble accessing CDATA in your simplexml document, you don't need to str_replace/preg_replace the CDATA out before loading it with simplexml.

You can do this instead, and all your CDATA contents will be merged into the element contents as strings.

$xml = simplexml_load_file($xmlfile,
'SimpleXMLElement', LIBXML_NOCDATA);
Andrez zenarter at hotmail dot com 16-Jul-2009 10:56
I just wanna add an additional to
"Append/combine/merge one simplexml to another"
The parent should has attributes too.

<?php

function append_simplexml(&$simplexml_to, &$simplexml_from)
{

static $firstLoop=true;

//Here adding attributes to parent
if( $firstLoop )
            {
                foreach( $simplexml_from->attributes() as $attr_key => $attr_value )
                {
                    $simplexml_to->addAttribute($attr_key, $attr_value);
                }
            }

foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

       $firstLoop=false;

        append_simplexml($simplexml_temp, $simplexml_child);
    }

unset( $firstLoop=false );
}

?>

I have aproblem to assign an object into a variable used as an object later, Then i found the code above, it solve half of my problem. I have it should have the parent name assign too but it didnt. Any better code?
Douglas Marsh 06-Jul-2009 08:53
SimpleXML is really nice for loading/converting XML data into native PHP data structures. I was considering crude searching of SVG for the width/height and since it really is an XML file... I found a SUPER easy method for parsing out the information I wanted:

<?php
// putting incomplete SVG data inline for readability
$RawXML = <<< XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://www.example.com/dc"
   xmlns:cc="http://www.example.com/cc"
   xmlns:rdf="http://www.example.com/rdf"
   xmlns:svg="http://www.example.com/svg"
   xmlns="http://www.example.com/"
   xmlns:sodipodi="http://www.example.com/sodipodi"
   xmlns:inkscape="http://www.example.com/inkscape"
   id="svg2"
   sodipodi:version="0.32"
   inkscape:version="0.46"
   width="586.25"
   height="743.75"
   xml:space="preserve"
   sodipodi:docname="some_svg_file.svg"
   inkscape:output_extension="org.inkscape.output.svg.inkscape">
 <!-- portions removed to keep this short -->
</svg>
XML;

$svg = new SimpleXMLElement($RawXML);

$height = $svg['height'];
$width = $svg['width'];

echo "The width x height is: ${width} x ${height} \n";

?>
info at ajaxforum dot ru 17-Jun-2009 12:32
Append/combine/merge one simplexml to another:

<?php
include 'example.php';
$el1 = new SimpleXMLElement($xmlstr);
$el2 = new SimpleXMLElement($xmlstr);

// wrong way!
// php convert $el2->movie[0] to string silently
$el1->addChild('movie', $el2->movie[0]);

// wrong way!
// php 5.1 convert $el2->movie[0] to string and generate Warning: It is not yet possible to assign complex types to properties. It is not possible to assign complex types to nodes
// php 5.2 convert $el2->movie[0] to string silently
$el1->addChild('movie');
$el1->movie[2] = $el2->movie[0];

// right way!
$el1_movie = $el1->addChild('movie');
append_simplexml($el1_movie, $el2->movie[0]);

echo "<pre>"; print_r($el1); echo "</pre>";

/**
 * Add one simplexml to another
 *
 * @param object $simplexml_to
 * @param object $simplexml_from
 * @author Boris Korobkov
 * @link http://www.ajaxforum.ru/
 */
function append_simplexml(&$simplexml_to, &$simplexml_from)
{
    foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

        append_simplexml($simplexml_temp, $simplexml_child);
    }
}
?>
codejunky32 at NOSPAM dot com 22-May-2009 08:45
Just wanted to add a post as to how you can extract the value from a SimpleXMLElement. Its not as straightforward as you think. Because its a complex object you can't just access the element directly. Here is a sample of data that represents a var_dump of a SimpleXmlElement

array(1) {
  [0]=>
  object(SimpleXMLElement)#13 (2) {
    ["@attributes"]=>
    array(1) {
      ["name"]=>
      string(5) "title"
    }
    [0]=>
    string(19) "PHP Tech Book"
  }
}

If you want to extract the title of the book you have to cast the specified element to a string like so.
$newTitle = (string) $title[0];

The $title variable is the SimpleXMLElement that you have extracted from the xml document using simplexml_load_string for instance.  To initially access the title element from the xml document you can do like so, using xpath.
$title = $doc->xpath('str[@name="title"]');

Hope this helps someone out there.
james dot ellis at gmail dot com 28-Aug-2008 06:55
While SimpleXML is a powerful tool, developers using it to process and handle large XML documents & strings should take into careful consideration its memory usage requirements.
SimpleXML requires the entire XML tree to be available prior to any processing actions on that tree -- this requires the entire tree to be in memory. Ok for a 40kb XML file but when dealing with > 100MB files you will see performance degradation, especially if you have a busy server.

An alternative to processing large XML files is the XMLReader class, which operates in streaming mode, of which an excellent tutorial is presented here:
http://www.ibm.com/developerworks/library/x-pullparsingphp.html

XML is an incredibly verbose format. If you are dealing with large data structures, especially in web services, do you you actually need to represent the data as an XML tree? - other serialisation formats such as JSON, Serialised PHP, Google Protocol Buffers (http://code.google.com/p/protobuf/) and even CSV can remarkably reduce processing time, bandwidth and load  when dealing with large files. A 110MB XML file can become a 65MB CSV file, with the same data in it, simply because the data identifiers (tags) are only represented once in the entire document.
m0sh3 at hotmail dot com 22-May-2008 03:24
Be aware of quirks like this one:

<?php

$a = new SimpleXMLElement('<a><b/></a>');

$a->b = 'test &amp; test';
$a->c = 'test &amp; test';

print_r($a);
/*
OUTPUT:

SimpleXMLElement Object
(
    [b] => test & test
    [c] => test &amp; test
)
*/
nathan at gimpstraw dot com 05-Apr-2008 09:43
I'm using SimpleXML to process data sent back from an API request, and I ran into the CDATA problem and the error you get from html entities, and here is a solution i came up with, don't know if it's the most practical, but it's working.

<?php
$str = <<< XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
    <item>
        <title><![CDATA[Caf&eacute;]]></title>
        <description><![CDATA[Some description.]]></description>
    </item>
</menu>
XML;

$str = preg_replace("/\<\!\[CDATA\[(.*?)\]\]\>/ies", "'[CDATA]'.base64_encode('$1').'[/CDATA]'", $str);
$xml = new SimpleXMLElement($str);

// Return item title's
foreach ($xml->item as $item) {
    $tmp = (string) $item->title;
    $tmp = preg_replace("/\[CDATA\](.*?)\[\/CDATA\]/ies", "base64_decode('$1')", $tmp);
    echo $tmp;
}
?>
ngkongs at gmail dot com 19-Mar-2008 10:44
fix the function i posted before, have a wrong quote placement

function implode2($glue="", $var){
    if ($var){
        foreach ($var as $value){
            $array[]=strval($value);
        }
        return implode($glue, $array);
    }
    else return false;
}
philippe_marc_--a---t--_novartis_com 12-Feb-2008 09:46
TIP: if you run into memory issue using simpleXML.
You may want to use PHP>5.2.5 in order to avoid that: http://bugs.php.net/bug.php?id=38604
If not possible, avoid "foreach ( $xmldata->node as $node )" like calls.
andrvm 02-Jan-2008 03:01
<?php
/**
    * Remove node/nodes xml with xpath
    *
    * @param SimpleXMLElement                 $xml
    * @param string XPath                     $path
    * @param string ('one'|'child'|'all')     $multi
    *
    * Use:
    *
    * Example xml file - http://ru2.php.net/manual/ru/ref.simplexml.php
    *
    * $xml = simplexml_load_file($xmlfile);
    *
    * //1. remove only 1 node (without child nodes)
    * //   $path must return only 1 (unique) node without child nodes
    * removeNode($xml, '//movie/rating[@type="thumbs"]');
    *
    * //2. remove 1 node (with 1 child nodes)
    * //    $path can return any nodes - will be removed only first node
    * //   with all child nodes
    * removeNode($xml, '//characters', 'child')
    *
    * //3. remove all nodes (with child nodes)
    * //   $path can return any nodes - will be removed all
    * //   with child nodes
    * removeNode($xml, '//rating', 'all')
    *
    * $xml->asXML($xmlfile);
    *
    */
   function removeNode($xml, $path, $multi='one')
   {
       $result = $xml->xpath($path);

          # for wrong $path
          if (!isset($result[0])) return false;

          switch ($multi) {
              case 'all':
                    $errlevel = error_reporting(E_ALL & ~E_WARNING);
                    foreach ($result as $r) unset ($r[0]);
                    error_reporting($errlevel);
                    return true;

                case 'child':
                   unset($result[0][0]);
                   return true;

                case 'one':
                   if (count($result[0]->children())==0 && count($result)==1) {
                       unset($result[0][0]);
                       return true;
                   }

                default:
                      return false;
          }
 }
?>

p.s. after use (if deleted all nodes):
<?php

   function trimXml($xmlfile)
   {
       $dom = new DOMDocument();

          $dom->preserveWhiteSpace = false;

         if (!$dom->load($xmlfile)) return false;

         $dom->formatOutput = true;

         if (!$dom->save($xmlfile)) return false;

         return true;
   }
?>
onPHP5.com 17-Nov-2007 04:37
It does not say in the docs, but SimpleXML will convert all text into UTF-8, if the source XML declaration has another encoding. Eg, if the source has the following XML decl:

<?xml version="1.0" encoding="windows-1251" ?>

all the text in the resulting SimpleXMLElement will be in UTF-8 automatically.
lordi at msdi dot ca 23-Oct-2007 05:35
If you need to do math calculations on values extracted from simplexml document, you might need to cast the value as float to prevent precision loss. Here is an example:

<?php
    $objXML = new SimpleXMLElement('<test x="-123.45"></test>');

    //Shows correctly
    echo $objXML['x']."\n";

    //We loose the decimals
    echo $objXML['x'] + $objXML['x']."\n";

    $x = $objXML['x'];

    //This works if we cast the amounts
    echo (float)$objXML['x'] + (float)$objXML['x']."\n";

    //Calculated on a string, no problem
    echo "-123.45" + "-123.45";

?>

This is due to the fact that $objXML['x'] is not a string (php would cast it automatically) neither a float, but a SimpleXMLElement object.

"echo var_dump($x);" will output this
~~
object(SimpleXMLElement)#3 (1) {
  [0]=>
  string(7) "-123.45"
}
~~

I opened a bug request on php but here is the answer they gave me:

~~
Status: Won't fix

The behavior is defined by the engine not the extension. When performing mathematical operations on objects, they are treated as integers. It is up to the user to cast the object to the appropriate type to maintain proper precision.
~~
cmsa at gmx dot de 27-Aug-2007 05:07
I had a problem with entities.

My first solution:
I saved Data that way:
$ENTRY_->
addchild('Nachricht',htmlentities($_POST["blog"]));

Had Entities in the XML-File like:
<!ENTITY auml "&amp;auml">

And I loaded the Data that way:
html_entity_decode($ENTRY->Nachname);

But after saving and
loading the xml-file the entity-entry
<!ENTITY auml "&amp;auml">
disappeared. strange...

My second solution:
With saving the Data this way:
$ENTRY_->
addchild('Nachricht',htmlentities(htmlentities($_POST["blog"])));

I can now load it with html_entity_decode without the
 entity-entry in the XML-file!
I tested it with ??ü.

Hope it helpes.
karsten dot bruch at bms-verlage dot de 16-Aug-2007 08:28
When creating a new XML document and adding text with umlauts and such

<?php $SimpleXMLElement->asXML(); ?>

will silently NOT output any content with umlauts.

Use htmlentities () while adding Umlauts & co to solve the "problem"
anthony dot parsons at manx dot net 03-Aug-2007 07:40
If you're handling lots of HTML or mixed-content XML you'll probably want to use the DOM functions instead of SimpleXML. Take this for example:
<?php
$html = new SimpleXMLElement('<div><p>Some text, <a href="#">a link,</a> more text</p></div>');

echo $html->p->a,"<br>\n"; // "a link,"
echo $html->p;             // "Some text, more text" (!)
?>
In the above example reconstructing the original markup is impossible because of the way SimpleXML represents the data.
php at werner dash ott dot de 28-Mar-2007 06:03
Concerning SimpleXML and sessions:

When creating a SimpleXML object (to be precise: a SimpleXMLElement object) in the context of a session and storing it in $_SESSION['XMLobject'], this object does not "survive" the session!

By the time re-entering the session, print_r($_SESSION['XMLobject']) says:

['XMLobject'] => SimpleXMLElement Object
Warning:  Node no longer exists in /your_php_file.php on line xyz
   (
   )

(Message simplified for the sake of better readability.)
codje2 at lboro dot ac dot uk 11-Mar-2007 01:46
Sometimes it's nice to mix up data storage types. This is a very simple SQL to XML converter. Feed it a SQL query and it outputs the result in XML.

The first paramater should be a mysql_query result
(optional)The second is the xml name for each row (i.e the second depth of XML)
(optional)The third is the name of the XML document, the root name

<?php
$result=mysql_query("SELECT * FROM users");
sql_to_xml($result,"users","members");

function sql_to_xml($mysql_result,$row_name="row",$doc_name="root")
{

    $xml= new SimpleXMLElement("<$doc_name></$doc_name>");
    while($line=mysql_fetch_assoc($mysql_result))
    {
        $row=$xml->addChild($row_name);
        foreach($line as $column => $value)
        {
            $row->$column="$value";
        }
    }
    return $xml->asXML();
}

?>
php at NOSPAM dot coutch dot com 21-Feb-2007 02:04
Memory leak when setting attributes as in example (#Example 2134. Setting values)

This probably goes unnoticed in web scripts (unless you do a LOT of xml manipulations), but I ran into this in my standalone script that processes a large number of XML files.

The following code will eat up memory quite fast:

<?php
include 'example.php';

while (true) {
  $xml = new SimpleXMLElement($xmlstr);
  $xml->movie[0]->characters->character[0]->name = 'Miss Coder';
}
?>

while this seems to behave correctly:

<?php
include 'example.php';

while (true) {
  $xml = new SimpleXMLElement($xmlstr);
  $c = $xml->xpath("//character");
  $c[0]->name = 'Miss Coder';
}
?>

This looks like bug #38604, and I just confirmed that in 6.0.0-dev (on Windows at least) it is fixed.  It is NOT fixed in 5.2.1 or  5.2.2-dev (2/21 build), so for 5.2 users, use the second form to avoid leaks.
joel [from the website] purerave.com 19-Feb-2007 05:57
It doesn't mention this anywhere, but creationg a new SimpleXMLElement object from a non-valid string throws an exception. It looks ugly in the php log as it dumps the stack in multiple lines.

The correct way to create a new SimpleXMLElement object is like so:
<?php
$xmlstr = ''; // empty to throw an exception
try {
   $xml = new SimpleXMLElement($xmlstr);
} catch (Exception $e) {
   // handle the error
   echo '$xmlstr is not a valid xml string';
}
?>
matt at mattbostock dot com 05-Nov-2006 11:40
Be careful when using var_export to debug element attributes - it won't work! Always use print() or similar for checking the contents of element attributes.
Arnaud Bienvenu 19-Oct-2006 07:35
As of PHP 5.1.4, trying to iterate on a non-existent node will actually create that node.

<?
$xml = simplexml_load_string('<root></root>');
foreach($xml->b as $dummy);
echo $xml->asXML();
?>

Gives :

<?xml version="1.0"?>
<root><b/></root>

You might think it is a bug, but PHP developers seam to consider it as a feature : http://bugs.php.net/bug.php?id=39164
Jason Sheets <jsheets at shadonet dot com> 31-May-2006 10:31
Here is my Simple XML to array function, it is recursive and has the benefit of maintaining key value relationships and has worked well for me.

<?php
function XMLToArray($xml)
{
  if ($xml instanceof SimpleXMLElement) {
    $children = $xml->children();
    $return = null;
  }

  foreach ($children as $element => $value) {
    if ($value instanceof SimpleXMLElement) {
      $values = (array)$value->children();

      if (count($values) > 0) {
        $return[$element] = XMLToArray($value);
      } else {
        if (!isset($return[$element])) {
          $return[$element] = (string)$value;
        } else {
          if (!is_array($return[$element])) {
            $return[$element] = array($return[$element], (string)$value);
          } else {
            $return[$element][] = (string)$value;
          }
        }
      }
    }
  }

  if (is_array($return)) {
    return $return;
  } else {
    return $false;
  }
}
?>
daniel dot oconnor at gmail dot com 17-May-2006 06:21
SimpleXML handles namespaces, but it's not documented very well here at all.

If you wanted to parse, say, an open office manifest file or a piece of RDF/XML, you have to get elements and attributes by the namespace url.

Example:
<?php
function display($in) {
    if (file_exists($in)) {
        $xml = simplexml_load_file($in);
    } else {
        throw new Exception($in . " does not exist");
    }

    $manifest = $xml->children('http://openoffice.org/2001/manifest');

    foreach ($manifest->xpath('//manifest:file-entry') as $file) {
        foreach ($file->attributes('http://openoffice.org/2001/manifest') as $key => $value) {
            print "Key:" . $key . "\n";
            print "Value:" . $value . "\n";
        }
    }

}
?>

File: manifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
 <manifest:file-entry manifest:media-type="application/vnd.sun.xml.writer" manifest:full-path="/"/>
 <manifest:file-entry manifest:media-type="application/vnd.sun.xml.ui.configuration" manifest:full-path="Configurations2/"/>
 <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="layout-cache"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/thumbnail.png"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
</manifest:manifest>
paul at preinheimer dot com 06-May-2005 05:11
Hi,

If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently.

You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result.
eg.

<?php
$xml->xpath('/data/time-layout/start-valid-time');
?>

You can also choose just to encapsulate the element names containing a dash:
<?php $xml->data->{'time-layout'}->{'start-valid-time'} ?>

--

On a only partially related note, dealing with SimpleXML is one of the only times I have employed casting with PHP. While iterating (foreach) through the valid times, echo'ing the element worked great (it merely echo'ed the apropriate time), assigning it to another variable resulted in a SimpleXML object containing the time to be assigned, rather than just the time itself. This was resolved by casting the time to a string:

<?php
foreach($xml->data->{'time-layout'}->{'start-valid-time'} AS $time)
{
 $weatherDates[] = (string) $time;
}
?>
T CHASSAGNETTE t_chassagnette at yahoo dot fr 04-May-2005 01:57
Another method to parse an XML Document into a PHP array with SIMPLEXML inspired from Daniel FAIVRE !

<?php
function xml2php($xml)
{
    $fils = 0;
    $tab = false;
    $array = array();
    foreach($xml->children() as $key => $value)
    {
        $child = xml2php($value);

        //To deal with the attributes
        foreach($node->attributes() as $ak=>$av)
        {
            $child[$ak] = (string)$av;

        }

        //Let see if the new child is not in the array
        if($tab==false && in_array($key,array_keys($array)))
        {
            //If this element is already in the array we will create an indexed array
            $tmp = $array[$key];
            $array[$key] = NULL;
            $array[$key][] = $tmp;
            $array[$key][] = $child;
            $tab = true;
        }
        elseif($tab == true)
        {
            //Add an element in an existing array
            $array[$key][] = $child;
        }
        else
        {
            //Add a simple element
            $array[$key] = $child;
        }

        $fils++;
      }

    if($fils==0)
    {
        return (string)$xml;
    }

    return $array;

}
?>
nelson_menezes at yahoo dot co dot uk 01-Mar-2005 05:05
Note that SimpleXML expects to both read and output XML in UTF-8 encoding. You'll need to add a line such as this at the top of your input XML file if it isn't saved in UTF-8 (adjust to whatever encoding used):

<?xml version="1.0" encoding="ISO-8859-1" ?>

On the output side of things, if you're not serving/handling UTF-8, you'll need to use utf8_decode() [red. but that will only work for ISO-8859-1, not other encodings]. Common mistake: http://bugs.php.net/bug.php?id=28154
brcavanagh AT NO SPAM hotmail.com 02-Jan-2005 09:18
If you are looking to use SimpleXML for anything but reading XML documents, you should really reconsider, and use the XML DOM library.  By the time you get enough utilities implemented in DOM to handle all the set backs in SimpleXML, you will have defeated the purpose of using SimpleXML.  There are a few reasons for this, and there are already many workrounds, but the primairy issues are this

1) No complex node assignment.  You cannot switch nodes or replace them.

2) No appending new child nodes

3) Whenever you do something like $new_node = $xml_doc->node you will always get a reference even if you use a clone method, which will crash the script.

Other than that, its a great tool for reading docs.


Get a SimpleXMLElement object from a DOM node

  • ? SimpleXML 函数
  • simplexml_load_file ?
  • PHP Manual
  • SimpleXML 函数
  • Get a SimpleXMLElement object from a DOM node

simplexml_import_dom

(PHP 5, PHP 7, PHP 8)

simplexml_import_dom — Get a SimpleXMLElement object from a DOM node

说明

simplexml_import_dom ( DOMNode $node , string $class_name = "SimpleXMLElement" ) : SimpleXMLElement|null

This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.

参数

node

A DOM Element node

class_name

You may use this optional parameter so that simplexml_import_dom() will return an object of the specified class. That class should extend the SimpleXMLElement class.

返回值

Returns a SimpleXMLElement or null on failure.

范例

Example #1 Importing DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

以上例程会输出：

blah

参见

  • dom_import_simplexml() - Gets a DOMElement object from a SimpleXMLElement object
  • Basic SimpleXML usage

User Contributed Notes

shirkaen at gmail dot com 10-Nov-2016 06:58
/*If tags in DOM have text and some part of this text is surrounded by other tag, simple_import_dom object doesn't contain position of child tag, so rendering it back to html/xml can be a problem. Printing such a node is also peculiar. Eg.*/

//////////////////////
$text = "<body><p>Some text before <em>italic </em>and after text.</p></body>";
$dom = new DOMDocument;
$dom->loadHTML($text);
$result = simplexml_import_dom($dom);
echo $result->p;

//////////////////////
//Prints :
//Some text before and after text.

print_r($result->p);
//Prints:
//SimpleXMLElement Object ( [em] => italic )

print_r($result->p->em)
//does more or less the same:
//SimpleXMLElement Object ( [0] => italic )

var_dump($result->p);
//Prints:
//object(SimpleXMLElement)#8 (1) { ["em"]=> string(7) "italic " }

var_dump($result->p->em)
//object(SimpleXMLElement)#9 (1) { [0]=> string(7) "italic " }

//but
echo $result->p->em;
//prints:
//italic
brandonkirsch at perceptionilluminates dot com 14-Aug-2013 03:38
simplexml_import_dom() will accept DOMNodes or other SimpleXMLElements.  This has a useful purpose if you are extending the SimpleXMLElement class and would prefer the xpath() method to return your class extension instead of basic SimpleXMLElements.  For example:

class MySimpleXML extends SimpleXMLElement{
    public function xpath($xpath){
        $return = array();
        $simpleXmls = parent::xpath($xpath); // run SimpleXMLElement xpath, returning an array of SimpleXMLElements
        foreach($simpleXmls as $xml){
            $return[] = simplexml_import_dom($xml,'MySimpleXML'); // copy SimpleXMLElement, returning as MySimpleXML instance
        }
        return $return;
    }
}

Now I can create an instance of MySimpleXML, run an xpath, and get my results back as an array of MySimpleXML elements instead of the native SimpleXMLElement:

$mySimpleXml = new mySimpleXml('<root><node/></root>');

$array = $mySimpleXml->xpath('/root/node'); // returns array with a single MySimpleXml object


Interprets an XML file into an object

  • ? simplexml_import_dom
  • simplexml_load_string ?
  • PHP Manual
  • SimpleXML 函数
  • Interprets an XML file into an object

simplexml_load_file

(PHP 5, PHP 7, PHP 8)

simplexml_load_file — Interprets an XML file into an object

说明

simplexml_load_file ( string $filename , string $class_name = "SimpleXMLElement" , int $options = 0 , string $ns = "" , bool $is_prefix = false ) : SimpleXMLElement|false

Convert the well-formed XML document in the given file to an object.

参数

filename

Path to the XML file

Note:

Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Since PHP 5.1.0 you don't need to do this because PHP will do it for you.

class_name

You may use this optional parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

Namespace prefix or URI.

is_prefix

true if ns is a prefix, false if it's a URI; defaults to false.

返回值

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, 或者在失败时返回 false.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

错误／异常

Produces an E_WARNING error message for each error found in the XML data.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

更新日志

版本 | 说明
5.2.0 | The optional parameter is_prefix was added.

范例

Example #1 Interpret an XML document

<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');

    print_r($xml);
} else {
    exit('Failed to open test.xml.');
}
?>

This script will display, on success:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

参见

  • simplexml_load_string() - Interprets a string of XML into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage

User Contributed Notes

sirgrayjn at gmail dot com 22-Sep-2016 09:51
// Be carefull if you migrate or use local machine
// for test/development.

// Windows directory separators: "\" and "/"
// You may mix separators "C:\somedir\www/img/bg.jpg".

// Mixed separators path work fine in other functions
// But simplexml_load_file() failed with mixed separators.

// Examples:
include("C:\dir\my.php");    // work (windows)
include("C:\dir/my.php");    // work (windows) with mixed
include("C:/dir/my.php");    // work (windows, linux)
simplexml_load_file("C:\dir\my.php");    // work
simplexml_load_file("C:\dir/my.php");    // failed with mixed
simplexml_load_file("C:/dir/my.php");    // work
rex111 at bigmir dot net 08-Sep-2016 03:02
Get all tags and their values. (recursive)

<?php
$xml = simplexml_load_file('settings.xml');

function all_tag($xml){
    $i=0; $name = "";
    foreach ($xml as $k){
        $tag = $k->getName();
        $tag_value = $xml->$tag;
        if ($name == $tag){ $i++;    }
                $name = $tag;
            echo $tag .' '.$tag_value[$i].'<br />';
        // recursive
           all_tag($xml->$tag->children());
    }
}

all_tag($xml);
?>
Rich 24-Nov-2015 02:51
I stumbled on this: a single element with a simple string in it becomes a string, but a single element with a *space* in it becomes an Array, with one element, the string space.

I'm sure to XML mystics this is wise and wonderful but it really confused me,  and I thought it might confuse others.

<?php
$parsed = simplexml_load_string('<container><space> </space><blank></blank><string>hello</string></container>');
$content = json_decode(json_encode($parsed),TRUE);
var_dump($content);
/* Output is:
array(3) {
  'space' => array(1) {           ← did NOT expect this!
    [0] => string(1) " "
  }
  'blank' => array(0) { }
  'string' => string(5) "hello"
}
 */
tuxedobob 30-Jun-2015 01:25
Occasionally you may try to load a file and have it complain about an entity and throw a parser error.

If this is the case, check to make sure that the file in question does not contain an ampersand (&) without a corresponding entity reference.

If it does, or if you want to err on the side of caution, then instead of using simplexml_load_file, try this:

$file = file_get_contents('stuff.xml');
$temp = preg_replace('/&(?!(quot|amp|pos|lt|gt);)/', '&amp;', $file);
$xml = simplexml_load_string($temp) or die("xml not loading");

Read the file into a string, add 'amp;' after any '&' that is not part of a character entity, then parse the string as xml.
kannan at 99deals dot in 04-Sep-2012 06:27
If you have some nodes which are having special characters, it would not load properly

for an instance see the nodes below
<node:number>1538-7445</node:number>
<node:coverDisplayDate>Sep  1 2012 12:00:00:000AM</node:coverDisplayDate>

either you have to change the : to other special characters like '-' in order to convert it properly

Correct Node
<node-number>1538-7445</node-number>
<node-coverDisplayDate>Sep  1 2012 12:00:00:000AM</node-coverDisplayDate>

I have wasted my precious time while debugging this. Please aware about this. ?
ricardo at ricardomartins dot info 21-Aug-2012 05:49
Sometimes we have xml's with hyphens nodes, like

<my_xml>
 <some-node>value</some-node>
</my_xml>

You'll need to use
<?php
$simpleXmlObj->{'some-node'}
?>

instead of
<?php
$simpleXmlObj->some-node;
?>
fusionstream at gmail dot com 05-Apr-2012 04:15
If you are loading many files, this may slow down your page load time.

To set a timeout, use file_get_context and then simplexml_load_string

<?php

$fp = fopen('http://www.example.com/rss', false, stream_create_context(array('http' => array('timeout', '1.5'))));

if ($fp) {
    print_r( simplexml_load_string($fp) );
} else {
    echo "The request timed out";
}
?>
sean at aliencreations dot com 17-Mar-2011 10:59
If you find that you are receiving 500 errors with simplexml_load_file() but you can access the xml/rss feed manually through a browser, your script is probably being blocked by a user agent sniffer.

Add this code before your xml call to remedy this issue

<?php

ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ini_set("max_execution_time", 0);
ini_set("memory_limit", "10000M");

$rss = simplexml_load_file($feed_url);

?>
Nanuit at ossi dot at 08-Feb-2011 01:51
A little function very helpfull in using simplexml_load_file behind a proxy

<?php
function getXMLfromURL($url) {
      $Proxy = getenv("HTTP_PROXY");

      if (strlen($Proxy) > 1) {
        $r_default_context = stream_context_get_default ( array
                    ('http' => array(
                        'proxy' => $Proxy,
                        'request_fulluri' => True,
                    ),
                )
            );
        libxml_set_streams_context($r_default_context);
      }
      $daten = simplexml_load_file($url);
      return ($daten);
    }
?>

where HTTP_PROXY is set to e.g.: tcp://proxy:8080
guego dot ol at ig dot com dot br 12-Nov-2010 03:26
Analyze fully XML.

<?php
$xml = simplexml_load_file('file.xml');

foreach($xml as $key0 => $value){
echo "..1..[$key0] => $value";
foreach($value->attributes() as $attributeskey0 => $attributesvalue1){
echo "________[$attributeskey0] = $attributesvalue1";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value as $key => $value2){
echo "....2.....[$key] => $value2";
foreach($value2->attributes() as $attributeskey => $attributesvalue2){
echo "________[$attributeskey] = $attributesvalue2";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value2 as $key2 => $value3){
echo ".........3..........[$key2] => $value3";
foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){
echo "________[$attributeskey2] = $attributesvalue3";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value3 as $key3 => $value4){
echo "...................4....................[$key3] => $value4";
foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){
echo "________[$attributeskey3] = $attributesvalue4";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value4 as $key4 => $value5){
echo ".....................5......................[$key4] => $value5";
foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){
echo "________[$attributeskey4] = $attributesvalue5";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value5 as $key5 => $value6){
echo "......................6.......................[$key5] => $value6";
foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){
echo "________[$attributeskey5] = $attributesvalue6";
}
echo '<br />';
}}}}}
echo '<br />';
}
?>
raduispas at gmail dot com 21-Oct-2010 06:12
if you want to check when this function fails,make sure to compare the return value with ===  instead of == :

<?php
$url = 'http://www.example.com';
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
if($xml ===  FALSE)
{
   //deal with error
}
else { //do stuff }
?>

Otherwise you may end up with FALSE all the time even if the document is ok. Hope this helps someone ;)
jamie at splooshmedia dot co dot uk 31-Mar-2010 06:17
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

<?php
function loadXML2($domain, $path, $timeout = 30) {

    /*
        Usage:

        $xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
        if($xml) {
            // xml doc loaded
        } else {
            // failed. show friendly error message.
        }
    */

    $fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
    if($fp) {
        // make request
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $domain\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);

        // get response
        $resp = "";
        while (!feof($fp)) {
            $resp .= fgets($fp, 128);
        }
        fclose($fp);
        // check status is 200
        $status_regex = "/HTTP\/1\.\d\s(\d+)/";
        if(preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {
            // load xml as object
            $parts = explode("\r\n\r\n", $resp);
            return simplexml_load_string($parts[1]);
        }
    }
    return false;

}
?>
Smokey 14-Mar-2010 10:16
for nested and same name values i'v made up this little bit for getting and displaying multiable values from google's geocode when a exact match is not found it returns all close matches in the following format(this is an abriged version of there output)

<Response>
  <Placemark id="1">
    <address> New York 24, NY, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.5850086,40.7207442,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="2">
    <address>New York 27, NY, USA</address>
    <AddressDetails>
      ...................
    </AddressDetails>
    <Point>
      <coordinates>-72.8987835,40.8003588,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="3">
    <address>Cedar Place School, 20 Cedar Pl, Yonkers, NY 10705, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.8966320,40.9256520,0</coordinates>
    </Point>
  </Placemark>
</Response>

<?php
// get and breakdown the results then store them in $var's
$Address = "99999 parkplace, new york, NY";
$urladdress = urlencode($Address);
$Base_url = "http://maps.google.com/maps/geo?q=";
$urlParts = "&output=xml";
$urlrequest = $Base_url . $urladdress . $urlParts;
$xml = simplexml_load_file($urlrequest);
$num = "0";
foreach ($xml->Response->Placemark as $value){
    $num++;
    $GeoFindAdd{$num} = $value->address;
    $GeoFindCords{$num} = $value->Point->coordinates;
}

// a simple display for the results
echo "Found ",$num," Possable Geo Data Sets <br>";
$CountNumResults = "0";
for ( ; $num > 0; $num--){
    $CountNumResults++;
    echo $countnum,"<br> Address = ",$GeoFindAdd{$num},"<br> Coordinates = ",$GeoFindCords{$num},"<br>";
}
echo "END";
?>
knl at bitflop dot com 11-Sep-2009 12:02
If you need to parse the data from SimpleXML into a session variable remember to define the data as a string first.

If you don't you will get warnings of "Node no longer exists" pointing to your session_start() function.

This will work:

<?php

    $new_version = simplexml_load_file('http://example.com/version.xml');
    $_SESSION['current_version'] = (string)$new_version->version;

?>
neil art neilanddeb dort com 17-Aug-2009 06:00
Because the encoding of my XML file is UTF-8 and the
encoding of my web page is iso-8859-1 I was getting strange characters such as a�™ instead of a right single quote.

The solution to this turned out to be hard to find, but really easy to implement.

http://uk3.php.net/manual/en/function.iconv.php

Using the iconv() function you can convert from one encodign to another, the TRANSLIT option seems to work best for what I needed.  Here's my example:

<?php
// convert string from utf-8 to iso8859-1
$horoscope = iconv( "UTF-8", "ISO-8859-1//TRANSLIT", $horoscope );
?>

I found the solution on this page...
http://tinyurl.com/lm39xc
Hope this helps
cryonyx at cerebrate dot ru 21-Oct-2008 03:34
In case you have a XML file with a series of equally named elements on one level simplexml incorrectly processes them and doesn't allow to walk through the array using foreach(). As far as I'm concerned, it is the problem caused by PHP xml_parser (see: http://ru2.php.net/manual/ru/function.xml-parser-create.php#53188).

To avoid this, just use count() and walk through the array using for().

Example:

<params>
  <param>
    <name>version.shell</name>
    <value>1.0</value>
  </param>
  <param>
      <name>version.core</name>
      <value>1.0</value>
  </param>
  <param>
      <name>file.lang</name>
      <value>vc.lang</value>
  </param>
  ...
</params>

<?php
$filename = '...';
$xml = simplexml_load_file($filename);
$p_cnt = count($xml->param);
for($i = 0; $i < $p_cnt; $i++) {
  $param = $xml->param[$i];
  ...;
}
?>
mario 02-Sep-2008 02:08
If you want CDATA in your object you should use LIBXML_NOCDATA

<?php
$xml = simplexml_load_file($file_xml, 'SimpleXMLElement',LIBXML_NOCDATA);

    print_r($xml);
?>
l [DOT] anzinger [AT] gmail [DOT] com 26-Mar-2008 09:03
If you don't want that the CDATA values get escaped, just load the XML with LIBXML_NOCDATA as an 3rd argument.

Note: A PHP version >= 5.1.0 is required for this to work.

Example:

<?php simplexml_load_file('xmldatei.xml', null, LIBXML_NOCDATA); ?>
php at werner dash ott dot de 29-Mar-2007 01:13
Making SimpleXMLElement objects session save.

Besides the effect of not surviving sessions, the SimpleXMLElement object may even crash the session_start() function when trying to re-enter the session!

To come up with a solution for this, I used a pattern as follows. The core idea is to transform the SimpleXMLElement between session calls to and from a string representation which of course is session save.

<?php
  //
  // session save handling of SimpleXMLElement objects
  // (applies to/ tested with PHP 5.1.5 and PHP 5.2.1)
  // The myClass pattern allows for conveniently accessing
  // XML structures while being session save
  //
  class myClass
  {
    private $o_XMLconfig = null;
    private $s_XMLconfig = '';

    public function __construct($args_configfile)
    {
      $this->o_XMLconfig = simplexml_load_file($args_configfile);
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
    } // __construct()

    public function __destruct()
    {
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
      unset($this->o_XMLconfig); // this object would otherwise crash
                                 // the subsequent call of
                                 // session_start()!
    } // __destruct()

    public function __wakeup()
    {
      $this->o_XMLconfig = simplexml_load_string($this->s_XMLconfig);
    } // __wakeup()

  } // class myClass
?>
wouter at code-b dot nl 20-Feb-2007 02:08
To correctly extract a value from a CDATA just make sure you cast the SimpleXML Element to a string value by using the cast operator:

<?php
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<rss>
    <channel>
        <item>
            <title><![CDATA[Tom & Jerry]]></title>
        </item>
    </channel>
</rss>';

$xml = simplexml_load_string($xml);

// echo does the casting for you
echo $xml->channel->item->title;

// but vardump (or print_r) not!
var_dump($xml->channel->item->title);

// so cast the SimpleXML Element to 'string' solve this issue
var_dump((string) $xml->channel->item->title);
?>

Above will output:

Tom & Jerry

object(SimpleXMLElement)#4 (0) {}

string(11) "Tom & Jerry"
Kyle 10-Dec-2006 02:35
In regards to Anonymous on 7th April 2006

There is a way to get back HTML tags. For example:

<?xml version="1.0"?>
<intro>
    Welcome to <b>Example.com</b>!
</intro>

<?php
// I use @ so that it doesn't spit out content of my XML in an error message if the load fails. The content could be passwords so this is just to be safe.
$xml = @simplexml_load_file('content_intro.xml');
if ($xml) {
    // asXML() will keep the HTML tags but it will also keep the parent tag <intro> so I strip them out with a str_replace. You could obviously also use a preg_replace if you have lots of tags.
    $intro = str_replace(array('<intro>', '</intro>'), '', $xml->asXML());
} else {
    $error = "Could not load intro XML file.";
}
?>

With this method someone can change the intro in content_intro.xml and ensure that the HTML is well formed and not ruin the whole site design.
Anonymous 06-Apr-2006 09:21
What has been found when using the script is that simplexml_load_file() will remove any HTML formating inside the XML file, and will also only load so many layers deep. If your XML file is to deap, it will return a boolean false.
fdouteaud at gmail dot com 09-Mar-2006 05:21
Be careful if you are using simplexml data directly to feed your MySQL database using MYSQLi and bind parameters.

The data coming from simplexml are Objects and the bind parameters functions of MySQLi do NOT like that! (it causes some memory leak and can crash Apache/PHP)

In order to do this properly you MUST cast your values to the right type (string, integer...) before passing them to the binding methods of MySQLi.
I did not find that in the documentation and it caused me a lot of headache.
info at evasion dot cc 06-Feb-2006 08:26
Sorry there's a mistake in the previous function :
<?php
   function &getXMLnode($object, $param) {
       foreach($object as $key => $value) {
           if(isset($object->$key->$param)) {
               return $object->$key->$param;
           }
           if(is_object($object->$key)&&!empty($object->$key)) {
               $new_obj = $object->$key;
               // Must use getXMLnode function there (recursive)
               $ret = getXMLnode($new_obj, $param);

           }
       }
       if($ret) return (string) $ret;
       return false;
   }
?>
skutter at imprecision dot net 03-Feb-2006 09:11
So it seems SimpleXML doesn't support CDATA... I bashed together this little regex function to sort out the CDATA before trying to parse XML with the likes of simplexml_load_file / simplexml_load_string. Hope it might help somebody and would be very interested to hear of better solutions. (Other than *not* using SimpleXML of course! ;)

It looks for any <![CDATA [Text and HTML etc in here]]> elements, htmlspecialchar()'s the encapsulated data and then strips the "<![CDATA [" and "]]>" tags out.

<?php
function simplexml_unCDATAise($xml) {
    $new_xml = NULL;
    preg_match_all("/\<\!\[CDATA \[(.*)\]\]\>/U", $xml, $args);

    if (is_array($args)) {
        if (isset($args[0]) && isset($args[1])) {
            $new_xml = $xml;
            for ($i=0; $i<count($args[0]); $i++) {
                $old_text = $args[0][$i];
                $new_text = htmlspecialchars($args[1][$i]);
                $new_xml = str_replace($old_text, $new_text, $new_xml);
            }
        }
    }

    return $new_xml;
}

//Usage:
$xml = 'Your XML with CDATA...';
$xml = simplexml_unCDATAise($xml);
$xml_object = simplexml_load_string($xml);
?>
info at evasion dot cc 03-Feb-2006 03:37
Suppose you have loaded a XML file into $simpleXML_obj.
The structure is like below :

SimpleXMLElement Object
(

    [node1] => SimpleXMLElement Object
        (
            [subnode1] => value1
            [subnode2] => value2
            [subnode3] => value3
        )

    [node2] => SimpleXMLElement Object
        (
            [subnode4] => value4
            [subnode5] => value5
            [subnode6] => value6
        )

)

When searching a specific node in the object, you may use this function :

<?php

    function &getXMLnode($object, $param) {
        foreach($object as $key => $value) {
            if(isset($object->$key->$param)) {
                return $object->$key->$param;
            }
            if(is_object($object->$key)&&!empty($object->$key)) {
                $new_obj = $object->$key;
                $ret = getCfgParam($new_obj, $param);
            }
        }
        if($ret) return (string) $ret;
        return false;
    }
?>

So if you want to get subnode4 value you may use this function like this :

<?php
$result = getXMLnode($simpleXML_obj, 'subnode4');
echo $result;
?>

It display "value4"
genialbrainmachine at NOSPAM dot tiscali dot it 30-Sep-2005 08:52
Micro$oft Word uses non-standard characters and they create problems in using simplexml_load_file.
Many systems include non-standard Word character in their implementation of ISO-8859-1. So an XML document containing that characters can appear well-formed (i.e.) to many browsers. But if you try to load this kind of documents with simplexml_load_file you'll have a little bunch of troubles..
I believe that this is exactly the same question discussed in htmlentites. Following notes to htmlentitles are interesting here too (given in the reverse order, to grant the history):
http://it.php.net/manual/en/function.htmlentities.php#26379
http://it.php.net/manual/en/function.htmlentities.php#41152
http://it.php.net/manual/en/function.htmlentities.php#42126
http://it.php.net/manual/en/function.htmlentities.php#42511
mark 12-Sep-2005 11:06
If the property of an object is empty the array is not created. Here is a version object2array that transfers properly.

<?php
function object2array($object)
{
    $return = NULL;

    if(is_array($object))
    {
        foreach($object as $key => $value)
            $return[$key] = object2array($value);
    }
    else
    {
        $var = get_object_vars($object);

        if($var)
        {
            foreach($var as $key => $value)
                $return[$key] = ($key && !$value) ? NULL : object2array($value);
        }
        else return $object;
    }

    return $return;
}
?>


Interprets a string of XML into an object

  • ? simplexml_load_file
  • WDDX ?
  • PHP Manual
  • SimpleXML 函数
  • Interprets a string of XML into an object

simplexml_load_string

(PHP 5, PHP 7, PHP 8)

simplexml_load_string — Interprets a string of XML into an object

说明

simplexml_load_string ( string $data , string $class_name = "SimpleXMLElement" , int $options = 0 , string $ns = "" , bool $is_prefix = false ) : SimpleXMLElement|false

Takes a well-formed XML string and returns it as an object.

参数

data

A well-formed XML string

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

Namespace prefix or URI.

is_prefix

true if ns is a prefix, false if it's a URI; defaults to false.

返回值

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, 或者在失败时返回 false.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

错误／异常

Produces an E_WARNING error message for each error found in the XML data.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

更新日志

版本 | 说明
5.2.0 | The optional parameter is_prefix was added.

范例

Example #1 Interpret an XML string

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

以上例程会输出：

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

At this point, you can go about using $xml->body and such.

参见

  • simplexml_load_file() - Interprets an XML file into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage

User Contributed Notes

erguven dot m at gmail dot com 11-May-2017 03:14
if you want to use a class which exists in a name space, use it full name. simple_load_string did not recognize short one.

class.new.php
<?php
namespace foo\bar;

class new extends SimpleXMLElement
{
    public function do()
    {
        echo "done";
    }
}
?>

false.php
<?php
use \foo\bar\new;

$result = simplexml_load_string($xml, 'new'); // it gives warning
$result->do(); // fatal error
?>

true.php
<?php
use \foo\bar\new;
$result = simplexml_load_string($xml, '\foo\bar\new');

$result->do(); // prints done
?>
artistan at gmail dot com 11-Jun-2015 12:32
Here is my update to Bob's simple SimpleXML wrapper function.
I noticed his version would turn an empty SimpleXMLElement into an empty array.

<?php
    /**
     * http://php.net/manual/en/function.simplexml-load-string.php#91564
     *
     * bool/array unserialize_xml ( string $input [ , callback $callback ] )
     * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
     * Returns false on all failure
     * Notes:
     * Root XML tags are stripped
     * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
     * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
     *
     * @param $input
     * @param null $callback
     * @param bool $recurse
     * @return array|mixed
     *
     */
    function unserialize_xml($input, $callback = null, $recurse = false)
    {
        // Get input, loading an xml string with simplexml if its the top level of recursion
        $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
        // Convert SimpleXMLElements to array
        if ($data instanceof SimpleXMLElement){
            if(!empty($data)){
                $data = (array) $data;
            } else {
                $data = '';
            }
        }
        // Recurse into arrays
        if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
        // Run callback and return
        return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
    }
?>
meustrus 07-May-2015 03:38
Be careful checking for parse errors. An empty SimpleXMLElement may resolve to FALSE, and if your XML contains no text or only contains namespaced elements your error check may be wrong. Always use `=== FALSE` when checking for parse errors.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<ns1:Root xmlns:ns1="http://example.com/custom">
<ns1:Node>There's stuff here</ns1:Node>
</ns1:Root>
XML;

$simplexml = simplexml_load_string($xml);

// This prints "Parse Error".
echo ($simplexml ? 'Valid XML' : 'Parse Error'), PHP_EOL;

// But this prints "There's stuff here", proving that
// the SimpleXML object was created successfully.
echo $simplexml->children('http://example.com/custom')->Node, PHP_EOL;

// Use this instead:
echo ($simplexml !== FALSE ? 'Valid XML' : 'Parse Error'), PHP_EOL;

?>

See:

https://bugs.php.net/bug.php?id=31045
https://bugs.php.net/bug.php?id=30972
https://bugs.php.net/bug.php?id=69596
dkrnl at yandex dot ru 30-Sep-2013 02:58
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php
AllenJB 12-Oct-2012 08:09
<?php
$xml = json_decode(json_encode((array) simplexml_load_string($string)), 1);
?>

A reminder that json_encode attempts to convert data to UTF-8 without specific knowledge of the source encoding. This method can cause encoding issues if you're not working in UTF-8.
Anonymous 29-Feb-2012 08:54
Use libxml_disable_entity_loader() to restrict loading of external files.  See http://www.idontplaydarts.com/2011/02/scanning-the-internal-network-using-simplexml/
Diego Araos, diego at klapmedia dot com 05-Feb-2011 12:57
A simpler way to transform the result into an array (requires json module).

<?php
function object2array($object) { return @json_decode(@json_encode($object),1); }
?>

Example:
<?php
$xml_object=simplexml_load_string('<SOME XML DATA');
$xml_array=object2array($xml_object);
?>
ascammon at hotmail dot com 28-Dec-2010 01:04
I had a hard time finding this documented, so posting it here in case it helps someone:

If you want to use multiple libxml options, separate them with a pipe, like so:

<?php
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
?>
jeff at creabilis dot com 17-Nov-2009 02:28
If you want to set the charset of the outputed xml, simply set the encoding attribute like this :

<?php simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><xml/>'); ?>

The generated xml outputed by $xml->asXML will containt accentuated characters like 'é' instead of &#xE9;.

Hope this help
Bob 17-Jun-2009 02:16
Here is my simple SimpleXML wrapper function.
As far as I can tell, it does the same as Julio Cesar Oliveira's (above).
It parses an XML string into a multi-dimensional associative array.
The second argument is a callback that is run on all data (so for example, if you want all data trimmed, like Julio does in his function, just pass 'trim' as the second arg).
<?php
function unserialize_xml($input, $callback = null, $recurse = false)
/* bool/array unserialize_xml ( string $input [ , callback $callback ] )
 * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
 * Returns false on all failure
 * Notes:
    * Root XML tags are stripped
    * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
    * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
 */
{
    // Get input, loading an xml string with simplexml if its the top level of recursion
    $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
    // Convert SimpleXMLElements to array
    if ($data instanceof SimpleXMLElement) $data = (array) $data;
    // Recurse into arrays
    if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
    // Run callback and return
    return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
?>
Julio Cesar Oliveira 30-Mar-2009 07:14
The XML2Array func now Recursive!

<?php
function XML2Array ( $xml , $recursive = false )
{
    if ( ! $recursive )
    {
        $array = simplexml_load_string ( $xml ) ;
    }
    else
    {
        $array = $xml ;
    }

    $newArray = array () ;
    $array = ( array ) $array ;
    foreach ( $array as $key => $value )
    {
        $value = ( array ) $value ;
        if ( isset ( $value [ 0 ] ) )
        {
            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
        }
        else
        {
            $newArray [ $key ] = XML2Array ( $value , true ) ;
        }
    }
    return $newArray ;
}
?>
javalc6 at gmail dot com 18-Oct-2008 06:25
I wanted to convert an array containing strings and other arrays of the same type into a simplexml object.

Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks.

<?php
function array2xml($array, $tag) {

    function ia2xml($array) {
        $xml="";
        foreach ($array as $key=>$value) {
            if (is_array($value)) {
                $xml.="<$key>".ia2xml($value)."</$key>";
            } else {
                $xml.="<$key>".$value."</$key>";
            }
        }
        return $xml;
    }

    return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}

$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

echo array2xml($test,"meal")->asXML();
?>
rowan dot collins at gmail dot com 10-Jul-2008 07:07
There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine under PHP 5.2.6

The key is noted above example #6 here:
http://uk2.php.net/manual/en/simplexml.examples.php

"To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object."

If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the string content of the element. So some functions, including print_r(), might not show what you expect. But if you explicitly cast to a string, you get the whole content.

<?php
$xml = simplexml_load_string('<foo>Text1 &amp; XML entities</foo>');
print_r($xml);
/*
SimpleXMLElement Object
(
    [0] => Text1 & XML entities
)
*/

$xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw data]]></foo>');
print_r($xml2);
/*
SimpleXMLElement Object
(
)
*/
// Where's my CDATA?

// Let's try explicit casts
print_r( (string)$xml );
print_r( (string)$xml2 );
/*
Text1 & XML entities
Text2 & raw data
*/
// Much better
?>
amir_abiri at ipcmedia dot com 08-Feb-2008 08:47
It doesn't seem to be documented anywhere, but you can refer to an element "value" for the purpose of changing it like so:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} = $xml->number->{0} + 1;

echo $xml->asXml();
?>

echos:
<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>2</number></root>

However, this only works with a direct assignment, not with any of the other operators:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} += 1;
// Or:
$xml->number->{0}++;

echo $xml->asXml();
?>

Both of the above cases would result in:

<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>1<0/></number></root>
bojan 04-Feb-2008 04:38
As was said before don't use var_dump() or print_r() to see SimpleXML object structure as they do not returns always what you expect.
Consider the following:

<?php

// data in xml
$xml_txt = '
<root>
  <folder ID="65" active="1" permission="1"><![CDATA[aaaa]]></folder>
  <folder ID="65" active="1" permission="1"><![CDATA[bbbb]]></folder>
</root>';

// load xml into SimpleXML object
$xml = simplexml_load_string($xml_txt, 'SimpleXMLElement', LIBXML_NOCDATA);//LIBXML_NOCDATA LIBXML_NOWARNING

// see object structure
print_r($xml);

/* this prints
SimpleXMLElement Object
(
    [folder] => Array
        (
            [0] => aaaa
            [1] => bbbb
        )

)
*/

// but...
foreach ($xml->folder as $value){
    print_r($value);
}
/* prints complete structure of each folder element:
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => aaaa
)

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => bbbb
)

*/
?>
hattori at hanso dot com 15-Oct-2007 03:19
Theres a problem with the below workaround when serializing fields containing html CDATA. For any other content type then HTML try to modfiy function parseCDATA.
Just add these lines before serializing.
This is also a workaround for this bug http://bugs.php.net/bug.php?id=42001

<?PHP
if(strpos($content, '<![CDATA[')) {
   function parseCDATA($data) {
      return htmlentities($data[1]);
   }
   $content = preg_replace_callback(
      '#<!\[CDATA\[(.*)\]\]>#',
      'parseCDATA',
      str_replace("\n", " ", $content)
   );
}
?>
nbijnens at servs dot eu 10-Sep-2007 05:17
Please note that not all LIBXML options are supported with the options argument.

For instance LIBXML_XINCLUDE does not work. But there is however a work around:

<?php
$xml = new DOMDocument();
$xml->loadXML ($XMLString);

$xml->xinclude();
$xml = simplexml_import_dom($xml);

?>
Pedro 06-Jul-2007 01:28
Attention:

simplexml_load_string has a problem with entities other than (&lt;, &gt;, &amp;, &quot; and &apos;).

Use numeric character references instead!
m dot ament at mailcity dot com 06-Mar-2007 06:51
Warning:

The parsing of XML-data will stop when reaching character 0.
Please avoid this character in your XML-data.
mindpower 30-Jan-2007 03:03
A simple extension that adds a method for retrieving a specific attribute:

<?php
class simple_xml_extended extends SimpleXMLElement
{
    public    function    Attribute($name)
    {
        foreach($this->Attributes() as $key=>$val)
        {
            if($key == $name)
                return (string)$val;
        }
    }

}

$xml = simplexml_load_string('
<xml>
  <dog type="poodle" owner="Mrs Smith">Rover</dog>
</xml>', 'simple_xml_extended');

echo $xml->dog->Attribute('type');

?>

outputs 'poodle'

I prefer to use this technique rather than typecasting attributes.
Maciek Ruckgaber <maciekrb at gmai dot com> 07-Jun-2005 05:07
after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P

when you have something like:

<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://foosite.foo/">2328</double>
XML;
?>

you will have the simpleXML object "transformed" to the text() content:

<?php
$xml = simplexml_load_string($xmlstr);
echo $xml; // this will echo 2328  (string)
?>
cellog at php dot net 31-Aug-2004 04:11
simplexml does not simply handle CDATA sections in a foreach loop.

<?php
$sx = simplexml_load_string('
<test>
 <one>hi</one>
 <two><![CDATA[stuff]]></two>
 <t>
  <for>two</for>
 </t>
 <multi>one</multi>
 <multi>two</multi>
</test>');
foreach((array) $sx as $tagname => $val) {
    if (is_string($val)) {
       // <one> will go here
    } elseif (is_array($val)) {
       // <multi> will go here because it happens multiple times
    } elseif (is_object($val)) {
      // <t> will go here because it contains tags
      // <two> will go here because it contains CDATA!
    }
}
?>

To test in the loop, do this

<?php
if (count((array) $val) == 0) {
    // this is not a tag that contains other tags
    $val = '' . $val;
    // now the CDATA is revealed magically.
}
?>


WDDX

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
    • wddx examples
  • WDDX 函数
    • wddx_add_vars — Add variables to a WDDX packet with the specified ID
    • wddx_deserialize — Unserializes a WDDX packet
    • wddx_packet_end — Ends a WDDX packet with the specified ID
    • wddx_packet_start — Starts a new WDDX packet with structure inside it
    • wddx_serialize_value — Serialize a single value into a WDDX packet
    • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

There are no user contributed notes for this page.


简介

Warning

This extension is DEPRECATED and UNBUNDLED as of PHP 7.4.0.

These functions are intended for work with » WDDX.

Warning

Do not pass untrusted user input to wddx_deserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

User Contributed Notes

alvaro at demogracia dot com 29-Sep-2008 08:49
From OpenWDDX.Org:

"The Web Distributed Data Exchange, or WDDX, is a free, open XML-based technology that allows Web applications created with any platform to easily exchange data with one another over the Web."

"WDDX is an XML-based technology that enables the exchange of complex data between Web programming languages, creating what some refer to as 'Web syndicate networks'. WDDX consists of a language-independent representation of data based on an XML 1.0 DTD, and a set of modules for a wide variety of languages that use WDDX. WDDX can be used with HTTP, SMTP, POP, FTP and other Internet protocols that support transferring textual data."


需求

此扩展需要 libxml PHP 扩展。这表示需要使用 --with-libxml，或在 PHP 7.4 之前的版本中使用 --enable-libxml， 尽管这将隐式完成因为 libxml 是缺省开启的。

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).

User Contributed Notes

There are no user contributed notes for this page.


安装

PHP 7.4

此扩展已被移至 » PECL 资源库且不再与 PHP 捆绑。7.4.0

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/wddx.

PHP < 7.4

After installing the required expat library, compile PHP with --enable-wddx, and use --with-libexpat-dir for expat.

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

This extension defines a WDDX packet identifier returned by wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.


范例

Table of Contents

  • wddx examples

User Contributed Notes

dormilich at netscape dot net 27-Nov-2008 06:37
If you want to use the WDDX 1.0 DTD for validation (http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt) check that you define the comment as element, not as attribute.

<?xml version="1.0" encoding="iso-8859-1" ?>
<wddxPacket version='1.0'>
    <header>
        <comment>PHP</comment>
    </header>
    <data><!-- WDDX serialized data --></data>
</wddxPacket>


wddx examples

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Example #1 Serializing a single value with WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Example #2 Using incremental packets with WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Note:

If you want to serialize non-ASCII characters you have to convert your data to UTF-8 first (see utf8_encode() and iconv()).

User Contributed Notes

There are no user contributed notes for this page.


WDDX 函数

Table of Contents

  • wddx_add_vars — Add variables to a WDDX packet with the specified ID
  • wddx_deserialize — Unserializes a WDDX packet
  • wddx_packet_end — Ends a WDDX packet with the specified ID
  • wddx_packet_start — Starts a new WDDX packet with structure inside it
  • wddx_serialize_value — Serialize a single value into a WDDX packet
  • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

iGEL 14-Mar-2008 02:03
As of version 5.2.5, this is wrong:

> Note: If you want to serialize non-ASCII characters you
> have to convert your data to UTF-8 first (see utf8_encode()
> and iconv()).

Serializing a string with WDDX will always convert it from ISO-8859-1 to UTF-8, no matter what the original encoding is. So if your data already are UTF-8, you get just gibberish.

You can restore the original encoding by using utf8_decode on the serialized wddx data, even though your original data may use chars not included in ISO-8859-1:

<?php
header("Content-Type: text/xml;encoding=utf-8");
echo utf8_decode(wddx_serialize_value("?? ???"));
?>

(This is why I dislike PHP, sorry)
egbert teeselink 23-Feb-2008 10:49
If your PHP doesn't have wddx support installed, and you need it, and you don't want to install PEAR just for wddx, try this short piece of code, based on SimpleXML:

//can read any wddx file generated from php arrays. assumes var elements are only inside struct elements and that only one packet exists.
function wddx_read_node($node, $type)
{
    switch($type)
    {
    case "boolean":
        return (string)$node;
    case "number":
    case "binary":
    case "string":
        return (string)$node;
    case "null":
        return null;
    case "array":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            $a[] = wddx_read_node($subnode, $subtype);
        }
        return $a;
    case "struct":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            list($key, $value) = wddx_read_node($subnode, $subtype); //must be a var element
            $a[$key] = $value;
        }
        return $a;
    case "var":
        list($subnode, $subtype) = getchild($node);
        return array((string)$node["name"], wddx_read_node($subnode, $subtype));
    case "data":
        list($subnode, $subtype) = getchild($node);
        return wddx_read_node($subnode, $subtype);
    }
}

function wddx_read($string)
{
    $xml = simplexml_load_string($string);
    $d = wddx_read_node($xml->data, "data");
    return $d;
}

important notice: this one may not work with all wddx input. multiple packets or variables outside a "struct" are not supported. basically, you always get a PHP (associative) array, never something else. feel free to make additions.
no at spam dot thx 12-Aug-2007 02:09
To bradburn at kiwi dot de:

PHP is only capable of serializing properly variables which match one of its native (scalar) types (See http://php.net/types). Which means that only variables of type booleans, integers, floating point numbers, string and NULL will be serialized properly.

I think there are two exceptions though:
- arrays are serialized by processing them recursively, so if its only composed of the above mentioned types, you should be fine.
- floating point numbers and integers may use the same representation while serialized in WDDX (I don't know much about WDDX, so I'm not 100% sure about this statement).

An interesting case would be whether objects can be serialized or not...
Jimmy Wimenta 15-Jul-2004 05:53
PHP's WDDX is useful only for exchanging data between PHP applications, but definetly not for exchanging data between different languages (which actually defeats the purpose of WDDX).

For example:

$hash1 = array ("2" => "Two", "4" => "Four", "5" => "Five");
$hash2 = array ("0" => "Zero", "1" => "One", "2" => "Two");

$hash1 will be serialized as hash, but
$hash2 will be serialized as array/list, because the key happen to be a sequence starting from 0.

Unless the library provide a way for users to specify the type, it can never be used for cross-platform data exchange.
Q1tum at hotmail dot com 21-Nov-2003 05:08
To insert arrays into a wddx variable here is a fine way to do it:

<?php

$sql = 'SELECT * FROM example';
$query = mysql_query($sql, $db) or die(mysql_error());

while($result = mysql_fetch_array($query)) {
    $id[] = $result[ 'id'];
    $name[] = $result['name'];
    $description[] = $result[$prefix . 'description'];
}

mysql_free_result($query);

wddx_add_vars($packet_id, "id");
wddx_add_vars($packet_id, "name");
wddx_add_vars($packet_id, "description");

$wddxSerializeValue = wddx_packet_end($packet_id);

?>
bradburn at kiwi dot de 30-Jul-2002 07:02
With ref to the above comment about typing, I have found that -- oddly enough -- PHP's WDDX supports the following WDDX types: null, boolean (true/false), number and string, *but* not date-time.

as an example, use the following values in an array that you then serialize:

$number = 5,
$null = NULL,
$bool = true,
$string = 'this is a string'.

they will all serialize correctly, e.g. the third entry comes out as:

<var name='bool'><boolean value='true'/></var>

i have tried with the 'official' format for WDDX 'datetime', e.g. '1998-9-15T09:05:32+4:0' (from the DTD @ http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt)  but have only succeeded in getting this encoded as a 'string' type.

if anyone else has any more information on this, it would be welcome. i would like to store the variables in 'appropriate' fields in a database, and the fact that only datetime is not supported is slightly irritating -- otherwise it would be a very useful function.
djm at web dot us dot uu dot net 18-Oct-1999 08:45
Since there aren't any examples of reversing the process, here's one. If you had the packet produced by the above example (without the htmlentities() call), you could retrieve the values like this:

<?php
$value = wddx_deserialize($packet);
print "pi is:<br>" . $value["pi"] . "<p>\n";
print "cities is:<br>\n";
while (list($key, $val) = each($value["cities"])) {
    print "$key => $val<br>\n";
}
?>

which outputs:

<pre>
pi is:
3.1415926

cities is:
0 => Austin
1 => Novato
2 => Seattle
</pre>


Add variables to a WDDX packet with the specified ID

  • ? WDDX 函数
  • wddx_deserialize ?
  • PHP Manual
  • WDDX 函数
  • Add variables to a WDDX packet with the specified ID

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Add variables to a WDDX packet with the specified ID

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

wddx_add_vars ( resource $packet_id , mixed $var_name , mixed ...$var_names ) : bool

Serializes the passed variables and add the result to the given packet.

参数

This function takes a variable number of parameters.

packet_id

A WDDX packet, returned by wddx_packet_start().

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

var_names

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

maciek at webenlinea dot com 05-Sep-2004 11:20
Here is a simple way of serializing dynamic values from an array:

<?PHP
//a unix timestamp
$date    = "1094095513";

//some data to be included
$books   = array('programming'   => array('php','perl','java'),
                'markup'        => array('UML','XML','HTML')
                );

//stick data to an array to iterate over
$data_to_serialize = array($date,$books);

//create the packet
$packet = wddx_packet_start("SOME DATA ARRAY");

//loop through the data
foreach($data_to_serialize as $key => $data)
{
  //create a var whith the name of the content of $key
  $$key = $data;
  wddx_add_vars($packet,$key);
}

echo wddx_packet_end($packet);

?>

Have fun !


Unserializes a WDDX packet

  • ? wddx_add_vars
  • wddx_packet_end ?
  • PHP Manual
  • WDDX 函数
  • Unserializes a WDDX packet

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Unserializes a WDDX packet

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

wddx_deserialize ( string $packet ) : mixed

Unserializes a WDDX packet.

Warning

Do not pass untrusted user input to wddx_deserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

参数

packet

A WDDX packet, as a string or stream.

返回值

Returns the deserialized value which can be a string, a number or an array. Note that structures are deserialized into associative arrays.

User Contributed Notes

valer underscore crisan at yahoo 01-Apr-2009 02:03
In PHP 5.2.9, we noticed that wddx serialize and deserialize seems to use UTF-8 encoding for XML input and the output data. There are some posts below that talk about fixing the input XML data so deserialize would work fine on special chars in ISO-8859-1 encoding, but none of the posts talks about the output encoding.

Consider this test:
$text = "Jür";
$packet = wddx_serialize_value($text);
$header = '<?xml version="1.0" encoding="iso-8859-1"?>';
$newText = wddx_deserialize($header . $packet);
echo "WDDX Packet: $packet\n";
echo "Deserialized Object: $newText\n";

The output is:

WDDX Packet: <wddxPacket version='1.0'><header/><data><string>Jür</string></data></wddxPacket>
Deserialized Object: J??r

The deserialized string is not in ISO-8859-1 encoding. It is in UTF-8 encoding. So we need to run utf8_decode() on the deserialized data to convert it back to ISO-8859-1 encoding which is what our application expects.

Hope this helps.
Magnus Deininger, dma05 at web dot de 12-Feb-2009 05:57
When writing your wddx file manually with an UTF-8 aware editor and saving it in utf-8, if your data gets its special characters mysteriously scrambled, try to add an xml header that marks the output as iso-8859-1, like this one:

<?xml version="1.1" encoding="iso-8859-1" ?>

This makes the wddx decode function treat the input as iso-8859-1, so it will not try to treat it as utf-8 and do an implicit decode to iso-8859-1. You will then have read all string data in the wddx packet in their original utf-8 encoding, so that 'echo' and other output functions will produce the intended result if you have set the output encoding to utf-8.

(Bugs reports on this behaviour seem to be treated as bogus, so it would seem in order to point out this incorrect and highly confusing side-effect.)
dormilich at netscape dot net 28-Nov-2008 05:13
When deserializing objects make sure you have the class definition loaded. wddx_deserialize() doesn't call the class itself, so you will receive a fatal error.
Nevertheless you can look for the class manually and delegate it to __autoload().

<?php
// $wddx_string needs to be valid XML to be loaded by SimpleXML.
// class_exists() will call the __autoload() function. if you don't
// want to use __autoloload(), use require_once()

function loadClassesFromWDDX($wddx_string)
{
    $xml = new SimpleXMLElement($wddx_string);

    foreach ($xml->xpath('//var') as $var)
    {
        if ($var['name'] == 'php_class_name')
        {
            if (!class_exists($var->string))
            {
                throw new Exception('Class '" . $var->string . "'not available.');
                // trigger_error('Class '" . $var->string . "'not available.', E_USER_ERROR);
            }
        }
    }
}
?>
dave at codexweb dot co dot za 21-Jan-2006 04:40
Here's a handy wddx_deserialize clone I wrote a while back. It uses PHP5 SimpleXML and recursion to do pretty much the same task as wddx_deserialize. Hope it comes in handy for someone.

<?php

if (!function_exists('wddx_deserialize'))
{
    /**
     * Clone implementation of wddx_deserialize
     */
    function wddx_deserialize($xmlpacket)
    {
        if ($xmlpacket instanceof SimpleXMLElement)
        {
            if (!empty($xmlpacket->struct))
            {
                $struct = array();
                foreach ($xmlpacket->xpath("struct/var") as $var)
                {
                    if (!empty($var["name"]))
                    {
                        $key = (string) $var["name"];
                        $struct[$key] = wddx_deserialize($var);
                    }
                }
                return $struct;
            }
            else if (!empty($xmlpacket->array))
            {
                $array = array();
                foreach ($xmlpacket->xpath("array/*") as $var)
                {
                    array_push($array, wddx_deserialize($var));
                }
                return $array;
            }
            else if (!empty($xmlpacket->string))
            {
                return (string) $xmlpacket->string;
            }
            else if (!empty($xmlpacket->number))
            {
                return (int) $xmlpacket->number;
            }
            else
            {
                if (is_numeric((string) $xmlpacket))
                {
                    return (int) $xmlpacket;
                }
                else
                {
                    return (string) $xmlpacket;
                }
            }
        }
        else
        {
            $sxe = simplexml_load_string($xmlpacket);
            $datanode = $sxe->xpath("/wddxPacket[@version='1.0']/data");
            return wddx_deserialize($datanode[0]);
        }
    }
}

?>
php dot net at werner-ott dot de 24-Nov-2005 12:20
On migrating wddx_deserialize() from PHP 4.x to PHP 5.1 (5.1.0RC6):

While

  $buffer = wddx_serialize_vars($some_array);
  $some_array = wddx_deserialize($buffer);

worked fine with PHP 4.x, the deserialization failed with PHP 5.1. In the above example $some_array will just be an empty string under 5.1

While wddx_serialize_vars() seems to behave identical in 4.x and 5.1, wddx_deserialize() does NOT.

Prepending XML encoding information to the buffer turned out to be at least a workaround. So, the following works with PHP 5.1:

  $buffer = wddx_serialize_vars($some_array);
  $buffer = '<?xml version="1.0"
          encoding="ISO-8859-1"?>'.
          $buffer;
  $some_array = wddx_deserialize($buffer);

NB: It may well be, that the behavioural difference between 4.x and 5.1 described above can only be observed if the array contains certain characters, i.e. german Umlaute (??????). So this workaround may not be necessary in each and every case.
mail_fidel at yahoo dot com 19-Nov-2004 12:11
To properly deserialize a wddx file it was to be utf8_encoded.

The following code will NOT work (PHP5.0.2 FreeBSD):

<?php
   $data = wddx_serialize_value(array("xyz???","abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>

Even thought the serialization is done right, the deserialization will not work unless you encode the text using utf8.

This code WILL work:

<?php
   $data = wddx_serialize_value(array(utf8_encode("xyz???"),"abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>
xavier at c-est-simple dot com 19-May-2004 04:09
JavaScript/PHP interroperability:

If you want to exchange wddx packets between a JavaScript application using the JS wddx library from openwddx (http://www.openwddx.org/downloads/), and a PHP script using wddx functions, be aware that the encoding of the classes of objects serialized in the wddx packet is not made the same way in both implementations.

The JS lib uses a 'type' attribute in the 'struct' tab and gives it the name of the class of the object serialized in the 'struct' element, while PHP uses a 'php_class_name' tag within the 'struct'.
NB : to get the type attribute with JS serialisation, you need to set the 'wddxSerializationType' member in your classes

Example with an object of class 'exemple' containing 2 members _attr1 and _attr2.
(NB : in french, 'example' is spelled 'exemple', okay ? :-)

JS serialization :
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct type="exemple">
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

php serialization:
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct>
   <var name='php_class_name'>
    <string>exemple</string>
   </var>
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

I like the JS approach better.
So if you need the compatibility, the workaround is quite simple:
- add a 'php_class_name' member in your JS objects, giving it the name of the class for value, and the JS generated packet will be correctly deserialized with PHP in classed objects.

- use a regexp on a PHP generated packet to add the 'type' attribute so that the JS deserialization instanciates objects of the right class:
      $pat = "/<struct><var name='php_class_name'><string>(\w+)<\/string>/" ;
      $rep = "<struct type='\$1'><var name='php_class_name'><string>\$1</string>" ;
      $serialised = preg_replace($pat, $rep, $serialised );
NB : this only works because the 'php_class_name' tag is just next to the 'struct' tag.
Who knows if this is going to be true in future releases... ?

This way, you can exchange JS and PHP objects (provided you define your JS and PHP classes the same way) smoothly...

It's worth saying that both implementations, as well as my interroperability workaround, handle correctly objects with members that are also objects.

NB : NB means Nota Bene.
xavier at c-est-simple.com 18-May-2004 10:19
Beware, although the deserialized objects are instanciated class objects (if the php_class_name tag is amongst the children of the struct tag and its text content is the name of a loaded class), the constructor of the class has not been called at all.
You can use the members and call the methods of the object all right, but any initialisation action that the constructor might be in charge of is missing.
php at mike2k dot com 10-Sep-2001 06:06
if you have WDDX data coming from a third party source and it isnt being parsed correctly in your php, try translating their WDDX. we have a third party sending us WDDX from cold fusion, and it uses a <recordset> element, which PHP seems to ignore (looking around the web we found some other people having trouble) so the (hopefully temporary) solution we found was to translate the WDDX midstream and then we were able to parse it:

$url = "http://somedomain.com/blah.wddx";
$fp = fopen($url,"r");
$page = fread($fp,10000);
fclose($fp);
$page = str_replace("<recordset","<struct",$page);
$page = str_replace("</recordset","</struct",$page);
$page = str_replace("<field","<var",$page);
$page = str_replace("</field","</var",$page);
$values = wddx_deserialize($page);
while(list($key,$val) = each($values)) {
        print "$key => $val<BR>";
}

this works for us. it's a hack, and hopefully php will support this in the future or something.
medvitz at medvitz dot net 14-Oct-2000 05:29
You can also serialize instantiated class objects with the wddx functions.
ie.

<?php
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "objvar");
$packet = wddx_packet_end($packet_id);

$a =  wddx_deserialize($packet);
$obj = $a[objvar];
?>

now $obj is a useable object, that looks like the original.

Note that with this method, you need to know what the variable name of the original object was.  You can use one of the array functions to get the object in the event that the original object's variable name was unknown.

*** only verified on linux with 4.0.2
djm at web dot us dot uu dot net 18-Oct-1999 09:58
The packet string you pass to this function doesn't have to be sanitized first; it searches for a WDDX packet within the string.  So the string can contain HTML markup and random text outside of the packet, and that is all ignored.
This means you can get a packet from another web page like this:
<?php
$fhandle = fopen("http://myserver.com/packet.php", "r");
if ($fhandle) {
        $page = fread($fhandle,10000);
        fclose($fhandle);
        $value = wddx_deserialize($page);
        print "pi is:<br>" . $value["pi"] . "<p>\n";
} else {
        print "could not get packet.php<p>";
}
?>


Ends a WDDX packet with the specified ID

  • ? wddx_deserialize
  • wddx_packet_start ?
  • PHP Manual
  • WDDX 函数
  • Ends a WDDX packet with the specified ID

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Ends a WDDX packet with the specified ID

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

wddx_packet_end ( resource $packet_id ) : string

Ends and returns the given WDDX packet.

参数

packet_id

A WDDX packet, returned by wddx_packet_start().

返回值

Returns the string containing the WDDX packet.

User Contributed Notes

There are no user contributed notes for this page.


Starts a new WDDX packet with structure inside it

  • ? wddx_packet_end
  • wddx_serialize_value ?
  • PHP Manual
  • WDDX 函数
  • Starts a new WDDX packet with structure inside it

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Starts a new WDDX packet with structure inside it

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

wddx_packet_start ( string $comment = ? ) : resource

Start a new WDDX packet for incremental addition of variables. It automatically creates a structure definition inside the packet to contain the variables.

参数

comment

An optional comment string.

返回值

Returns a packet ID for use in later functions, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Serialize a single value into a WDDX packet

  • ? wddx_packet_start
  • wddx_serialize_vars ?
  • PHP Manual
  • WDDX 函数
  • Serialize a single value into a WDDX packet

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serialize a single value into a WDDX packet

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

wddx_serialize_value ( mixed $var , string $comment = ? ) : string

Creates a WDDX packet from a single given value.

参数

var

The value to be serialized

comment

An optional comment string that appears in the packet header.

返回值

Returns the WDDX packet, or false on error.

User Contributed Notes

chris at digitalbase dot com 04-Jan-2002 04:36
When serializing JavaScript objects to interact with PHP objects, you should make the JavaScript object's first entry a php_class_name.

PHP:
class myclass {
    var $name;
    var $age;
    var $ssn;
    ...

    function myclass() {
        $this->name = "";
        $this->age = "";
        $this->ssn = "";
        ...
    }
}

JavaScript:
// serialization example code is from the
// WDDX SDK http://www.openwddx.org
function SerializeMsg(name, age, ssn, ...) {
    var MyObj = new Object;

    // the following line is necessary in order
    // to deserialize back to a PHP object
    MyObj.php_class_name = "myclass";

    MyObj.name = name;
    MyObj.age = age;
    MyObj.ssn = ssn;
    ...

    // Create a new serializer "object" to do our work for us
    MySer = new WddxSerializer;

    // Serialize the Message variable into a WDDX Packet
    MyWDDXPacket = MySer.serialize(MyObj);

    // Output WDDX Packet so we can see what it looks like
    return MyWDDXPacket;
}

Now you can use this in a page which is its own form action:
<?php
// don't forget to include the class definition from above!
if (!isSet($wddx_packet))
    $MyObj = new myclass();
else
    $MyObj = wddx_deserialize($wddx_packet);
?>

<html>
<head>
<script language="JavaScript">
<!--
function Init() {
    // sets the form's text-elements
    tmp = document.MyForm;

    tmp.name.value = "<? echo $MyObj->name ?>";
    tmp.age.value = "<? echo $MyObj->age ?>";
    tmp.ssn.value = "<? echo $MyObj->ssn ?>";
    ...
}

function SerializeMsg(name, age, ssn, ...) {
// see above!
}

function SubmitForm() {
    // sumbits the form
    tmp = document.MyForm;

    tmp.wddx_packet.value =
    SerializeMsg(tmp.name.value, tmp.age.value, tmp.ssn.value,...);
    document.submit();
}
// -->
</script>
</head>
<body>
...
<form name="MyForm"
action="<? echo $PHP_SELF ?>" method="post">
<input name="wddx_packet" type="hidden">
<input name="name" type="text">
<input name="age" type="text">
<input name="ssn" type="text">
...
<input name="SubmitBtn" type="button" onclick="SumbitForm()">
</form>
</body>
</html>

---------------------------------
If you don't provide that first 'php_class_name' in the JavaScript function, then when PHP deserializes it will deserialize into an associative array and not an object instance.

Note that this provides a way to maintain state without
using sessions or cookies - just good old HTML!

Hope this helps!
--
Chris Hansen


Serialize variables into a WDDX packet

  • ? wddx_serialize_value
  • XMLDiff ?
  • PHP Manual
  • WDDX 函数
  • Serialize variables into a WDDX packet

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serialize variables into a WDDX packet

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

wddx_serialize_vars ( mixed $var_name , mixed ...$var_names ) : string

Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.

参数

This function takes a variable number of parameters.

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

var_names

返回值

Returns the WDDX packet, or false on error.

范例

Example #1 wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

以上例程会输出：

<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

User Contributed Notes

kangus at jaga dot us 13-Oct-2003 03:57
A function to use for dates with PHP & WDDX
getdate()

$ta="<FORM><TEXTAREA rows=15 cols=80>" ;
$te="</TEXTAREA></FORM>";
$packet_id=wddx_packet_start("Date Example--");
$myDate=getdate();
wddx_add_vars($packet_id,'myDate');
$package=wddx_packet_end($packet_id);
print($ta.$package.$te);

Produces:

<wddxPacket version='1.0'><header><comment>Date Example--</comment></header>
<data><struct><var name='myDate'>
<struct><var name='seconds'><number>12</number></var>
<var name='minutes'><number>55</number></var>
<var name='hours'><number>1</number></var>
<var name='mday'><number>13</number></var>
<var name='wday'><number>1</number></var>
<var name='mon'><number>10</number></var>
<var name='year'><number>2003</number></var>
<var name='yday'><number>285</number></var>
<var name='weekday'><string>Monday</string></var>
<var name='month'><string>October</string></var>
<var name='0'><number>1066031712</number>
</var></struct></var></struct></data></wddxPacket>
tychay at alumni dot caltech dot edu 31-Mar-2002 12:15
The above feature will cause a slight trouble since the name of the variable will always be "wddxtemp" but you can use preg_replace to fix that.

Also, a better approach is to serialize the entire class. WDDX will that write a reserved "php_class_name" variable which can be used to reconstruct the class during a deserialize.
tychay at alumni dot caltech dot edu 30-Mar-2002 10:49
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
tychay at alumni dot caltech dot edu 30-Mar-2002 10:45
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
christian dot knoflach at gmx dot at 21-May-2001 03:56
Be careful using WDDX - functions on object variables. As I just had to find out the following won't work:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx = wddx_serialize_vars("this->str");
    print(htmlentities($this->wddx));
  }
}

new Test();
?>

That's what you'll get:
<wddxPacket version='1.0'><header/><data><struct></struct></data></wddxPacket>


XML diff and merge

  • 简介
  • 安装／配置
    • 需求
    • 安装
  • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\Base::__construct — Constructor
    • XMLDiff\Base::diff — Produce diff of two XML documents
    • XMLDiff\Base::merge — Produce new XML document based on diff
  • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\DOM::diff — Diff two DOMDocument objects
    • XMLDiff\DOM::merge — Produce merged DOMDocument
  • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\Memory::diff — Diff two XML documents
    • XMLDiff\Memory::merge — Produce merged XML document
  • XMLDiff\File — The XMLDiff\File class
    • XMLDiff\File::diff — Diff two XML files
    • XMLDiff\File::merge — Produce merged XML document

User Contributed Notes

There are no user contributed notes for this page.


简介

The extension is able to produce diffs of two XML documents and then to apply the difference to the source document. The diff is a XML document containing copy/insert/delete instruction nodes in human readable format. DOMDocument objects, local files and strings in memory can be processed.

User Contributed Notes

There are no user contributed notes for this page.


需求

libdiffmark - version 0.10 is bundled with the extension. If diffmark is available from your system packages, its usage is strongly encouraged.

libxml extension

DOM extension

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/xmldiff.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/xmldiff/.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\Base class

(PECL xmldiff >= 0.8.0)

简介

Base abstract class for all the comparsion classes in the extension.

类摘要

XMLDiff\Base {
/* 方法 */
public __construct ( string $nsname )
abstract public diff ( mixed $from , mixed $to ) : mixed
abstract public merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\Base::__construct — Constructor
  • XMLDiff\Base::diff — Produce diff of two XML documents
  • XMLDiff\Base::merge — Produce new XML document based on diff

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? XMLDiff\Base
  • XMLDiff\Base::diff ?
  • PHP Manual
  • XMLDiff\Base
  • Constructor

XMLDiff\Base::__construct

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::__construct — Constructor

说明

public XMLDiff\Base::__construct ( string $nsname )

Base constructor for all the worker classes in the xmldiff extension.

参数

nsname

Custom namespace name for the diff document. The default namespace is http://www.locus.cz/diffmark and that's enough to avoid namespace conflicts. Use this parameter if you want to change it for some reason.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Produce diff of two XML documents

  • ? XMLDiff\Base::__construct
  • XMLDiff\Base::merge ?
  • PHP Manual
  • XMLDiff\Base
  • Produce diff of two XML documents

XMLDiff\Base::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::diff — Produce diff of two XML documents

说明

abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed

Abstract diff method to be implemented by inheriting classes.

The basic purpose of this method is to produce diff of the two documents. The param order matters and will produce different output.

参数

from

Source XML document.

to

Target XML document.

返回值

Implementation dependent.

User Contributed Notes

There are no user contributed notes for this page.


Produce new XML document based on diff

  • ? XMLDiff\Base::diff
  • XMLDiff\DOM ?
  • PHP Manual
  • XMLDiff\Base
  • Produce new XML document based on diff

XMLDiff\Base::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::merge — Produce new XML document based on diff

说明

abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed

Abstract merge method to be implemented by inheriting classes.

Basically the method purpose is to produce a new XML document based on the diff information.

参数

src

Source XML document.

diff

Document produced by the diff method.

返回值

Implementation dependent.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\DOM class

(PECL xmldiff >= 0.8.0)

简介

类摘要

XMLDiff\DOM extends XMLDiff\Base {
/* 方法 */
public diff ( DOMDocument $from , DOMDocument $to ) : DOMDocument
public merge ( DOMDocument $src , DOMDocument $diff ) : DOMDocument
/* 继承的方法 */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\DOM::diff — Diff two DOMDocument objects
  • XMLDiff\DOM::merge — Produce merged DOMDocument

User Contributed Notes

There are no user contributed notes for this page.


Diff two DOMDocument objects

  • ? XMLDiff\DOM
  • XMLDiff\DOM::merge ?
  • PHP Manual
  • XMLDiff\DOM
  • Diff two DOMDocument objects

XMLDiff\DOM::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::diff — Diff two DOMDocument objects

说明

public XMLDiff\DOM::diff ( DOMDocument $from , DOMDocument $to ) : DOMDocument

Diff two DOMDocument instances and produce the new one containing the diff information.

参数

from

Source DOMDocument object.

to

Target DOMDocument object.

返回值

DOMDocument with the diff information or NULL.

User Contributed Notes

jeewiya at gmail dot com 28-Mar-2018 10:43
XMLDiff\DOM can be use like this, for compare xml files changes.

<?php

function getChangeElements($currentContent, $oldContent) {
        try {
            $currentDoc = new DOMDocument();
            $currentDoc->loadXML($currentContent);

            $oldDoc = new DOMDocument();
            $oldDoc->loadXML($oldContent);
            $xmldiff = new XMLDiff\DOM();
            return $xmldiff->diff($oldDoc, $currentDoc);
        } catch (Exception $ex) {
            throw $ex;
        }
    }

getChangeElements('updated.xml', 'old.xml');

?>


Produce merged DOMDocument

  • ? XMLDiff\DOM::diff
  • XMLDiff\Memory ?
  • PHP Manual
  • XMLDiff\DOM
  • Produce merged DOMDocument

XMLDiff\DOM::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::merge — Produce merged DOMDocument

说明

public XMLDiff\DOM::merge ( DOMDocument $src , DOMDocument $diff ) : DOMDocument

Create new DOMDocument based on the diff.

参数

src

Source DOMDocument object.

diff

DOMDocument object containing the diff information.

返回值

Merged DOMDocument or NULL.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\Memory class

(PECL xmldiff >= 0.8.0)

简介

类摘要

XMLDiff\Memory extends XMLDiff\Base {
/* 方法 */
public diff ( string $from , string $to ) : string
public merge ( string $src , string $diff ) : string
/* 继承的方法 */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\Memory::diff — Diff two XML documents
  • XMLDiff\Memory::merge — Produce merged XML document

User Contributed Notes

There are no user contributed notes for this page.


Diff two XML documents

  • ? XMLDiff\Memory
  • XMLDiff\Memory::merge ?
  • PHP Manual
  • XMLDiff\Memory
  • Diff two XML documents

XMLDiff\Memory::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::diff — Diff two XML documents

说明

public XMLDiff\Memory::diff ( string $from , string $to ) : string

Diff two strings containing XML documents and produce the diff information.

参数

from

Source XML document.

to

Target XML document.

返回值

String with the XML document containing the diff information or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Produce merged XML document

  • ? XMLDiff\Memory::diff
  • XMLDiff\File ?
  • PHP Manual
  • XMLDiff\Memory
  • Produce merged XML document

XMLDiff\Memory::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::merge — Produce merged XML document

说明

public XMLDiff\Memory::merge ( string $src , string $diff ) : string

Create new XML document based on diffs and source document.

参数

src

Source XML document.

diff

XML document containing diff information.

返回值

String with the new XML document or NULL.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\File class

(PECL xmldiff >= 0.8.0)

简介

类摘要

XMLDiff\File extends XMLDiff\Base {
/* 方法 */
public diff ( string $from , string $to ) : string
public merge ( string $src , string $diff ) : string
/* 继承的方法 */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\File::diff — Diff two XML files
  • XMLDiff\File::merge — Produce merged XML document

User Contributed Notes

ngbabu at gmail dot com 21-Nov-2015 08:45
The following snippet will show the use case of XMLDiff\File.

<?php
$dxml=new XMLDiff\File;
$diff = $dxml->diff("file1.xml", "file2.xml");
$difffile = 'difference.xml';
file_put_contents($difffile, $diff);
?>


Diff two XML files

  • ? XMLDiff\File
  • XMLDiff\File::merge ?
  • PHP Manual
  • XMLDiff\File
  • Diff two XML files

XMLDiff\File::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\File::diff — Diff two XML files

说明

public XMLDiff\File::diff ( string $from , string $to ) : string

Diff two local XML files and produce string with the diff information.

参数

from

Path to the source document.

to

Path to the target document.

返回值

String with the XML document containing the diff information or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Produce merged XML document

  • ? XMLDiff\File::diff
  • XML 解析器 ?
  • PHP Manual
  • XMLDiff\File
  • Produce merged XML document

XMLDiff\File::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\File::merge — Produce merged XML document

说明

public XMLDiff\File::merge ( string $src , string $diff ) : string

Create new XML document based on diffs and source document.

参数

src

Path to the source XML document.

diff

Path to the XML document with the diff information.

返回值

String with the new XML document or NULL.

User Contributed Notes

There are no user contributed notes for this page.


XML 解析器

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 事件处理器
  • Case Folding(大写转换)
  • 错误代码
  • 字符编码
  • 范例
    • XML 元素结构例程
    • XML 标签映射例程
    • XML 外部实体例程
  • XML 解析器函数
    • utf8_decode — 将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。
    • utf8_encode — 将 ISO-8859-1 编码的字符串转换为 UTF-8 编码
    • xml_error_string — 获取 XML 解析器的错误字符串
    • xml_get_current_byte_index — 获取 XML 解析器的当前字节索引
    • xml_get_current_column_number — 获取 XML 解析器的当前列号
    • xml_get_current_line_number — 获取 XML 解析器的当前行号
    • xml_get_error_code — 获取 XML 解析器错误代码
    • xml_parse_into_struct — 将 XML 数据解析到数组中
    • xml_parse — 开始解析一个 XML 文档
    • xml_parser_create_ns — 生成一个支持命名空间的 XML 解析器
    • xml_parser_create — 建立一个 XML 解析器
    • xml_parser_free — 释放指定的 XML 解析器
    • xml_parser_get_option — 从 XML 解析器获取选项设置信息
    • xml_parser_set_option — 为指定 XML 解析进行选项设置
    • xml_set_character_data_handler — 建立字符数据处理器
    • xml_set_default_handler — 建立默认处理器
    • xml_set_element_handler — 建立起始和终止元素处理器
    • xml_set_end_namespace_decl_handler — 建立终止命名空间声明处理器
    • xml_set_external_entity_ref_handler — 建立外部实体指向处理器
    • xml_set_notation_decl_handler — 建立注释声明处理器
    • xml_set_object — 在对象中使用 XML 解析器
    • xml_set_processing_instruction_handler — 建立处理指令（PI）处理器
    • xml_set_start_namespace_decl_handler — 建立起始命名空间声明处理器
    • xml_set_unparsed_entity_decl_handler — 建立未解析实体定义声明处理器

User Contributed Notes

marcgear at gmail dot com 04-Aug-2010 10:12
While this SAX event based parser is better for memory management than the tree based parsers of SimpleXML and DOM, the pull-based parser XMLReader is much easier to use than the xml_parser_* functions, and still doesn't require loading the file into memory.


简介

XML(可扩展标记语言，eXtensible Markup Language) 是一种在互联网上用于结构化文档交互的数据格式。 它是互联网协会(W3C)定义的一个标准。与 XML 及其相关技术的信息可访问 » http://www.w3.org/XML/。

此 PHP 扩展实现 支持 James Clark 使用 PHP 编写的 expat。 此工具包可解析(但不能验证) XML 文档。它支持 PHP 所提供的 3 种字符编码： US-ASCII, ISO-8859-1 和 UTF-8。 不支持 UTF-16。

此扩展可 创建 XML 解析器 并为不同的 XML 事件定义 处理程序(handler)。 每个 XML 解析器还存在少数可以调节的 参数。

User Contributed Notes

There are no user contributed notes for this page.


需求

此扩展需要 libxml PHP 扩展。这表示需要使用 --with-libxml，或在 PHP 7.4 之前的版本中使用 --enable-libxml， 尽管这将隐式完成因为 libxml 是缺省开启的。

缺省情况下，此扩展使用expat compat layer 。也可使用expat， 此库位于 » http://www.jclark.com/xml/expat.html。 使用expat库中的 Makefile 是不会默认构建出库文件的，可使用以下构建规则进行构建：

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
expat 的源代码 RPM 安装包可在 » http://sourceforge.net/projects/expat/ 找到。

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-xml

这些函数默认为有效的，使用了捆绑的 expat 库。您可以通过参数 --disable-xml 来屏蔽 XML 的支持。如果您将 PHP 编译为 Apache 1.3.9 或更高版本的一个模块， PHP 将自动使用 Apache 捆绑的 expat 库。如果您不希望使用该捆绑的 expat 库，请在运行 PHP 的 configure 配置脚本时使用参数 --with-expat-dir=DIR，其中 DIR 应该指向 expat 安装的根目录。

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

User Contributed Notes

Alex Ivaylov 15-Feb-2018 09:03
Ubuntu users, please note that this extension might not enabled for you by default. You may need to install by doing "sudo apt-get install php-xml" followed by web server restart.


资源类型

xml_parser_create() 与 xml_parser_create_ns() 返回的 XML 资源会引用 XML 解析器实例，以被此扩展提供的函数使用。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

XML_ERROR_NONE (integer)
XML_ERROR_NO_MEMORY (integer)
XML_ERROR_SYNTAX (integer)
XML_ERROR_NO_ELEMENTS (integer)
XML_ERROR_INVALID_TOKEN (integer)
XML_ERROR_UNCLOSED_TOKEN (integer)
XML_ERROR_PARTIAL_CHAR (integer)
XML_ERROR_TAG_MISMATCH (integer)
XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)
XML_ERROR_PARAM_ENTITY_REF (integer)
XML_ERROR_UNDEFINED_ENTITY (integer)
XML_ERROR_RECURSIVE_ENTITY_REF (integer)
XML_ERROR_ASYNC_ENTITY (integer)
XML_ERROR_BAD_CHAR_REF (integer)
XML_ERROR_BINARY_ENTITY_REF (integer)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)
XML_ERROR_MISPLACED_XML_PI (integer)
XML_ERROR_UNKNOWN_ENCODING (integer)
XML_ERROR_INCORRECT_ENCODING (integer)
XML_ERROR_UNCLOSED_CDATA_SECTION (integer)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)
XML_OPTION_CASE_FOLDING (integer)
XML_OPTION_TARGET_ENCODING (integer)
XML_OPTION_SKIP_TAGSTART (integer)
XML_OPTION_SKIP_WHITE (integer)
XML_SAX_IMPL (string)
指定 SAX 实现方法。可为 libxml 或 expat.

User Contributed Notes

There are no user contributed notes for this page.


事件处理器

XML 事件处理器的定义如下：

被支持的 XML 处理器
PHP 处理器函数 | 事件描述
xml_set_element_handler() | 当 XML 解析器遇到开始或结束标签时，会触发元素事件。 开始标签和结束标签有不同的处理器。
xml_set_character_data_handler() | 字符数据范指 XML 文档中所有非标记的内容，包括标签之间的空格。 注意，XML 解析器不会添加或删除任何空格，由应用程序(你)来判断空格是否有意义。
xml_set_processing_instruction_handler() | PHP 程序员必须熟练掌握处理指令(PI)。<?php ?>是处理指令， 其中php被称为"处理指令对象"。 除所有以"XML"开头的处理指令对象是系统保留的外， 其他的处理函数均是由应用程序指定的。
xml_set_default_handler() | 不执行其他处理函数，则会执行缺省的处理函数。 在缺省的处理函数中可取得如 XML 和文档类型声明等信息。
xml_set_unparsed_entity_decl_handler() | 未解析的实体声明(NDATA)会调用此处理函数。
xml_set_notation_decl_handler() | 符号声明会调用此处理函数
xml_set_external_entity_ref_handler() | 当 XML 解析器发现对外部已解析的普通实体的引用时， 会调用此处理函数。例如，引用一个文件或URL。实例可参见 XML 外部实体例程。

User Contributed Notes

There are no user contributed notes for this page.


Case Folding(大写转换)

元素处理函数可取得元素名称转换为 case-folded(大写字母)形式。 Case-folding 被定义为"将非大写字母替换为相对应的大写字母的字符串操作"。换句话说，在 XML 中，case-folding 就是转换为大写。

默认情况下，所有的通过处理函数的元素名都被转换为大写字母。每个 XML 解析器可分别通过xml_parser_get_option()与 xml_parser_set_option()函数来查询与控制此项功能。

User Contributed Notes

There are no user contributed notes for this page.


错误代码

下列常量是 XML 相关的错误代码(xml_parse()函数的返回值):

  • XML_ERROR_NONE
  • XML_ERROR_NO_MEMORY
  • XML_ERROR_SYNTAX
  • XML_ERROR_NO_ELEMENTS
  • XML_ERROR_INVALID_TOKEN
  • XML_ERROR_UNCLOSED_TOKEN
  • XML_ERROR_PARTIAL_CHAR
  • XML_ERROR_TAG_MISMATCH
  • XML_ERROR_DUPLICATE_ATTRIBUTE
  • XML_ERROR_JUNK_AFTER_DOC_ELEMENT
  • XML_ERROR_PARAM_ENTITY_REF
  • XML_ERROR_UNDEFINED_ENTITY
  • XML_ERROR_RECURSIVE_ENTITY_REF
  • XML_ERROR_ASYNC_ENTITY
  • XML_ERROR_BAD_CHAR_REF
  • XML_ERROR_BINARY_ENTITY_REF
  • XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
  • XML_ERROR_MISPLACED_XML_PI
  • XML_ERROR_UNKNOWN_ENCODING
  • XML_ERROR_INCORRECT_ENCODING
  • XML_ERROR_UNCLOSED_CDATA_SECTION
  • XML_ERROR_EXTERNAL_ENTITY_HANDLING

User Contributed Notes

Teet 24-May-2019 02:04
If you wonder, what values those constant have, here you go:

<?php
XML_ERROR_NONE = 0
XML_ERROR_NO_MEMORY = 1
XML_ERROR_SYNTAX = 2
XML_ERROR_NO_ELEMENTS = 3
XML_ERROR_INVALID_TOKEN = 4
XML_ERROR_UNCLOSED_TOKEN = 5
XML_ERROR_PARTIAL_CHAR = 6
XML_ERROR_TAG_MISMATCH = 7
XML_ERROR_DUPLICATE_ATTRIBUTE = 8
XML_ERROR_JUNK_AFTER_DOC_ELEMENT = 9
XML_ERROR_PARAM_ENTITY_REF = 10
XML_ERROR_UNDEFINED_ENTITY = 11
XML_ERROR_RECURSIVE_ENTITY_REF = 12
XML_ERROR_ASYNC_ENTITY = 13
XML_ERROR_BAD_CHAR_REF = 14
XML_ERROR_BINARY_ENTITY_REF = 15
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF = 16
XML_ERROR_MISPLACED_XML_PI = 17
XML_ERROR_UNKNOWN_ENCODING = 18
XML_ERROR_INCORRECT_ENCODING = 19
XML_ERROR_UNCLOSED_CDATA_SECTION = 20
XML_ERROR_EXTERNAL_ENTITY_HANDLING = 21
?>


字符编码

PHP 的 XML 扩展通过几种不同的字符编码支持» Unicode 字符集。 有两类字符编码， 原始编码 和 目标编码. 在PHP的内部展现中，文档始终是使用UTF-8编码。

当 XML 被 解析 后，原始编码就完成了。 在创建 XML 解析器时, 可以指定原始编码(在XML 解析器此后的生命周期里，不能修改此编码)。 被支持的原始编码有 ISO-8859-1, US-ASCII 和 UTF-8. 前两种是单字节编码, 即每一个字符表现为一个字节。 UTF-8 可将字符编码为一串不定数量(最高21)的位(bit), 排列成1到4个字节。 PHP 中使用的默认原始编码是ISO-8859-1.

当 PHP 将数据传给 XML 处理函数时，目标编码就完成了。 在创建 XML 处理器时，目标编码被设定为与原始编码相同，但可任意修改。 目标编码会影响字符数据及标签名，与处理指令目标。

如 XML 解析器遇到原始编码所能表示的范围之外的字符时，会返回一个错误。

如 PHP 遇到在被解析的 XML 文档中不能用所指定的目标编码表示的字符时， 这个问题字符会被"降级"。通常来说，就是那些字符会被替换成问号(?)。

User Contributed Notes

There are no user contributed notes for this page.


范例

Table of Contents

  • XML 元素结构例程
  • XML 标签映射例程
  • XML 外部实体例程

User Contributed Notes

There are no user contributed notes for this page.


XML 元素结构例程

第一个例程缩进显示文档中的开始元素结构。

Example #1 显示 XML 元素结构

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs)
{
    global $depth;
    for ($i = 0; $i < $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name)
{
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>

User Contributed Notes

Sample at hotmail dot com 04-Jul-2013 10:32
<?php

public static function xml2array($element, $arr = array())
    {
        if(is_string($element))
        {
            $element = (strlen($element) > 5 && substr($element, -4) === '.xml')
                            ? simplexml_load_file(DATAPATH.$element)
                            : simplexml_load_string($element);
        }
         $iter = 0;
        foreach($element->children() as $b)
        {
            $a = $b->getName();
            if(!$b->children()){
                    $arr[$a] = trim($b[0]);
            }
            else{
                    $arr[$a][$iter] = array();
                    $arr[$a][$iter] = self::xml2array($b,$arr[$a][$iter]);
            }
                $iter++;
        }
        return $arr;
    }
}

?>
roan at horning dot us 30-Oct-2009 09:07
The following example will echo back an xml file using the basic event based parser.  Currently, (at least in the version of PHP5 I'm using) it will skip The XML declaration and the Doctype declaration--they don't seem to be captured by the default handler.

<?php
echo "<pre>";

$file = "test.xml";
echo $file."\n";
global $inTag;

$inTag = "";
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_set_processing_instruction_handler($xml_parser, "pi_handler");
xml_set_default_handler($xml_parser, "parseDEFAULT");
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents");

if (!($fp = fopen($file, "r"))) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);

function startElement($parser, $name, $attrs) {

    global $inTag;
    global $depth;

    $padTag = str_repeat(str_pad(" ", 3), $depth);

    if (!($inTag == "")) {
        echo "&gt;";
    }
    echo "\n$padTag&lt;$name";
    foreach ($attrs as $key => $value) {
        echo "\n$padTag".str_pad(" ", 3);
        echo " $key=\"$value\"";
    }
    $inTag = $name;
    $depth++;
}

function endElement($parser, $name) {

    global $depth;
   global $inTag;
    global $closeTag;

    $depth--;

   if ($closeTag == TRUE) {
       echo "&lt/$name&gt;";
       $inTag = "";
   } elseif ($inTag == $name) {
       echo " /&gt;";
       $inTag = "";
   } else {
         $padTag = str_repeat(str_pad(" ", 3), $depth);
       echo "\n$padTag&lt/$name&gt;";
    }
}

function contents($parser, $data) {

    global $closeTag;

    $data = preg_replace("/^\s+/", "", $data);
    $data = preg_replace("/\s+$/", "", $data);

    if (!($data == ""))  {
        echo "&gt;$data";
        $closeTag = TRUE;
    } else {
        $closeTag = FALSE;
     }
}

function parseDEFAULT($parser, $data) {

    $data = preg_replace("/</", "&lt;", $data);
    $data = preg_replace("/>/", "&gt;", $data);
    echo $data;
}

function pi_handler($parser, $target, $data) {

    echo "&lt;?$target $data?&gt;\n";
}
echo "</pre>";
?>


XML 标签映射例程

Example #1 将 XML 映射为 HTML

此例程直接地将 XML 标签映射为 HTML 标签。 在"map_array"中未找到的元素将被忽略。 当然，此例程只针对特定的 XML 文档类型起作用。

<?php
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";
    }
}

function endElement($parser, $name)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";
    }
}

function characterData($parser, $data)
{
    echo $data;
}

$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>

User Contributed Notes

There are no user contributed notes for this page.


XML 外部实体例程

此例程用于加亮 XML 代码。举例说明如何使用外部实体引用来包含和解析其他文档， 及处理指令是如何被处理的，及判断处理指令所包含代码是否"可信任"的一种方法

用于此例程的 XML 文档位于此例程的下方(xmltest.xml 和 xmltest2.xml)。

Example #1 外部实体例程

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
    // 仅信任本地文件
    if (!preg_match("@^([a-z]+)\:\/\/@i", $file)
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs)
{
    echo "&lt;<font color=\"#0000cc\">$name</font>";
    if (count($attribs)) {
        foreach ($attribs as $k => $v) {
            echo " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    echo "&gt;";
}

function endElement($parser, $name)
{
    echo "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data)
{
    echo "<b>$data</b>";
}

function PIHandler($parser, $target, $data)
{
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // 如何要解析的文档是"可信任"的, 则说明可安全
            // 地执行其内部的 PHP 代码。否则，显示代码内容。
            if (trustedFile($parser_file[$parser])) {
                eval($data);
            } else {
                printf("Untrusted PHP code: <i>%s</i>",
                        htmlspecialchars($data));
            }
            break;
    }
}

function defaultHandler($parser, $data)
{
    if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
        printf('<font color="#aa00aa">%s</font>',
                htmlspecialchars($data));
    } else {
        printf('<font size="-1">%s</font>',
                htmlspecialchars($data));
    }
}

function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
                                  $publicId) {
    if ($systemId) {
        if (!list($parser, $fp) = new_xml_parser($systemId)) {
            printf("Could not open entity %s at %s\n", $openEntityNames,
                   $systemId);
            return false;
        }
        while ($data = fread($fp, 4096)) {
            if (!xml_parse($parser, $data, feof($fp))) {
                printf("XML error: %s at line %d while parsing entity %s\n",
                       xml_error_string(xml_get_error_code($parser)),
                       xml_get_current_line_number($parser), $openEntityNames);
                xml_parser_free($parser);
                return false;
            }
        }
        xml_parser_free($parser);
        return true;
    }
    return false;
}

function new_xml_parser($file)
{
    global $parser_file;

    $xml_parser = xml_parser_create();
    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
    xml_set_element_handler($xml_parser, "startElement", "endElement");
    xml_set_character_data_handler($xml_parser, "characterData");
    xml_set_processing_instruction_handler($xml_parser, "PIHandler");
    xml_set_default_handler($xml_parser, "defaultHandler");
    xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");

    if (!($fp = @fopen($file, "r"))) {
        return false;
    }
    if (!is_array($parser_file)) {
        settype($parser_file, "array");
    }
    $parser_file[$xml_parser] = $file;
    return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
    die("could not open XML input");
}

echo "<pre>";
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d\n",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
echo "</pre>";
echo "parse complete\n";
xml_parser_free($xml_parser);

?>

Example #2 xmltest.xml

<?xml version='1.0'?>
<!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
<!ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
 <TITLE>Title &plainEntity;</TITLE>
 <para>
  <informaltable>
   <tgroup cols="3">
    <tbody>
     <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
     <row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
 &systemEntity;
 <section id="about">
  <title>About this Document</title>
  <para>
   <!-- this is a comment -->
   <?php echo 'Hi!  This is PHP version ' . phpversion(); ?>
  </para>
 </section>
</chapter>

此文件包含在 xmltest.xml 中:

Example #3 xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "This is some more PHP code being executed."; ?>
</foo>

User Contributed Notes

There are no user contributed notes for this page.


XML 解析器函数

Table of Contents

  • utf8_decode — 将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。
  • utf8_encode — 将 ISO-8859-1 编码的字符串转换为 UTF-8 编码
  • xml_error_string — 获取 XML 解析器的错误字符串
  • xml_get_current_byte_index — 获取 XML 解析器的当前字节索引
  • xml_get_current_column_number — 获取 XML 解析器的当前列号
  • xml_get_current_line_number — 获取 XML 解析器的当前行号
  • xml_get_error_code — 获取 XML 解析器错误代码
  • xml_parse_into_struct — 将 XML 数据解析到数组中
  • xml_parse — 开始解析一个 XML 文档
  • xml_parser_create_ns — 生成一个支持命名空间的 XML 解析器
  • xml_parser_create — 建立一个 XML 解析器
  • xml_parser_free — 释放指定的 XML 解析器
  • xml_parser_get_option — 从 XML 解析器获取选项设置信息
  • xml_parser_set_option — 为指定 XML 解析进行选项设置
  • xml_set_character_data_handler — 建立字符数据处理器
  • xml_set_default_handler — 建立默认处理器
  • xml_set_element_handler — 建立起始和终止元素处理器
  • xml_set_end_namespace_decl_handler — 建立终止命名空间声明处理器
  • xml_set_external_entity_ref_handler — 建立外部实体指向处理器
  • xml_set_notation_decl_handler — 建立注释声明处理器
  • xml_set_object — 在对象中使用 XML 解析器
  • xml_set_processing_instruction_handler — 建立处理指令（PI）处理器
  • xml_set_start_namespace_decl_handler — 建立起始命名空间声明处理器
  • xml_set_unparsed_entity_decl_handler — 建立未解析实体定义声明处理器

User Contributed Notes

filip dot rydlo at gmail dot com 18-Apr-2017 09:28
// Fix for xmlToArrayParser  .......... hope this helps somebody. :-)

// FIXED the "MULTIPLE-CALLS to callback for one string" issue of 'cdata' in  xmlToArrayParser written by:
// Glen at ITIStudios dot ca  (2012)

  private function cdata($parser, $cdata) {
    if(isset($this->pointer['cdata'])) {      // This FIXes the issue with "INCOMPLETE STRINGS" containing html-entities
      $this->pointer['cdata'] .= $cdata;
    } else {
      $this->pointer['cdata'] = $cdata;
    }
  }
anrdaemon at freemail dot ru 10-Feb-2016 06:06
You must not, never ever use utf8_encode() and utf8_decode().
If you need multibyte conversion utility, use iconv() instead. At the very least, you will get a notification, if your string can not be converted.
utf8_* crap, like other crap of this nature, is ONLY SUPPORTING ONE CONVERSION. ISO-8859-1 <=> UTF-8.
Glen at ITIStudios dot ca 15-Aug-2013 06:42
Update: concatenate element contents in function cdata()
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  3.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata){
    if (isset($this->pointer['cdata'])) { $this->pointer['cdata'] .= $cdata;}
    else { $this->pointer['cdata'] = $cdata; }
  }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}
    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);
    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag]) && !is_array($this->pointer[$tag])){
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>
Glen at ITIStudios dot ca 05-Apr-2013 07:38
Update: corrected isset() in convert_to_array() function
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  2.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);

    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag]) && !is_array($this->pointer[$tag])){
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>
Glen at ITIStudios dot ca 02-Dec-2011 03:37
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  2.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);

    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag][$item])) {
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>

This is supplimental information for the "class xmlToArrayParser".
This is a fully functional error free, extensively tested php class unlike the posts that follow it.

Key phrase: Fully functional, fully tested, error free XML To Array parser.

<?php
/**
 * class xmlToArrayParser
 *
  Notes:
  1. 'attrib' and 'cdata' are keys added to the array when the element contains both attributes and content.
  2. Ignores content that is not in between it's own set of tags.
  3. Don't know if it recognizes processing instructions nor do I know about processing instructions.
     <\?some_pi some_attr="some_value"?>  This is the same as a document declaration.
  4. Empty elements are not included unless they have attributes.
  5. Version 2.0, Dec. 2, 2011, added xml error reporting.

  Usage:
    $domObj = new xmlToArrayParser($xml);
    $elemVal = $domObj->array['element']
    Or assign the entire array to its own variable:
    $domArr = $domObj->array;
    $elemVal = $domArr['element']

  Example:
    $xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <top>
      <element1>element content 1</element1>
      <element2 var2="val2" />
      <element3 var3="val3" var4="val4">element content 3</element3>
      <element3 var5="val5">element content 4</element3>
      <element3 var6="val6" />
      <element3>element content 7</element3>
    </top>';

    $domObj = new xmlToArrayParser($xml);
    $domArr = $domObj->array;

    if($domObj->parse_error) echo $domObj->get_xml_error();
    else print_r($domArr);

    On Success:
    $domArr['top']['element1'] => element content 1
    $domArr['top']['element2']['attrib']['var2'] => val2
    $domArr['top']['element3']['0']['attrib']['var3'] => val3
    $domArr['top']['element3']['0']['attrib']['var4'] => val4
    $domArr['top']['element3']['0']['cdata'] => element content 3
    $domArr['top']['element3']['1']['attrib']['var5'] => val5
    $domArr['top']['element3']['1']['cdata'] => element content 4
    $domArr['top']['element3']['2']['attrib']['var6'] => val6
    $domArr['top']['element3']['3'] => element content 7

    On Error:
    Error Code [76] "Mismatched tag", at char 58 on line 3
 *
 */
?>
wolfon.AT-DoG.inbox.ru 28-Jul-2008 03:09
Finally a simple xml => array class.
Functioning like SimpleXML library.

<?php
class xml  {
    private $parser;
    private $pointer;
    public $dom;

    public function __construct($data) {
        $this->pointer =& $this->dom;
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
        xml_parse($this->parser, $data);
    }

    private function tag_open($parser, $tag, $attributes) {
        if (isset($this->pointer[$tag]['@attributes'])) {
            $content = $this->pointer[$tag];
            $this->pointer[$tag] = array(0 => $content);
            $idx = 1;
        } else if (isset($this->pointer[$tag]))
            $idx = count($this->pointer[$tag]);

        if (isset($idx)) {
            $this->pointer[$tag][$idx] = Array(
                '@idx' => $idx,
                '@parent' => &$this->pointer);
               $this->pointer =& $this->pointer[$tag][$idx];
        } else {
            $this->pointer[$tag] = Array(
                '@parent' => &$this->pointer);
            $this->pointer =& $this->pointer[$tag];
        }
        if (!empty($attributes))
            $this->pointer['@attributes'] = $attributes;
    }

    private function cdata($parser, $cdata) {
           $this->pointer['@data'] = $cdata;
    }

    private function tag_close($parser, $tag) {
        $current = & $this->pointer;
        if (isset($this->pointer['@idx']))
            unset($current['@idx']);

        $this->pointer = & $this->pointer['@parent'];

          unset($current['@parent']);
           if (isset($current['@data']) && count($current) == 1)
               $current = $current['@data'];
           else if (empty($current['@data'])||$current['@data']==0)
               unset($current['@data']);
    }
}
?>

maybe I'll do some explanations on habr
geoff at spacevs dot com 07-Nov-2007 09:13
Reading xml into a class:

<?PHP
        class XmlData {}
        $elements = array();
        $elements[] =& new XmlData();
        function startElement($parser, $name, $attrs) {
                global $elements;
                $element =& new XMLData();
                $elements[count($elements)-1]->$name =& $element;
                $elements[] =& $element;
        }
        function endElement($parser, $name) {
                global $elements;
                array_pop($elements);
        }
        function characterData($parser, $data) {
                global $elements;
                $elements[count($elements)-1]->data = $data;
        }
        $xml_parser     = xml_parser_create();
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_set_character_data_handler($xml_parser, "characterData");
        xml_parse($xml_parser, $xml, true);
        xml_parser_free($xml_parser);
        $request =& array_pop($elements);

        echo $request->LOGIN->USER->data;
?>
demonpants at gmail dot com 22-Oct-2007 08:59
I wanted to access the ISBN database, and was previously parsing the HTML string generated from their main page, that is until I discovered they have an API that returns XML.

So, if anyone wants to get some information from the ISBN database, all you need to do is the following.

<?php
//Search the ISBN database for the book.
            $url = "http://www.isbndb.com/api/books.xml? access_key=KEY&index1=isbn&value1=$_GET[ISBN]";
            $p = xml_parser_create();
            xml_parse_into_struct($p,file_get_contents($url),$results,$index);
            xml_parser_free($p);

            $title = $results[$index[TITLELONG][0]][value];
            $author = $results[$index[AUTHORSTEXT][0]][value];
            $publisher = $results[$index[PUBLISHERTEXT][0]][value];
?>

You will need to get an access key from isbndb.com, but it takes two seconds and is free. When you get it, replace KEY in the URL with your own key. Also, my code above will search for the book that fits the ISBN number stored in the GET variable ISBN - you can search by other parameters and return more than one result, but my example is  for a simple ISBN search.
Zvjezdan Patz 09-Sep-2007 08:22
The problem I had was I needed to generate xml on the screen for users to actually see and copy to a file.

I'm generating the xml manually from a php file and the browser kept interpreting the xml...not very helpful.

This is how you get around it:

<?php

$file  = file_get_contents("http://example.com/xml.php?whatever=$whatever");
print nl2br(htmlentities($file));

?>

Prints all my xml quite nicely.
v9 at fakehalo dot us 13-Jul-2007 08:04
I needed this for work/personal use.  Sometimes you'll have a XML string generated as one long string and no line breaks...nusoap in the case of today/work, but there are any other number of possible things that will generate these.  Anyways, this simply takes a long XML string and returns an indented/line-breaked version of the string for display/readability.

<?php
function xmlIndent($str){
    $ret = "";
    $indent = 0;
    $indentInc = 3;
    $noIndent = false;
    while(($l = strpos($str,"<",$i))!==false){
        if($l!=$r && $indent>0){ $ret .= "\n" . str_repeat(" ",$indent) . substr($str,$r,($l-$r)); }
        $i = $l+1;
        $r = strpos($str,">",$i)+1;
        $t = substr($str,$l,($r-$l));
        if(strpos($t,"/")==1){
            $indent -= $indentInc;
            $noIndent = true;
        }
        else if(($r-$l-strpos($t,"/"))==2 || substr($t,0,2)=="<?"){ $noIndent = true; }
        if($indent<0){ $indent = 0; }
        if($ret){ $ret .= "\n"; }
        $ret .= str_repeat(" ",$indent);
        $ret .= $t;
        if(!$noIndent){ $indent += $indentInc; }
        $noIndent = false;
    }
    $ret .= "\n";
    return($ret);
}
?>

(...this was only tested for what i needed at work, could POSSIBLY need additions)
geoffers [at] gmail [dot] com 30-Dec-2006 03:27
Time to add my attempt at a very simple script that parses XML into a structure:

<?php

class Simple_Parser
{
    var $parser;
    var $error_code;
    var $error_string;
    var $current_line;
    var $current_column;
    var $data = array();
    var $datas = array();

    function parse($data)
    {
        $this->parser = xml_parser_create('UTF-8');
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
        xml_set_element_handler($this->parser, 'tag_open', 'tag_close');
        xml_set_character_data_handler($this->parser, 'cdata');
        if (!xml_parse($this->parser, $data))
        {
            $this->data = array();
            $this->error_code = xml_get_error_code($this->parser);
            $this->error_string = xml_error_string($this->error_code);
            $this->current_line = xml_get_current_line_number($this->parser);
            $this->current_column = xml_get_current_column_number($this->parser);
        }
        else
        {
            $this->data = $this->data['child'];
        }
        xml_parser_free($this->parser);
    }

    function tag_open($parser, $tag, $attribs)
    {
        $this->data['child'][$tag][] = array('data' => '', 'attribs' => $attribs, 'child' => array());
        $this->datas[] =& $this->data;
        $this->data =& $this->data['child'][$tag][count($this->data['child'][$tag])-1];
    }

    function cdata($parser, $cdata)
    {
        $this->data['data'] .= $cdata;
    }

    function tag_close($parser, $tag)
    {
        $this->data =& $this->datas[count($this->datas)-1];
        array_pop($this->datas);
    }
}

$xml_parser = new Simple_Parser;
$xml_parser->parse('<foo><bar>test</bar></foo>');

?>
Didier: dlvb ** free * fr 24-Dec-2006 09:53
Hi !

After parsing the XML and modifying it, I just add a method to rebuild the XML form the internal structure (xmlp->document).
The method xmlp->toXML writes into xmlp->XML attributes. Then, you just have to output it.
I hope it helps.

<?php
class XMLParser {

var $parser;
var $filePath;
var $document;
var $currTag;
var $tagStack;
var $XML;
var $_tag_to_close = false;
var $TAG_ATTRIBUT = 'attr';
var $TAG_DATA = 'data';

function XMLParser($path) {
    $this->parser = xml_parser_create();
    $this->filePath = $path;
    $this->document = array();
    $this->currTag =& $this->document;
    $this->tagStack = array();
    $this->XML = "";
}

function parse() {
    xml_set_object($this->parser, $this);
    xml_set_character_data_handler($this->parser, 'dataHandler');
    xml_set_element_handler($this->parser, 'startHandler', 'endHandler');

   if(!($fp = fopen($this->filePath, "r"))) {
       die("Cannot open XML data file: $this->filePath");
       return false;
     }

    while($data = fread($fp, 4096)) {
        if(!xml_parse($this->parser, $data, feof($fp))) {
            die(sprintf("XML error: %s at line %d",
                xml_error_string(xml_get_error_code($this->parser)),
             xml_get_current_line_number($this->parser)));
      }
    }

    fclose($fp);
    xml_parser_free($this->parser);

    return true;
}

function startHandler($parser, $name, $attribs) {
     if(!isset($this->currTag[$name]))
          $this->currTag[$name] = array();

     $newTag = array();
     if(!empty($attribs))
          $newTag[$this->TAG_ATTRIBUT] = $attribs;
     array_push($this->currTag[$name], $newTag);

     $t =& $this->currTag[$name];
     $this->currTag =& $t[count($t)-1];
     array_push($this->tagStack, $name);
}

function dataHandler($parser, $data) {
    $data = trim($data);

    if(!empty($data)) {
      if(isset($this->currTag[$this->TAG_DATA]))
            $this->currTag[$this->TAG_DATA] .= $data;
      else
            $this->currTag[$this->TAG_DATA] = $data;
    }
}

function endHandler($parser, $name) {
     $this->currTag =& $this->document;
     array_pop($this->tagStack);

     for($i = 0; $i < count($this->tagStack); $i++) {
          $t =& $this->currTag[$this->tagStack[$i]];
          $this->currTag =& $t[count($t)-1];
     }
}

function clearOutput () {
    $this->XML = "";
}

function openTag ($tag) {
    $this->XML.="<".strtolower ($tag);
    $this->_tag_to_close = true;
}

function closeTag () {
    if ($this->_tag_to_close) {
        $this->XML.=">";
        $this->_tag_to_close = false;
    }
}

function closingTag ($tag) {
    $this->XML.="</".strtolower ($tag).">";
}

function output_attributes ($contenu_fils) {
    foreach ($contenu_fils[$this->TAG_ATTRIBUT] as $nomAttribut => $valeur) {
        $this->XML.= " ".strtolower($nomAttribut)."=\"".$valeur."\"";
    }
}

function addData ($texte) {
// to be completed
    $ca  = array ("é", "è", "ê", "à");
    $par = array ("&eacute;", "&egrave;", "&ecirc;", "agrave;");
    return htmlspecialchars(str_replace ($ca, $par, $texte), ENT_NOQUOTES);
}

function toXML ($tags="") {
    if ($tags=="") {
        $tags = $this->document;
      $this->clearOutput ();
    }

    foreach ($tags as $tag => $contenu) {
        $this->process ($tag, $contenu);
    }
}

function process ($tag, $contenu) {
     // Pour tous les TAGs
    foreach ($contenu as $indice => $contenu_fils) {
         $this->openTag ($tag);

         // Pour tous les fils (non attribut et non data)
         foreach ($contenu_fils as $tagFils => $fils) {
             switch ($tagFils) {
                 case $this->TAG_ATTRIBUT:
                         $this->output_attributes ($contenu_fils);
                        $this->closeTag ();
                         break;
                 case $this->TAG_DATA:
                        $this->closeTag ();
                         $this->XML.= $this->addData ($contenu_fils [$this->TAG_DATA]);
                         break;
                 default:
                         $this->closeTag ();
                         $this->process ($tagFils, $fils);
                         break;
             }
         }

        $this->closingTag ($tag);
    }
}

}
?>
forquan 28-Jan-2006 03:45
Here's code that will create an associative array from an xml file.  Keys are the tag data and subarrays are formed from attributes and child tags

<?php
$p =& new xmlParser();
$p->parse('/*xml file*/');
print_r($p->output);
?>

<?php
class xmlParser{
   var $xml_obj = null;
   var $output = array();
   var $attrs;

   function xmlParser(){
       $this->xml_obj = xml_parser_create();
       xml_set_object($this->xml_obj,$this);
       xml_set_character_data_handler($this->xml_obj, 'dataHandler');
       xml_set_element_handler($this->xml_obj, "startHandler", "endHandler");
   }

   function parse($path){
       if (!($fp = fopen($path, "r"))) {
           die("Cannot open XML data file: $path");
           return false;
       }

       while ($data = fread($fp, 4096)) {
           if (!xml_parse($this->xml_obj, $data, feof($fp))) {
               die(sprintf("XML error: %s at line %d",
               xml_error_string(xml_get_error_code($this->xml_obj)),
               xml_get_current_line_number($this->xml_obj)));
               xml_parser_free($this->xml_obj);
           }
       }

       return true;
   }

   function startHandler($parser, $name, $attribs){
       $_content = array();
       if(!empty($attribs))
         $_content['attrs'] = $attribs;
       array_push($this->output, $_content);
   }

   function dataHandler($parser, $data){
       if(!empty($data) && $data!="\n") {
           $_output_idx = count($this->output) - 1;
           $this->output[$_output_idx]['content'] .= $data;
       }
   }

   function endHandler($parser, $name){
       if(count($this->output) > 1) {
           $_data = array_pop($this->output);
           $_output_idx = count($this->output) - 1;
           $add = array();
           if ($_data['attrs'])
                $add['attrs'] = $_data['attrs'];
           if ($_data['child'])
                $add['child'] = $_data['child'];
           $this->output[$_output_idx]['child'][$_data['content']] = $add;
       }
   }
}
?>
Greg S 17-Nov-2005 08:56
If you need utf8_encode support and configure PHP with --disable-all you will have some trouble. Unfortunately the configure options aren't completely documented. If you need utf8 functions and have everything disabled just recompile PHP with --enable-xml and you should be good to go.
compu_global_hyper_mega_net_2 at yahoo dot com 19-Sep-2004 01:35
The documentation regarding white space was never complete I think.

The XML_OPTION_SKIP_WHITE doesn't appear to do anything.  I want to preserve the newlines in a cdata section.  Setting XML_OPTION_SKIP_WHITE to 0 or false doesn't appear to help.  My character_data_handler is getting called once for each line.  This obviously should be reflected in the documentation as well.  When/how often does the handler get called exactly?  Having to build separate test cases is very time consuming.

Inserting newlines myself in my cdata handler is no good either.  For non actual CDATA sections that cause my handler to get called, long lines are split up in multiple calls.  My handler would not be able to tell the difference whether or not the subsequent calls would be due to the fact that the data is coming from the next line or the fact that some internal buffer is long enough for it to 'flush' out and call the handler.
This behaviour also needs to be properly documented.
odders 18-Mar-2004 10:36
I wrote a simple xml parser mainly to deal with rss version 2. I found lots of examples on the net, but they were all masive and bloated and hard to manipulate.

Output is sent to an array, which holds arrays containg data for each item.

Obviously, you will have to make modifications to the code to suit your needs, but there isnt a lot of code there, so that shouldnt be a problem.

<?php

   $currentElements = array();
   $newsArray = array();

   readXml("./news.xml");

   echo("<pre>");
   print_r($newsArray);
   echo("</pre>");

   // Reads XML file into formatted html
   function readXML($xmlFile)
   {

      $xmlParser = xml_parser_create();

      xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
      xml_set_element_handler($xmlParser, startElement, endElement);
      xml_set_character_data_handler($xmlParser, characterData);

      $fp = fopen($xmlFile, "r");

      while($data = fread($fp, filesize($xmlFile))){
         xml_parse($xmlParser, $data, feof($fp));}

      xml_parser_free($xmlParser);

   }

   // Sets the current XML element, and pushes itself onto the element hierarchy
   function startElement($parser, $name, $attrs)
   {

      global $currentElements, $itemCount;

      array_push($currentElements, $name);

      if($name == "item"){$itemCount += 1;}

   }

   // Prints XML data; finds highlights and links
   function characterData($parser, $data)
   {

      global $currentElements, $newsArray, $itemCount;

      $currentCount = count($currentElements);
      $parentElement = $currentElements[$currentCount-2];
      $thisElement = $currentElements[$currentCount-1];

      if($parentElement == "item"){
         $newsArray[$itemCount-1][$thisElement] = $data;}
      else{
         switch($name){
            case "title":
               break;
            case "link":
               break;
            case "description":
               break;
            case "language":
               break;
            case "item":
               break;}}

   }

   // If the XML element has ended, it is poped off the hierarchy
   function endElement($parser, $name)
   {

      global $currentElements;

      $currentCount = count($currentElements);
      if($currentElements[$currentCount-1] == $name){
         array_pop($currentElements);}

   }

?>
software at serv-a-com dot com 22-Jan-2003 02:08
use:

<?php
while ($data = str_replace("\n","",fread($fp, 4096))){
 // ...
}
?>

instead of:

<?php
while ($data = fread($fp, 4096)) {
  // ...
}
?>

[UPDATE 17-FEB-2003: This post] resulted in some of the visitors e-mailg me on the carriage return stripping issue with questions. I'll try to make the following mumble as brief and easy to understand as possible.

1. Overview of the 4096 fragmentation issue
As you know the following freads the file 4096 bytes at a time (that is 4KB) this is perhaps ok for testing expat and figuring out how things work, but it it rather dangerous in the production environment. Data may not be fully understandable due to fread fragmentation and improperly formatted due to numerous sources(formats) of data contained within (i.e. end of line delimited CDATA).

<?php
while ($data = fread($fp, 4096)) {
  if (!xml_parse($xml_parser, $data, feof($fp))) {
    // ...
  }
}
?>

Sometimes to save time one may want to load it all up into a one big variable and leave all the worries to expat. I think anything under 500 KB is ok (as long as nobody knows about it). Some may argue that larger variables are acceptable or even necessary because of the magic that take place while parsing using xml_parse. Our XML parser(expat) works and can be successfully implemented only when we know what type of XML data we are dealing with, it's average size and structure of general layout and data contained within tags. For example if the tags are followed by a line delimiter like a new line we can read it with fgets in and with minimal effort make sure that no data will be sent to the function that does not end with a end tag. But this require a fair knowledge of the file's preference for storing XML data and tags (and a bit of code between reading data and xml_parse'ing it).
It will save you a headache.

2. Pre Parser Strings and New Line Delimited Data
One important thing to note at this point is that the xml_parse function requires a string variable. You can manipulate the content of any string variable easily as we all know.

A better approach to removing newlines than:

<?php
while ($data = fread($fp, 4096)) {
$data = preg_replace("/\n|\r/","",$data); //flarp
if (!xml_parse($xml_parser, $data, feof($fp))) {...
?>

Above works across all 3 line-delimited text files  (\n, \r, \r\n). But this could potentially (or will most likely) damage or scramble data contained in for example CDATA areas. As far as I am concerned end of line characters should not be used _within_ XML tags. What seems to be the ultimate solution is to pre-parse the loaded data this would require checking the position within the XML document and adding or subtracting (using a in-between fread temporary variable) data based on conditions like: "Is within tag", "Is within CDATA" etc. before fedding it to the parser. This of course opens up a new can of worms (as in parse data for the parser...). (above procedure would take place between fread and xml_parser calls this method would be compatible with the general usage examples on top of the page)

3. The Answer to parsing arbitrary XML and Preprocessor Revisited
You can't just feed any XML document to the parser you constructed and assuming that it will work! You have to know what kind of methods for storing data are used, for example is there a end of line delimited data in the  file ?, Are there any carriage returns in the tags etc... XML files come formatted in different ways some are just a one long string of characters with out any end of line markers others have newlines, carriage returns or both (Microsloth Windows). May or may not contain space and other whitespace between tags. For this reason it is important to what I call Normalize the data before feeding it to the parser. You can perform this with regular expressions or plain old str_replace and concatenation. In many cases this can be done to the file it self sometimes to string data on the fly( as shown in the example above). But I feel it is important to normalize the data before even calling the function to call xml_parse. If you have the ability to access all data before that call you can convert it to what you fell the data should have been in the first place and omit many surprises and expensive regular expression substitution (in a tight spot) while fread'ing the data.
guy at bhaktiandvedanta dot com 27-Sep-2002 12:01
For a simple XML parser you can use this function. It doesn't require any extensions to run.

<?php
// Extracts content from XML tag

function GetElementByName ($xml, $start, $end) {

    global $pos;
    $startpos = strpos($xml, $start);
    if ($startpos === false) {
        return false;
    }
    $endpos = strpos($xml, $end);
    $endpos = $endpos+strlen($end);
    $pos = $endpos;
    $endpos = $endpos-$startpos;
    $endpos = $endpos - strlen($end);
    $tag = substr ($xml, $startpos, $endpos);
    $tag = substr ($tag, strlen($start));

    return $tag;

}

// Open and read xml file. You can replace this with your xml data.

$file = "data.xml";
$pos = 0;
$Nodes = array();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}
while ($getline = fread($fp, 4096)) {
    $data = $data . $getline;
}

$count = 0;
$pos = 0;

// Goes throw XML file and creates an array of all <XML_TAG> tags.
while ($node = GetElementByName($data, "<XML_TAG>", "</XML_TAG>")) {
    $Nodes[$count] = $node;
    $count++;
    $data = substr($data, $pos);
}

// Gets infomation from tag siblings.
for ($i=0; $i<$count; $i++) {
$code = GetElementByName($Nodes[$i], "<Code>", "</Code>");
$desc = GetElementByName($Nodes[$i], "<Description>", "</Description>");
$price = GetElementByName($Nodes[$i], "<BasePrice>", "</BasePrice>");
}
?>

Hope this helps! :)
Guy Laor
dmarsh dot NO dot SPAM dot PLEASE at spscc dot ctc dot edu 18-Sep-2002 12:27
Some reference code I am working on as "XML Library" of which I am folding it info an object. Notice the use of the DEFINE:

Mainly Example 1 and parts of 2 & 3 re-written as an object:
--- MyXMLWalk.lib.php ---
<?php

if (!defined("PHPXMLWalk")) {
define("PHPXMLWalk",TRUE);

class XMLWalk {
 var $p; //short for xml parser;
 var $e; //short for element stack/array

  function prl($x,$i=0) {
    ob_start();
    print_r($x);
    $buf=ob_get_contents();
    ob_end_clean();
    return join("\n".str_repeat(" ",$i),split("\n",$buf));
  }

 function XMLWalk() {
  $this->p = xml_parser_create();
  $this->e = array();
  xml_parser_set_option($this->p, XML_OPTION_CASE_FOLDING, true);
  xml_set_element_handler($this->p, array(&$this, "startElement"), array(&$this, "endElement"));
  xml_set_character_data_handler($this->p, array(&$this, "dataElement"));
  register_shutdown_function(array(&$this, "free")); // make a destructor
  }

  function startElement($parser, $name, $attrs) {
    if (count($attrs)>=1) {
      $x = $this->prl($attrs, $this->e[$parser]+6);
    } else {
      $x = "";
    }

    print str_repeat(" ",$this->e[$parser]+0). "$name $x\n";
    $this->e[$parser]++;
    $this->e[$parser]++;
  }

  function dataElement($parser, $data) {
    print str_repeat(" ",$this->e[$parser]+0). htmlspecialchars($data, ENT_QUOTES) ."\n";
  }

  function endElement($parser, $name) {
    $this->e[$parser]--;
    $this->e[$parser]--;
  }
  function parse($data, $fp) {
    if (!xml_parse($this->p, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($this->p)),
                    xml_get_current_line_number($this->p)));
    }
  }

  function free() {
    xml_parser_free($this->p);
  }

} // end of class

} // end of define

?>

--- end of file ---

Calling code:
<?php

...

require("MyXMLWalk.lib.php");

$file = "x.xml";

$xme = new XMLWalk;

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
  $xme->parse($data, $fp);
}

...
?>
jon at gettys dot org 14-Aug-2002 01:59
[Editor's note: see also xml_parse_into_struct().]

Very simple routine to convert an XML file into a PHP structure. $obj->xml contains the resulting PHP structure. I would be interested if someone could suggest a cleaner method than the evals I am using.

<?php
$filename = 'sample.xml';
$obj->tree = '$obj->xml';
$obj->xml = '';

function startElement($parser, $name, $attrs) {
    global $obj;

    // If var already defined, make array
    eval('$test=isset('.$obj->tree.'->'.$name.');');
    if ($test) {
      eval('$tmp='.$obj->tree.'->'.$name.';');
      eval('$arr=is_array('.$obj->tree.'->'.$name.');');
      if (!$arr) {
        eval('unset('.$obj->tree.'->'.$name.');');
        eval($obj->tree.'->'.$name.'[0]=$tmp;');
        $cnt = 1;
      }
      else {
        eval('$cnt=count('.$obj->tree.'->'.$name.');');
      }

      $obj->tree .= '->'.$name."[$cnt]";
    }
    else {
      $obj->tree .= '->'.$name;
    }
    if (count($attrs)) {
        eval($obj->tree.'->attr=$attrs;');
    }
}

function endElement($parser, $name) {
    global $obj;
    // Strip off last ->
    for($a=strlen($obj->tree);$a>0;$a--) {
        if (substr($obj->tree, $a, 2) == '->') {
            $obj->tree = substr($obj->tree, 0, $a);
            break;
        }
    }
}

function characterData($parser, $data) {
    global $obj;

    eval($obj->tree.'->data=\''.$data.'\';');
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($filename, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
print_r($obj->xml);
return 0;

?>
hans dot schneider at bbdo-interone dot de 24-Jan-2002 08:43
I had to TRIM the data when I passed one large String containig a wellformed XML-File to xml_parse. The String was read by CURL, which aparently put a BLANK at the end of the String. This BLANK produced a "XML not wellformed"-Error in xml_parse!
sam at cwa dot co dot nz 28-Sep-2000 07:39
I've discovered some unusual behaviour in this API when ampersand entities are parsed in cdata; for some reason the parser breaks up the section around the entities, and calls the handler repeated times for each of the sections. If you don't allow for this oddity and you are trying to put the cdata into a variable, only the last part will be stored.

You can get around this with a line like:

$foo .= $cdata;

If the handler is called several times from the same tag, it will append them, rather than rewriting the variable each time. If the entire cdata section is returned, it doesn't matter.

May happen for other entities, but I haven't investigated.

Took me a while to figure out what was happening; hope this saves someone else the trouble.
Daniel dot Rendall at btinternet dot com 07-Jul-1999 10:21
When using the XML parser, make sure you're not using the magic quotes option (e.g. use set_magic_quotes_runtime(0) if it's not the compiled default), otherwise you'll get 'not well-formed' errors when dealing with tags with attributes set in them.


将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。

  • ? XML 解析器函数
  • utf8_encode ?
  • PHP Manual
  • XML 解析器函数
  • 将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。

utf8_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

utf8_decode — 将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。

描述

utf8_decode ( string $data ) : string

该函数将用 UTF-8 编码的数据解码为 ISO-8859-1 编码。

请参阅 utf8_encode() 以查看关于 UTF-8 编码的解释。

User Contributed Notes

Aleksandr 30-Jun-2017 02:46
In addition to note by yannikh at gmeil dot com, another way to decode strings with non-latin chars from unix console like

C=RU, L=\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0,

<?php preg_replace_callback('/\\\\x([0-9A-F]{2})/', function($a){ return pack('H*', $a[1]); }, $str); ?>

The code above will output:
C=RU, L=Москва,
kode68 02-May-2016 06:09
Update Answer from okx dot oliver dot koenig at gmail dot com for PHP 5.6 since e/ modifier is depreciated

// This finally helped me to do the job, thanks to Blackbit, had to modify deprecated ereg:
// original comment: "Squirrelmail contains a nice function in the sources to convert unicode to entities:"

function charset_decode_utf_8($string)
    {
        /* Only do the slow convert if there are 8-bit characters */
        if ( !preg_match("/[\200-\237]/", $string) && !preg_match("/[\241-\377]/", $string) )
               return $string;

        // decode three byte unicode characters
          $string = preg_replace_callback("/([\340-\357])([\200-\277])([\200-\277])/",
                    create_function ('$matches', 'return \'&#\'.((ord($matches[1])-224)*4096+(ord($matches[2])-128)*64+(ord($matches[3])-128)).\';\';'),
                    $string);

        // decode two byte unicode characters
          $string = preg_replace_callback("/([\300-\337])([\200-\277])/",
                    create_function ('$matches', 'return \'&#\'.((ord($matches[1])-192)*64+(ord($matches[2])-128)).\';\';'),
                    $string);

        return $string;
    }

Enjoy
okx dot oliver dot koenig at gmail dot com 08-Feb-2015 11:48
// This finally helped me to do the job, thanks to Blackbit, had to modify deprecated ereg:
// original comment: "Squirrelmail contains a nice function in the sources to convert unicode to entities:"

function charset_decode_utf_8 ($string) {
    /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (!preg_match("/[\200-\237]/", $string)
     && !preg_match("/[\241-\377]/", $string)
    ) {
        return $string;
    }

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
        "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",
        $string
    );

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
        "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",
        $string
    );

    return $string;
}
sashott at gmail dot com 04-Dec-2014 11:57
Use of utf8_decode was not enough for me by get page content from another site. Problem appear by different alphabet from standard latin. As example some chars (corresponding to HTML codes &bdquo; , &nbsp; and others) are converted to "?" or "xA0" (hex value). You need to make some conversion before execute utf8_decode. And you can not replace simple, that they can be part of 2 bytes code for a char (UTF-8 use 2 bytes). Next is for cyrillic alphabet, but for other must be very close.

function convertMethod($text){
    //Problem is that utf8_decode convert HTML chars for &bdquo; and other to ? or &nbsp; to \xA0. And you can not replace, that they are in some char bytes and you broke cyrillic (or other alphabet) chars.
    $problem_enc=array(
        'euro',
        'sbquo',
        'bdquo',
        'hellip',
        'dagger',
        'Dagger',
        'permil',
        'lsaquo',
        'lsquo',
        'rsquo',
        'ldquo',
        'rdquo',
        'bull',
        'ndash',
        'mdash',
        'trade',
        'rsquo',
        'brvbar',
        'copy',
        'laquo',
        'reg',
        'plusmn',
        'micro',
        'para',
        'middot',
        'raquo',
        'nbsp'
    );
    $text=mb_convert_encoding($text,'HTML-ENTITIES','UTF-8');
    $text=preg_replace('#(?<!\&ETH;)\&('.implode('|',$problem_enc).');#s','--amp{$1}',$text);
    $text=mb_convert_encoding($text,'UTF-8','HTML-ENTITIES');
    $text=utf8_decode($text);
    $text=mb_convert_encoding($text,'HTML-ENTITIES','UTF-8');
    $text=preg_replace('#\-\-amp\{([^\}]+)\}#su','&$1;',$text);
    $text=mb_convert_encoding($text,'UTF-8','HTML-ENTITIES');
    return $text;
}

If this don't work, try to set "die($text);" on some places to look, what is happen to this row. Is better to test with long text. It is very possible to broke other alphabet character. In this case, it is very possible, that for you alphabet set "&ETH;" is not the right one. You need to set "die($text);" after this preg_replace and look HTML code for character before set "--amp".
christoffer 29-Oct-2012 10:35
The preferred way to use this on an array would be with the built in PHP function "array_map()", as for example:
$array = array_map("utf8_decode", $array);
deceze at gmail dot com 14-Jul-2011 07:01
Please note that utf8_decode simply converts a string encoded in UTF-8 to ISO-8859-1. A more appropriate name for it would be utf8_to_iso88591. If your text is already encoded in ISO-8859-1, you do not need this function. If you don't want to use ISO-8859-1, you do not need this function.

Note that UTF-8 can represent many more characters than ISO-8859-1. Trying to convert a UTF-8 string that contains characters that can't be represented in ISO-8859-1 to ISO-8859-1 will garble your text and/or cause characters to go missing. Trying to convert text that is not encoded in UTF-8 using this function will most likely garble the text.

If you need to convert any text from any encoding to any other encoding, look at iconv() instead.
gabriel arobase gabsoftware dot com 12-Jun-2011 08:41
If you want to retrieve some UTF-8 data from your database, you don't need utf8_decode().

Simply do the following query before any SELECT :

$result = mysql_query("SET NAMES utf8");
info at vanylla dot it 26-Jan-2009 12:21
IMPORTANT: when converting UTF8 data that contains the EURO sign DON'T USE utf_decode function.

utf_decode converts the data into ISO-8859-1 charset. But ISO-8859-1 charset does not contain the EURO sign, therefor the EURO sign will be converted into a question mark character '?'

In order to convert properly UTF8 data with EURO sign you must use:

iconv("UTF-8", "CP1252", $data)
Blackbit 12-Aug-2008 04:40
Squirrelmail contains a nice function in the sources to convert unicode to entities:

<?php
function charset_decode_utf_8 ($string) {
      /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",        \
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",    \
    $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e", \
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'", \
    $string);

    return $string;
}
?>
punchivan at gmail dot com 24-Jun-2008 02:13
EY! the bug is not in the function 'utf8_decode'. The bug is in the function 'mb_detect_encoding'. If you put a word with a special char at the end like this 'accentué', that will lead to a wrong result (UTF-8) but if you put another char at the end like this 'accentuée' you will get it right. So you should always add a ISO-8859-1 character to your string for this check. My advise is to use a blank space.
I′ve tried it and it works!

function ISO_convert($array)
{
    $array_temp = array();

    foreach($array as $name => $value)
    {
        if(is_array($value))
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = ISO_convert($value);
        else
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = (mb_detect_encoding($value." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($value) : $value );
    }

    return $array_temp;
}
haugas at gmail dot com 08-May-2008 02:11
If you don't know exactly, how many times your string is encoded, you can use this function:

<?php

function _utf8_decode($string)
{
  $tmp = $string;
  $count = 0;
  while (mb_detect_encoding($tmp)=="UTF-8")
  {
    $tmp = utf8_decode($tmp);
    $count++;
  }

  for ($i = 0; $i < $count-1 ; $i++)
  {
    $string = utf8_decode($string);

  }
  return $string;

}

?>
lukasz dot mlodzik at gmail dot com 05-Mar-2008 04:46
Update to MARC13 function utf2iso()
I'm using it to handle AJAX POST calls.
Despite using
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'; charset='utf-8');
it still code Polish letters using UTF-16

This is only for Polish letters:

<?php
function utf16_2_utf8 ($nowytekst) {
        $nowytekst = str_replace('%u0104','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0106','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0118','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0141','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0143','?',$nowytekst);    //?
        $nowytekst = str_replace('%u00D3','ó',$nowytekst);    //ó
        $nowytekst = str_replace('%u015A','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0179','?',$nowytekst);    //?
        $nowytekst = str_replace('%u017B','?',$nowytekst);    //?

        $nowytekst = str_replace('%u0105','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0107','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0119','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0142','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0144','ń',$nowytekst);    //ń
        $nowytekst = str_replace('%u00F3','ó',$nowytekst);    //ó
        $nowytekst = str_replace('%u015B','?',$nowytekst);    //?
        $nowytekst = str_replace('%u017A','?',$nowytekst);    //?
        $nowytekst = str_replace('%u017C','?',$nowytekst);    //?
   return ($nowytekst);
   }
?>

Everything goes smooth, but it doesn't change '%u00D3','ó' and '%u00F3','ó'. I dont have idea what to do with that.

Remember! File must be saved in UTF-8 coding.
ludvig dot ericson at gmail dot com 15-Jul-2007 10:52
A better way to convert would be to use iconv, see http://www.php.net/iconv -- example:

<?php
$myUnicodeString = "???";
echo iconv("UTF-8", "ISO-8859-1", $myUnicodeString);
?>

Above would echo out the given variable in ISO-8859-1 encoding, you may replace it with whatever you prefer.

Another solution to the issue of misdisplayed glyphs is to simply send the document as UTF-8, and of course send UTF-8 data:

<?php
# Replace text/html with whatever MIME-type you prefer.
header("Content-Type: text/html; CHARSET=gb2312");
?>
MARC13 07-Jul-2007 07:50
I did this function to convert data from AJAX call to insert to my database.
It converts UTF-8 from XMLHttpRequest() to ISO-8859-2 that I use in LATIN2 MySQL database.

<?php
function utf2iso($tekst)
{
        $nowytekst = str_replace("%u0104","\xA1",$tekst);    //?
        $nowytekst = str_replace("%u0106","\xC6",$nowytekst);    //?
        $nowytekst = str_replace("%u0118","\xCA",$nowytekst);    //?
        $nowytekst = str_replace("%u0141","\xA3",$nowytekst);    //?
        $nowytekst = str_replace("%u0143","\xD1",$nowytekst);    //?
        $nowytekst = str_replace("%u00D3","\xD3",$nowytekst);    //ó
        $nowytekst = str_replace("%u015A","\xA6",$nowytekst);    //?
        $nowytekst = str_replace("%u0179","\xAC",$nowytekst);    //?
        $nowytekst = str_replace("%u017B","\xAF",$nowytekst);    //?

        $nowytekst = str_replace("%u0105","\xB1",$nowytekst);    //?
        $nowytekst = str_replace("%u0107","\xE6",$nowytekst);    //?
        $nowytekst = str_replace("%u0119","\xEA",$nowytekst);    //?
        $nowytekst = str_replace("%u0142","\xB3",$nowytekst);    //?
        $nowytekst = str_replace("%u0144","\xF1",$nowytekst);    //ń
        $nowytekst = str_replace("%u00D4","\xF3",$nowytekst);    //ó
        $nowytekst = str_replace("%u015B","\xB6",$nowytekst);    //?
        $nowytekst = str_replace("%u017A","\xBC",$nowytekst);    //?
        $nowytekst = str_replace("%u017C","\xBF",$nowytekst);    //?

    return ($nowytekst);
}
?>

In my case also the code file that deals with AJAX calls must be in UTF-8 coding.
visus at portsonline dot net 23-Jun-2007 09:08
Following code helped me with mixed (UTF8+ISO-8859-1(x)) encodings. In this case, I have template files made and maintained by designers who do not care about encoding and MySQL data in utf8_binary_ci encoded tables.

<?php

class Helper
{
    function strSplit($text, $split = 1)
    {
        if (!is_string($text)) return false;
        if (!is_numeric($split) && $split < 1) return false;

        $len = strlen($text);

        $array = array();

        $i = 0;

        while ($i < $len)
        {
            $key = NULL;

            for ($j = 0; $j < $split; $j += 1)
            {
                $key .= $text{$i};

                $i += 1;
            }

            $array[] = $key;
        }

        return $array;
    }

    function UTF8ToHTML($str)
    {
        $search = array();
        $search[] = "/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e";
        $search[] = "/&#228;/";
        $search[] = "/&#246;/";
        $search[] = "/&#252;/";
        $search[] = "/&#196;/";
        $search[] = "/&#214;/";
        $search[] = "/&#220;/";
        $search[] = "/&#223;/";

        $replace = array();
        $replace[] = 'Helper::_UTF8ToHTML("\\1")';
        $replace[] = "?";
        $replace[] = "?";
        $replace[] = "ü";
        $replace[] = "?";
        $replace[] = "?";
        $replace[] = "ü";
        $replace[] = "?";

        $str = preg_replace($search, $replace, $str);

        return $str;
    }

    function _UTF8ToHTML($str)
    {
        $ret = 0;

        foreach((Helper::strSplit(strrev(chr((ord($str{0}) % 252 % 248 % 240 % 224 % 192) + 128).substr($str, 1)))) as $k => $v)
            $ret += (ord($v) % 128) * pow(64, $k);
        return "&#".$ret.";";
    }
}

// Usage example:

$tpl = file_get_contents("template.tpl");
/* ... */
$row = mysql_fetch_assoc($result);

print(Helper::UTF8ToHTML(str_replace("{VAR}", $row['var'], $tpl)));

?>
luka8088 at gmail dot com 22-Jun-2007 07:03
simple UTF-8 to HTML conversion:

function utf8_to_html ($data)
    {
    return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '_utf8_to_html("\\1")', $data);
    }

function _utf8_to_html ($data)
    {
    $ret = 0;
    foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)
        $ret += (ord($v) % 128) * pow(64, $k);
    return "&#$ret;";
    }

Example:
echo utf8_to_html("a b ? ? ? こ に ち わ ()[]{}!#$?*");

Output:
a b &#269; &#263; &#382; &#12371; &#12395; &#12385; &#12431; ()[]{}!#$?*
Sadi 13-Jun-2007 03:38
Once again about polish letters. If you use fananf's solution, make sure that PHP file is coded with cp1250 or else it won't work. It's quite obvious, however I spent some time before I finally figured that out, so I thought I post it here.
alexlevin at kvadro dot net 20-May-2007 08:20
If you running Gentoo Linux and encounter problems with some PHP4 applications saying:
Call to undefined function: utf8_decode()
Try reemerge PHP4 with 'expat' flag enabled.
sam 06-Feb-2007 08:20
In addition to yannikh's note, to convert a hex utf8 string

<?php

echo utf8_decode("\x61\xc3\xb6\x61");
// works as expected

$abc="61c3b661";
$newstr = "";
$l = strlen($abc);
for ($i=0;$i<$l;$i+=2){
    $newstr .= "\x".$abc[$i].$abc[$i+1];
}
echo utf8_decode($newstr);
// or varieties  of "\x": "\\x" etc does NOT output what you want

echo utf8_decode(pack('H*',$abc));
// this outputs the correct string, like the first line.

?>
Ajgor 28-Dec-2006 05:38
small upgrade for polish decoding:

function utf82iso88592($text) {
 $text = str_replace("\xC4\x85", '?', $text);
 $text = str_replace("\xC4\x84", '?', $text);
 $text = str_replace("\xC4\x87", '?', $text);
 $text = str_replace("\xC4\x86", '?', $text);
 $text = str_replace("\xC4\x99", '?', $text);
 $text = str_replace("\xC4\x98", '?', $text);
 $text = str_replace("\xC5\x82", '?', $text);
 $text = str_replace("\xC5\x81", '?', $text);
 $text = str_replace("\xC3\xB3", 'ó', $text);
 $text = str_replace("\xC3\x93", 'ó', $text);
 $text = str_replace("\xC5\x9B", '?', $text);
 $text = str_replace("\xC5\x9A", '?', $text);
 $text = str_replace("\xC5\xBC", '?', $text);
 $text = str_replace("\xC5\xBB", '?', $text);
 $text = str_replace("\xC5\xBA", '?', $text);
 $text = str_replace("\xC5\xB9", '?', $text);
 $text = str_replace("\xc5\x84", 'ń', $text);
 $text = str_replace("\xc5\x83", '?', $text);

return $text;
} // utf82iso88592
paul.hayes at entropedia.co.uk 27-Oct-2006 07:10
I noticed that the utf-8 to html functions below are only for 2 byte long codes. Well I wanted 3 byte support (sorry haven't done 4, 5 or 6). Also I noticed the concatination of the character codes did have the hex prefix 0x and so failed with the large 2 byte codes)

<?
  public function utf2html (&$str) {

    $ret = "";
    $max = strlen($str);
    $last = 0;  // keeps the index of the last regular character
    for ($i=0; $i<$max; $i++) {
        $c = $str{$i};
        $c1 = ord($c);
        if ($c1>>5 == 6) {  // 110x xxxx, 110 prefix for 2 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c1 &= 31; // remove the 3 bit two bytes prefix
            $c2 = ord($str{++$i}); // the next byte
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
            $c1 >>= 2; // c1 shifts 2 to the right
            $ret .= "&#" . ($c1 * 0x100 + $c2) . ";"; // this is the fastest string concatenation
            $last = $i+1;
        }
        elseif ($c1>>4 == 14) {  // 1110 xxxx, 110 prefix for 3 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c2 = ord($str{++$i}); // the next byte
            $c3 = ord($str{++$i}); // the third byte
            $c1 &= 15; // remove the 4 bit three bytes prefix
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 |= (($c2 & 3) << 6); // last 2 bits of c2 become first 2 of c3
            $c2 >>=2; //c2 shifts 2 to the right
            $c2 |= (($c1 & 15) << 4); // last 4 bits of c1 become first 4 of c2
            $c1 >>= 4; // c1 shifts 4 to the right
            $ret .= '&#' . (($c1 * 0x10000) + ($c2 * 0x100) + $c3) . ';'; // this is the fastest string concatenation
            $last = $i+1;
        }
    }
    $str=$ret . substr($str, $last, $i); // append the last batch of regular characters
}
?>
tobias at code-x dot de 20-Oct-2006 05:13
converting uft8-html sign &#301; to uft8

<?
function uft8html2utf8( $s ) {
        if ( !function_exists('uft8html2utf8_callback') ) {
             function uft8html2utf8_callback($t) {
                     $dec = $t[1];
            if ($dec < 128) {
              $utf = chr($dec);
            } else if ($dec < 2048) {
              $utf = chr(192 + (($dec - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            } else {
              $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
              $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            }
            return $utf;
             }
        }
        return preg_replace_callback('|&#([0-9]{1,});|', 'uft8html2utf8_callback', $s );
}
echo uft8html2utf8('test: &#301;');
?>
2ge at NO2geSPAM dot us 26-Jan-2006 01:00
Hello all,

I like to use COOL (nice) URIs, example: http://example.com/try-something
I'm using UTF8 as input, so I have to write a function UTF8toASCII to have nice URI. Here is what I come with:

<?php
function urlize($url) {
 $search = array('/[^a-z0-9]/', '/--+/', '/^-+/', '/-+$/' );
 $replace = array( '-', '-', '', '');
 return preg_replace($search, $replace, utf2ascii($url));
}

function utf2ascii($string) {
 $iso88591  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7";
 $iso88591 .= "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
 $iso88591 .= "\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF7";
 $iso88591 .= "\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF";
 $ascii = "aaaaaaaceeeeiiiidnooooooouuuuyyy";
 return strtr(mb_strtolower(utf8_decode($string), 'ISO-8859-1'),$iso88591,$ascii);
}

echo urlize("Fucking ?m?l");

?>

I hope this helps someone.
php-net at ---NOSPAM---lc dot yi dot org 08-Dec-2005 12:04
I've just created this code snippet to improve the user-customizable emails sent by one of my websites.

The goal was to use UTF-8 (Unicode) so that non-english users have all the Unicode benefits, BUT also make life seamless for English (or specifically, English MS-Outlook users).  The niggle: Outlook prior to 2003 (?)  does not properly detect unicode emails.  When "smart quotes" from MS Word were pasted into a rich text area and saved in Unicode, then sent by email to an Outlook user, more often than not, these characters were wrongly rendered as "greek".

So, the following code snippet replaces a few strategic characters into html entities which Outlook XP (and possibly earlier) will render as expected.  [Code based on bits of code from previous posts on this and the htmlenties page]
<?php
    $badwordchars=array(
        "\xe2\x80\x98", // left single quote
        "\xe2\x80\x99", // right single quote
        "\xe2\x80\x9c", // left double quote
        "\xe2\x80\x9d", // right double quote
        "\xe2\x80\x94", // em dash
        "\xe2\x80\xa6" // elipses
    );
    $fixedwordchars=array(
        "&#8216;",
        "&#8217;",
        '&#8220;',
        '&#8221;',
        '&mdash;',
        '&#8230;'
    );
    $html=str_replace($badwordchars,$fixedwordchars,$html);
?>
yannikh at gmeil dot com 07-Dec-2005 11:34
I had to tackle a very interesting problem:

I wanted to replace all \xXX in a text by it's letters. Unfortunatelly XX were ASCII and not utf8. I solved my problem that way:
<?php preg_replace ('/\\\\x([0-9a-fA-F]{2})/e', "pack('H*',utf8_decode('\\1'))",$v); ?>
thierry.bo # netcourrier point com 30-Sep-2005 12:38
In response to fhoech (22-Sep-2005 11:55), I just tried a simultaneous test with the file UTF-8-test.txt using your regexp, 'j dot dittmer' (20-Sep-2005 06:30) regexp (message #56962), `php-note-2005` (17-Feb-2005 08:57) regexp in his message on `mb-detect-encoding` page (http://us3.php.net/manual/en/function.mb-detect-encoding.php#50087) who is using a regexp from the W3C (http://w3.org/International/questions/qa-forms-utf-8.html), and PHP mb_detect_encoding function.

Here are a summarize of the results :

201 lines are valid UTF8 strings using phpnote regexp
203 lines are valid UTF8 strings using j.dittmer regexp
200 lines are valid UTF8 strings using fhoech regexp
239 lines are valid  UTF8 strings using using mb_detect_encoding

Here are the lines with differences (left to right, phpnote, j.dittmer and fhoech) :

Line #70 : NOT UTF8|IS UTF8!|IS UTF8! :2.1.1 1 byte (U-00000000): ""
Line #79 : NOT UTF8|IS UTF8!|IS UTF8! :2.2.1 1 byte (U-0000007F): ""
Line #81 : IS UTF8!|IS UTF8!|NOT UTF8 :2.2.3 3 bytes (U-0000FFFF): "&#65535;" |
Line #267 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.1 U+FFFE = ef bf be = "&#65534;" |
Line #268 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.2 U+FFFF = ef bf bf = "&#65535;" |

Interesting is that you said that your regexp corrected j.dittmer regexp that failed on 5.3 section, but it my test I have the opposite result ?!

I ran this test on windows XP with PHP 4.3.11dev. Maybe these differences come from operating system, or PHP version.

For mb_detect_encoding I used the command :

mb_detect_encoding($line, 'UTF-8, ISO-8859-1, ASCII');
fhoech 22-Sep-2005 10:55
Sorry, I had a typo in my last comment. Corrected regexp:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbd]|
\\xee[\\x80-\\xbf]{2}|
\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$
fhoech 22-Sep-2005 10:12
JF Sebastian's regex is almost perfect as far as I'm concerned. I found one error (it failed section 5.3 "Other illegal code positions" from http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt) which I corrected as follows:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbc]|
\\xee[\\x80-\\xbf]{2}|
\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$

(Again, concatenate to one single line to make it work)
j dot dittmer at portrix dot net 20-Sep-2005 05:30
The regex in the last comment has some typos. This is a
syntactically valid one, don't know if it's correct though.
You've to concat the expression in one long line.

^(
[\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
[\xe0][\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
[\xed][\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
[\xf0][\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
[\xf4][\x80-\x8f][\x80-\xbf]{2}
)*$
rasmus at flajm dot se 19-Jan-2005 02:57
If you don't have the multibyte extension installed, here's a function to decode UTF-16 encoded strings. It support both BOM-less and BOM'ed strings, (big- and little-endian byte order.)

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 *
 * @param   string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode( $str ) {
    if( strlen($str) < 2 ) return $str;
    $bom_be = true;
    $c0 = ord($str{0});
    $c1 = ord($str{1});
    if( $c0 == 0xfe && $c1 == 0xff ) { $str = substr($str,2); }
    elseif( $c0 == 0xff && $c1 == 0xfe ) { $str = substr($str,2); $bom_be = false; }
    $len = strlen($str);
    $newstr = '';
    for($i=0;$i<$len;$i+=2) {
        if( $bom_be ) { $val = ord($str{$i})   << 4; $val += ord($str{$i+1}); }
        else {        $val = ord($str{$i+1}) << 4; $val += ord($str{$i}); }
        $newstr .= ($val == 0x228) ? "\n" : chr($val);
    }
    return $newstr;
}
?>
Aidan Kehoe <php-manual at parhasard dot net> 31-Jan-2004 05:35
The fastest way I've found to check if something is valid UTF-8 is
<?php
if (iconv('UTF-8', 'UTF-8', $input) != $input) {
        /* It's not UTF-8--for me, it's probably CP1252, the Windows
           version of Latin 1, with directed quotation marks and
           the Euro sign.  */
}
 ?>.
The iconv() C library fails if it's told a string is UTF-8 and it isn't; the PHP one doesn't, it just returns the conversion up to the point of failure, so you have to compare the result to the input to find out if the conversion succeeded.
gto at interia dot pl 25-Nov-2003 07:12
Correction to function converting utf82iso88592 and iso88592tutf8.
Janusz forgot about "&#324;", and "&#380;" exchanged from "&#378;" here and there.

GTo

function utf82iso88592($tekscik) {
     $tekscik = str_replace("\xC4\x85", "&#261;", $tekscik);
     $tekscik = str_replace("\xC4\x84", '&#260;', $tekscik);
     $tekscik = str_replace("\xC4\x87", '&#263;', $tekscik);
     $tekscik = str_replace("\xC4\x86", '&#262;', $tekscik);
     $tekscik = str_replace("\xC4\x99", '&#281;', $tekscik);
     $tekscik = str_replace("\xC4\x98", '&#280;', $tekscik);
     $tekscik = str_replace("\xC5\x82", '&#322;', $tekscik);
     $tekscik = str_replace("\xC5\x81", '&#321;', $tekscik);
     $tekscik = str_replace("\xC5\x84", '&#324;', $tekscik);
     $tekscik = str_replace("\xC5\x83", '&#323;', $tekscik);
     $tekscik = str_replace("\xC3\xB3", '?', $tekscik);
     $tekscik = str_replace("\xC3\x93", '?', $tekscik);
     $tekscik = str_replace("\xC5\x9B", '&#347;', $tekscik);
     $tekscik = str_replace("\xC5\x9A", '&#346;', $tekscik);
     $tekscik = str_replace("\xC5\xBC", '&#380;', $tekscik);
     $tekscik = str_replace("\xC5\xBB", '&#379;', $tekscik);
     $tekscik = str_replace("\xC5\xBA", '&#378;', $tekscik);
     $tekscik = str_replace("\xC5\xB9", '&#377;', $tekscik);
     return $tekscik;
} // utf82iso88592

function iso885922utf8($tekscik) {
     $tekscik = str_replace("&#261;", "\xC4\x85", $tekscik);
     $tekscik = str_replace('&#260;', "\xC4\x84", $tekscik);
     $tekscik = str_replace('&#263;', "\xC4\x87", $tekscik);
     $tekscik = str_replace('&#262;', "\xC4\x86", $tekscik);
     $tekscik = str_replace('&#281;', "\xC4\x99", $tekscik);
     $tekscik = str_replace('&#280;', "\xC4\x98", $tekscik);
     $tekscik = str_replace('&#322;', "\xC5\x82", $tekscik);
     $tekscik = str_replace('&#321;', "\xC5\x81", $tekscik);
     $tekscik = str_replace('&#324;', "\xC5\x84", $tekscik);
     $tekscik = str_replace('&#323;',"\xC5\x83", $tekscik);
     $tekscik = str_replace('?', "\xC3\xB3", $tekscik);
     $tekscik = str_replace('?', "\xC3\x93", $tekscik);
     $tekscik = str_replace('&#347;', "\xC5\x9B", $tekscik);
     $tekscik = str_replace('&#346;', "\xC5\x9A", $tekscik);
     $tekscik = str_replace('&#380;', "\xC5\xBC", $tekscik);
     $tekscik = str_replace('&#379;', "\xC5\xBB", $tekscik);
     $tekscik = str_replace('&#378;', "\xC5\xBA", $tekscik);
     $tekscik = str_replace('&#377;', "\xC5\xB9", $tekscik);
     return $tekscik;
} // iso885922utf8


将 ISO-8859-1 编码的字符串转换为 UTF-8 编码

  • ? utf8_decode
  • xml_error_string ?
  • PHP Manual
  • XML 解析器函数
  • 将 ISO-8859-1 编码的字符串转换为 UTF-8 编码

utf8_encode

(PHP 4, PHP 5, PHP 7, PHP 8)

utf8_encode — 将 ISO-8859-1 编码的字符串转换为 UTF-8 编码

描述

utf8_encode ( string $data ) : string

该函数将 data 字符串转换为 UTF-8 编码，并返回编码后的字符串。UTF-8 是一种用于将宽字符值转换为字节流的 Unicode 的标准机制。UTF-8 对于纯 ASCII 字符来说是透明的，且是自同步的（也就是说这使得程序能够得知字符从字节流的何处开始），并可被普通字符串比较函数用以比较等操作。PHP 可将 UTF-8 编码为多达四个字节的字符，如：

UTF-8 编码
字节（bytes） | 位（bits） | 表 示
1 | 7 | 0bbbbbbb
2 | 11 | 110bbbbb 10bbbbbb
3 | 16 | 1110bbbb 10bbbbbb 10bbbbbb
4 | 21 | 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb

每个 UTF-8 表示一个能被用以储存字符数据的位。

User Contributed Notes

rattones at gmail dot com 18-Feb-2021 03:08
/**
 * Convert all values of an array to utf8_encode
 * @author Marcelo Ratton
 * @version 1.0
 *
 * @param  array  $arr   array to encode values
 * @param  bool   $keys  true to convert keys to UTF8
 * @return array  same   array but with all values encoded to UTF8
 */
function arrayEncodeToUTF8(array $arr, bool $keys= false) : array {
  $ret= [];
  foreach ($arr as $k=>$v) {
    if (is_array($v)) {
      $ret[$k]= arrayEncodeToUTF8($v);
    } else {
      if ($keys) {
        $k= utf8_encode((string)$k);
      }
      $ret[$k]= utf8_encode((string)$v);
    }
  }

  return $ret;
}
Pini 16-Nov-2015 03:14
My version of utf8_encode_deep,
In case you need one that returns a value without changing the original.

        /**
        * Convert Anything To UTF-8
        * @param mixed $var The variable you want to convert.
        * @param boolean $deep Deep convertion? (*Default: TRUE).
        * @return mixed
        */
        function anything_to_utf8($var,$deep=TRUE){
            if(is_array($var)){
                foreach($var as $key => $value){
                    if($deep){
                        $var[$key] = anything_to_utf8($value,$deep);
                    }elseif(!is_array($value) && !is_object($value) && !mb_detect_encoding($value,'utf-8',true)){
                         $var[$key] = utf8_encode($var);
                    }
                }
                return $var;
            }elseif(is_object($var)){
                foreach($var as $key => $value){
                    if($deep){
                        $var->$key = anything_to_utf8($value,$deep);
                    }elseif(!is_array($value) && !is_object($value) && !mb_detect_encoding($value,'utf-8',true)){
                         $var->$key = utf8_encode($var);
                    }
                }
                return $var;
            }else{
                return (!mb_detect_encoding($var,'utf-8',true))?utf8_encode($var):$var;
            }
        }
a dot rueedlinger at gmail dot com 22-Jun-2013 01:06
If you need a function which converts a string array into a utf8 encoded string array then this function might be useful for you:

<?php
function utf8_string_array_encode(&$array){
    $func = function(&$value,&$key){
        if(is_string($value)){
            $value = utf8_encode($value);
        }
        if(is_string($key)){
            $key = utf8_encode($key);
        }
        if(is_array($value)){
            utf8_string_array_encode($value);
        }
    };
    array_walk($array,$func);
    return $array;
}
?>
Oscar Broman 06-Sep-2012 11:15
Walk through nested arrays/objects and utf8 encode all strings.

<?php
// Usage
class Foo {
    public $somevar = 'whoop whoop';
}

$structure = array(
    'object' => (object) array(
        'entry' => 'hello w?rld',
        'another_array' => array(
            'string',
            1234,
            'another string'
        )
    ),
    'string' => 'foo',
    'foo_object' => new Foo
);

utf8_encode_deep($structure);

// $structure is now utf8 encoded
print_r($structure);

// The function
function utf8_encode_deep(&$input) {
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else if (is_array($input)) {
        foreach ($input as &$value) {
            utf8_encode_deep($value);
        }

        unset($value);
    } else if (is_object($input)) {
        $vars = array_keys(get_object_vars($input));

        foreach ($vars as $var) {
            utf8_encode_deep($input->$var);
        }
    }
}
?>
deceze at gmail dot com 14-Jul-2011 06:51
Please note that utf8_encode only converts a string encoded in ISO-8859-1 to UTF-8. A more appropriate name for it would be "iso88591_to_utf8". If your text is not encoded in  ISO-8859-1, you do not need this function. If your text is already in UTF-8, you do not need this function. In fact, applying this function to text that is not encoded in ISO-8859-1 will most likely simply garble that text.

If you need to convert text from any encoding to any other encoding, look at iconv() instead.
powtac 4t gmx d0t de 11-Feb-2011 01:11
I tried a lot of things, but this seems to be the final fail save method to convert any string to proper UTF-8.

<?php
function _convert($content) {
    if(!mb_check_encoding($content, 'UTF-8')
        OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {

        $content = mb_convert_encoding($content, 'UTF-8');

        if (mb_check_encoding($content, 'UTF-8')) {
            // log('Converted to UTF-8');
        } else {
            // log('Could not converted to UTF-8');
        }
    }
    return $content;
}
?>
Yumok 15-Sep-2010 04:26
Avoiding use of preg_match to detect if utf8_encode is needed:

<?php
                $string = $string_input; // avoid being destructive

                $string = preg_replace("#[\x09\x0A\x0D\x20-\x7E]#"        ,"",$string);         // ASCII
                $string = preg_replace("#[\xC2-\xDF][\x80-\xBF]#"            ,"",$string);             // non-overlong 2-byte
                $string = preg_replace("#\xE0[\xA0-\xBF][\x80-\xBF]#"    ,"",$string);     // excluding overlongs
                $string = preg_replace("#[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}#","",$string);     // straight 3-byte
                $string = preg_replace("#\xED[\x80-\x9F][\x80-\xBF]#"    ,"",$string);     // excluding surrogates
                $string = preg_replace("#\xF0[\x90-\xBF][\x80-\xBF]{2}#","",$string);     // planes 1-3
                $string = preg_replace("#[\xF1-\xF3][\x80-\xBF]{3}#"    ,"",$string);     //  planes 4-15
                $string = preg_replace("#\xF4[\x80-\x8F][\x80-\xBF]{2}#","",$string);     // plane 16

                $rc = ($string == ""?true:false);
?>
rogeriogirodo at gmail dot com 19-Mar-2009 04:24
This function may be useful do encode array keys and values [and checks first to see if it's already in UTF format]:

<?php
public static function to_utf8($in)
{
        if (is_array($in)) {
            foreach ($in as $key => $value) {
                $out[to_utf8($key)] = to_utf8($value);
            }
        } elseif(is_string($in)) {
            if(mb_detect_encoding($in) != "UTF-8")
                return utf8_encode($in);
            else
                return $in;
        } else {
            return $in;
        }
        return $out;
}
?>

Hope this may help.

[NOTE BY danbrown AT php DOT net: Original function written by (cmyk777 AT gmail DOT com) on 28-JAN-09.]
www.tricinty.com 11-Jun-2008 03:43
<?php
    /**
    * Encodes an ISO-8859-1 mixed variable to UTF-8 (PHP 4, PHP 5 compat)
    * @param    mixed    $input An array, associative or simple
    * @param    boolean  $encode_keys optional
    * @return    mixed     ( utf-8 encoded $input)
    */

    function utf8_encode_mix($input, $encode_keys=false)
    {
        if(is_array($input))
        {
            $result = array();
            foreach($input as $k => $v)
            {
                $key = ($encode_keys)? utf8_encode($k) : $k;
                $result[$key] = utf8_encode_mix( $v, $encode_keys);
            }
        }
        else
        {
            $result = utf8_encode($input);
        }

        return $result;
    }
?>
emze at donazga dot net 17-Dec-2006 09:42
/*
Every function seen so far is incomplete or resource consumpting. Here are two -- integer 2 utf sequence (i3u) and utf sequence to integer (u3i). Below is a code snippet that checks well behavior at the range boundaries.

Someday they might be hardcoded into PHP...
*/

function i3u($i) { // returns UCS-16 or UCS-32 to UTF-8 from an integer
  $i=(int)$i; // integer?
  if ($i<0) return false; // positive?
  if ($i<=0x7f) return chr($i); // range 0
  if (($i & 0x7fffffff) <> $i) return '?'; // 31 bit?
  if ($i<=0x7ff) return chr(0xc0 | ($i >> 6)) . chr(0x80 | ($i & 0x3f));
  if ($i<=0xffff) return chr(0xe0 | ($i >> 12)) . chr(0x80 | ($i >> 6) & 0x3f)
      . chr(0x80  | $i & 0x3f);
  if ($i<=0x1fffff) return chr(0xf0 | ($i >> 18)) . chr(0x80 | ($i >> 12) & 0x3f)
      . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  if ($i<=0x3ffffff) return chr(0xf8 | ($i >> 24)) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  return chr(0xfc | ($i >> 30)) . chr(0x80 | ($i >> 24) & 0x3f) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
}

function u3i($s,$strict=1) { // returns integer on valid UTF-8 seq, NULL on empty, else FALSE
  // NOT strict: takes only DATA bits, present or not; strict: length and bits checking
  if ($s=='') return NULL;
  $l=strlen($s); $o=ord($s{0});
  if ($o <= 0x7f && $l==1) return $o;
  if ($l>6 && $strict) return false;
  if ($strict) for ($i=1;$i<$l;$i++) if (ord($s{$i}) > 0xbf || ord($s{$i})< 0x80) return false;
  if ($o < 0xc2) return false; // no-go even if strict=0
  if ($o <= 0xdf && ($l=2 && $strict)) return (($o & 0x1f) << 6 | (ord($s{1}) & 0x3f));
  if ($o <= 0xef && ($l=3 && $strict)) return (($o & 0x0f) << 12 | (ord($s{1}) & 0x3f) << 6
     |  (ord($s{2}) & 0x3f));
  if ($o <= 0xf7 && ($l=4 && $strict)) return (($o & 0x07) << 18 | (ord($s{1}) & 0x3f) << 12
     | (ord($s{2}) & 0x3f) << 6 |  (ord($s{3}) & 0x3f));
  if ($o <= 0xfb && ($l=5 && $strict)) return (($o & 0x03) << 24 | (ord($s{1}) & 0x3f) << 18
     | (ord($s{2}) & 0x3f) << 12 | (ord($s{3}) & 0x3f) << 6 |  (ord($s{4}) & 0x3f));
  if ($o <= 0xfd && ($l=6 && $strict)) return (($o & 0x01) << 30 | (ord($s{1}) & 0x3f) << 24
     | (ord($s{2}) & 0x3f) << 18 | (ord($s{3}) & 0x3f) << 12
     | (ord($s{4}) & 0x3f) << 6 |  (ord($s{5}) & 0x3f));
  return false;
}

// boundary behavior checking
$do=array(0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff);
foreach ($do as $ii) for ($i=$ii;$i<=$ii+1; $i++) {
  $o=i3u($i);
  for ($j=0;$j<strlen($o);$j++) print "O[$j]=" . sprintf('%08b',ord($o{$j})) . ", ";
  print "c=$i, o=[$o].\n";
  print "Back: [$o] => [" . u3i($o) . "]\n";
}
rocketman 16-Mar-2006 04:46
If you are looking for a function to replace special characters with the hex-utf-8 value (e.g. für Webservice-Security/WSS4J compliancy) you might use this:

$textstart = "Gr??e";
$utf8 ='';
$max = strlen($txt);

for ($i = 0; $i < $max; $i++) {

if ($txt{i} == "&"){
$neu = "&x26;";
}
elseif ((ord($txt{$i}) < 32) or (ord($txt{$i}) > 127)){
$neu = urlencode(utf8_encode($txt{$i}));
$neu = preg_replace('#\%(..)\%(..)\%(..)#','&#x\1;&#x\2;&#x\3;',$neu);
$neu = preg_replace('#\%(..)\%(..)#','&#x\1;&#x\2;',$neu);
$neu = preg_replace('#\%(..)#','&#x\1;',$neu);
}
else {
$neu = $txt{$i};
}

$utf8 .= $neu;
} // for $i

$textnew = $utf8;

In this example $textnew will be "Gr&#xC3;&#xB6;&#xC3;&#x9F;e"
mailing at jcn50 dot com 20-Jan-2006 10:40
I recommend using this alternative for every language:

$new=mb_convert_encoding($s,"UTF-8","auto");

Don't forget to set all your pages to "utf-8" encoding, otherwise just use HTML entities.

jcn50.
04-Nov-2005 02:34
// Reads a file story.txt ascii (as typed on keyboard)
// converts it to Georgian character using utf8 encoding
// if I am correct(?) just as it should be when typed on Georgian computer
// it outputs it as an html file
//
// http://www.comweb.nl/keys_to_georgian.html
// http://www.comweb.nl/keys_to_georgian.php
// http://www.comweb.nl/story.txt

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<HTML>
<HEAD>
<TITLE>keys to unicode code</TITLE>

// this meta tag is needed
<meta http-equiv="Content-Type" content="text/html;CHARSET=gb2312" >

// note the sylfean font seems to be standard installed on Windows XP
// It supports Georgian

<style TYPE="text/css">
<!--
body {font-family:sylfaen; }
-->
</style>
</HEAD>

<BODY>

<?
$eng=array(97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,87,82,84,83,
67,74,90);
$geo=array(4304,4305,4330,4307,4308,4324,4306,4336,4312,4335,4313,
4314,4315,4316,4317,4318,4325,4320,4321,4322,4323,4309,
4332,4334,4327,4310,4333,4326,4311,4328,4329,4319,4331,
91,93,59,39,44,46,96);

$fc=file("story.txt");
foreach($fc as $line)
{
   $spacestart=1;
   for ($i=0; $i<strlen($line); $i+=1)
   {
      $character=ord(substr($line,$i,1));
      $found=0;
      for ($k=0; $k<count($eng); $k+=1)
      {
         if ($eng[$k]==$character)
         {
             print code2utf( $geo[$k] );
             $found=1;
         }
      }
      if ($found==0)
      {
         if ($character==126 || $character==32 || $character==10 || $character==9)
         {
            if ($character==9)  { print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; }
            if ($character==10) { print "<BR>\n"; }
            if ($character==32)
            {
               if ($spacestart==1) {print '&nbsp;'; } else { print " "; }
            }
            if ($character==126){ print "~";      }
         } else
         {
            print substr($line,$i,1);
         }
      }
      if ($character!=32) { $spacestart=0; }
   }
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
*/
function code2utf($num)
{
   if($num<128)return chr($num);
   if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
   if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
   if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
   return '';
}
?>

</BODY>
</HTML>
Janci 04-Nov-2005 04:00
I was searching for a function similar to Javascript's unescape(). In most cases it is OK to use url_decode() function but not if you've got UTF characters in the strings. They are converted into %uXXXX entities that url_decode() cannot handle.
I googled the net and found a function which actualy converts these entities into HTML entities (&#xxx;) that your browser can show correctly. If you're OK with that, the function can be found here: http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps

But it was not OK with me because I needed a string in my charset to make some comparations and other stuff. So I have modified the above function and in conjuction with code2utf() function mentioned in some other note here, I have managed to achieve my goal:

<?php
/**
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8).
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
 *
 * @param string $source escaped with Javascript's escape() function
 * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
 * @return string
 */
function unescape($source, $iconv_to = 'UTF-8') {
    $decodedStr = '';
    $pos = 0;
    $len = strlen ($source);
    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == '%') {
            $pos++;
            $charAt = substr ($source, $pos, 1);
            if ($charAt == 'u') {
                // we got a unicode character
                $pos++;
                $unicodeHexVal = substr ($source, $pos, 4);
                $unicode = hexdec ($unicodeHexVal);
                $decodedStr .= code2utf($unicode);
                $pos += 4;
            }
            else {
                // we have an escaped ascii character
                $hexVal = substr ($source, $pos, 2);
                $decodedStr .= chr (hexdec ($hexVal));
                $pos += 2;
            }
        }
        else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }

    if ($iconv_to != "UTF-8") {
        $decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
    }

    return $decodedStr;
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
 */
function code2utf($num){
    if($num<128)return chr($num);
    if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
    if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
    if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
    return '';
}
?>
suttichai at ceforce dot com 28-May-2005 12:26
This function I use convert Thai font (iso-8859-11) to UTF-8. For my case, It work properly. Please try to use this function if you have a problem to convert charset iso-8859-11 to UTF-8.

function iso8859_11toUTF8($string) {

     if ( ! ereg("[\241-\377]", $string) )
         return $string;

     $iso8859_11 = array(
"\xa1" => "\xe0\xb8\x81",
"\xa2" => "\xe0\xb8\x82",
"\xa3" => "\xe0\xb8\x83",
"\xa4" => "\xe0\xb8\x84",
"\xa5" => "\xe0\xb8\x85",
"\xa6" => "\xe0\xb8\x86",
"\xa7" => "\xe0\xb8\x87",
"\xa8" => "\xe0\xb8\x88",
"\xa9" => "\xe0\xb8\x89",
"\xaa" => "\xe0\xb8\x8a",
"\xab" => "\xe0\xb8\x8b",
"\xac" => "\xe0\xb8\x8c",
"\xad" => "\xe0\xb8\x8d",
"\xae" => "\xe0\xb8\x8e",
"\xaf" => "\xe0\xb8\x8f",
"\xb0" => "\xe0\xb8\x90",
"\xb1" => "\xe0\xb8\x91",
"\xb2" => "\xe0\xb8\x92",
"\xb3" => "\xe0\xb8\x93",
"\xb4" => "\xe0\xb8\x94",
"\xb5" => "\xe0\xb8\x95",
"\xb6" => "\xe0\xb8\x96",
"\xb7" => "\xe0\xb8\x97",
"\xb8" => "\xe0\xb8\x98",
"\xb9" => "\xe0\xb8\x99",
"\xba" => "\xe0\xb8\x9a",
"\xbb" => "\xe0\xb8\x9b",
"\xbc" => "\xe0\xb8\x9c",
"\xbd" => "\xe0\xb8\x9d",
"\xbe" => "\xe0\xb8\x9e",
"\xbf" => "\xe0\xb8\x9f",
"\xc0" => "\xe0\xb8\xa0",
"\xc1" => "\xe0\xb8\xa1",
"\xc2" => "\xe0\xb8\xa2",
"\xc3" => "\xe0\xb8\xa3",
"\xc4" => "\xe0\xb8\xa4",
"\xc5" => "\xe0\xb8\xa5",
"\xc6" => "\xe0\xb8\xa6",
"\xc7" => "\xe0\xb8\xa7",
"\xc8" => "\xe0\xb8\xa8",
"\xc9" => "\xe0\xb8\xa9",
"\xca" => "\xe0\xb8\xaa",
"\xcb" => "\xe0\xb8\xab",
"\xcc" => "\xe0\xb8\xac",
"\xcd" => "\xe0\xb8\xad",
"\xce" => "\xe0\xb8\xae",
"\xcf" => "\xe0\xb8\xaf",
"\xd0" => "\xe0\xb8\xb0",
"\xd1" => "\xe0\xb8\xb1",
"\xd2" => "\xe0\xb8\xb2",
"\xd3" => "\xe0\xb8\xb3",
"\xd4" => "\xe0\xb8\xb4",
"\xd5" => "\xe0\xb8\xb5",
"\xd6" => "\xe0\xb8\xb6",
"\xd7" => "\xe0\xb8\xb7",
"\xd8" => "\xe0\xb8\xb8",
"\xd9" => "\xe0\xb8\xb9",
"\xda" => "\xe0\xb8\xba",
"\xdf" => "\xe0\xb8\xbf",
"\xe0" => "\xe0\xb9\x80",
"\xe1" => "\xe0\xb9\x81",
"\xe2" => "\xe0\xb9\x82",
"\xe3" => "\xe0\xb9\x83",
"\xe4" => "\xe0\xb9\x84",
"\xe5" => "\xe0\xb9\x85",
"\xe6" => "\xe0\xb9\x86",
"\xe7" => "\xe0\xb9\x87",
"\xe8" => "\xe0\xb9\x88",
"\xe9" => "\xe0\xb9\x89",
"\xea" => "\xe0\xb9\x8a",
"\xeb" => "\xe0\xb9\x8b",
"\xec" => "\xe0\xb9\x8c",
"\xed" => "\xe0\xb9\x8d",
"\xee" => "\xe0\xb9\x8e",
"\xef" => "\xe0\xb9\x8f",
"\xf0" => "\xe0\xb9\x90",
"\xf1" => "\xe0\xb9\x91",
"\xf2" => "\xe0\xb9\x92",
"\xf3" => "\xe0\xb9\x93",
"\xf4" => "\xe0\xb9\x94",
"\xf5" => "\xe0\xb9\x95",
"\xf6" => "\xe0\xb9\x96",
"\xf7" => "\xe0\xb9\x97",
"\xf8" => "\xe0\xb9\x98",
"\xf9" => "\xe0\xb9\x99",
"\xfa" => "\xe0\xb9\x9a",
"\xfb" => "\xe0\xb9\x9b"
 );

     $string=strtr($string,$iso8859_11);
     return $string;
 }

Suttichai Mesaard-www.ceforce.com
bisqwit at iki dot fi 20-May-2005 01:15
For reference, it may be insightful to point out that:
  utf8_encode($s)
is actually identical to:
  recode_string('latin1..utf8', $s)
and:
  iconv('iso-8859-1', 'utf-8', $s)
That is, utf8_encode is a specialized case of character set conversions.

If your string to be converted to utf-8 is something other than iso-8859-1 (such as iso-8859-2 (Polish/Croatian)), you should use recode_string() or iconv() instead rather than trying to devise complex str_replace statements.
JF Sebastian 09-Apr-2005 03:54
The following Perl regular expression tests if a string is well-formed Unicode UTF-8 (Broken up after each | since long lines are not permitted here. Please join as a single line, no spaces, before use.):

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
\xe0[\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
\xed[\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
f0[\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
\xf4[\x80-\x8f][\x80-\xbf]{2})*$

NOTE: This strictly follows the Unicode standard 4.0, as described in chapter 3.9, table 3-6, "Well-formed UTF-8 byte sequences" ( http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G31703 ).

ISO-10646, a super-set of Unicode, uses UTF-8 (there called "UCS", see http://www.unicode.org/faq/utf_bom.html#1 ) in a relaxed variant that supports a 31-bit space encoded into up to six bytes instead of Unicode's 21 bits in up to four bytes. To check for ISO-10646 UTF-8, use the following Perl regular expression (again, broken up, see above):

^([\x00-\x7f]|
[\xc0-\xdf][\x80-\xbf]|
[\xe0-\xef][\x80-\xbf]{2}|
[\xf0-\xf7][\x80-\xbf]{3}|
[\xf8-\xfb][\x80-\xbf]{4}|
[\xfc-\xfd][\x80-\xbf]{5})*$

The following function may be used with above expressions for a quick UTF-8 test, e.g. to distinguish ISO-8859-1-data from UTF-8-data if submitted from a <form accept-charset="utf-8,iso-8859-1" method=..>.

function is_utf8($string) {
   return (preg_match('/[insert regular expression here]/', $string) === 1);
}
hrpeters (at) gmx (dot) net 13-Dec-2004 10:46
// Validate Unicode UTF-8 Version 4
// This function takes as reference the table 3.6 found at http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf
// It also flags overlong bytes as error

function is_validUTF8($str)
{
    // values of -1 represent disalloweded values for the first bytes in current UTF-8
    static $trailing_bytes = array (
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    );

    $ups = unpack('C*', $str);
    if (!($aCnt = count($ups))) return true; // Empty string *is* valid UTF-8
    for ($i = 1; $i <= $aCnt;)
    {
        if (!($tbytes = $trailing_bytes[($b1 = $ups[$i++])])) continue;
        if ($tbytes == -1) return false;

        $first = true;
        while ($tbytes > 0 && $i <= $aCnt)
        {
            $cbyte = $ups[$i++];
            if (($cbyte & 0xC0) != 0x80) return false;

            if ($first)
            {
                switch ($b1)
                {
                    case 0xE0:
                        if ($cbyte < 0xA0) return false;
                        break;
                    case 0xED:
                        if ($cbyte > 0x9F) return false;
                        break;
                    case 0xF0:
                        if ($cbyte < 0x90) return false;
                        break;
                    case 0xF4:
                        if ($cbyte > 0x8F) return false;
                        break;
                    default:
                        break;
                }
                $first = false;
            }
            $tbytes--;
        }
        if ($tbytes) return false; // incomplete sequence at EOS
    }
    return true;
}
Mark AT modernbill DOT com 09-Nov-2004 11:56
If you haven't guessed already: If the UTF-8 character has no representation in the ISO-8859-1 codepage, a ? will be returned. You might want to wrap a function around this to make sure you aren't saving a bunch of ???? into your database.
Aidan Kehoe <php-manual at parhasard dot net> 30-Aug-2004 07:05
Here's some code that addresses the issue that Steven describes in the previous comment;

<?php

/* This structure encodes the difference between ISO-8859-1 and Windows-1252,
   as a map from the UTF-8 encoding of some ISO-8859-1 control characters to
   the UTF-8 encoding of the non-control characters that Windows-1252 places
   at the equivalent code points. */

$cp1252_map = array(
    "\xc2\x80" => "\xe2\x82\xac", /* EURO SIGN */
    "\xc2\x82" => "\xe2\x80\x9a", /* SINGLE LOW-9 QUOTATION MARK */
    "\xc2\x83" => "\xc6\x92",     /* LATIN SMALL LETTER F WITH HOOK */
    "\xc2\x84" => "\xe2\x80\x9e", /* DOUBLE LOW-9 QUOTATION MARK */
    "\xc2\x85" => "\xe2\x80\xa6", /* HORIZONTAL ELLIPSIS */
    "\xc2\x86" => "\xe2\x80\xa0", /* DAGGER */
    "\xc2\x87" => "\xe2\x80\xa1", /* DOUBLE DAGGER */
    "\xc2\x88" => "\xcb\x86",     /* MODIFIER LETTER CIRCUMFLEX ACCENT */
    "\xc2\x89" => "\xe2\x80\xb0", /* PER MILLE SIGN */
    "\xc2\x8a" => "\xc5\xa0",     /* LATIN CAPITAL LETTER S WITH CARON */
    "\xc2\x8b" => "\xe2\x80\xb9", /* SINGLE LEFT-POINTING ANGLE QUOTATION */
    "\xc2\x8c" => "\xc5\x92",     /* LATIN CAPITAL LIGATURE OE */
    "\xc2\x8e" => "\xc5\xbd",     /* LATIN CAPITAL LETTER Z WITH CARON */
    "\xc2\x91" => "\xe2\x80\x98", /* LEFT SINGLE QUOTATION MARK */
    "\xc2\x92" => "\xe2\x80\x99", /* RIGHT SINGLE QUOTATION MARK */
    "\xc2\x93" => "\xe2\x80\x9c", /* LEFT DOUBLE QUOTATION MARK */
    "\xc2\x94" => "\xe2\x80\x9d", /* RIGHT DOUBLE QUOTATION MARK */
    "\xc2\x95" => "\xe2\x80\xa2", /* BULLET */
    "\xc2\x96" => "\xe2\x80\x93", /* EN DASH */
    "\xc2\x97" => "\xe2\x80\x94", /* EM DASH */

    "\xc2\x98" => "\xcb\x9c",     /* SMALL TILDE */
    "\xc2\x99" => "\xe2\x84\xa2", /* TRADE MARK SIGN */
    "\xc2\x9a" => "\xc5\xa1",     /* LATIN SMALL LETTER S WITH CARON */
    "\xc2\x9b" => "\xe2\x80\xba", /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
    "\xc2\x9c" => "\xc5\x93",     /* LATIN SMALL LIGATURE OE */
    "\xc2\x9e" => "\xc5\xbe",     /* LATIN SMALL LETTER Z WITH CARON */
    "\xc2\x9f" => "\xc5\xb8"      /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
);

function cp1252_to_utf8($str) {
        global $cp1252_map;
        return  strtr(utf8_encode($str), $cp1252_map);
}

?>
Net Raven 24-Jun-2004 12:58
I often need to convert multi language text sent to me for use in websites and other apps into UTF8 encoded so I can insert it into source code and databases.

I knocked up a small web page with its charset set to UTF8 then set it up so I can paste from the original doc (eg word or excel) and have the page return the UTF8 encoded version.

Of course the browser will convert the unicode to UTF8 for you as part of the submit (I use IE5 or better for this) then all you have to do in the PHP is encode the UTF8 so the browser will show it in its raw form.

Its a bit bulky but I just convert ALL character to html numbered entities (brute force and ignorance does it again.)

I've used this to encode everything from Hebrew to Japanese without problems

<?
header("Content-Type: text/plain; CHARSET=gb2312");
$code = (get_magic_quotes_gpc())?stripslashes($GLOBALS[code]):$GLOBALS[code];
?>
<html>
<head>
    <title>UTF8 ENCODER PAGE</title>
    <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">
</head>
<body>
<form method=post action="?seed=<?=time()?>">
    Original Unicode<br />
    <textarea name="code" cols="80" rows="10"><?=$code?></textarea><br />
    Encoded UTF8<br />
    <textarea name="encd" cols="80" rows="10"><?
        for ($i = 0; $i < strlen($code); $i++) {
            echo '&#'.ord(substr($code,$i,1));
        }
    ?></textarea><br />
    <input type="submit" value="encode">
</form>
</body>
</html>
Karen 01-Oct-2003 12:33
Re the previous post about converting GB2312 code to Unicode code which displayed the following function:

<?
// Program by sadly (www.phpx.com)

function gb2unicode($gb)
{
   if(!trim($gb))
    return $gb;
   $filename="gb2312.txt";
   $tmp=file($filename);
   $codetable=array();
   while(list($key,$value)=each($tmp))
    $codetable[hexdec(substr($value,0,6))]=substr($value,9,4);
   $utf="";
   while($gb)
    {
      if (ord(substr($gb,0,1))>127)
     {
        $this=substr($gb,0,2);
        $gb=substr($gb,2,strlen($gb));
        $utf.="&#x".$codetable[hexdec(bin2hex($this))-0x8080].";";
      }
     else
     {
      $gb=substr($gb,1,strlen($gb));
      $utf.=substr($gb,0,1);
     }
     }
  return $utf;
}
?>

I found that a small change was needed in the code to properly handle latin characters embedded in the middle of gb2312 text, as when the text includes a URL or email address. Just reverse the two lines in the part of the statement above that handles ord vals !>127.

Change:

$gb=substr($gb,1,strlen($gb));
$utf.=substr($gb,0,1);

to:

$utf.=substr($gb,0,1);
$gb=substr($gb,1,strlen($gb));

In the original function, the first latin chacter was dropped and it was not converting the first non-latin character after the latin text (everything was shifted one character too far to the right). Reversing those two lines makes it work correctly in every example I have tried.

Also, the source of the gb2312.txt file needed for this to work has changed. You can find it a couple places:

http://tcl.apache.org/sources/tcl/tools/encoding/gb2312.txt
ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/GB/GB2312.TXT
ronen at greyzone dot com 07-Mar-2002 12:01
The following function will utf-8 encode unicode entities &#nnn(nn); with n={0..9}

/**
* takes a string of unicode entities and converts it to a utf-8 encoded string
* each unicode entitiy has the form &#nnn(nn); n={0..9} and can be displayed by utf-8 supporting
* browsers.  Ascii will not be modified.
* @param $source string of unicode entities [STRING]
* @return a utf-8 encoded string [STRING]
* @access public
*/
function utf8Encode ($source) {
    $utf8Str = '';
    $entityArray = explode ("&#", $source);
    $size = count ($entityArray);
    for ($i = 0; $i < $size; $i++) {
        $subStr = $entityArray[$i];
        $nonEntity = strstr ($subStr, ';');
        if ($nonEntity !== false) {
            $unicode = intval (substr ($subStr, 0, (strpos ($subStr, ';') + 1)));
            // determine how many chars are needed to reprsent this unicode char
            if ($unicode < 128) {
                $utf8Substring = chr ($unicode);
            }
            else if ($unicode >= 128 && $unicode < 2048) {
                $binVal = str_pad (decbin ($unicode), 11, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 5);
                $binPart2 = substr ($binVal, 5);

                $char1 = chr (192 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $utf8Substring = $char1 . $char2;
            }
            else if ($unicode >= 2048 && $unicode < 65536) {
                $binVal = str_pad (decbin ($unicode), 16, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 4);
                $binPart2 = substr ($binVal, 4, 6);
                $binPart3 = substr ($binVal, 10);

                $char1 = chr (224 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $utf8Substring = $char1 . $char2 . $char3;
            }
            else {
                $binVal = str_pad (decbin ($unicode), 21, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 3);
                $binPart2 = substr ($binVal, 3, 6);
                $binPart3 = substr ($binVal, 9, 6);
                $binPart4 = substr ($binVal, 15);

                $char1 = chr (240 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $char4 = chr (128 + bindec ($binPart4));
                $utf8Substring = $char1 . $char2 . $char3 . $char4;
            }

            if (strlen ($nonEntity) > 1)
                $nonEntity = substr ($nonEntity, 1); // chop the first char (';')
            else
                $nonEntity = '';

            $utf8Str .= $utf8Substring . $nonEntity;
        }
        else {
            $utf8Str .= $subStr;
        }
    }

    return $utf8Str;
}

Ronen.


获取 XML 解析器的错误字符串

  • ? utf8_encode
  • xml_get_current_byte_index ?
  • PHP Manual
  • XML 解析器函数
  • 获取 XML 解析器的错误字符串

xml_error_string

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_error_string — 获取 XML 解析器的错误字符串

说明

xml_error_string ( int $code ) : string

根据给定的 code 获得 XML 解析器错误字符串。

参数

code

由 xml_get_error_code() 返回的错误代码。

返回值

返回与 code 描述的错误代码参数对应的文本描述字符串，若没有与之对应的描述，则返回 false。

参见

  • xml_get_error_code() - 获取 XML 解析器错误代码

User Contributed Notes

greg at getnetez dot com 23-Aug-2012 07:27
Two notes in one.

Here is the combination of xml_get_error_code() and xml_error_string() to get the error printout as an echo response

Also, I tested before and after xml_parser_free() -- as expected, the error is indeed cleared with the free() so check your error before calling xml_parser_free()

Pushing a deadline or I would add in sample faulted xml for full p.o.c.

somebody else want to step up for that??

G

<?php
$p = xml_parser_create();
xml_parse_into_struct($p, $data, $vals, $index);
//This call prints error
echo 'ERROR if any '.xml_error_string(xml_get_error_code($p));
xml_parser_free($p);
echo "Index array\\n";
print_r($index);
echo "\\nVals array\\n";
print_r($vals);
//No Error left here to be printed
echo 'ERROR if any '.xml_error_string(xml_get_error_code($p));
exit;
?>


获取 XML 解析器的当前字节索引

  • ? xml_error_string
  • xml_get_current_column_number ?
  • PHP Manual
  • XML 解析器函数
  • 获取 XML 解析器的当前字节索引

xml_get_current_byte_index

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_current_byte_index — 获取 XML 解析器的当前字节索引

说明

xml_get_current_byte_index ( resource $parser ) : int

获取指定的 XML 解析器的当前字节索引（current byte index）。

参数

parser

指向要取得字节索引的 XML 解析器的引用。

返回值

如果 parser 没有指向一个合法的解析器，该函数将返回 false，否则将返回解析器当前在其数据缓冲区中的字节索引（起始值为 0）。

注释

Warning

该函数将返回根据UTF-8编码的文本的字节索引，而不论输入是否是其他的编码。

参见

  • xml_get_current_column_index()
  • xml_get_current_line_index()

User Contributed Notes

turan dot yuksel at tcmb dot gov dot tr 20-Sep-2005 03:38
The outcome of this function is heavily dependent on the parser implementation used. For example, at the point where the start_element_ callback is called, libxml2 parser consumes the entire element name and attributes, however expat does not.


获取 XML 解析器的当前列号

  • ? xml_get_current_byte_index
  • xml_get_current_line_number ?
  • PHP Manual
  • XML 解析器函数
  • 获取 XML 解析器的当前列号

xml_get_current_column_number

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_current_column_number — 获取 XML 解析器的当前列号

说明

xml_get_current_column_number ( resource $parser ) : int

获得指定 XML 解析器当前的列号。

参数

parser

一个指向要获取列号的 XML 解析器的指针。

返回值

如果 parser 参数没有指向一个合法的解析器，该函数将返回 false，否则将返回指定解析器所在行（由函数 xml_get_current_line_number() 给定）的当前列号。

参见

  • xml_get_current_byte_index() - 获取 XML 解析器的当前字节索引
  • xml_get_current_line_index()

User Contributed Notes

shaun at 5810 dot com 05-Jul-2003 09:04
Column numbers apparently start at 0. So you may want to add 1.
javajohn at gulfbridge.net 22-Mar-2003 10:03
"Column number" refers to the current character position within the current line of the XML document.


获取 XML 解析器的当前行号

  • ? xml_get_current_column_number
  • xml_get_error_code ?
  • PHP Manual
  • XML 解析器函数
  • 获取 XML 解析器的当前行号

xml_get_current_line_number

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_current_line_number — 获取 XML 解析器的当前行号

说明

xml_get_current_line_number ( resource $parser ) : int

获取指定 XML 解析器当前的行号。

参数

parser

一个指向要获取当前行号的 XML 解析器的指针。

返回值

如果 parser 参数没有指向一个合法的解析器，该函数将返回 false，否则将返回指定解析器在其缓存中的当前行号。

参见

  • xml_get_current_column_index()
  • xml_get_current_byte_index() - 获取 XML 解析器的当前字节索引

User Contributed Notes

There are no user contributed notes for this page.


获取 XML 解析器错误代码

  • ? xml_get_current_line_number
  • xml_parse_into_struct ?
  • PHP Manual
  • XML 解析器函数
  • 获取 XML 解析器错误代码

xml_get_error_code

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_error_code — 获取 XML 解析器错误代码

说明

xml_get_error_code ( resource $parser ) : int

获取 XML 解析器错误代码。

参数

parser

一个指向要返回错误代码的 XML 解析器的指针

返回值

如果 parser 参数没有指向一个合法的解析器，该函数将返回 false，否则将返回错误代码列表中的一个错误代码。

参见

  • xml_error_string() - 获取 XML 解析器的错误字符串

User Contributed Notes

There are no user contributed notes for this page.


将 XML 数据解析到数组中

  • ? xml_get_error_code
  • xml_parse ?
  • PHP Manual
  • XML 解析器函数
  • 将 XML 数据解析到数组中

xml_parse_into_struct

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parse_into_struct — 将 XML 数据解析到数组中

说明

xml_parse_into_struct ( resource $parser , string $data , array &$values , array &$index = ? ) : int

该函数将 XML 文件解析到两个对应的数组中，index 参数含有指向 values 数组中对应值的指针。最后两个数组参数可由指针传递给函数。

Note:

xml_parse_into_struct() 失败返回 0，成功返回 1。这和 false 与 true 不同，使用例如 === 的运算符时要注意。

以下范例显示了由该函数生成的数组的内部结构。我们简单地将一个 note 嵌入到一个 para 标记中，解析后我们可以打印出生成的数组的结构：

Example #1 xml_parse_into_struct() 示例

<?php
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);
?>

运行以上代码，我们得到的输出将是：

Index array
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

Vals array
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => simple note
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

如果您的 XML 文档很复杂，基于该文档的事件处理（Event-driven）解析（基于 expat 扩展库）也会对应的变得复杂。该函数生成的并非 DOM 风格的对象，而是横向的树状结构。因此，我们能够方便的建立表达 XML 文件数据的对象。我们假设以下 XML 文件表示一个关于氨基酸信息的小型数据库：

Example #2 moldb.xml - 分子信息的小型数据库

<?xml version="1.0"?>
<moldb>

    <molecule>
        <name>Alanine</name>
        <symbol>ala</symbol>
        <code>A</code>
        <type>hydrophobic</type>
    </molecule>

    <molecule>
        <name>Lysine</name>
        <symbol>lys</symbol>
        <code>K</code>
        <type>charged</type>
    </molecule>

</moldb>
以下是解析该文档并生成相应对象的代码：

Example #3 parsemoldb.php - 将 moldb.xml 解析到分子（molecular）对象的数组中

<?php

class AminoAcid {
    var $name;  // aa 姓名
    var $symbol;    // 三字母符号
    var $code;  // 单字母代码
    var $type;  // hydrophobic, charged 或 neutral

    function AminoAcid ($aa)
    {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename)
{
    // 读取 aminoacids 的 XML 数据
    $data = implode("",file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);

    // 遍历 XML 结构
    foreach ($tags as $key=>$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // each contiguous pair of array entries are the
            // lower and upper range for each molecule definition
            for ($i=0; $i < count($molranges); $i+=2) {
                $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues)
{
    for ($i=0; $i < count($mvalues); $i++) {
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);

?>
在执行完 parsemoldb.php 后，变量 $db 将包含有一个由 AminoAcid 对象组成的数组，该脚本的输出如下：
** Database of AminoAcid objects:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

User Contributed Notes

Adam Tylmad 30-Apr-2009 12:58
Thanx to jukea i've upgraded the characterData-function to allow the value 0. Here is the new complete code:

<?php

class XMLParser {
    var $path;
    var $result;

    function cleanString($string) {
        return trim(str_replace("'", "&#39;", $string));
    }

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

    function startElement($parser, $tag, $attributeList) {
        $this->path .= "->".$tag;
        eval("\$data = ".$this->path.";");
        if (is_array($data)) {
            $index = sizeof($data);
            $this->path .= "[".$index."]";
        } else if (is_object($data)) {
            eval($this->path." = array(".$this->path.");");
            $this->path .= "[1]";
        }

        foreach($attributeList as $name => $value)
            eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
    }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        if (strlen($data = XMLParser::cleanString($data)))
            eval($this->path." = '$data';");
    }
}

?>
aerik at thesylvans dot com 28-Nov-2008 03:55
Here's another attempt at dealing with rebuilding the xml from the array.  I'm basically preventing certain tags from being self closing by just checking for them explicitly (sure wish expat didn't interpret <textarea /> and <textarea></textarea> the same way (as "complete" tags).

<?php
function array2xml($xmlary){
  $o='';
  foreach($xmlary as $tag ){
    if($tag['tag'] == 'textarea' && !isset($tag['value'])){
      //fake a value so it won't self close
      $tag['value']='';
    }
    //tab space:
    $t = '';
    for($i=1; $i < $tag['level'];$i++){
      $t.="\t";
    }
    switch($tag['type']){
      case 'complete':
      case 'open':
        $o.=$t.'<'.$tag['tag'];
        if(isset($tag['attributes'])){
          foreach($tag['attributes'] as $attr=>$aval){
            $o.=' '.$attr.'="'.$aval.'"';
          }//foreach
        }//attributes
        if($tag['type'] == 'complete'){
          if(!isset($tag['value'])){
            $o .= ' />'."\n";
          } else {
            $o .= '>'."\n".$t.$tag['value']."\n".$t.'</'.$tag['tag'].'>'."\n";
          }
        }else{
          $o .= '>'."\n";
        }
        break;
      case 'close':
        $o .= $t.'</'.$tag['tag'].'>'."\n";
        break;
      case 'cdata':
        $o .= $t.$tag['value']."\n";
        break;
    }//switch
  }//foreach
}
?>
dale at ucsc dot edu 25-Sep-2008 04:16
here you can [re]assemble xml from a xml_parse_into_struct generated array: ie array2xml

<?php
$xml_parser = xml_parser_create( 'UTF-8' ); // UTF-8 or ISO-8859-1
xml_parser_set_option( $xml_parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option( $xml_parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct( $xml_parser, $my_text_xml, $aryXML );
xml_parser_free($xml_parser);

//now use aryXML array to xml string:
        $o='';
        foreach( $aryXML as $tag ){
            //tab space:
            for($i=1; $i < $tag['level'];$i++)
                $o.="\t";
            if($tag['type']!='close'){
                if($tag['type']!='cdata')
                    $o.='<'.$tag['tag'];
                if(isset($tag['attributes'])){
                    foreach($tag['attributes'] as $attr=>$aval){
                        $o.=' '.$attr.'="'.$aval.'"';
                    }
                }
                if($tag['type']!='cdata'){
                    $o.=($tag['type']=='complete')?'/>'."\n":'>'."\n";
                }
                $o.=(isset($tag['value']))?$tag['value']:'';
            }else{
                $o.='</'.$tag['tag'].'>';
            }
        }
?>
Llorenc 09-Sep-2008 03:20
Sorry, forgot my last post below, I confused CDATA sections (<![CDATA[]]>) with the value type "cdata", which despite its name it's very different! The first allows adding markup (&,<,>) as regular text and the second is to indicate a not complete node between the open and close nodes. What is true is that the CDATA delimiters are lost after xml_parse_into_struct so it's not possible to revert the process.

Please, feel free to remove my comments or leave them if you think they can help anyone.
wickedfather at hotmail dot com 06-Jul-2008 12:33
Had a comment up that was removed saying I'd found drawbacks, but here's a class what I wrote which works fine for me.  Comments removed due to post restrictions.  Pass the xml into the parse method or in the constructor.  Php4 and 5 safe.

class XMLThing
{
    var $rawXML;
    var $valueArray = array();
    var $keyArray = array();
    var $parsed = array();
    var $index = 0;
    var $attribKey = 'attributes';
    var $valueKey = 'value';
    var $cdataKey = 'cdata';
    var $isError = false;
    var $error = '';

    function XMLThing($xml = NULL)
    {
        $this->rawXML = $xml;
    }

    function parse($xml = NULL)
    {
        if (!is_null($xml))
        {
            $this->rawXML = $xml;
        }

        $this->isError = false;

        if (!$this->parse_init())
        {
            return false;
        }

        $this->index = 0;
        $this->parsed = $this->parse_recurse();
        $this->status = 'parsing complete';

        return $this->parsed;
    }

    function parse_recurse()
    {
        $found = array();
        $tagCount = array();

        while (isset($this->valueArray[$this->index]))
        {
            $tag = $this->valueArray[$this->index];
            $this->index++;

            if ($tag['type'] == 'close')
            {
                return $found;
            }

            if ($tag['type'] == 'cdata')
            {
                $tag['tag'] = $this->cdataKey;
                $tag['type'] = 'complete';
            }

            $tagName = $tag['tag'];

            if (isset($tagCount[$tagName]))
            {
                if ($tagCount[$tagName] == 1)
                {
                    $found[$tagName] = array($found[$tagName]);
                }

                $tagRef =& $found[$tagName][$tagCount[$tagName]];
                $tagCount[$tagName]++;
            }
            else
            {
                $tagCount[$tagName] = 1;
                $tagRef =& $found[$tagName];
            }

            switch ($tag['type'])
            {
                case 'open':
                    $tagRef = $this->parse_recurse();

                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                    }

                    if (isset($tag['value']))
                    {
                        if (isset($tagRef[$this->cdataKey]))
                        {
                            $tagRef[$this->cdataKey] = (array)$tagRef[$this->cdataKey];
                            array_unshift($tagRef[$this->cdataKey], $tag['value']);
                        }
                        else
                        {
                            $tagRef[$this->cdataKey] = $tag['value'];
                        }
                    }
                    break;

                case 'complete':
                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                        $tagRef =& $tagRef[$this->valueKey];
                    }

                    if (isset($tag['value']))
                    {
                        $tagRef = $tag['value'];
                    }
                    break;
            }
        }

        return $found;
    }

    function parse_init()
    {
        $this->parser = xml_parser_create();

        $parser = $this->parser;
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        if (!$res = (bool)xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray))
        {
            $this->isError = true;
            $this->error = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
        }
        xml_parser_free($parser);

        return $res;
    }
}
jemptymethod at gmail dot com 16-Jun-2008 01:39
@wickedfather, re: beaudurrant....I just cannot concur that the latter's class is "great"....First of all, it doesn't handle attributes.  Second of all, as my code below demonstrates, there is no need waste processing by determining duplicates within their own loop.  Thirdly, when there are duplicates, it collapses the layer in the array above the duplicates.

Here is some much more consise code, though not (yet) object oriented, and also not yet handling attributes; it maintains a stack for each level:

<?php
function xml_parse_into_assoc($file) {
  $data = implode("", file($file));
  $p = xml_parser_create();

  xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);

  xml_parse_into_struct($p, $data, $vals, $index);
  xml_parser_free($p);

  $levels = array(null);

  foreach ($vals as $val) {
    if ($val['type'] == 'open' || $val['type'] == 'complete') {
      if (!array_key_exists($val['level'], $levels)) {
        $levels[$val['level']] = array();
      }
    }

    $prevLevel =& $levels[$val['level'] - 1];
    $parent = $prevLevel[sizeof($prevLevel)-1];

    if ($val['type'] == 'open') {
      $val['children'] = array();
      array_push(&$levels[$val['level']], $val);
      continue;
    }

    else if ($val['type'] == 'complete') {
      $parent['children'][$val['tag']] = $val['value'];
    }

    else if ($val['type'] == 'close') {
      $pop = array_pop($levels[$val['level']]);
      $tag = $pop['tag'];

      if ($parent) {
        if (!array_key_exists($tag, $parent['children'])) {
          $parent['children'][$tag] = $pop['children'];
        }
        else if (is_array($parent['children'][$tag])) {
          $parent['children'][$tag][] = $pop['children'];
        }
      }
      else {
        return(array($pop['tag'] => $pop['children']));
      }
    }

    $prevLevel[sizeof($prevLevel)-1] = $parent;
  }
}
?>
wickedfather at hotmail dot com 12-Apr-2008 08:36
To beaudurrant - that class is great and structures things in a very sensible way.  Only problem is that it raises an error if a tag is empty, so would suggest a simple mod to the parse method just to add an isset test.

if (isset($val['value']))
{
    $this->setArrayValue($this->output, $stack, $val['value']);
}
mathiasrav at gmail dot com 10-Mar-2008 08:42
In response to Anonymous' post at 26-Feb-2008 11:50:

Saying that you "don't understand everything" isn't going to get you very popular - you should understand the code you use.
foreach isn't *slow* in PHP, it is actually faster than the equivalent for-construct (which, in many cases, isn't available).

The reason your script is slow is simply your use of xml_parse_into_struct - it reads the whole XML-string and doesn't return until it has parsed and validated it all. If you're looking for efficiency, you'll have to use the more low-level xml_parser_create, xml_set_*_handler functions. Then make sure you don't keep everything in a huge array before outputting it (at least don't if you're going for efficiency).
beaudurrant at gmail dot com 19-Dec-2007 11:23
This is extending what Alf Marius Foss Olsen had posted above.

It takes into account array keys with the same name and uses an increment for them instead of overwriting the keys.

I am using it for SOAP requests (20K - 150K) and it parses very fast compared to PEAR.

<?

class XMLParser  {

    // raw xml
    private $rawXML;
    // xml parser
    private $parser = null;
    // array returned by the xml parser
    private $valueArray = array();
    private $keyArray = array();

    // arrays for dealing with duplicate keys
    private $duplicateKeys = array();

    // return data
    private $output = array();
    private $status;

    public function XMLParser($xml){
        $this->rawXML = $xml;
        $this->parser = xml_parser_create();
        return $this->parse();
    }

    private function parse(){

        $parser = $this->parser;

        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);     // Dont bother with empty info
        if(!xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray)){
            $this->status = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
            return false;
        }
        xml_parser_free($parser);

        $this->findDuplicateKeys();

        // tmp array used for stacking
        $stack = array();
        $increment = 0;

        foreach($this->valueArray as $val) {
            if($val['type'] == "open") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack, $val['tag']);
                }
            } elseif($val['type'] == "close") {
                array_pop($stack);
                // reset the increment if they tag does not exists in the stack
                if(array_key_exists($val['tag'], $stack)){
                    $this->duplicateKeys[$val['tag']] = 0;
                }
            } elseif($val['type'] == "complete") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack,  $val['tag']);
                }
                $this->setArrayValue($this->output, $stack, $val['value']);
                array_pop($stack);
            }
            $increment++;
        }

        $this->status = 'success: xml was parsed';
        return true;

    }

    private function findDuplicateKeys(){

        for($i=0;$i < count($this->valueArray); $i++) {
            // duplicate keys are when two complete tags are side by side
            if($this->valueArray[$i]['type'] == "complete"){
                if( $i+1 < count($this->valueArray) ){
                    if($this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'] && $this->valueArray[$i+1]['type'] == "complete"){
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                    }
                }
            }
            // also when a close tag is before an open tag and the tags are the same
            if($this->valueArray[$i]['type'] == "close"){
                if( $i+1 < count($this->valueArray) ){
                    if(    $this->valueArray[$i+1]['type'] == "open" && $this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'])
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                }
            }

        }

    }

    private function setArrayValue(&$array, $stack, $value){
        if ($stack) {
            $key = array_shift($stack);
            $this->setArrayValue($array[$key], $stack, $value);
            return $array;
        } else {
            $array = $value;
        }
    }

    public function getOutput(){
        return $this->output;
    }

    public function getStatus(){
        return $this->status;
    }

}

?>

Usage:

$p = new XMLParser($xml);
$p->getOutput();
Alf Marius Foss Olsen 12-Sep-2007 06:46
<?php
/*
  An easy lightweight (Array ->) XML -> Array algorithm..

  Typical case: You have an array you want to export to an external server,
                so you make XML out of it, exports it, and "on the other side"
                make it into an array again. These two functions will take care
                of that last part, ie XML -> Array

  NOTE! The function XMLToArray assumes that the XML _dont_ have nodes on the
        same level with the same name, then it just wont work. This is not a
        problem, as this case deals with Array -> XML -> Array, and an array
        cant have to identical indexes/keys.
*/

function XMLToArray($xml) {
  $parser = xml_parser_create('ISO-8859-1'); // For Latin-1 charset
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); // Dont bother with empty info
  xml_parse_into_struct($parser, $xml, $values);
  xml_parser_free($parser);

  $return = array(); // The returned array
  $stack = array(); // tmp array used for stacking
  foreach($values as $val) {
    if($val['type'] == "open") {
      array_push($stack, $val['tag']);
    } elseif($val['type'] == "close") {
      array_pop($stack);
    } elseif($val['type'] == "complete") {
      array_push($stack, $val['tag']);
      setArrayValue($return, $stack, $val['value']);
      array_pop($stack);
    }//if-elseif
  }//foreach
  return $return;
}//function XMLToArray

function setArrayValue(&$array, $stack, $value) {
  if ($stack) {
    $key = array_shift($stack);
    setArrayValue($array[$key], $stack, $value);
    return $array;
  } else {
    $array = $value;
  }//if-else
}//function setArrayValue

// USAGE:
$xml = <<<QQQ
<?xml version="1.0"?>
<root>
  <node1>Some text</node1>
  <node2a>
    <node2b>
      <node2c>Some text</node2c>
    </node2b>
  </node2a>
</root>\n
QQQ;
$array = XMLToArray($xml);
print "<pre>";
print_r($array);
print "</pre>";
//  Output:
//
//  Array
//  (
//      [root] => Array
//          (
//              [node1] => Some text
//              [node2a] => Array
//                  (
//                      [node2b] => Array
//                          (
//                              [node2c] => Some text
//                          )
//                  )
//          )
//  )
?>
vinod at citadel-soft dot com 01-Sep-2007 03:43
My previous code was having some bugs in, that is fixed now

<?php
class CSLXmlReader {
    private $tagstack;
    private $xmlvals;
    private  $xmlvarArrPos;
    private $xmlfile;
    function __construct($filename)  // constructor to intialize the stack and val array
    {

        $this->tagstack = array();   // contain the open tags till now
        $this->xmlvals = array();
        $this->xmlvarArrPos = $this->xmlvals;  // temporary variable to hold the current tag position
        $this->xmlfile = $filename;
    }
    function readDatabase()
    {
        // read the XML database
        $data = implode("", file($this->xmlfile));
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $data, $values, $tags);
        xml_parser_free($parser);

        foreach($values as $key => $val)  //
        {
            if($val['type'] == "open")
            {
                array_push($this->tagstack, $val['tag']);
                $this->getArrayPath();
                if(count($this->xmlvarArrPos) > 0 && (!array_key_exists(0,$this->xmlvarArrPos)))
                {
                    $temp1 = $this->xmlvarArrPos;
                    $this->xmlvarArrPos =  array();
                    $this->xmlvarArrPos[0] = $temp1;
                    array_push($this->tagstack, 1);
                }
                else if( array_key_exists(0,$this->xmlvarArrPos)){
                    $opncount = count($this->xmlvarArrPos);
                    array_push($this->tagstack, $opncount);
                }
                $tagStackPointer += 1;
            }else if($val['type'] == "close")
            {
                while( $val['tag'] != ($lastOpened = array_pop($this->tagstack))){}
            }else if($val['type'] ==  "complete")
            {
                $this->getArrayPath();
                if( array_key_exists($val['tag'],$this->xmlvarArrPos))
                {
                    if(array_key_exists(0,$this->xmlvarArrPos[$val['tag']]))
                    {
                        $elementCount = count($this->xmlvarArrPos[$val['tag']]);
                        $this->xmlvarArrPos[$val['tag']][$elementCount] = $val['value'];
                    }else
                    {
                        $temp1 = $this->xmlvarArrPos[$val['tag']];
                        $this->xmlvarArrPos[$val['tag']] =  array();
                        $this->xmlvarArrPos[$val['tag']][0] = $temp1;
                        $this->xmlvarArrPos[$val['tag']][1] = $val['value'];
                    }
                } else
                {
                    $this->xmlvarArrPos[$val['tag']] = $val['value'];
                }
            }
        }
        reset($this->xmlvals);
        return $this->xmlvals;
    }
    function getArrayPath()
    {

        reset($this->xmlvals);
        $this->xmlvarArrPos = &$this->xmlvals;
        foreach($this->tagstack as $key)
        {
            $this->xmlvarArrPos = &$this->xmlvarArrPos[$key];

        }
    }

}

$readerObj  = new CSLXmlReader("test.xml");
$xmlvals = $readerObj->readDatabase();

echo "########## XML Values In array as the multidimentional array  #############\n";
echo "<pre>";
print_r($xmlvals);
echo "</pre>";

?>
siteres at gmail dot com 07-Feb-2007 01:38
PHP: XML to Array and backwards:

Here the XML with PHP solution: XML->Array and Array->XML.
Work with it as with usual array.

Sources are here:
http://mysrc.blogspot.com/2007/02/php-xml-to-array-and-backwards.html
(leave me comments:)

Example #1 (1.xml):

<ddd>
 <onemore dd="55">
  <tt>333</tt>
  <tt ss="s1">555</tt>
  <tt>777</tt>
 </onemore>
 <two>sdf rr</two>
</ddd>

The code:

$xml=xml2ary(file_get_contents('1.xml'));
print_r($xml);

Here is the Array result:

Array
(
   [ddd] => Array (
           [_c] => Array (
                   [_p] => Array *RECURSION*
                   [onemore] => Array (
                           [_a] => Array (
                                   [dd] => 55
                               )
                           [_c] => Array (
                                   [_p] => Array  *RECURSION*
                                   [tt] => Array (
                                           [0] => Array (
                                                   [_v] => 333
                                               )
                                           [1] => Array (
                                                   [_a] => Array (
                                                           [ss] => s1
                                                       )
                                                   [_v] => 555
                                               )
                                           [2] => Array (
                                                   [_v] => 777
                                               )
                                       )
                               )
                       )
                   [two] => Array (
                           [_v] => sdf rr
                       )
               )
       )
)
webmaster at after5webdesign dot com 30-Nov-2006 04:48
That parser also has a problem in which it will not parse more items than the current level it is on. That is, parsing this:  <1><2>A</2><2>B</2><2>C</2></1>
Will only result in this: A B
C is never processed.

It might be better with something like this:
          $file = get_url('http://news.search.yahoo.com/news/rss?p=current+events', URL_CONTENT);
          $data = $file['content'];
          $xml_parser = xml_parser_create();
          xml_parse_into_struct($xml_parser, $data, $vals, $index);
          xml_parser_free($xml_parser);
          //Uncomment the lines below to see the entire structure of your XML document
          //echo "<pre>INDEX: \n";
          //print_r ($index);
          //echo "\n \n \n VALUES:";
          //print_r ($vals);
          //echo "</pre>";
          $params = array();
          $level = array();
          $start_level = 1;
          foreach ($vals as $xml_elem) {
            if ($xml_elem['type'] == 'open') {
              if (array_key_exists('attributes',$xml_elem)) {
                list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
              } else {
                $level[$xml_elem['level']] = $xml_elem['tag'];
              }
            }
            if ($xml_elem['type'] == 'complete') {
              $php_stmt = '$params';
              while($start_level < $xml_elem['level']) {
                $php_stmt .= '[$level['.$start_level.']]';
                $start_level++;
              }
              $php_stmt .= '[$xml_elem[\'tag\']][] = $xml_elem[\'value\'];';
              eval($php_stmt);
              $start_level--;
            }
          }
          echo "<pre>";
          print_r ($params);
          echo "</pre>";

~Tim_Myth
A3 03-Nov-2006 05:28
XML -> Array
<?
    $data = '<root><a><b x="s" a="2">asdf</b><c></c></a></root>';

    $p = xml_parser_create();
    xml_parse_into_struct($p, $data, $vals);
    xml_parser_free($p);

    $key = $output = array();
   foreach ($vals as $id=>$item) {
      if ($item["type"]=="open" || $item["level"]>count($key)) {// && count($key)<=$item["level"])
          array_push($key, $id);
          $temp = array("tag"=>$item["tag"], "value"=>"", "attributes"=>array());
          eval("\$output[".implode("][", $key)."] = \$temp;");
      }
      if ($item["type"]=="close" || $item["level"]<count($key))// && $item["level"]>=count($key))
          array_pop($key);
      if (isset($item["attributes"]))
          eval("\$output[".implode("][", $key)."]['attributes'] = array_merge(\$output[".implode("][", $key)."]['attributes'], \$item['attributes']);");
      if (isset($item["value"]))
          eval("\$output[".implode("][", $key)."]['value'] .= \$item['value'];");
   }
?>
Elad Elrom 12-Sep-2006 02:14
This is a quick fix for parsing XML from remote URL, some of the example above will work when trying to parse on your local server without "http://" but not when trying to parse from remote server using "http://www.URL"...

<?
$file="http://www.URL.com/file.XML";

$xml_parser = xml_parser_create();

$handle = fopen($file, "rb");
$contents = '';
while (!feof($handle)) {
  $data .= fread($handle, 8192);
}
fclose($handle);

xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
   if (array_key_exists('attributes',$xml_elem)) {
     list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
   } else {
     $level[$xml_elem['level']] = $xml_elem['tag'];
   }
  }
  if ($xml_elem['type'] == 'complete') {
   $start_level = 1;
   $php_stmt = '$params';
   while($start_level < $xml_elem['level']) {
     $php_stmt .= '[$level['.$start_level.']]';
     $start_level++;
   }
   $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
   eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>
efredricksen at gmail dot com 24-May-2006 12:55
Perhaps the one true parser:? I modified xademax's fine code to tidy it up, codewise and style wise, rationalize some minor crazyness, and make names fit nomenclature from the XML spec. (There are no uses of eval, and shame on you people who do.)

<?php
class XmlElement {
  var $name;
  var $attributes;
  var $content;
  var $children;
};

function xml_to_object($xml) {
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $xml, $tags);
  xml_parser_free($parser);

  $elements = array();  // the currently filling [child] XmlElement array
  $stack = array();
  foreach ($tags as $tag) {
    $index = count($elements);
    if ($tag['type'] == "complete" || $tag['type'] == "open") {
      $elements[$index] = new XmlElement;
      $elements[$index]->name = $tag['tag'];
      $elements[$index]->attributes = $tag['attributes'];
      $elements[$index]->content = $tag['value'];
      if ($tag['type'] == "open") {  // push
        $elements[$index]->children = array();
        $stack[count($stack)] = &$elements;
        $elements = &$elements[$index]->children;
      }
    }
    if ($tag['type'] == "close") {  // pop
      $elements = &$stack[count($stack) - 1];
      unset($stack[count($stack) - 1]);
    }
  }
  return $elements[0];  // the single top-level element
}

// For example:
$xml = '
<parser>
   <name language="en-us">Fred Parser</name>
   <category>
       <name>Nomenclature</name>
       <note>Noteworthy</note>
   </category>
</parser>
';
print_r(xml_to_object($xml));
?>

will give:

xmlelement Object
(
    [name] => parser
    [attributes] =>
    [content] =>
    [children] => Array
        (
            [0] => xmlelement Object
                (
                    [name] => name
                    [attributes] => Array
                        (
                            [language] => en-us
                        )

                    [content] => Fred Parser
                    [children] =>
                )

            [1] => xmlelement Object
                (
                    [name] => category
                    [attributes] =>
                    [content] =>
                    [children] => Array
                        (
                            [0] => xmlelement Object
                                (
                                    [name] => name
                                    [attributes] =>
                                    [content] => Nomenclature
                                    [children] =>
                                )

                            [1] => xmlelement Object
                                (
                                    [name] => note
                                    [attributes] =>
                                    [content] => Noteworthy
                                    [children] =>
                                )

                        )

                )

        )

)
Stuart 23-May-2006 03:26
This is a great little function for a lot of XML work, but note that this function does not handle XML entities properly.

The basic XML entities &lt; &gt; &amp; &quot; are fine, just anything else will not work:

If the entity is defined in the XML header, the parser will drop it completely from the struct it creates.

If the entity is not defined in the XML then the parser will crash out with an undefined entity error.

You should be able to work around this limitation by using a preg_replace on your XML string before passing it to the parser.

(Further details in Bug #35271; this is just a warning to those thinking of using this function for parsing real XML documents not just trivial XML examples)
xademax at gmail dot com 08-Jan-2006 12:15
This is just another simple xml parser :)

<?php

class Xml
{
    var $tag;
    var $value;
    var $attributes;
    var $next;
}

function xml2array($xml_string)
{
    $Parser = xml_parser_create();
    xml_parser_set_option($Parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($Parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($Parser, $xml_string, $Xml_Values);
    xml_parser_free($Parser);
    $XmlClass = array();
    $LastObj = array();
    $NowObj = &$XmlClass;

    foreach($Xml_Values as $Xml_Key => $Xml_Value)
    {
        $Index = count($NowObj);
        if($Xml_Value["type"] == "complete")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
        }
        elseif($Xml_Value["type"] == "open")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
            $NowObj[$Index]->next = array();
            $LastObj[count($LastObj)] = &$NowObj;
            $NowObj = &$NowObj[$Index]->next;
        }
        elseif($Xml_Value["type"] == "close")
        {
            $NowObj = &$LastObj[count($LastObj) - 1];
            unset($LastObj[count($LastObj) - 1]);
        }

    }

    return $XmlClass;
}

$String = "
<parser>
    <parseur_name>MyParser</parseur_name>
    <category>
        <name>Name 1</name>
        <note>A note 1</note>
    </category>
</parser>
";
$Xml = xml2array($String);

print_r($Xml);
?>

This exemple will show :
Array
(
    [0] => Xml Object
        (
            [tag] => parser
            [value] =>
            [attributes] =>
            [next] => Array
                (
                    [0] => Xml Object
                        (
                            [tag] => parseur_name
                            [value] => MyParser
                            [attributes] =>
                            [next] =>
                        )

                    [1] => Xml Object
                        (
                            [tag] => category
                            [value] =>
                            [attributes] =>
                            [next] => Array
                                (
                                    [0] => Xml Object
                                        (
                                            [tag] => name
                                            [value] => Name 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                    [1] => Xml Object
                                        (
                                            [tag] => note
                                            [value] => A note 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                )

                        )

                )

        )

)
mbirth at webwriters dot de 08-Nov-2005 03:48
Searching for a nice and working way to get a RSS feed into an array-structure, I found the solution posted by kieran but disliked those several eval()s. So I wrote my own using references/pointers.

<?php

class RSSParser {

  var $struct = array();  // holds final structure
  var $curptr;  // current branch on $struct
  var $parents = array();  // parent branches of current branch

  function RSSParser($url) {
    $this->curptr =& $this->struct;  // set ref to base
    $xmlparser = xml_parser_create();
    xml_set_object($xmlparser, $this);
    xml_set_element_handler($xmlparser, 'tag_open', 'tag_close');
    xml_set_character_data_handler($xmlparser, 'cdata');
    $fp = fopen($url, 'r');

    while ($data = fread($fp, 4096))
      xml_parse($xmlparser, $data, feof($fp))
      || die(sprintf("XML error: %s at line %d",
         xml_error_string(xml_get_error_code($xmlparser)),
         xml_get_current_line_number($xmlparser)));

    fclose($fp);
    xml_parser_free($xmlparser);
  }

  function tag_open($parser, $tag, $attr) {
    $i = count($this->curptr['children']);
    $j = count($this->parents);
    $this->curptr['children'][$i]=array();  // add new child element
    $this->parents[$j] =& $this->curptr;  // store current position as parent
    $this->curptr =& $this->curptr['children'][$i];  // submerge to newly created child element
    $this->curptr['name'] = $tag;
    if (count($attr)>0) $this->curptr['attr'] = $attr;
  }

  function tag_close($parser, $tag) {
    $i = count($this->parents);
    if ($i>0) $this->curptr =& $this->parents[$i-1];  // return to parent element
    unset($this->parents[$i-1]);  // clear from list of parents
  }

  function cdata($parser, $data) {
    $data = trim($data);
    if (!empty($data)) {
      $this->curptr['value'] .= $data;
    }
  }

}

$myparser = new RSSParser('getitems.xml');
$anotherparser = new RSSParser('http://johndoe:secret@myfeeds.com/getfeed.xml');

print_r($myparser->struct);
print_r($anotherparser->struct);

?>
kieran at kieran dot ca 20-Oct-2005 09:20
<?
/*
|
| _xml2array - another abstraction layer on xml_parse_into_struct
|              that returns a nice nested array.
|
|      @param: $xml is a string containing a full xml document
|
|     returns: a nested php array that looks like this:
|
|              array
|              (
|                  [_name] => the name of the tag
|                  [_attributes] => an array of 'attribute'=>'value' combos
|                  [_value] => the text contents of the node
|                  [_children] => an array of these arrays, one for each node.
|              )
|
|       notes: thanks to 'jeffg at activestate dot com' who inspired
|              me to essentially re-write his example code from php.net
|
|           me: Kieran Huggins < kieran[at]kieran[dot]ca >
|
*/
function _xml2array($xml){
    global $keys;
    global $level;
    if(!is_array($xml)){ // init on first run
        $raw_xml = $xml;
        $p = xml_parser_create();
        xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($p, $raw_xml, $xml, $idx);
        xml_parser_free($p);
    }
    for($i=0;$i<count($xml,1);$i++){
        // set the current level
        $level = $xml[$i]['level'];

        if($level<1)break;

        // mark this level's tag in the array
        $keys[$level] = '['.$i.']';

        // if we've come down a level, sort output and destroy the upper level
        if(count($keys)>$level) unset($keys[count($keys)]);

        // ignore close tags, they're useless
        if($xml[$i]['type']=="open" || $xml[$i]['type']=="complete"){

            // build the evalstring
            $e = '$output'.implode('[\'_children\']',$keys);

            // set the tag name
            eval($e.'[\'_name\'] = $xml[$i][\'tag\'];');

            // set the attributes
            if($xml[$i]['attributes']){
                eval($e.'[\'_attributes\'] = $xml[$i][\'attributes\'];');
            }

            // set the value
            if($xml[$i]['value']){
                eval($e.'[\'_value\'] = trim($xml[$i][\'value\']);');
            }

        }

    }

    return $output;
}
?>
Chris Hester 28-Jul-2005 05:06
The array generated from XML stores not only the elements but also any spaces and linebreaks between the tags. This results in a much longer array. (I had 24 array fields instead of 10!) To cure this use the following code when creating the parser:

<?php
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
?>
grusin at gmail dot com 19-Jul-2005 11:54
Here is a simple patch to peter's xml2array function.

Replace:

<?
case 'open':
$tag_or_id = (array_key_exists ('attributes', xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
$ptrs[$level][$tag_or_id] = array ();
$ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
break;
?>

with:

<?
case 'open':
$tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
$ptrs[$level][$tag_or_id][] = array ();
$ptrs[$level+1] = & $ptrs[$level][$tag_or_id][count($ptrs[$level][$tag_or_id])-1];
break;
?>

and now code should handle multiple element case :)
Dustin 13-Jul-2005 08:39
If you happen to have problems with weird charaters, I added this code to the first line of dUDA's function:

$XML = utf8_decode($XML);
PhF at madmac dot fr 23-Jun-2005 01:11
The code previously posted by noob at noobsrule dot com doesn't work when the same tag name is used at different levels.
(but perhaps "$php_used_prefix" was intended for that ?)
For example:
<RatedShipment>
  <TransportationCharges>
    ...
  </TransportationCharges>
  <RatedPackage>
    <TransportationCharges>
      ...
    </TransportationCharges>
  </RatedPackage>
</RatedShipment>
<?php
    $p = xml_parser_create();
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($p, $UPSxml, $values, $idx);
    xml_parser_free($p);

    // tracking used keys
    $usedKeys = array();
    $deepLevel = -1;

    // start a php array string (evaluated later)
    $forEvalPrefix = '$xml_array';

    // loop throught the value array
    foreach ($values as $key => $val) {
        $tagName = $val['tag']; // pass the key tag into a more friendly looking variable
        $level = $val['level']; // idem
        if($val['type'] == 'open') {
            $deepLevel++; // increase deep level
            $forEvalPrefix .= '[\''. $tagName .'\']';

            // begin used keys checks to allow multidimensionatity under the same tag
            (isset($usedKeys[$level][$tagName])) ? $usedKeys[$level][$tagName]++ : $usedKeys[$level][$tagName] = 0;
            $forEvalPrefix .= '['. $usedKeys[$level][$tagName] .']';
        }
        if($val['type'] == 'complete') {
            ($level > $deepLevel) ? $deepLevel++ : ''; // increase $deepLevel only if current level is bigger
            $tagValue = addslashes($val['value'] ); // format the value for evaluation as a string
            $forEvalSuffix = '[\''. $tagName .'\'] = \''. $tagValue .'\';'; // create a string to append to the current prefix
            $forEval = $forEvalPrefix . $forEvalSuffix; // (without "$php_used_prefix"...)
            eval($forEval); // write the string to the array structure
        }
        if($val['type'] == 'close') {
            unset($usedKeys[$deepLevel]); // Suppress tagname's keys useless
            $deepLevel--;
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the used keys node
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the end level of the array string prefix
        }
    }
echo '<pre>';
print_r ($xml_array);
echo '</pre>';
?>

MADmac ;-)
peter at elemental dot org 15-Jun-2005 08:46
Quick addendum to my post below... The code does *not* handle cases where multiple elements are used without attribute IDs, as is the case with the moldb example.  (It is probably worth noting that some of the other code below doesn't do this either, and is still more complex.)

It is not difficult to add that functionality, but I have yet to find an elegant way to integrate that feature, and since I don't need that functionality at the moment, I'm going leave that as an exercise to the reader.  ;-)

-p.
peter at elemental dot org 14-Jun-2005 04:09
Some of the code posted previously seemed absurdly complex, so I thought I'd see if I could simplify things a bit. Here's what I came up with.  (I'm still a PHP newbie, so perhaps I simplified too much.  ;-)  Untested for speed, but it *should* be pretty quick since it uses references instead of lookups or (gack) evals.

Enjoy!

/*
 *  Convert a string containing XML into a nested array
 *
 *  Takes a raw XML string as input
 *  Returns a nested array
 */

function xml2array ($xml_data)
{
    // parse the XML datastring
    $xml_parser = xml_parser_create ();
    xml_parse_into_struct ($xml_parser, $xml_data, $vals, $index);
    xml_parser_free ($xml_parser);

    // convert the parsed data into a PHP datatype
    $params = array();
    $ptrs[0] = & $params;
    foreach ($vals as $xml_elem) {
        $level = $xml_elem['level'] - 1;
        switch ($xml_elem['type']) {
        case 'open':
            $tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
            $ptrs[$level][$tag_or_id] = array ();
            $ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
            break;
        case 'complete':
            $ptrs[$level][$xml_elem['tag']] = (isset ($xml_elem['value'])) ? $xml_elem['value'] : '';
            break;
        }
    }

    return ($params);

}
gleber at mapnet dot pl 26-Mar-2005 03:03
XMLtoArray created by dudus at onet dot pl was not good enough for me, that's why i decided to create my own version, and here's the result:

<?php

function &last(&$array) {
if (!count($array)) return null;
end($array);
return $array[key($array)];
}

function myParseXML(&$vals, &$dom, &$lev) {
    do {
        $curr = current($vals);
        $lev = $curr['level'];
        switch ($curr['type']) {
            case 'open':
                if (isset($dom[$curr['tag']])) {
                    $tmp = $dom[$curr['tag']];
                    if (!$tmp['__multi'])
                        $dom[$curr['tag']] = array('__multi' => true, $tmp);
                    array_push($dom[$curr['tag']], array());
                    $new =& last($dom[$curr['tag']]);
                } else {
                    $dom[$curr['tag']] = array();
                    $new =& $dom[$curr['tag']];
                }
                next($vals);
                myParseXML(&$vals, $new, $lev);
                break;
            case 'cdata':
                break;
            case 'complete':
                if (!isset($dom[$curr['tag']]))
                    $dom[$curr['tag']] = $curr['value'];
                else {
                    if (is_array($dom[$curr['tag']]))
                        array_push($dom[$curr['tag']] , $curr['value']);
                    else
                        array_push($dom[$curr['tag']] = array($dom[$curr['tag']]) , $curr['value']);
                }
                break;
            case 'close':
                return;
        }
    }
    while (next($vals)!==FALSE);
}

function MyXMLtoArray($XML) {
       $xml_parser = xml_parser_create();
       xml_parse_into_struct($xml_parser, $XML, $vals);
       xml_parser_free($xml_parser);
       reset($vals);
       $dom = array(); $lev = 0;
       myParseXML($vals, $dom, $lev);
       return $dom;
}

?>

MyXMLtoArray() is that function you should call, other are for "internal" use.

P.S. It's 4-5 time faster then dudus at onet dot pl 's code
noob at noobsrule dot com 24-Jan-2005 10:59
This is my first time contributing but I found all the examples either didn't work or were beyond my comprehension.  I also wanted to maintain the XML multi-dimensionality so I could do loops based on keys I was expecting rather than numbers or some other whatnot.  This script is probably way inefficient, but should give you a multidimensional array with a depth that will match the XML source.  Great for situations when you aren't sure what you'll be getting back.  Its also only based on the values array of xml_parse_into_str() using the 3 tag types (open, complete, and close) -- hopefully it will make more sense to other noobs.

Basically it just constructs a string ($php_prefix) that is tweaked if it hits an "open" or "close" tag and evaluated if it hits a "complete" tag.

Thanks.

<?php

# initiate curl session...
$ch = curl_init( "http://yourtargethost" ) or die ( "could not initialize curl" );

# set curl options...
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $request_str );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0 );
curl_setopt( $ch, CURLOPT_REFERER, https://foobar.com" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

# execute curl commands...
$curl_result = curl_exec( $ch ) or die ( "could not execute the post" );
curl_close( $ch ); // close curl session

# pass the XML result into 2 arrays ( index and values )...
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($p, $curl_result, $vals, $index);
xml_parser_free($p);

# create an empty used key tracker...
$used_keys = array();

# start a php array string (evaluated later)...
$php_prefix = "$"."my_array";

# loop through the values array...
foreach ($vals as $key => $val) {
    if( $val['type'] == "open" ) {
        $my_tag = $val['tag']; // pass the key tag into a more friendly looking variable...
        $php_prefix .= "['".$my_tag."']"; # add a new level to the array string...

        # begin used key checks to allow multidimensionality under the same tag, adds a number to the prefix if necessary...
        if( ! array_key_exists( $my_tag, $used_keys ) ) {
            $used_keys[$my_tag] = 0;
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }else {
            $used_keys[$my_tag]++; // increment the key tracker to avoid overwriting existing key...
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }
    } elseif( $val['type'] == "complete" ) {
        $my_value = addslashes( $val['value'] ); # format the value for evaluation as a string...
        $php_suffix = "['".$val['tag']."'] = \"".$my_value."\";"; # create a string with the tag and value to append to the current prefix (just used here)...
        $php_str = $php_prefix.$php_used_prefix.$php_suffix;
        eval( $php_str ); # write the string to the array structure...
    }
    if( $val['type'] == "close" ) {
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the used keys node...
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the end level of the array string prefix...
    }
}

echo "<pre>";
//print_r ($index);
//echo "<br><br><br>";
//print_r ($vals);
//echo "<br><br><br>";
print_r ($my_array);
echo "</pre>";

?>
dudus at onet dot pl 18-Jan-2005 06:33
This function return array from XML. Included attributes and tags in same level.
I wrote this function based on mmustafa code.

enjoy!
dUDA

-------------------------------

<?
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close')
        {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete')
        {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while($start_level < $x_level)
        {
              $php_stmt .= '[$level['.$start_level.']]';
              if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                  $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
              $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete'))
        {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
             $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes',$xml_elem))
        {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes',$xml_elem))
        {
            if (isset($xml_elem['value']))
            {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value)
            {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
     return $xml_array;
}    // END XMLtoArray
?>
memandeemail at gmail dot com 03-Dec-2004 04:32
If you have de XML:
<?xml version="1.0" encoding="iso-8859-1"?>
<teste>
    <teste>
        <teste>
        </teste>
    </teste>
</teste>

this function will return this tags:
Array
(
    [teste] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
        )

)

With this function (right below) will convert the struc to OPEN and CLOSE concept.

The New Struct:
Array
(
    [teste] => Array
        (
            [0] => 0
            [1] => 4
            [2] => 1
            [3] => 3
            [4] => 2
        )

)
The Function:

<?php
/**
 * @return bool
 * @param xml_array $values
 * @param xml_array[reference] $tags
 * @desc Reconstruct xml_parse_into_struct
*/
function reconstruct_tag($values, &$tags) {
    unset($return);
    foreach ($tags as $tkey => $tvalue) {
        foreach ($tvalue as $vvalue) {
            if ($values[$vvalue]['type'] == 'open' or $values[$vvalue]['type'] == 'complete') {
                $return[$tkey][] = $vvalue;
            }
            if ($values[$vvalue]['type'] == 'open') {
                foreach ($tvalue as $tv_value) {
                    if ($values[$tv_value]['type'] == 'close'
                    and $values[$tv_value]['level'] == $values[$vvalue]['level']
                    and $tv_value > $vvalue) {
                        $return[$tkey][] = $tv_value;
                        break;
                    }
                }
            }
        }
    }
    $tags = $return;
    return (bool) $tags;
}
?>

Ahh, DO NOT forget this comment:

jukkaho at mail dot student dot oulu dot fi
29-Jun-2004 12:17
Everyone seems to forget the return value of this function (including people making examples!), but it is there for a reason:
0 if failed (invalid XML), 1 if succeeded.

Return value really is an integer, be careful with those === operators.
happyseb at free dot fr 24-Aug-2004 08:51
I would just add something about the solution proposed by "gordon at kanazawa dot ac dot jp".

Something went wrong about the fact that "cdata" are treated the same way as "complete" in the xml_get_children first and in the xml_get_child then.

When ?
with this method, something like this :
<tagA>
  <tagB>valueB</tagB>
  valueA
  <tagC>valueC</tagC>
</tagA>
is considered as the same thing as
<tagA>
  <tagB>valueB</tagB>
  <tagA>valueA</tagA>
  <tagC>valueC</tagC>
</tagA>

The algorithm is nomore bijective.

Even if it might not be perfect :-) i propose a little modification of the xml_get_child function :

function xml_get_child(&$v, $children=NULL) {
      $c = array(); // the "child"
      if (isset($v['tag']) && $v['type'] != 'cdata') $c['tag'] = $v['tag'];
      if (isset($v['value'])) $c['value'] = $v['value'];
      if (isset($v['attributes'])) $c['attributes'] = $v['attributes'];
      if (is_array($children)) $c['children'] = $children;
      return $c;
}

moreover, the following function will take the tree (made from the xml_get_tree function) as a parameter and build the xml content back

    /*
    // setTree
    // set xml Tree from a well-formed array
    // manage indentation
    // Parameters are :
    // $1 (needed) : Tree to transform
    // $2 (optional) : Indentation type (default is one tabulation)
    // $3 (optional) : First indent (default is empty string)
    */

    function setTree($Atree, $indentType = '    ', $Sindent = '')
    {
      if (! isset ($Atree['tag']) && isset ($Atree['value'])) return ($Sindent.trim($Atree['value'])."\r\n") ;
      else {
        $Stemp = $Sindent.'<'.$Atree['tag'].' ' ;
        if (isset ($Atree['attributes']) && is_array ($Atree['attributes'])) {
          foreach ($Atree['attributes'] as $Aattribute => $Svalue) $Stemp .= $Aattribute.'="'.$Svalue.'" ' ;
        }
        if (! isset ($Atree['children']) && ! isset ($Atree['value'])) $Stemp .= '/>'."\r\n" ;
        else {
          $Stemp .= '>'."\r\n" ;
          if (isset ($Atree['value'])) $Stemp .= $Sindent.$indentType.trim($Atree['value'])."\r\n" ;
          if (isset ($Atree['children']) && is_array ($Atree['children']))
            foreach ($Atree['children'] as $Achild) $Stemp .= $this->setTree($Achild, $indentType, $Sindent.$indentType) ;
          $Stemp .= $Sindent.'</'.$Atree['tag'].'>'."\r\n" ;
        }
        return ($Stemp) ;
      }
    }
sdh33 at cornell dot edu 13-Jun-2004 10:12
(The previous post I wrote was incorrect.  I fix that herein)
I used the algorithm from stephane for writing back to a file, but ran into the following problem.  My original XML looks like

<ENTRY id="1"> ... </ENTRY><ENTRY id="2"> ... </ENTRY>

This got saved back as

<1> ... </1><2> ... </2>,

which expat doesn't like.  So I propose the following modification:

function writeXmlToFile($data, $f, $niv = 0) {
  foreach($data as $name => $elem) {
    if (preg_match("/\A[0-9]/",$name)) {
      $open = "ENTRY id=\"$name\""; $name = "ENTRY";
    } else {
      $open = $name;
    }
    if(is_array($elem)) {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    } else {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">".$elem."</".$name.">"."\n");
    }
  }
}
stephane dot dekeyzer at noemail dot com 08-Apr-2004 11:54
for writing the array of mmustafa back to a xml file, use this code:

function writeXmlFile($fileName, $struct){
  $f = fopen($fileName, "w");
  writeXmlToFile($struct, $f);
  fclose($f);
}

function writeXmlToFile($data, $f, $niv = 0){
  foreach($data as $name => $elem){
    if(is_array($elem)){
      fwrite($f, str_repeat("  ", $niv)."<".$name.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    }
    else{
      fwrite($f, str_repeat("  ", $niv)."<".$name.">".$elem."</".$name.">"."\n");
    }
  }
}
mmustafa at vsnl dot com 06-Jan-2004 12:19
A small and simple php code to convert the raw array returned by xml_parse_into_struct into a proper data structure ..

<?php
$file = "data.xml";
$xml_parser = xml_parser_create();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

$data = fread($fp, filesize($file));
fclose($fp);
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
    if (array_key_exists('attributes',$xml_elem)) {
      list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
    } else {
      $level[$xml_elem['level']] = $xml_elem['tag'];
    }
  }
  if ($xml_elem['type'] == 'complete') {
    $start_level = 1;
    $php_stmt = '$params';
    while($start_level < $xml_elem['level']) {
      $php_stmt .= '[$level['.$start_level.']]';
      $start_level++;
    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
    eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>

Converts an XML document like ..

<country id="ZZ">
<name>My Land</name>
<location>15E</location>
<area>40000</area>
<state1>
<name>Hi State</name>
<area>1000</area>
<population>2000</population>
<city1>
<location>13E</location>
<population>500</population>
<area>500</area>
</city1>
<city2>
<location>13E</location>
<population>500</population>
<area>5000</area>
</city2>
</state1>
<state2>
<name>Low State</name>
<area>3000</area>
<population>20000</population>
<city1>
<location>15E</location>
<population>5000</population>
<area>1500</area>
</city1>
</state2>
</country>

To a php datastructure like ..

Array
(
    [ZZ] => Array
        (
            [NAME] => My Land
            [LOCATION] => 15E
            [AREA] => 40000
            [STATE1] => Array
                (
                    [NAME] => Hi State
                    [AREA] => 1000
                    [POPULATION] => 2000
                    [CITY1] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 500
                        )

                    [CITY2] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 5000
                        )

                )

            [STATE2] => Array
                (
                    [NAME] => Low State
                    [AREA] => 3000
                    [POPULATION] => 20000
                    [CITY1] => Array
                        (
                            [LOCATION] => 15E
                            [POPULATION] => 5000
                            [AREA] => 1500
                        )

                )

        )

)
bisqwit at iki dot fi dot not dot for dot ads dot invalid 20-Nov-2002 08:33
I made my own xml2tree()-function.
The difference to the previously suggested ones on this manual page is that this creates a tree where the tags are keys.

Example input:

<tree>
 <leaf name="gruu"> pl?? </leaf>
 <animal type="cat" />
</tree>

Example output:

Array
( 'tree' => Array
     ( 0 => Array
          ( 'children' => Array
               ( 'leaf' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('name' => 'gruu'),
                           'values' => Array(0 => ' pl?? ')
                    )    ),
                 'animal' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('type' => 'cat')
)    )   )    )    )   )

function xml2tree2($string)
{
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $string, $vals, $index);
  xml_parser_free($parser);

  $stack = array( array() );
  $stacktop = 0;
  $parent = array();
  foreach($vals as $val)
  {
    $type = $val['type'];
    if($type=='open' || $type=='complete')
    {
      // open tag
      $stack[$stacktop++] = $tagi;
      $tagi = array('tag' => $val['tag']);

      if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
      if(isset($val['value']))
        $tagi['values'][] = $val['value'];
    }
    if($type=='complete' || $type=='close')
    {
      // finish tag
      $tags[] = $oldtagi = $tagi;
      $tagi = $stack[--$stacktop];
      $oldtag = $oldtagi['tag'];
      unset($oldtagi['tag']);
      $tagi['children'][$oldtag][] = $oldtagi;
      $parent = $tagi;
    }
    if($type=='cdata')
    {
      $tagi['values'][] = $val['value'];
    }
  }
  return $parent['children'];
}

Ps: Note that the xml parsing for some reason chokes if the values contain <> (even inside ""). You need to escape them as &lt; and &gt;.
Same for & (for obvious reasons). Escape it as &amp;.
For example "&nbsp;" should be written as "&amp;nbsp;".
09-Aug-2002 01:20
This is based on a comment above by mh@mainlab.de.  This version makes more sense to me and I included a few comments that might make it more usefull for specific purposes.

// Look through $vals and $index,
// generated by parse_xml_data(),
// for $location.  $location resembles a unix path.
// E.g. "my/xml/path/to/my/data".
// Note: This is NOT a full-feature xml utility.
// Your path must be unique in the xml data
// and the tags must not contain slashes.
//
// returns: cdata from last element of $location
//          or NULL.
function get_xml_values($vals, $index, $location) {
  $location = explode('/', $location);
  $location_level = count($location);
  for ($n=0; $n<$location_level; ++$n) {
    $val_indexes=$index[$location[$n]];
    $good=0;
    for ($i=0; $i<count($val_indexes); ++$i) {
      $v = $vals[$val_indexes[$i]];
      // level is 1 based, n is 0 based:
      if ($v['level']-1 == $n) {
        if ($v['type'] == 'open') {
          // We found an open tag at the correct level.
          $good=1;
          break; // Remove break to avoid 'open' hiding
                 // 'complete' at last $n. (Speed Vs. Robustness:
                 // For now, I'm going with speed).
        }
        if ($v['type'] == 'complete') {
          // We found it, after finding all the prior elements:
          // You may want to change this to
          // return $v
          // so you can call $v['value'] and $v['attributes']
          return $v['value'];
        }
      }
    }
    if (!$good) {
      return NULL;
    }
  }
}
farinspace-at-hotmail-dot-com 20-Jul-2002 06:41
Wow, took a while to consume all of this. I am a noobie at XML, in fact i just really started working with it today. I went ahead and added to the above code by gdemartini@bol.com.br. I also added the update by nyk@cowham.net.

Added 'value' => $vals[$i]['value'] to the open case, as some nodes have both cdata as well as a children node. In previous versions of the functions the cdata of a node(a) that also had children would get stored in the children's array of the parent node(a). Now only children values are in the children array and the cdata is in the value key of the parent node(a).

Added 'value' => $vals[$i]['value'] to tree array as the vals array produced by PHP includes a value to the top most node if no children exist (for completeness).

Also, using xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,1) will strip all white space from both around the XML tags as well as inside the cdata. I added a piece of code by waldo@wh-e.com to take care of this. All SPACE characters are now only stripped from around the XML tags and cdata spacing is retained.

CODE:
***************************************

function GetChildren($vals, &$i) {

    $children = array();

    while (++$i < sizeof($vals)) {

        // compair type
        switch ($vals[$i]['type']) {

            case 'cdata':
                $children[] = $vals[$i]['value'];
                break;
            case 'complete':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value']
                );
                break;
            case 'open':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value'],
                    'children' => GetChildren($vals, $i)
                );
                break;
            case 'close':
                return $children;
        }
    }
}

function GetXMLTree($file) {

    $data = implode('', file($file));

    // by: waldo@wh-e.com - trim space around tags not within
    $data = eregi_replace(">"."[[:space:]]+"."<","><",$data);

    // XML functions
    $p = xml_parser_create();

    // by: anony@mous.com - meets XML 1.0 specification
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parse_into_struct($p, $data, &$vals, &$index);
    xml_parser_free($p);

    $i = 0;
    $tree = array();
    $tree[] = array(
        'tag' => $vals[$i]['tag'],
        'attributes' => $vals[$i]['attributes'],
        'value' => $vals[$i]['value'],
        'children' => GetChildren($vals, $i)
    );

    return $tree;
}

***************************************
dave at ovumdesign dot com 03-Apr-2002 03:32
Here is another variation on gdemartini@bol.com.br's nice tree algorithm. I have included nyk@cowham.net's "cdata" suggestion. I made a few changes to suppress unitialized variable warnings with error_reporting(E_ALL), and made a few stylistic changes.

There are two functional modifications as well. The first is the added option to expat to turn off "case folding", since XML is technically a case-sensitive language. The second is the returned tree - instead of returning a single-element list (an array with index 0 pointing to the top node) like the original algorithm, it returns the top node itself. This saves you an unnecessary level of indirection.

function xml_get_children($vals, &$i) {
    $children = array();
    if (isset($vals[$i]['value'])) $children[] = $vals[$i]['value'];

    while (++$i < count($vals)) {
        switch ($vals[$i]['type']) {
        case 'cdata':
            $children[] = $vals[$i]['value'];
            break;

        case 'complete':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'value'      => $vals[$i]['value'],
            );
            break;

        case 'open':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'children'   => xml_get_children($vals, $i),
            );
            break;

        case 'close':
            return $children;
        }
    }
}

function xml_get_tree($file) {
    $data = join('', file($file));

    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,   1);
    xml_parse_into_struct($parser, $data, $vals, $index);
    xml_parser_free($parser);

    return array(
        'tag'        => $vals[0]['tag'],
        'attributes' => isset($vals[0]['attributes'])?
                        $vals[0]['attributes'] : null,
        'children'   => xml_get_children($vals, $i = 0),
    );
}

This function takes a tree returned by xml_get_tree() and simplifies it similarly to voncken@mailandnews.com and oknapp@soly.de's suggestions. It finds any nodes that expat considered "complete" (childless) and contain no attributes, and it moves the tag name (as the key) and value into an element in the parent node's "values" array.

For example:
$tree = xml_get_tree('moldb.xml');
$tree = xml_condense_tree($tree);
echo $tree['children'][1]['values']['name'];

Outputs:
Lysine

function xml_condense_tree($tree) {
    foreach ($tree['children'] as $index => $node) {
        if (isset($node['children'])) {
            $tree['children'][$index] = xml_condense_tree($node);

        } elseif (isset($node['value']) and !$node['attributes']) {
            $tree['values'][$node['tag']] = $node['value'];
            unset($tree['children'][$index]);
        }
    }

    if (!$tree['children']) unset($tree['children']);
    return $tree;
}

Enjoy,
Dave


开始解析一个 XML 文档

  • ? xml_parse_into_struct
  • xml_parser_create_ns ?
  • PHP Manual
  • XML 解析器函数
  • 开始解析一个 XML 文档

xml_parse

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parse — 开始解析一个 XML 文档

说明

xml_parse ( resource $parser , string $data , bool $is_final = false ) : int

xml_parse() 解析 XML 文档。已配置事件的处理器根据需要被无限次调用。

参数

parser

一个指向将要使用的 XML 解析器的指针

data

需要解析的数据集。您可以多次对新的数据调用 xml_parse() 函数来分段解析一个文档；只要在解析最后一段数据时将 is_final 参数设置为 true。

is_final

如果被设置为 true，则 data 为当前解析中最后一段数据。

返回值

成功时返回1，失败时返回0

若解析失败，可以使用如下函数获取错误信息：
xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() 和
xml_get_current_byte_index()。

Note:

将 is_final 参数设置为 true，项目的错误将会报告在数据的末尾。

User Contributed Notes

Programmerdude 06-Aug-2014 07:26
Due to restrictions in libxml2 the maximum length of $data is 9.5MB. If you need to process more than 9.5MB you can do so by calling the function multiple times and setting $is_final on the last call.
alejandro dot anv at gmail dot com 13-Mar-2014 01:00
Here is my array2xml function. I made it because I coudn't find a generic recursive function that generates a prety formatted XML from any array.

Usage:

<?php echo xml2array('rootname',$myarray); ?>

or if you want to specify a spacing character(s) other than TAB:

<?php echo xml2array('rootname',$myarray,'   '); ?>

or if you want avoid spacing at all

<?php echo xml2array('rootname',$myarray,''); ?>

<?php
function array2xml($nombre,$valor,$tab="\t",$nivel=0){

if ($nivel==0) $r='<?xml version="1.0" encoding="ISO-8859-1"?>';

$arr=!is_numeric($nombre);
$spacing=str_repeat($tab,$nivel);
if ($tab!='') $newline="\n";
else $newline='';

if (is_array($valor)){

   if (count($valor)>0){
      $r.=$newline;
      //$r.=str_repeat($tab,$nivel);
      foreach($valor as $k=>$v){
         if ($arr) $r.="$spacing<$nombre>";

         if (is_array($v))  $r.=array2xml($k,$v,$tab,$nivel+$arr);
         else $r.="$spacing<$k>$v</$k>$newline";

         if ($arr) $r.="$spacing</$nombre>$newline";
         }//foreach
      }//count
   else $r.="$spacing<$nombre></$nombre>"; // it's an empty array
   }
else {
     if ($arr) $r.="$spacing<$nombre>";
     $r.=$valor;
     if ($arr) $r.="</$nombre>$newline";
     }

return $r;
}
?>
Ashok dot 893 at gmail dot com 25-Apr-2010 10:52
This is very simple way to convert all applicable objects into associative array.  This works with not only SimpleXML but any kind of object. The input can be either array or object. This function also takes an options parameter as array of indices to be excluded in the return array. And keep in mind, this returns only the array of non-static and accessible variables of the object since using the function get_object_vars().

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();

    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }

    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}
?>

Usage:

<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
?>
lz_speedy at web dot de 30-Dec-2008 10:20
Best seen xml2array function ever
<?php
function xml2array($url, $get_attributes = 1, $priority = 'tag')
{
    $contents = "";
    if (!function_exists('xml_parser_create'))
    {
        return array ();
    }
    $parser = xml_parser_create('');
    if (!($fp = @ fopen($url, 'rb')))
    {
        return array ();
    }
    while (!feof($fp))
    {
        $contents .= fread($fp, 8192);
    }
    fclose($fp);
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);
    if (!$xml_values)
        return; //Hmm...
    $xml_array = array ();
    $parents = array ();
    $opened_tags = array ();
    $arr = array ();
    $current = & $xml_array;
    $repeated_tag_index = array ();
    foreach ($xml_values as $data)
    {
        unset ($attributes, $value);
        extract($data);
        $result = array ();
        $attributes_data = array ();
        if (isset ($value))
        {
            if ($priority == 'tag')
                $result = $value;
            else
                $result['value'] = $value;
        }
        if (isset ($attributes) and $get_attributes)
        {
            foreach ($attributes as $attr => $val)
            {
                if ($priority == 'tag')
                    $attributes_data[$attr] = $val;
                else
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }
        if ($type == "open")
        {
            $parent[$level -1] = & $current;
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
            {
                $current[$tag] = $result;
                if ($attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                $current = & $current[$tag];
            }
            else
            {
                if (isset ($current[$tag][0]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    if (isset ($current[$tag . '_attr']))
                    {
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset ($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = & $current[$tag][$last_item_index];
            }
        }
        elseif ($type == "complete")
        {
            if (!isset ($current[$tag]))
            {
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            }
            else
            {
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes)
                    {
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                        if ($attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                }
            }
        }
        elseif ($type == 'close')
        {
            $current = & $parent[$level -1];
        }
    }
    return ($xml_array);
}
?>

Returns a well formed array like the structure of the xml-document

<root>
 <child1>
  <child1child1/>
 </child1>
</root>

create an array like
array[root][child1][child1child1]

lg
neoyahuu at yahoo dot com 12-Dec-2007 08:18
Instead of passing a URL, we can pass the XML content to this class (either you
 want to use CURL, Socks or fopen to retrieve it first) and instead of using
 array, I'm using separator '|' to identify which data to get (in order to make
 it short to retrieve a complex XML data). Here is my class with built-in fopen
 which you can pass URL or you can pass the content instead :

p/s : thanks to this great help page.

<?php

class xx_xml {

    // XML parser variables
    var $parser;
    var $name;
    var $attr;
    var $data  = array();
    var $stack = array();
    var $keys;
    var $path;

    // either you pass url atau contents.
    // Use 'url' or 'contents' for the parameter
    var $type;

    // function with the default parameter value
    function xx_xml($url='http://www.example.com', $type='url') {
        $this->type = $type;
        $this->url  = $url;
        $this->parse();
    }

    // parse XML data
    function parse()
    {
        $data = '';
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, 'startXML', 'endXML');
        xml_set_character_data_handler($this->parser, 'charXML');

        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);

        if ($this->type == 'url') {
            // if use type = 'url' now we open the XML with fopen

            if (!($fp = @fopen($this->url, 'rb'))) {
                $this->error("Cannot open {$this->url}");
            }

            while (($data = fread($fp, 8192))) {
                if (!xml_parse($this->parser, $data, feof($fp))) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        } else if ($this->type == 'contents') {
            // Now we can pass the contents, maybe if you want
            // to use CURL, SOCK or other method.
            $lines = explode("\n",$this->url);
            foreach ($lines as $val) {
                if (trim($val) == '')
                    continue;
                $data = $val . "\n";
                if (!xml_parse($this->parser, $data)) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        }
    }

    function startXML($parser, $name, $attr)    {
        $this->stack[$name] = array();
        $keys = '';
        $total = count($this->stack)-1;
        $i=0;
        foreach ($this->stack as $key => $val)    {
            if (count($this->stack) > 1) {
                if ($total == $i)
                    $keys .= $key;
                else
                    $keys .= $key . '|'; // The saparator
            }
            else
                $keys .= $key;
            $i++;
        }
        if (array_key_exists($keys, $this->data))    {
            $this->data[$keys][] = $attr;
        }    else
            $this->data[$keys] = $attr;
        $this->keys = $keys;
    }

    function endXML($parser, $name)    {
        end($this->stack);
        if (key($this->stack) == $name)
            array_pop($this->stack);
    }

    function charXML($parser, $data)    {
        if (trim($data) != '')
            $this->data[$this->keys]['data'][] = trim(str_replace("\n", '', $data));
    }

    function error($msg)    {
        echo "<div align=\"center\">
            <font color=\"red\"><b>Error: $msg</b></font>
            </div>";
        exit();
    }
}

?>

And example of retrieving XML data:
p/s: example use to retrieve weather

<?php
include_once "xx_xml.class.php";

// Im using simple curl (the original is in class) to get the contents

$pageurl = "http://xml.weather.yahoo.com/forecastrss?p=MYXX0008&u=c";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $pageurl );
$thecontents = curl_exec ( $ch );
curl_close($ch);

// We want to pass only a ready XML content instead of URL
// But if you want to use URL , skip the curl functions above and use this
// $xx4 = new xx_xml("url here",'url');

$xx4 = new xx_xml($thecontents,'contents');
// As you can see, we use saparator '|' instead of long array
$Code = $xx4->data ['rss|channel|item|yweather:condition']['code'] ;
$Celcius = $xx4->data ['rss|channel|item|yweather:condition']['temp'] ;
$Text = $xx4->data ['rss|channel|item|yweather:condition']['text'] ;
$Cityname = $xx4->data ['rss|channel|yweather:location']['city'] ;

?>

Hope this helps.
joris dot landman at chello dot nl 28-Jul-2007 07:42
This page has been a great help! I've adapted the examples below to make a class to parse an X(HT)ML file to a multidimensional array.

Spaces, tabs, breaks, etc. are included in the array as TEXT_NODE, since in XHTML they may be functional. A function to trim them can easily be added if so desired.

I've written my class to store multiple tags with the same name. In order to do this I've used nested arrays with the key NODES to store the order in which tags and data were parsed. These NODES arrays can be used as a blueprint to reconstruct the X(HT)ML part of the document in it's entirity, including formatting. (Doctype will have to be added for validity).

<?php

class my_xml_object {

    var $xml_data; # raw xml data from file
    function parse_xml_file($my_uri) {
        $this->xml_data = null; # clear previously parsed file and related variables
        if (is_file($my_uri) && is_readable($my_uri)) { # existing and readable uri?
            $my_file = fopen($my_uri, "r");
            while($my_xml_input = fread($my_file, filesize($my_uri))) {
                $this->xml_data .= $my_xml_input; # add data to xml_data
            }
            fclose($my_file);
            $this->parse_xml_data($this->xml_data); # parse data
        } else {
            trigger_error("supplied argument is not a URI to a (readable) file", E_USER_ERROR);
        }
    }

    var $xml_array = Array(); # xml array from parsed data
    function parse_xml_data($my_data) { # adapted from class by randlem@gmail.com, tgrabietz@bupnet.de, bbellwfu@gmail.com, Kyle Bresin - see http://nl2.php.net/xml_parse
        $this->xml_array = Array(0 => Array()); # clear previously parsed file and related variables; populate first element
        $my_parser = xml_parser_create(); # set up parser
        xml_set_object($my_parser, $this); # enable parser within object
        xml_set_element_handler($my_parser, "xml_tag_open", "xml_tag_close");
        xml_set_character_data_handler($my_parser, "xml_tag_data");
        if (!xml_parse($my_parser, $my_data)) {
            trigger_error("data can not be parsed", E_USER_ERROR); # inspect problems #die(sprintf("<br />\n<b>Error</b>:  %s on line <b>%d</b><br />\n", xml_error_string(xml_get_error_code($my_parser)), xml_get_current_line_number($my_parser)));
        }
        xml_parser_free($my_parser); # free parser
        return $this->xml_array; # return xml array
    }

    var $my_branch = Array();
    function xml_tag_open($my_parser, $my_name, $my_attributes) {
        array_push($this->my_branch, $my_name); # add tag name to branch
        $this->xml_array[] = Array(); # nest array in xml array for data
        if (count($my_attributes)) {
            $this->xml_array[count($this->xml_array) - 1]["ATTRIBUTES"] = $my_attributes; # nest attributes array
        }
    }

    function xml_tag_data($my_parser, $my_data) {
        $this->xml_array[count($this->my_branch)]["TEXT_NODE"][] = $my_data; # add data to nested array
        $this->xml_array[count($this->my_branch)]["NODES"][] = "TEXT_NODE"; # add text node to nested NODES array
    }

    function xml_tag_close($my_parser, $my_name) {
        $this->xml_array[count($this->my_branch) - 1][$this->my_branch[count($this->my_branch) - 1]][] = $this->xml_array[count($this->xml_array) - 1]; # nest arrays to follow document structure
        array_pop($this->xml_array); # pop off element that was nested
        $this->xml_array[count($this->my_branch) - 1]["NODES"][] = $my_name; # add tag node to nested NODES array
        array_pop($this->my_branch); # update branch
    }

?>
dgrimes at scvl dot com 29-Jun-2007 06:14
One note about magic quotes: magic_quotes_runtime needs to be disabled before parsing XML. It can cause strange errors during parsing. Just add the following at the top of your program:

set_magic_quotes_runtime(0);

If you need magic quotes you can use stripslashes or save the current magic quotes setting with get_magic_quotes_runtime() then disable and parse your XML and then restore the previous magic quotes setting.
php at b635 dot com 23-Jun-2007 10:17
The suggestions below have been a great help, but there was one thing I really needed...

I'm parsing Amazon XML data, and I wanted to be able to index into the array using something like:

<?php
  print "<p>" . $strAXML->arrOutput[ITEMLOOKUPRESPONSE][ITEMS][ITEM][SMALLIMAGE][URL];
?>

To solve this, I had to push all of the open tags onto a separate stack, add any tag data to the tail end of an attributed multi-dimensional array, and then pop the tag name off of the stack once it was closed...

<?php

class xml2array {

  var $arrOutput = array();
  var $arrName = array();
  var $objParser;
  var $strXmlData;

  function parse($strInputXML) {

    // standard XML parse object setup

    $this->objParser = xml_parser_create ();
    xml_set_object($this->objParser,$this);
    xml_set_element_handler($this->objParser, "tagOpen", "tagClosed");

    xml_set_character_data_handler($this->objParser, "tagData");

    $this->strXmlData = xml_parse($this->objParser,$strInputXML );
    if(!$this->strXmlData) {
      die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->objParser)),
        xml_get_current_line_number($this->objParser)));
    }

    xml_parser_free($this->objParser);

    return $this->arrOutput;
  }

  function tagOpen($parser, $name, $attrs) {
    // push the current tag name to an array of still-open tag names
    array_push ($this->arrName, $name);

    // merge the array of current attributes to the open tag
    // NOTE: this does not currently handle multiple attributes with the same name
    // (i.e. it will overwrite them with the last values)

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }
    $strEval = $strEval . " = array_merge (" . $strEval . ",\$attrs);";

    eval ($strEval);
  }

  function tagData($parser, $tagData) {

    // set the latest open tag equal to the tag data

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }

    $strEval = $strEval . " = \$tagData;";

    eval ($strEval);
  }

  function tagClosed($parser, $name) {

    // pop this tag (and any subsequent tags) off the stack of open tag names

    for ($i = count ($this->arrName) - 1; $i > 0; $i--) {
      $currName = $this->arrName[$i];
      array_pop ($this->arrName);
      if ($currName == $name) {
        break;
      }
    }
  }

}

?>
james @at@ mercstudio dot Com dot nospam 02-Apr-2006 12:10
hi,

i've modified bbellwfu at gmail dot com to as below:

features added:
  - toXML (convert back array to xml string)
  - changed name, according to macromedia flash xml concept : children -> childrens, tagdata -> nodevalue, name -> nodename,
  - added pointer firstchild to childrens[0] (if exists)

some findings that i would like to share:
 - <![cdata[my value here]]> (does not work on property value
 - xml file must be htmlentity based (if not using cdata)
 - xml line feed on node data seems to be double line feed on windows (still figuring why)
 - xml line feed on attribute value seems to be ignored...

here's my code below :)

class u007xml
{
   var $arrOutput = array();
   var $resParser;
   var $strXmlData;

    function u007xml($tfile = "")
    {
        if(trim($tfile) != "") { $this->loadFile($tfile);}
    }

    function loadFile($tfile)
    {
        $this->thefile = $tfile;

        $th = file($tfile);
        $tdata = implode("\n", $th);

        return $this->parse($tdata);
    }

   function parse($strInputXML)
   {
        $this->resParser = xml_parser_create ();
        xml_set_object($this->resParser,$this);
        xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

        xml_set_character_data_handler($this->resParser, "tagData");

        $this->strXmlData = xml_parse($this->resParser,$strInputXML );

        if(!$this->strXmlData) {
           die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->resParser)),
        xml_get_current_line_number($this->resParser)));
        }

        xml_parser_free($this->resParser);

        return $this->arrOutput;
   }

   //called on each xml tree
   function tagOpen($parser, $name, $attrs) {
       $tag=array("nodename"=>$name,"attributes"=>$attrs);
       array_push($this->arrOutput,$tag);
   }

  //called on data for xml
   function tagData($parser, $tagData) {
       if(trim($tagData)) {
           if(isset($this->arrOutput[count($this->arrOutput)-1]['nodevalue'])) {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] .= $this->parseXMLValue($tagData);
           }
           else {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] = $this->parseXMLValue($tagData);
           }
       }
   }

  //called when finished parsing
   function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['childrens'][] = $this->arrOutput[count($this->arrOutput)-1];

       if(count ($this->arrOutput[count($this->arrOutput)-2]['childrens'] ) == 1)
       {
            $this->arrOutput[count($this->arrOutput)-2]['firstchild'] =& $this->arrOutput[count($this->arrOutput)-2]['childrens'][0];
       }
       array_pop($this->arrOutput);
   }

    function toArray()
    {
        //not used, we can call loadString or loadFile instead...
    }

    function parseXMLValue($tvalue)
    {
        $tvalue = htmlentities($tvalue);
        return $tvalue;
    }

    function toXML($tob = null)
    {
        //return back xml
        $result = "";

        if( $tob == null)
        {
            $tob = $this->arrOutput;
        }

        if(!isset($tob))
        {
            echo "XML Array empty...";
            return null;
        }

        for($c = 0; $c < count($tob); $c++)
        {
            $result .="<" . $tob[$c]["nodename"];

            while (list($key, $value) = each($tob[$c]["attributes"]))
            {
                $result .=" " . $key."=\"" . $this->parseXMLValue($value) . "\"";
            }

            $result .= ">";

            //assign node value
            if( isset($tob[$c]["nodevalue"]) )
            {
                $result .= $tob[$c]["nodevalue"];
            }

            if( count($tob[$c]["childrens"]) > 0 )
            {
                $result .= "\r\n" . $this->toXML(&$tob[$c]["childrens"]) . "";
            }

            $result .= "</" . $tob[$c]["nodename"] . ">\r\n";

        }//end of each array...

        return $result;
    }

    function displayXML()
    {
        print_r($this->arrOutput);
    }

    function getXML($tob = null)
    {
        return "<?xml version='1.0'?>\r\n" . $this->toXML($tob);
    }

}//end of u007xml class

//examples below:

$xx = new u007xml();
$xx->loadFile("xml3.xml");

//$xx->displayXML();

print $xx->getXML();
ben at autonomic dot net 16-Mar-2006 05:12
bbellwfu's code does not handle 'text nodes' properly.
Consider the innards of a tag like <root>xxx<tag2/>yyy</root>
The 'tagData' for root will be "xxxyyy" and you have lost all information about where "tag2" was in that sequence.

Quick and dirty hack.

Replace tagData with this code :
   function tagData($parser, $tagData) {
          $last_element=count($this->arrOutput)-1;
        $this->arrOutput[$last_element]['children'][] = array("textnode",$tagData);
   }

What this does is adds 'textnodes' as children of its containing parent, *in the right sequence* (rather like the internet browsers do it). This then lets you do some more sensible secondary work like recursively looking up internal references within the document...
Kyle Bresin 19-Jan-2006 03:15
Just wanted to note a small bug in bbellwfu's class (which is really great btw).

It fails to capture any datums which are equal to numerical zero.

The problem lies in the function tagData, the first if statement should be:

if(trim($tagData) != '') {
tim at alloutinteraction dot com 01-Oct-2005 07:29
I wanted to create a really simple XML parser, but I found the array management in xml_parse a bit daunting. So I flattened my XML and parsed it using string matching. It wouldn't be difficult to add xml depth (of 2 plus levels) by modifying the parsedXML array.

<?
// here's the raw html
$xmlRaw="<order>Order data</order><label>Label data</label><control>123</control>";
// here are the xml field names
$xmlFieldNames=array("order", "label", "control");
// for each xml field...
foreach ($xmlFieldNames as $xmlField) {
    if(strpos($xmlRaw,$xmlField)!==false){
        // I've broken 1 single line into 4 for display purposes
        $parsedXML[$xmlField]=substr($xmlRaw,
        strpos($xmlRaw,"<$xmlField>")+strlen("<$xmlField>"),
        strpos($xmlRaw,"</$xmlField>")-strlen("<$xmlField>")
        -strpos($xmlRaw,"<$xmlField>"));
    }
}
print_r($parsedXML);
// prints: Array ( [order] => Order data [label] => Label data [control] => 123 )

?>

Hope you find this useful (coded it while ill in bed with streaming cold, but felt much better afterwards!)

Tim (a lazy coder)
bbellwfu at gmail dot com 05-May-2005 02:51
Just improving a little bit on the code examples from tgrabietz and randlem below... everything in one pretty class, plus some checks in place so that the element data doesnt get split up (thanks to flobee on the xml_set_character_data_handler page)

<?php

/* Usage
 Grab some XML data, either from a file, URL, etc. however you want. Assume storage in $strYourXML;

 $objXML = new xml2Array();
 $arrOutput = $objXML->parse($strYourXML);
 print_r($arrOutput); //print it out, or do whatever!

*/
class xml2Array {

    var $arrOutput = array();
    var $resParser;
    var $strXmlData;

    function parse($strInputXML) {

            $this->resParser = xml_parser_create ();
            xml_set_object($this->resParser,$this);
            xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

            xml_set_character_data_handler($this->resParser, "tagData");

            $this->strXmlData = xml_parse($this->resParser,$strInputXML );
            if(!$this->strXmlData) {
               die(sprintf("XML error: %s at line %d",
            xml_error_string(xml_get_error_code($this->resParser)),
            xml_get_current_line_number($this->resParser)));
            }

            xml_parser_free($this->resParser);

            return $this->arrOutput;
    }
    function tagOpen($parser, $name, $attrs) {
       $tag=array("name"=>$name,"attrs"=>$attrs);
       array_push($this->arrOutput,$tag);
    }

    function tagData($parser, $tagData) {
       if(trim($tagData)) {
            if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
            }
            else {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
            }
       }
    }

    function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1];
       array_pop($this->arrOutput);
    }
}
?>

Will output something like...

<snippet>
Array
(
    [0] => Array
        (
            [name] => GETMESSAGESRESPONSE
            [attrs] => Array
                (
                )

            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => STATUS
                            [attrs] => Array
                                (
                                )

                        )

</snippet>
alex dot garcia at noos dot fr 14-Mar-2005 01:47
Here is the inverse function which takes parsed xml array in entry and outputs xml string

enjoy !

function getXmlFromArray($root){

        if(count($root) > 0){

            $curr_name = $root['name'];
            $attribs = $root['attrs'];
            $curr_childs = $root['children'];
            $curr_data = $root['cdata'];

            $xml .= '<'.$curr_name;

            if(count($attribs) > 0){
                $i = 1;
                foreach($attribs as $key => $value){
                    $curr_attribs .= $key.'="'.$value.'"';
                    $i++;
                    if($i <= count($attribs)){
                        $curr_attribs .= ' ';
                    }
                }
                $xml .= ' '.$curr_attribs;
            }

            if($curr_data != ''){
                $xml .= '><![CDATA['.$curr_data.']]></'.$curr_name.'>';
            } else {
                if(count($curr_childs) > 0){
                    $xml .= '>';
                    foreach($curr_childs as $child){
                        $xml .= getXmlFromArray($child);
                    }
                    $xml .= '</'.$curr_name.'>';
                } else {
                    $xml .= '/>';
                }
            }

        }
        return $xml;
    }
tgrabietz at bupnet dot de 22-Sep-2004 08:05
it's like randlem at gmail dot com's great code, without using a "class container" but parsing cdata. The script returns the tree-structure in a single array.

<?php
$file = 'simple.xml';
$stack = array();

function startTag($parser, $name, $attrs)
{
   global $stack;
   $tag=array("name"=>$name,"attrs"=>$attrs);
   array_push($stack,$tag);

}

function cdata($parser, $cdata)
{
    global $stack,$i;

    if(trim($cdata))
    {
        $stack[count($stack)-1]['cdata']=$cdata;
    }
}

function endTag($parser, $name)
{
   global $stack;
   $stack[count($stack)-2]['children'][] = $stack[count($stack)-1];
   array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "cdata");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
   die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}

xml_parser_free($xml_parser);

print("<pre>\n");
print_r($stack);
print("</pre>\n");
?>
ByK 16-Sep-2004 08:12
modified from yours code. I think it's work!!.
class CXml
{
    var $xml_data;
    var $obj_data;
    var $pointer;

    function CXml() { }

    function Set_xml_data( &$xml_data )
    {
        $this->index = 0;
        $this->pointer[] = &$this->obj_data;

        //strip white space between tags
        $this->xml_data = eregi_replace(">"."[[:space:]]+"."<","><",$xml_data);
        $this->xml_parser = xml_parser_create( "UTF-8" );

        xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
        xml_set_object( $this->xml_parser, &$this );
        xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
        xml_set_character_data_handler( $this->xml_parser, "_cData" );

        xml_parse( $this->xml_parser, $this->xml_data, true );
        xml_parser_free( $this->xml_parser );
    }

    function _startElement( $parser, $tag, $attributeList )
    {
        foreach( $attributeList as $name => $value )
        {
            $value = $this->_cleanString( $value );
            $object->$name = $value;
        }
        //replaces the special characters with the underscore (_) in tag name
        $tag = preg_replace("/[:\-\. ]/", "_", $tag);
        eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
        eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
        eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

        $this->index++;
    }

    function _endElement( $parser, $tag )
    {
        array_pop( $this->pointer );
        $this->index--;
    }

    function _cData( $parser, $data )
    {
        if (empty($this->pointer[$this->index])) {
            if (rtrim($data, "\n"))
                $this->pointer[$this->index] = $data;
        } else {
            $this->pointer[$this->index] .= $data;
        }
    }

    function _cleanString( $string )
    {
        return utf8_decode( trim( $string ) );
    }
}

$m_xml = new CXml();
$xml_data = file_get_contents( $filename );

$m_xml->Set_XML_data( $xml_data );

$newsid = $m_xml->obj_data->root[0]->NewsID[0];
randlem at gmail dot com 15-Sep-2004 08:43
Here's a handy way to generate a tree that can be can be decended easily.

<?php
$file = 'xmltest.xml';

$tag_tree = array();
$stack = array();

class tag {
    var $name;
    var $attrs;
    var $children;
    function tag($name, $attrs, $children) {
        $this->name = $name;
        $this->attrs = $attrs;
        $this->children = $children;
    }
}

function startTag($parser, $name, $attrs) {
    global $tag_tree, $stack;
    $tag = new tag($name,$attrs,'');
    array_push($stack,$tag);
}

function endTag($parser, $name) {
    global $stack;
    $stack[count($stack)-2]->children[] = $stack[count($stack)-1];
    array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
    die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}

xml_parser_free($xml_parser);

print("\n");
print_r($stack);
print("\n");
?>
michelek 26-Oct-2003 10:42
its maybe not better, but me thinks its more stright-forward

--INPUT:

<?xml version="1.0" encoding="UTF-8"?>
<world>
    <country name="sweden">
        <city name="stockholm">
            <user>Adam</user>
            <user>Eva</user>
        </city>
        <city name="g?teborg">
            <user>God</user>
        </city>
    </country>
    <country name="usa">
        <city name="new york">
            <user>Clinton</user>
            <user>Bush</user>
        </city>
    </country>
</world>

--CODE:
<?
/**
 * m_i_h_k_e_l_AT_w_w_DOT_e_e
 * 26.10.2003
**/
$filename = "m.m.xml";
$xmlC = new XmlC();
$xml_data = file_get_contents( $filename );

$xmlC->Set_XML_data( $xml_data );

echo( "<pre>\n" );
print_r( $xmlC->obj_data );
echo( "</pre>\n" );

class XmlC
{
  var $xml_data;
  var $obj_data;
  var $pointer;

  function XmlC()
  {
  }

  function Set_xml_data( &$xml_data )
  {
    $this->index = 0;
    $this->pointer[] = &$this->obj_data;

    $this->xml_data = $xml_data;
    $this->xml_parser = xml_parser_create( "UTF-8" );

    xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
    xml_set_object( $this->xml_parser, &$this );
    xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
    xml_set_character_data_handler( $this->xml_parser, "_cData" );

    xml_parse( $this->xml_parser, $this->xml_data, true );
    xml_parser_free( $this->xml_parser );
  }

  function _startElement( $parser, $tag, $attributeList )
  {
    foreach( $attributeList as $name => $value )
    {
      $value = $this->_cleanString( $value );
      $object->$name = $value;
    }
    eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
    eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
    eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

    $this->index++;
  }

  function _endElement( $parser, $tag )
  {
    array_pop( $this->pointer );
    $this->index--;
  }

  function _cData( $parser, $data )
  {
    if( trim( $data ) )
    {
      $this->pointer[$this->index] = trim( $data );
    }
  }

  function _cleanString( $string )
  {
    return utf8_decode( trim( $string ) );
  }

}
?>
Adam Tylmad 11-Sep-2003 01:11
I've created a parser that returns an
object based on a xml document.

example:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<country name="sweden">
    <city name="stockholm">
        <user>Adam</user>
        <user>Eve</user>
    </city>
    <city name="g?teborg">
        <user>God</user>
    </city>
</country>
<country name="usa">
    <city name="new york">
        <user>Clinton</user>
        <user>Bush</user>
    </city>
</country>

generates the following object structure:
[country] => Array
(
    [0] => stdClass Object
        (
            [name] => sweden
            [city] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => stockholm
                            [user] => Array
                                (
                                    [0] => Adam
                                    [1] => Eve
                                )
                        )
                    [1] => stdClass Object
                        (
                            [name] => g?teborg
                            [user] => God
                        )
                )
        )
    [1] => stdClass Object
        (
            [name] => usa
            [city] => stdClass
                (
                    [name] => new york
                    [user] => Array
                        (
                            [0] => Clinton
                            [1] => Bush
                        )
                )
        )
)

Here is the code:

class XMLParser {
    var $path;
    var $result;

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

        function startElement($parser, $tag, $attributeList) {
            eval("\$vars = get_object_vars(".$this->path.");");
            $this->path .= "->".$tag;
            if ($vars and array_key_exists($tag, $vars)) {
                 eval("\$data = ".$this->path.";");
                     if (is_array($data)) {
                           $index = sizeof($data);
                           $this->path .= "[".$index."]";
                     } else if (is_object($data)) {
                           eval($this->path." = array(".$this->path.");");
                           $this->path .= "[1]";
                     }
            }
            eval($this->path." = null;");

            foreach($attributeList as $name => $value)
                eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
        }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        eval($this->path." = '".trim($data)."';");
    }
}

enjoy! And please make it better if you can ;-)


生成一个支持命名空间的 XML 解析器

  • ? xml_parse
  • xml_parser_create ?
  • PHP Manual
  • XML 解析器函数
  • 生成一个支持命名空间的 XML 解析器

xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

xml_parser_create_ns — 生成一个支持命名空间的 XML 解析器

描述

xml_parser_create_ns ( string $encoding = ? , string $sep = ? ) : resource

函数 xml_parser_create_ns() 建立一个新的支持 XML 命名空间的解析器并返回可被其它 XML 函数使用的资源句柄。

通过有命名空间支持的解析器，传递给各种各样句柄函数的标签参数将由命名空间和标签名组成。命名空间和标签名的分隔符由 seperator 参数制定的字符串决定，其默认值为":"。

可选参数 encoding 在 PHP 4 中用来指定要被解析的 XML 输入的字符编码方式。PHP 5 开始，自动侦测输入的 XML 的编码，因此 encoding 参数仅用来指定解析后输出数据的编码。在 PHP 4 总，默认输出的编码与输入数据的编码是相同的。如果传递了空字符串，解析器会尝试搜索头 3 或 4 个字节以确定文档的编码。在 PHP 5.0.0 和 5.0.1 总，默认输出的字符编码是 ISO-8859-1，而 PHP 5.0.2 及以上版本是 UTF-8。解析器支持的编码有 ISO-8859-1, UTF-8 和 US-ASCII。

请参阅函数 xml_parser_create() 和 xml_parser_free()。

User Contributed Notes

bishop at php dot net 17-Feb-2019 04:24
Internals has proposed[1] changing this extension from resource-based to object-based. When this change is made, xml_parser_create_ns will return an object, not a resource. Application developers are encouraged to replace any checks for explicit success, like:

<?php
$res = xml_parser_create_ns(/*...*/);
if (! is_resource($res)) {
    // ...
}
?>

With a check for explicit failure:
<?php
$res = xml_parser_create_ns(/*...*/);
if (false === $res) {
    // ...
}

[1]: https://marc.info/?l=php-internals&m=154998365013373&w=2
jonnyNO at SPAM dot sanriowasteland dot net 11-Jun-2002 05:49
This is from the Expat Function Reference by Clark Cooper, which is a reference to the C api.

"XML_Parser XML_ParserCreateNS(const XML_Char*encoding, XML_Char sep)
Constructs a new parser that has namespace processing in effect. Namespace expanded element names and attribute names are returned as a concatenation of the namespace URI, sep, and the local part of the name. This means that you should pick a character for sep that can't be part of a legal URI."

(from http://www.xml.com/pub/a/1999/09/expat/reference.html)

So thats what this function is for.  Now you know.


建立一个 XML 解析器

  • ? xml_parser_create_ns
  • xml_parser_free ?
  • PHP Manual
  • XML 解析器函数
  • 建立一个 XML 解析器

xml_parser_create

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_create — 建立一个 XML 解析器

描述

xml_parser_create ( string $encoding = ? ) : resource

函数 xml_parser_create() 建立一个新的 XML 解析器并返回可被其它 XML 函数使用的资源句柄。

可选参数 encoding 在 PHP 4 中用来指定要被解析的 XML 输入的字符编码方式。PHP 5 开始，自动侦测输入的 XML 的编码，因此 encoding 参数仅用来指定解析后输出数据的编码。在 PHP 4 总，默认输出的编码与输入数据的编码是相同的。如果传递了空字符串，解析器会尝试搜索头 3 或 4 个字节以确定文档的编码。在 PHP 5.0.0 和 5.0.1 总，默认输出的字符编码是 ISO-8859-1，而 PHP 5.0.2 及以上版本是 UTF-8。解析器支持的编码有 ISO-8859-1, UTF-8 和 US-ASCII。

请参阅函数 xml_parser_create_ns() 和 xml_parser_free()。

User Contributed Notes

bishop at php dot net 17-Feb-2019 04:23
Internals has proposed[1] changing this extension from resource-based to object-based. When this change is made, xml_parser_create will return an object, not a resource. Application developers are encouraged to replace any checks for explicit success, like:

<?php
$res = xml_parser_create(/*...*/);
if (! is_resource($res)) {
    // ...
}
?>

With a check for explicit failure:
<?php
$res = xml_parser_create(/*...*/);
if (false === $res) {
    // ...
}

[1]: https://marc.info/?l=php-internals&m=154998365013373&w=2
marek995 at seznam dot cz 24-Sep-2010 11:46
I created a function, which combines xml_paresr_create and all functions around.

<?php
function html_parse($file)
     {
      $array = str_split($file, 1);
      $count = false;
      $text = "";
      $end = false;
      foreach($array as $temp)
       {
        switch($temp)
         {
          case "<":
           between($text);
           $text = "";
           $count = true;
           $end = false;
           break;
          case ">":
           if($end == true) {end_tag($text);}
           else {start_tag($text);}
           $text = "";
           break;
          case "/":
           if($count == true) {$end = true;}
           else {$text = $text . "/";}
           break;
          default:
           $count = false;
           $text = $text . $temp;
         }
       }
     }
?>
The input value is a string.
It calls functions start_tag() , between() and end_tag() just like the original xml parser.

But it has a few differences:
  - It does NOT check the code. Just resends values to that three functions, no matter, if they are right
  - It works with parameters. For example: from tag <sth b="42"> sends sth b="42"
  - It works wit diacritics. The original parser sometimes wrapped the text before the first diacritics appearance.
  - Works with all encoding. If the input is UTF-8, the output will be UTF-8 too
  - It works with strings. Not with file pointers.
  - No "Reserved XML name" error
  - No doctype needed
  - It does not work with commentaries, notes, programming instructions etc. Just the tags

definition of the handling functions is:

<?php
function between($stuff) {}
?>

No other attributes
juanhdv at NOSPAM dot divvol dot org 05-Dec-2007 12:08
In PHP 5, when including in your xml file the definition '<?xml version="1.0" encoding="ISO-8859-1" ?>',   I'd also recommend adding the option below:

xml_parser_set_option($xml_parser,XML_OPTION_TARGET_ENCODING, "ISO-8859-1").

It works fine!

If your enconding is 'UTF-8', just replace 'ISO-8859-1'.
19-Apr-2006 07:42
I'd also recommend adding the option below
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
Tobbe 25-May-2005 06:01
The above "XML to array" code does not work properly if you have several tags on the same level and with the same name, example:

<currenterrors>
<error>
<description>This is a real error...</description>
</error>
<error>
<description>This is a second error...</description>
</error>
<error>
<description>Lots of errors today...</description>
</error>
<error>
<description>This is the last error...</description>
</error>
</currenterrors>

It will then only display the first <error>-tag.
In this case you will need to number the tags automatically or maybe have several arrays for each new element.
php at stock-consulting dot com 21-Feb-2005 02:47
Even though I passed "UTF-8" as encoding type PHP (Version 4.3.3) did *not* treat the input file as UTF-8. The input file was missing the BOM header bytes (which may indeed be omitted, according to RFC3629...but things are a bit unclear there. The RFC seems to make mere recommendations concering the BOM header). If you want to sure that PHP treats an UTF-8 encoded file correctly, make sure that it begins with the corresponding 3 byte BOM header (0xEF 0xBB 0xBF)
jcalvert at gmx dot net 03-Apr-2004 10:39
To maintain compatibility between PHP4 and PHP5 you should always pass a string argument to this function. PHP4 autodetects the format of the input if you leave it out whereas PHP5 will assume the format to be ISO-8859-1 (and choke on the byte order marker of UTF-8 files).

Calling the function as <?php $res = xml_parser_create('') ?> will cause both versions of PHP to autodetect the format.


释放指定的 XML 解析器

  • ? xml_parser_create
  • xml_parser_get_option ?
  • PHP Manual
  • XML 解析器函数
  • 释放指定的 XML 解析器

xml_parser_free

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_free — 释放指定的 XML 解析器

描述

xml_parser_free ( resource $parser ) : bool

parser
指向要释放的 XML 解析器的指针。

如果 parser 参数没有指向一个合法的解析器，该函数将返回 false，否则将释放指定的解析器并返回 true。

User Contributed Notes

nidzho 27-Aug-2016 08:12
Unset the parser after calling xml_parser_free() to prevent memory leaks:

<?php
xml_parser_free($parser);
unset($parser);
?>
dio at edu dot uni-klu dot ac dot at 01-Oct-2005 09:56
If you try to free an XML parser while it is still parsing, strange things will happen - your script will "hang" and no output will be sent to the browser. Consider this pseudo-code example:

-------

...
if (!xml_parse($parser)) echo 'XML error';

xml_parser_free($parser);

...

function SomeCallbackWhichWasSetBefore(...)
{
global $parser;

...

if (some_error_happened) xml_parser_free($parser);  //problem!

...

}

------

It would be logical that xml_parse would return false if the parser was freed while parsing, right? Wrong! Instead, everything hangs and no output will be sent out (no matter whether output buffering is on or not). It took me more than an hour to figure out why: you cannot free a parser handle that is currently parsing. A simple solution:

-------

$xml_error = false;
if (!xml_parse($parser))
echo 'XML error (directly from parser)';
else if ($xml_error)
echo 'XML error (from some callback function);

xml_parser_free($parser);

...

function SomeCallbackWhichWasSetBefore(...)
{
global $parser;
global $xml_error;

if ($xml_error)
return;

...

if (some_error_occured)
{
$xml_error = false;
return;
}

...

}

-------

If you use this solution you will have to check for $xml_error in every callback function. Essentially what you're doing is that, in case you want to stop parsing because of an error, you continue until xml_parse() is finished (without actually doing anything) and then free the parser and act on the error.

Of course the underlying problem is that you cannot stop a parser while it is parsing. There should be some function like xml_throw_error() or xml_parser_stop() or whatever, but unfortunately there isn't.
php dot net at gwprogramming dot com (George Webb) 30-Oct-2003 06:56
I found that with PHP 4.3.4RC1, if you don't call xml_parser_free() before your script ends, some sort of ugliness occurs with the webserver; i.e. the HTTP connection is closed.  (The apache error_log says "exit signal Segmentation fault (11)".)

Usually PHP tends to clean up connections you don't explicitly close (e.g. database connections), but in this case apparently it doesn't.

Some web browsers (MSIE for one) do not actually show this problem, so you may not actually notice it.  Opera 7.11 does show it, which is how I discovered it.

So don't forget to call xml_parser_free() ... always!


从 XML 解析器获取选项设置信息

  • ? xml_parser_free
  • xml_parser_set_option ?
  • PHP Manual
  • XML 解析器函数
  • 从 XML 解析器获取选项设置信息

xml_parser_get_option

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_get_option — 从 XML 解析器获取选项设置信息

描述

xml_parser_get_option ( resource $parser , int $option ) : mixed

parser
指向要获取设置信息的 XML 解析器的指针。
option
要获取的设置选项名称。可以使用 XML_OPTION_CASE_FOLDING 和 XML_OPTION_TARGET_ENCODING 常量。其说明见 xml_parser_set_option()。

如果 parser 参数没有指向一个合法的解析器或者 option 参数无效，该函数将返回 false（同时产生 E_WARNING 警告）。否则将返回指定设置选项的值。

User Contributed Notes

dnricky at hotmail dot com 24-Jun-2017 04:57
<?php
$xmlparser = xml_parser_create();

echo "XML_OPTION_CASE_FOLDING:" . xml_parser_get_option($xmlparser, XML_OPTION_CASE_FOLDING) . "<br />"; //Specifies if case-folding is enabled. Enabled by default. Can be 1 (TRUE) or 0 (FALSE)

echo "XML_OPTION_TARGET_ENCODING:" . xml_parser_get_option($xmlparser, XML_OPTION_TARGET_ENCODING ) . "<br />"; //Specifies which target encoding to use in this XML parser. By default, it is set to the same as the xml_parser_create() function. Supported target encodings are ISO-8859-1, US-ASCII and UTF-8.

xml_parser_free($xmlparser);
?>


为指定 XML 解析进行选项设置

  • ? xml_parser_get_option
  • xml_set_character_data_handler ?
  • PHP Manual
  • XML 解析器函数
  • 为指定 XML 解析进行选项设置

xml_parser_set_option

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_set_option — 为指定 XML 解析进行选项设置

说明

xml_parser_set_option ( resource $parser , int $option , mixed $value ) : bool

parser
指向要设置选项信息的 XML 解析器的指针。
option
要设置的选项名称。请参考下文。
value
要给选项设置的新值。

如果 parser 参数没有指向一个合法的解析器或者指定的选项无法设置，该函数将返回 false，否则将会把选项设置为指定的值并返回 true。

可被设置的选项如下：

XML 解析器选项
选项常量 | 数据类型 | 描述
XML_OPTION_CASE_FOLDING | integer | 控制在该 XML 解析器中 大小写折叠（case-folding） 是否有效。其默认值为有效。
XML_OPTION_SKIP_TAGSTART | integer | 指明在一个标记名前应略过几个字符。
XML_OPTION_SKIP_WHITE | integer | 是否略过由白空字符组成的值。
XML_OPTION_TARGET_ENCODING | string | 设置该 XML 解析器所使用的目标编码（target encoding）方式。其默认值和由 xml_parser_create() 函数设置的源编码（source encoding）方式相同。支持的目标编码方式有 ISO-8859-1、US-ASCII 和 UTF-8。

User Contributed Notes

www.thomaskoch.it 31-Jul-2008 02:22
The option XML_OPTION_SKIP_WHITE has no effect in my PHP 5.2.6 (with expat-1.95.8-5). To skip cdata composed of white space only, simply check for that at the beginning of your cdata callback function:

<?php
function callback_cdata($parser, $cdata)
{
 if(!trim($cdata))
  return;

 // ... continue processing ...
}
?>
j[no_spam_please] at [thx]jessepearson dot net 08-Mar-2007 08:08
In the function below, you need to update two lines if you don't want php to throw warnings.

change these two:
           $elements[$index]['attributes'] = $tag['attributes'];
           $elements[$index]['content'] = $tag['value'];

to this:
      $elements[$index]['attributes'] = empty($tag['attributes']) ? "" : $tag['attributes'];
      $elements[$index]['content']    = empty($tag['value']) ? "" : $tag['value'];
06-Sep-2006 07:56
A little mod to a function posted here...

function xml_to_array( $file )
{
    $parser = xml_parser_create();
    xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
    xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
    xml_parse_into_struct( $parser, file_get_contents($file), $tags );
    xml_parser_free( $parser );

    $elements = array();
    $stack = array();
    foreach ( $tags as $tag )
    {
        $index = count( $elements );
        if ( $tag['type'] == "complete" || $tag['type'] == "open" )
        {
            $elements[$index] = array();
            $elements[$index]['name'] = $tag['tag'];
            $elements[$index]['attributes'] = $tag['attributes'];
            $elements[$index]['content'] = $tag['value'];

            if ( $tag['type'] == "open" )
            {    # push
                $elements[$index]['children'] = array();
                $stack[count($stack)] = &$elements;
                $elements = &$elements[$index]['children'];
            }
        }

        if ( $tag['type'] == "close" )
        {    # pop
            $elements = &$stack[count($stack) - 1];
            unset($stack[count($stack) - 1]);
        }
    }
    return $elements[0];
}
ksavage at achaean dot com 28-Mar-2005 01:25
Had one heck of a time getting curl to send my XML request.  Tried a lot of different things, FINALLY ended up with this.

Im making a curl request to paymentech / Orbital 's payment gateway.   Essentially, I took the same header i made for the fsockopen() request, and used it for this curl request. (Hostinc company didnt allow fsockopen().

You'll note that this specific gateway requires a custom content type header.  Thats what gave me the most trouble.  When using the CURLOPT_HTTPHEADER, and CURLOPT_POSTFIELDS together, it doesnt matter, it sends the default post header because of CURLOPT_POSTFIELDS.

<?php

$url = "https://example.com";
$page = "/proccessing_page.cgi";

$post_string = "<YourXML>All XML stuff Here</YourXML>";

       $header  = "POST ".$page." HTTP/1.0 \r\n";
        $header .= "MIME-Version: 1.0 \r\n";
        $header .= "Content-type: application/PTI26 \r\n";
        $header .= "Content-length: ".strlen($post_string)." \r\n";
        $header .= "Content-transfer-encoding: text \r\n";
        $header .= "Request-number: 1 \r\n";
        $header .= "Document-type: Request \r\n";
        $header .= "Interface-Version: Test 1.4 \r\n";
        $header .= "Connection: close \r\n\r\n";
        $header .= $post_string;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);

        $data = curl_exec($ch);         if (curl_errno($ch)) {
           print curl_error($ch);
        } else {
           curl_close($ch);
        }

// use XML Parser on $data, and your set!

        $xml_parser = xml_parser_create();
        xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
        xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
        xml_parse_into_struct($xml_parser, $data, $vals, $index);
        xml_parser_free($xml_parser);

// $vals = array of XML tags.  Go get em!

?>

Worked like a dream for me.  Enjoy!
matt at mcbridematt dot dhs dot org 16-Dec-2002 05:56
Re: anony at mous dot com
case folding is a violation of the XHTML specification. xhtml is all in lowercase to be inline with the DOM
pupeno at pupeno dot com 16-Nov-2002 01:14
XML is case sensitive, then, from my point of view, disabling case folding doesn't goes against xml 1.0 specifications but the contrary, disabling case folding allow us to distiguish between diferent cases of the same letter ('a' and 'A') which of XML are two diferent things.
From my point of view, disabling case folding is a good practice and I think it should be disabled by default.
More information on:
http://www.isacat.net/2001/xml/case.htm
and
http://www.w3.org/TR/REC-xml
Thank you.
ta at NOSPAM dot magicsquare dot info 09-Jul-2002 04:52
XML_OPTION_SKIP_WHITE works for me (linux, php 4.2.1)

phpinfo says :

XML Support active
XML Namespace Support active
EXPAT Version expat_1.95.2

i guess it depends on expat version/presence
chris at wildcharacters dot com 21-Oct-2001 07:32
The two 'skip' tags are not available to windows users using PHP 4.0.4.  The following:

$skipWhite = xml_parser_get_option ($xmlParser,XML_OPTION_SKIP_WHITE);
$skipTagStart = xml_parser_get_option ($xmlParser,XML_OPTION_SKIP_TAGSTART);

generates the following errors:
Warning: xml_parser_get_option: unknown option in c:/program files/abria merlin/apache/htdocs/xml/sax_test.php on line 230
anony at mous dot com 20-Apr-2000 05:26
Disable case folding or your code will be violating the XML 1.0 specification.


建立字符数据处理器

  • ? xml_parser_set_option
  • xml_set_default_handler ?
  • PHP Manual
  • XML 解析器函数
  • 建立字符数据处理器

xml_set_character_data_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_character_data_handler — 建立字符数据处理器

说明

xml_set_character_data_handler ( resource $parser , callable $handler ) : bool

为 parser 变量指向的 XML 解析器指定字符数据处理函数。

参数

parser

XML 解析器的引用，用于建立字符数据处理器。

handler

handler 为表示一个函数名称的字符串，该函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受两个参数：

handler ( resource $parser , string $data )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
data
第二个参数 data 为包含有字符数据的字符串。

Character data handler is called for every piece of a text in the XML document. It can be called multiple times inside each fragment (e.g. for non-ASCII strings).

如果处理器函数名被设置为空字符串或者 false，则该有问题的处理器将被屏蔽。

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

svanegmond at tinyplanet dot ca 08-Oct-2010 12:06
For those who are having their character entities eaten by this function (e.g. &amp; &lt; and so forth):

You will notice that your callback gets called several times.

input: Give me some beans &amp; rice. &#032;

call 1: Give me some beans
call 2: amp; and rice
call 3: #032;

There is an obvious workaround. This is not perfect:

<?php
        $text = preg_replace('/^([a-z]+;)/','&\1', $text);
        $text = preg_replace('/^(#[0-9]+;)/', '&\1', $text);
?>
jhill at live dot com 28-Aug-2008 07:11
To detect that concatenation of data is taking place, you can keep track of whether the last function call was to the data processing function.
e.g. using $this->inside_data variable below:

<?php
xml_set_element_handler($this->parser, "start_tag", "end_tag");
xml_set_character_data_handler($this->parser, "contents");

protected function contents($parser, $data)
{
    switch ($this->current_tag) {
            case "name":
                if ($this->inside_data)
                    $this->name .= $data; // need to concatenate data
                else
                    $this->name = $data;
                break;
         ...
    }
    $this->inside_data = true;
}

protected function start_tag($parser, $name)
{
    $this->current_tag = $name;
    $this->inside_data = false;
}

protected function end_tag() {
    $this->current_tag = '';
    $this->inside_data = false;
}
?>
unspammable-iain at iaindooley dot com 03-Jan-2006 01:41
re: jason at omegavortex dot com below, another way to deal with whitespace issues is:

        function charData($parser,$data)
        {
            $char_data = trim($data);

            if($char_data)
                $char_data = preg_replace('/  */',' ',$data);

            $this->cdata .= $char_data;
        }

This means that:

    <p>here is my text <a href="something">my text</a>
    and here is some more after some spaces at the
    beginning of the line</p>

comes out properly. You could do further replacements if you want to deal with tabs in your files. i only ever use spaces. if you only use trim() then you would lose the space before the <a> tag above, but trim() is a good way to check for completely empty char data, then just replace more than one space with a single space. this will preserve a single space at the beginning and end of the cdata.
jason at omegavortex dot com 06-Dec-2005 11:00
I don't believe the problem has been addressed, but if you're parsing an XML file and run into the line break (or tab) problem I believe this function may help:

if (!preg_match("/((\r|)\n)/i", $data) || preg_match("/\\t+/i", $data)) {
(Code Here)
}
wako057 at gmx dot fr 22-Aug-2005 09:39
That give an example about the note.
When you are creating a class and you need to use a method of your class to the function xml_set_character_data_handler that is the way to point give the method:

class example
{
   function example()
   {
   }

  function data($parseur, $texte)
  {
      switch ($this->derniereBaliseRencontree)
      {
         case "TITLE":
                     -----
          break;
         case "LINK"
                    -----
         break;
        case "DESCRIPTION":
                    -----
        break;
     }
  }

  function fetchOpen($parseur, $nomBalise, $tableauAttributs)
  {
     ----------------
  }

  function fetchClose($parseur, $nomBalise)
  {
     ----------------
  }

  function ZZZ()
  {
      $parseurXML = xml_parser_create();
       xml_set_element_handler($parseurXML, Array(&$this, 'fetchOpen'),   Array(&$this, 'fetchClose'));
         ---------------- <IMPORTANT> --------------------------
       xml_set_character_data_handler($parseurXML, Array(&$this, 'data'));
        ---------------- </IMPORTANT> --------------------------
}
ben at removethis emediastudios dotcom 05-Aug-2005 03:53
I too love the undocumented "splitting" functionality :-p.

Rather than concatinating the data based on whether or not the current tag name has changed from the previous tag name I suggest always concatinating like the following with the $catData variable being unset in the endElement function:

<?php

function endElement ($parser, $data) {
  global $catData;

  // Because we are at an element end we know any splitting is finished
  unset($GLOBALS['catData']);
}

function characterData ($parser, $data) {
  global $catData;

  // Concatinate data in case splitting is taking place
  $catData.=$data;

}

?>

This got me around a problem with data like the following where, because characterData is not called for empty tags, the previous and current tag names were the same even though splitting was not taking place.

<companydept>
<companydeptID></companydeptID>
<companyID>1</companyID>
<companydeptName></companydeptName>
</companydept>
<companydept>
<companydeptID></companydeptID>
<companyID>2</companyID>
<companydeptName></companydeptName>
</companydept>
<companydept>
<companydeptID></companydeptID>
<companyID>3</companyID>
<companydeptName></companydeptName>
</companydept>
yaroukh at email dot cz 25-Apr-2005 08:51
It would be nice if someone could complete documentation of this function. I think that the "splitting" behaviour should (at least) be mentioned within the documentation, if not explained (please!). I'm not quite sure whether the cut comes after each 1024bytes/chars of data.

My experience looks as follows:
[xmlFile]
...
    <label>slo|?ka</label>
    <comment>koment|?&#345; slo?ky</comment>
...
[/xmlFile]
(Places where the character-data got splitted are marked with pipes. Plus there was latin small letter 'r' with caron instead of &#345;.)

Since the splitting is not mentioned in documentation one could assume that it is a bug; especially when you work with UTF-8 and the cuts come right before some special characters.
(Should the concatenating of $cData be considered to be the proper & 'final' way of processing character-data?)

Also I'd suggest to add another line in "Description" when fc has an alternate usage (instead of hiding it within the "Note" :o); in this particular case I'd prefer this:

Description:
bool xml_set_character_data_handler ( resource parser, callback handler )
bool xml_set_character_data_handler ( resource parser, object reference, method name )

... there are dozens of functions ofcourse where documentation works this way (I mean not mentioning the alternate usage in the "Description" part).

Have a nice day
  Yaroukh
flobee 12-Feb-2005 09:53
re. to Philippe Marc , and  karuna_gadde examples

i found out that the xml_set_character_data_handler call back  function can be called more often for the same element in particular the content is just a few chars long (happen on windows)

so a check up can give you the answer an may be for long strings too.
eg:
<?php
xml_set_character_data_handler($this->parser, "cdata");
//...
function cdata($parser, $cdata) {
// ...
if(isset($this->data[$this->currentItem][$this->currentField])) {
    $this->data[$this->currentItem][$this->currentField] .= $cdata;
} else {
    $this->data[$this->currentItem][$this->currentField] = $cdata;
}
?>
Philippe Marc 28-Oct-2004 07:21
How to overide the 1024 characters limitation of xml_set_character_data_handler.
Took me some time to find out how to deal with that!

When calling a basic XML parser:
$parseurXML = xml_parser_create();
xml_set_element_handler($parseurXML, "opentagfunction", "closetagfunction");
xml_set_character_data_handler($parseurXML, "textfunction");

The textfunction only receive 1024 characters at once, even if the text is 4000 characters long. In facts, the parser seems to split the data in pieces of 1024 characters. The way to handle that is to concatenate them.

example:
If you have an XML tag called UNIPROT_ABSTRACT containing a 4000 characters protein description:
function textfunction($parser, $text)
    {
     if ($last_tag_read=='UNIPROT_ABSTRACT') $uniprot.=$text;
    }
The function is called 4 times and receives 1024+1024+1024+928 characters that will be concatenated in the $uniprot variable using the ".=" concatenation fonction.

Easy to do, but not documented!
Brad dot Harrison at griffith dot edu dot au 11-Jul-2004 10:23
If you need to trim the white space for HTML code and don't rely on spaces for formatting text (if you are then it is time to use Style Sheets) then this code will come in very useful.

 $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
 $data=eregi_replace(">"."[[:space:]]+",">",$data);
 $data=eregi_replace("[[:space:]]+"."<","<",$data);
karuna_gadde at yahoo dot com 27-May-2004 07:01
<?
class Parser {

var $att;
var $id;
var $title;
var $content;
var $index=-1;
var $xml_parser;
var $tagname;

function parser()
{
$file = "data.xml";
$this->xml_parser = xml_parser_create();
xml_set_object($this->xml_parser,$this);
xml_set_element_handler($this->xml_parser, "startElement", "endElement");
xml_set_character_data_handler($this->xml_parser, 'elementContent');
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
if (!xml_parse($this->xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->xml_parser)),
xml_get_current_line_number($this->xml_parser)));
}
}
xml_parser_free($this->xml_parser);
}

function startElement($parser, $name, $attrs) {
if (($name=="TREE") or ($name=="NODE") or ($name=="LEAFNODE"))
    {
         $this->index++;
         $this->att[$this->index]=$name;
    }
    $this->tagname=$name;
}

function elementContent($parser, $data) {
switch ($this->tagname)
{
     case 'ID':
                 $this->id[$this->index]=trim($data);
                 break;
     case 'TITLE' :
                 $this->title[$this->index]=trim($data);
                 //echo $data;
                 break;
     case 'CONTENT'    :
                 $this->content[$this->index]=trim($data);
                 break;

}
}
function endElement($parser, $name){
$this->tagname=="";
}
}
?>

I thought this class is more help full to know about xml_parser with no white spaces
michael dot stilson at wmich dot edu 04-Mar-2004 12:31
Hello,

This is an addition to the note posted by:
wiart at yahoo dot com
22-Aug-2003 05:31
Which is located below.

I had similar problems manually creating XML docs and adding new-lines within my node data, e.g.

<root>
    ...
    <node attribute="something">
        Here is some data. There is a lot of data, and I want to
        be able to read the data from a terminal window, so I add
        newlines to fit everything within 80 columns.
    </node>
    ...
</root>

So, given the above example, my data handler gets called 3 times and the result left in my variable is:

"newlines to fit everything within 80 columns."

Instead of all of the data within "node", which I was expecting.

By using the concatenation operator; however, as suggested by the mentioned note, I was able to get what I needed. Which is of course:

"Here is some data. There is a lot of data, and I want to be able to read the data from a terminal window, so I add newlines to fit everything within 80 columns."
dan30odd08 at hotmail dot com 01-Dec-2003 04:38
I just want to mention that i ran into a problem when parsing an xml file using the character data handler. If you happen to have a string which is also an internal php function stored in your xml data file and you want to output it as a string the parser dosent seem to recognize it.
   I found a way around this problem. In my case i was storing a string with the value read. This would not allow me to output the data so to work around this problem i added a backslash for every character in the data element.

   e.g.      <xml>
    from    <element>read</element>
    to       <element>////read</element>

i dont know if anyone has ran into this problem or not but i thought i would just put it here just so in case someone is getting stuck with this.
wiart at yahoo dot com 22-Aug-2003 05:31
WARNING !!!
Always use concatenation for getting the content of a XML tag when you write the function that will deal with the Character Data handling

Example:

$mycontent = '';
$xml_parser = xml_parser_create ();
xml_set_character_data_handler($xml_parser, "_characterdata");

function _characterdata($parser, $data){
  global $mycontent;
  //HERE: use .= and not =
  $mycontent .= $data;
}

...

while ($data = fread($fp, 4096)) {
    xml_parse($xml_parser, $data, feof($fp));
}

I had the following problem with the use of '=$data' :

In one of my XML documents, the parsing stopped in the middle of a character data :

In original document:
<prop name="nbres">100</prop>

What happened:
<prop name="nbres">10[parsing stopped here in chunck of 4096bytes]0</prop>

As I did not use the concatenation, when I displayed the value of the 'nbres' property, the value was 0 instead of 100 because the first time the function characterdata was called :
$mycontent = 10;

and the second time:
$mycontent = 0;      //!!!!!!!!!!!!! HO HO !! some problem occured ...

Instead of $mycontent = 100;

CONCLUSION:
IN YOUR CHARACTER DATA HANDLER FUNCTIONS, NEVER FORGET THE . (concatenation operator) !!!!! IF YOU DON'T WANT TO HAVE WEIRD BUGS SOME TIMES
morris_hirsch at hotmail dot com 18-Aug-2003 09:15
Thanks to Christian Stocker for clearing up my entity issues,  where some entities are parsed correctly and others not.

The problem is the ''wide'' entities that have a large numeric code simply can not fit in a single byte, which is the default encoding for both source input to the parser and data output from the parser.  So the parser puts out a ''?'' to say it could not store the code value. One could argue that if the input has a &1234; the output should simply copy it as &1234; instead of the ''?'' but that would still mean the  parser behaves two different ways according to the code values, and anyway they don't do it.

So, we need utf8 encoding for the output, and the slightly not obvious way to say so is

  $xml_parser = xml_parser_create ("UTF-8");

which means BOTH source input and data output are utf8.
Remember that utf8 is a superset of basic ASCII but not of extended ASCII, so your input can contain e.g. &eacute;
spelled out, but a native eacute character is wrong here.
Just utf8_encode your input to be sure.

That should do it, and thanks again for the help.
morris_hirsch at hotmail dot com 06-Aug-2003 12:23
Here are two ways to deal with named entities in the XML.

1. Put a list of named entities at the front so the parser knows what they all mean

  $decl = '<!DOCTYPE rootname [

<!ENTITY frac12  "&#x00BD;" >
<!ENTITY frac14  "&#x00BC;" >
<!ENTITY frac34  "&#x00BE;" >
<!ENTITY frac18  "&#x215B;" >
<!ENTITY frac38  "&#x215C;" >
<!ENTITY frac58  "&#x215D;" >
<!ENTITY frac78  "&#x215E;" >
<!ENTITY frac13  "&#x2153;" >
<!ENTITY frac23  "&#x2154;" >
<!ENTITY frac15  "&#x2155;" >
<!ENTITY frac25  "&#x2156;" >
<!ENTITY frac35  "&#x2157;" >
<!ENTITY frac45  "&#x2158;" >
<!ENTITY frac16  "&#x2159;" >
<!ENTITY frac56  "&#x215A;" >

<!ENTITY mdash  "&#x2014;" >

 ..... lots of others

<!ENTITY uuml    "&#252;" >
<!ENTITY yacute  "&#253;" >
<!ENTITY thorn   "&#254;" >
<!ENTITY yuml    "&#255;" >

]>';

$parseThis = $decl . "<rootname> ..... </rootname>";

This works fine for all the single-byte (European) codes,
but not the wide codes like emdash or frac18.
They seem to be trashed when the character data handler gets them.  They all echo as "?"

There may be a way to make them work, but until I find it,
or a newer release takes care of it, here is a work-around that does work.

2. Rewrite every ampersand as &amp; in the input stream

 $ampXML = str_replace ("&", "&amp;", $sourceXML);

Now the parser will see &amp;foo; instead of &foo;

It does not try to decode it, so wide (two byte) values are not a problem, and no list of names is needed.

When you write that to your output you have &foo;

which is usually fine for the next stage of your process.
www.PhoC.de 20-May-2003 07:39
In some cases it's better to avoid storing data which is not needed. In these cases the function

chop()  ( => Alias of function rtrim() )

could be usefull to prevent data like

"\t"
"\r"
"\o"
"\n"
"\x0B"
" "

to be stored in a array or a string or something like this.

Example: (storing data in a string)
________________
$filename="xyz.xml";

if(!($fp=fopen($filename,"r"))){
   die("Cannot open $filename ");
}

while (!feof($fp))
{
   $data .= chop(fgets($fp, 4096));
}

fclose($fp);
________________

Have a look at the documentation of rtrim() http://www.php.net/manual/en/function.rtrim.php.

Greetz
PhoC
waldo at wh-e dot com 06-Mar-2002 09:52
Here's a way to strip all the spaces between tags in an xml document.

//strip white space between tags
$data=eregi_replace(">"."[[:space:]]+"."<","><",$data);

So this:

<house>
  <garage>
    <car>Waldo</car>
  </garage>
</house>

would be changed to:

<house><garage><car>Waldo</car></garage></house>

It was useful to me. Maybe you too?
ken at positive-edge dot com 29-Jan-2002 08:20
the function handler is called several times when it parses the character data.  It doesn't return the entire string as it suggests.  There are special exceptions that will always force the parser to stop scanning and call the character data handler.  This is when:

- The parser runs into an Entity Declaration, such as &amp; (&) or &apos; (?)
- The parser finishes parsing an entity
- The parser runs into the new-line character (\n)
- The parser runs into a series of tab characters (\t)

And perhaps others.

For instance, if we have this xml content:

<mytag name=?Ken Egervari? title=?Chief Technology Officer?>
    Ken has been Positive Edge&apos;s Chief Technology Officer for 2 years.
</mytag>

The parser will call the character data handler 6 times.  This is what will happen:

1    \n
2    \t
3    Ken has been Positive Edge
4    ?
5    s Chief Technology Officer for 2 years.
6    \n

I hope that helps people out.
mogmios at mlug dot missouri dot edu 24-Oct-2001 04:24
If you want to strip unwanted whitespace in an HTML-like manner then there are two steps.

The first you need to strip consecutive whitespaces from all you input data like this:  $data = eregi_replace ( "[[:space:]]+", " ", $data );

Then in your cdata handler make a check to see if it's blank space. An easy way is like this: if ( trim ( $cdata ) ) { work on cdata }

That should take care of any whitespace issues you might have.
annies at cs dot tu-berlin dot de 03-Aug-2001 10:43
The maximum size of the second parmeter $data seems to be 1024. Is there more character data  in the XML text the handler is called again immediately with the next portion.


建立默认处理器

  • ? xml_set_character_data_handler
  • xml_set_element_handler ?
  • PHP Manual
  • XML 解析器函数
  • 建立默认处理器

xml_set_default_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_default_handler — 建立默认处理器

说明

xml_set_default_handler ( resource $parser , callable $handler ) : bool

为 parser 指定的 XML 处理器建立默认处理函数。

参数

parser

XML 解析器的引用，用于建立默认处理器函数。

handler

handler 为表示一个函数名称的字符串，该函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受两个参数：

handler ( resource $parser , string $data )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
data
第二个参数 data 为包含有字符数据的字符串。其内容可以是 XML 声明、文档类型声明、实体名或者其它没有已存在处理器的地数据。

如果处理器函数名被设置为空字符串或者 false，则该有问题的处理器将被屏蔽。

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

anoril at anoril dot com 13-Jul-2006 07:54
I have the same issue using two installation of PHP5: on accepts to use the default handler while the other only uses the character_data one.

Maybe a configuration problem...

;) Nonor.
phillip 26-Apr-2005 02:13
it seems to me that in PHP5 the function defined as default-handler (using xml_set_default_handler()) doesen't get passed the cdata anymore:

i.e.:
xml_set_element_handler($this->parser, 'parseSTART', 'parseEND');
xml_set_default_handler($this->parser, 'parseDEFAULT');
function parseSTART() { ... }
function parseEND() { ... }
function parseDEFAULT() { ... }

under PHP5, parseDEFAULT will NOT get passed any cdata, but unter PHP4 it will. at least that's my take on the strange stuff (not) happening after migrating to PHP5.

my solution was to add a xml_set_character_data_handler($parser, 'parseDEFAULT'). it worked for me.


建立起始和终止元素处理器

  • ? xml_set_default_handler
  • xml_set_end_namespace_decl_handler ?
  • PHP Manual
  • XML 解析器函数
  • 建立起始和终止元素处理器

xml_set_element_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_element_handler — 建立起始和终止元素处理器

说明

xml_set_element_handler ( resource $parser , callable $start_element_handler , callable $end_element_handler ) : bool

为 parser 参数指定的 XML 解析器建立元素处理器函数。参数 start_element_handler 和 end_element_handler 为表示函数名称的字符串，这些函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

参数

parser

XML 解析器的引用，用于建立起始和终止元素处理器。

start_element_handler

由 start_element_handler 参数命名的函数名必须接受三个参数：

start_element_handler ( resource $parser , string $name , array $attribs )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
name
第二个参数 name 为该处理器为之被调用的元素名。如果大小写折叠（case-folding）对该解析器有效，元素名将用大写字母表示。
attribs
第三个参数 attribs 为一个包含有对应元素的属性的数组（如果该元素有属性）。数组元素的下标为属性名，元素的值即为属性的值。属性名将以和元素名同样的标准进行大小写折叠（case-folded），其值不进行大小写折叠。 属性的原始顺序将会被参数保留，用 each() 函数遍历 attribs 时，该数组下表的顺序和属性的顺序相同。

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

end_element_handler

由 end_element_handler 参数命名的函数名必须接受两个参数：

end_element_handler ( resource $parser , string $name )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
name
第二个参数 name 为该处理器为之被调用的元素名。如果大小写折叠（case-folding）对该解析器有效，元素名将用大写字母表示。

如果处理器函数名被设置为空字符串或者 false，则该有问题的处理器将被屏蔽。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

kok at nachon dot nl 26-Sep-2008 06:44
Here is another example of detecting empty elements. I works with libxml2. Note that it handles buffer boundaries.

<?php

$depth = 0; //current depth, used for pretty printing
$empty = false; //whether the tag is empty
$offset = 0; //the index of the start of the current buffer within the stream

function tagStart($parser, $name, array $attribs) {
    global $depth, $empty, $data, $offset, $lastchar;
    $idx = xml_get_current_byte_index($parser);
    /* xml_get_current_byte_index returns index within the streams and not
       within the buffer.*/

    /* Check if the index is within the buffer. */
    if (isset($data[$idx - $offset])) {
        $c = $data[$idx - $offset];
    } else {
        /* If it isn't simple use the last character of the buffer. */
        $c = $lastchar;
    }
    $empty = $c == '/';
    echo str_repeat("\t", $depth), "<$name", ($empty ? '/>' : '>'), "\n";
    if (!$empty) ++$depth;
}

function tagEnd($parser, $name) {
    global $depth, $empty;
    if (!$empty) {
        --$depth;
        echo str_repeat("\t", $depth), "</$name>\n";
    } else {
        $empty = false;
    }
}

$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($parser, 'tagStart', 'tagEnd');

$data1 = '
<test>
    <empty att="3" />
    <nocontent></nocontent>
    <content>
        <empty/>
        <empty/>
    </content>
    <empty/';

$data2 = '>
    <empty att="5" />
</test>
';

$data = &$data1;
$length = strlen($data1);
$lastchar = $data[$length-1];
xml_parse($parser, $data1);
$offset .= $length;
$data = &$data2;
xml_parse($parser, $data2);
darien at etelos dot com 12-Feb-2007 10:48
This documentation is somewhat awry. I know it's been said many times before, but it bears repeating...

If using PHP4, you may be required to use xml_set_object() instead of calling any of the xml_set_*_handler() functions with a two-item array. It will work fine on PHP5, but move the same code to PHP4 and it will create one copie of $this (even if you use &$this) for each handler you set!

<?php
// This code will fail mysteriously on PHP4.
$this->parser = xml_parser_create();
xml_set_element_handler(
            $this->parser,
            array(&$this,"start_tag"),
            array(&$this,"end_tag")
        );
        xml_set_character_data_handler(
            $this->parser,
            array(&$this,"tag_data")
        );
?>

<?php
// This code will work on PHP4.
$this->parser = xml_parser_create();
xml_set_object($this->parser,&$this);
xml_set_element_handler(
            $this->parser,
            "start_tag",
            "end_tag"
        );
        xml_set_character_data_handler(
            $this->parser,
            "tag_data"
        );
?>
lloeki at gmail dot com 31-Oct-2006 03:07
I modified the previous script, so that it is associative. I find it more useful that way. BTW I prefer strtolower() things, but that's not mandatory at all.

<?php

$file = "data.xml";
$depth = 0;
$tree = array();
$tree['name'] = "root";
$stack[] = &$tree;

function startElement($parser, $name, $attrs) {
   global $depth;
   global $stack;
   global $tree;

   $element = array();
   foreach ($attrs as $key => $value) {
       $element[strtolower($key)]=$value;
   }

   end($stack);
   $stack[key($stack)][strtolower($name)] = &$element;
   $stack[strtolower($name)] = &$element;

   $depth++;
}

function endElement($parser, $name) {
   global $depth;
   global $stack;

   array_pop($stack);
   $depth--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
   die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
   if (!xml_parse($xml_parser, $data, feof($fp))) {
       die(sprintf("XML error: %s at line %d",
                   xml_error_string(xml_get_error_code($xml_parser)),
                   xml_get_current_line_number($xml_parser)));
   }
}
xml_parser_free($xml_parser);
$tree = end(end($stack));
echo "<pre>";
print_r($tree);
echo "</pre>";

?>
rubentrancoso at gmail dot com 29-Aug-2006 01:44
My 25 cents. This example show how to parse a XML in a associative array tree.

<?php

$file = "flow/flow.xml";
$depth = 0;
$tree = array();
$tree['name'] = "root";
$stack[count($stack)] = &$tree;

function startElement($parser, $name, $attrs) {
   global $depth;
   global $stack;
   global $tree;

   $element = array();
   $element['name'] = $name;
   foreach ($attrs as $key => $value) {
        //echo $key."=".$value;
        $element[$key]=$value;
    }

   $last = &$stack[count($stack)-1];
   $last[count($last)-1] = &$element;
   $stack[count($stack)] = &$element;

   $depth++;
}

function endElement($parser, $name) {
   global $depth;
   global $stack;

   array_pop($stack);
   $depth--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
   die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
   if (!xml_parse($xml_parser, $data, feof($fp))) {
       die(sprintf("XML error: %s at line %d",
                   xml_error_string(xml_get_error_code($xml_parser)),
                   xml_get_current_line_number($xml_parser)));
   }
}
xml_parser_free($xml_parser);
$tree = $stack[0][0];
echo "<pre>";
print_r($tree);
echo "</pre>";
redb 15-May-2006 05:48
Example below (BadParser) works fine with some changes.

xml_set_element_handler ( $parser, array ( &$this, 'tagStart' ), array ( &$this, 'tagEnd' ) );
xml_set_character_data_handler ( $parser, array ( &$this, 'tagContent' ) );
vladimir-leontiev at uiowa dot edu 13-Dec-2005 09:44
It seems that characterData() gets characters in chuncks of 1024; therefore if you have string of characters between you tags that is longer than 1024 then characterData() will be called more that once for single pair of tags. I don't know if this feature(bug?) is documented anywhere, I just wanted to warn everyone about this; it had tripped me. I use php 4.3.10 on Linux.
hendra_g at hotmail dot com 19-Nov-2005 08:10
I ran into the same problem with 'ibjoel at hotmail dot com' in regards to self-closing tags, and found that the script that he/she wrote did not work as I expected.
I played around with some of php's functions and examples and compiled something, which may not be the neatest solution, but it works for the data that 'ibjoel at hotmail dot com' provided.
The data needs to be read from a file though, so the fp can be utilised. It still uses the xml_get_current_byte_index(resource parser) trick, but this time, I check for the last 2 character before the index and test if it's "/>".

<?php
/* myxmltest.xml:
<normal_tag>
  <self_close_tag />
     data
  <normal_tag>data
     <self_close_tag attr="value" />
  </normal_tag>
     data
  <normal_tag></normal_tag>
</normal_tag>
*/

//## Global Variables ##//
$file = "myxmltest.xml";
$character_data_on = false;
$tag_complete = true;

function startElement($parser, $name, $attrs)
{
    global $character_data_on;
    global $tag_complete;

    echo "&lt;<font color=\"#0000cc\">$name</font>";
    //## Print the attributes ##//
    if (sizeof($attrs)) {
        while (list($k, $v) = each($attrs)) {
            echo " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    //## Tag is still still incomplete,
    //## will be completed at either endElement or characterData ##//
    $tag_complete = false;
    $character_data_on = false;
}

function endElement($parser, $name)
{
    global $fp;
    global $character_data_on;
    global $tag_complete;

    //#### Test for self-closing tag ####//
    //## xml_get_current_byte_index(resource parser) when run in this
    //## function, gives the index at (indicated by *):
    //##   for self closing tag: <br />*
    //##   for individual closing tag: <div>character data*</div>
    //## So to test for self-closing tag, we can just test for the last 2
    //## characters from the index
    //###################################//

    if (!$character_data_on) {
        //## Record current fp position ##//
        $temp_fp = ftell($fp);

        //## Point fp to 2 bytes before the end element byte index ##//
        $end_element_byte_index = xml_get_current_byte_index($parser);
        fseek($fp,$end_element_byte_index-2);

        //## Gets the last 2 characters before the end element byte index ##//
        $validator = fgets($fp, 3);

        //## Restore fp position ##//
        fseek($fp,$temp_fp);

        //## If the last 2 character is "/>" ##//
        if ($validator=="/>") {
            //// Complete the self-closing tag ////
            echo " /&gt";
            //// Otherwise it is an individual closing tag ////
        } else echo "&gt&lt/<font color=\"#0000cc\">$name</font>&gt";
        $tag_complete = true;
    } else echo "&lt/<font color=\"#0000cc\">$name</font>&gt";

    $character_data_on = false;
}

function characterData($parser, $data)
{
    global $character_data_on;
    global $tag_complete;

    if ((!$character_data_on)&&(!$tag_complete)) {
        echo "&gt";
        $tag_complete = true;
    }
    echo "<b>$data</b>";
    $character_data_on = true;
}

$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

echo "<pre>";
while ($file_content = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $file_content, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
echo "</pre>";
xml_parser_free($xml_parser);
?>
turan dot yuksel at tcmb dot gov dot tr 20-Sep-2005 03:41
The method that 'ibjoel at hotmail dot com' have described requires libxml2 as the xml parser, it does not work with expat. For a brief explanation, see xml_get_current_byte_index.
ibjoel at hotmail dot com 01-Aug-2005 03:49
I noticed that in the example below, and all the examples I've seen on this site for viewing xml in html, the look of self closing tags such as <br /> are not preserved. The parser cannot distinguish between <tag /> and <tag></tag>, and if your start and end element functions are like these examples, both instances will be output with both an indvidual start and end tag.  I needed to preserve self-closing tags and it took me a while to figure out this work around. Hope this helps someone...

The start tag is left open, and then completed by it's first child, the next start tag or its end tag.  The end tag will complete with " />", or </tag> depending on the number of bytes between the start and end tags in the parsed data.
<?php
//$data=filepath or string
$data=<<<DATA
<normal_tag>
  <self_close_tag />
      data
  <normal_tag>data
     <self_close_tag attr="value" />
  </normal_tag>
      data
  <normal_tag></normal_tag>
</normal_tag>
DATA;

function startElement($parser, $name, $attrs)
{
        xml_set_character_data_handler($parser, "characterData");
        global $first_child, $start_byte;
        if($first_child)          //close start tag if neccessary
                echo "><br />";
        $first_child=true;
        $start_byte=xml_get_current_byte_index ($parser);
        if(count($attrs)>=1){
                foreach($attrs as $x=>$y){
                        $attr_string .= " $x=\"$y\"";
                }
        }
        echo htmlentities("<{$name}{$attr_string}"); //unclosed starttag
}

function endElement($parser, $name)
{
        global $first_child, $start_byte;
        $byte=xml_get_current_byte_index ($parser);
        if($byte-$start_byte>2){           //if end tag is more than 2 bytes from start tag
                if($first_child)          //close start tag if neccessary
                        echo "><br />";
                echo htmlentities("</{$name}>")."<br />";  //individual end tag
        }else
                echo " /><br />";  // self closing tag
        $first_child=false;

}

function characterData($parser, $data)
{
        global $first_child;
        if($first_child)  //if $data is first child, close start tag
                echo "><br />";
        if($data=trim($data))
                echo "<font color='blue'>$data</font><br />";
        $first_child=false;
}

function ParseData($data)
{
        $xml_parser = xml_parser_create();
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
        if(is_file($data))
        {
                if (!($fp = fopen($file, "r"))) {
                        die("could not open XML input");
                }

                while ($data = fread($fp, 4096)) {
                        if (!xml_parse($xml_parser, $data, feof($fp))) {
                                $error=xml_error_string(xml_get_error_code($xml_parser));
                               $line=xml_get_current_line_number($xml_parser);
                                die(sprintf("XML error: %s at line %d",$error,$line));
                        }
                }
        }else{
                if (!xml_parse($xml_parser, $data, 1)) {
                                $error=xml_error_string(xml_get_error_code($xml_parser));
                                $line=xml_get_current_line_number($xml_parser);
                                die(sprintf("XML error: %s at line %d",$error,$line));
                }
        }

        xml_parser_free($xml_parser);
}

ParseData($data);
?>
youniforever at naver dot com 30-Apr-2005 03:41
<html>
  <head>
    <title>SAX Demonstration</title>
   <META HTTP-EQUIV='Content-type' CONTENT='text/html; charset=euc-kr'>
  </head>
  <body>
    <h1>RSS ??????</h1>

      <?php

     $file = "data.xml";

      $currentTag = "";
      $currentAttribs = "";

      function startElement($parser, $name, $attribs)
      {
          global $currentTag, $currentAttribs;
          $currentTag = $name;

          $currentAttribs = $attribs;
          switch ($name) {

          default:
              echo("<b>&lt$name&gt</b><br>");
              break;
          }
      }

      function endElement($parser, $name)
      {
          global $currentTag;
          switch ($name) {
          default:
              echo("<br><b>&lt/$name&gt</b><br><br>");
              break;
          }
          $currentTag = "";
          $currentAttribs = "";
      }

      function characterData($parser, $data)
      {
          global $currentTag;
          switch ($currentTag) {
          case "link":
              echo("<a href=\"$data\">$data</a>\n");
              break;
          case "title":
              echo("title : $data");
              break;
          default:
              echo($data);
              break;
          }
      }

     $xmlParser = xml_parser_create();

      $caseFold = xml_parser_get_option($xmlParser,
                                        XML_OPTION_CASE_FOLDING);

      $targetEncoding = xml_parser_get_option($xmlParser,
                                              XML_OPTION_TARGET_ENCODING);

      if ($caseFold == 1) {
          xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
      }

      xml_set_element_handler($xmlParser, "startElement", "endElement");
      xml_set_character_data_handler($xmlParser, "characterData");

      if (!($fp = fopen($file, "r"))) {
          die("Cannot open XML data file: $file");
      }

     while ($data = fread($fp, 4096)) {
          if (!xml_parse($xmlParser, $data, feof($fp))) {
              die(sprintf("XML error: %s at line %d",
                          xml_error_string(xml_get_error_code($xmlParser)),
                          xml_get_current_line_number($xmlParser)));
              xml_parser_free($xmlParser);
          }
      }
      xml_parser_free($xmlParser);
      ?>
    </table>
  </body>
</html>
13-Mar-2005 01:34
In response to aw at avatartechnology dot com...
In response to landb at mail dot net...

When your functions are in an object:
Careful ! Don't forget to add: & (reference) to your parameters.

xml_set_element_handler($parser, array(&$this,"_startElement"), array(&$this,"_endElement"));
--> xmlparse will work on your object (good).

instead of:
xml_set_element_handler($parser, array($this,"_startElement"), array($this,"_endElement"));
---> xmlparse will work on a COPY of your object (often bad)

Vin-s
(sorry for my english)
aw at avatartechnology dot com 21-Oct-2004 08:40
In response to landb at mail dot net...

As the notes mention, you can pass an array that contains the reference to an object and a method name when you need... so you can call methods in your own class as handlers like this:

xml_set_element_handler($parser, array($this,"_startElement"), array($this,"_endElement"));

Hope it helps...
tj at tobyjoe dot com 31-Jan-2003 11:22
It seems that the tag handlers don't block on one another (the end handler is called whether or not the begin handler has finished). this can put you in a tight spot if you don't realize it while planning your app.
11-Oct-2001 04:09
You CAN use classes to parse XML. Just take a look at the following function:

xml_set_object
jg at jmkg dot net 07-May-2001 11:08
If you are using a class for xml parsing, and want to check the return value of xml_set_element_handler in case it  fails, you must do this outside of the class's constructor. Inside the constructor, PHP-4.0.5 will die.

Basically, put all your xml initialisation code in another function of the class, and keep it out of the constructor.


建立终止命名空间声明处理器

  • ? xml_set_element_handler
  • xml_set_external_entity_ref_handler ?
  • PHP Manual
  • XML 解析器函数
  • 建立终止命名空间声明处理器

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

xml_set_end_namespace_decl_handler — 建立终止命名空间声明处理器

说明

xml_set_end_namespace_decl_handler ( resource $parser , callable $handler ) : bool

Set a handler to be called when leaving the scope of a namespace declaration. This will be called, for each namespace declaration, after the handler for the end tag of the element in which the namespace was declared.

参数

parser

A reference to the XML parser.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters, and should return an integer value. If the value returned from the handler is false (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
prefix
The prefix is a string used to reference the namespace within an XML object.

If a handler function is set to an empty string, or false, the handler in question is disabled.

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

This event is not supported under LibXML.

参见

  • xml_set_start_namespace_decl_handler() - 建立起始命名空间声明处理器

User Contributed Notes

There are no user contributed notes for this page.


建立外部实体指向处理器

  • ? xml_set_end_namespace_decl_handler
  • xml_set_notation_decl_handler ?
  • PHP Manual
  • XML 解析器函数
  • 建立外部实体指向处理器

xml_set_external_entity_ref_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_external_entity_ref_handler — 建立外部实体指向处理器

说明

xml_set_external_entity_ref_handler ( resource $parser , callable $handler ) : bool

为 parser 参数指定的 XML 解析器建立外部实体指向处理器函数。

参数

parser

XML 解析器的引用，用于建立外部实体指向处理器。

handler

参数 handler 为表示函数名称的字符串，函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受五个参数，并应该返回一个整型值。如果处理器的返回值为 false（这也是函数没有确定返回值时的返回值），XML 解析器将停止解析， xml_get_error_code() 函数将返回 XML_ERROR_EXTERNAL_ENTITY_HANDLING。

handler ( resource $parser , string $open_entity_names , string $base , string $system_id , string $public_id )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
open_entity_names
第二个参数 open_entity_names 是为该实体的解析开放的实体名列表（包括被指向的实体名），这些实体名由空格隔开。
base
这个参数是解析外部实体的系统标识符（system_id）的基础。当前该参数通常都被设置为空字符串。
system_id
第四个参数 system_id 是在实体定义声明中指定的系统标识符。
public_id
第五个参数 public_id 是在实体定义声明中指定的公共标识符，如果未指定任何标识符，则该字符串为空。公共标识符中的空格将按照 XML 的要求被正常化。

如果处理器函数名被设置为空字符串或者 false，则该有问题的处理器将被屏蔽。

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


建立注释声明处理器

  • ? xml_set_external_entity_ref_handler
  • xml_set_object ?
  • PHP Manual
  • XML 解析器函数
  • 建立注释声明处理器

xml_set_notation_decl_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_notation_decl_handler — 建立注释声明处理器

说明

xml_set_notation_decl_handler ( resource $parser , callable $handler ) : bool

为 parser 参数指定的 XML 解析器建立注释声明处理器函数。

注释声明是文档 DTD 的一部分，并有如下格式：

<!NOTATION <parameter>name</parameter>
{<parameter>system_id</parameter> | <parameter>public_id</parameter>}?>
。请参考 » XML 1.0 参考的第 4.7 节以了解注释声明的定义。

参数

parser

XML 解析器的引用，用于设置声明处理器函数。

handler

handler 为表示函数名称的字符串，函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受五个参数：

handler ( resource $parser , string $notation_name , string $base , string $system_id , string $public_id )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
notation_name
该参数为以上注释格式定义中的 name 参数。
base
这个参数是解析注释声明的系统标识符（system_id）的基础。当前该参数通常都被设置为空字符串。
system_id
外部注释声明的系统标识符。
public_id
外部注释声明的公共标识符。

如果处理器函数名被设置为空字符串或者 false，则该有问题的处理器将被屏蔽。

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


在对象中使用 XML 解析器

  • ? xml_set_notation_decl_handler
  • xml_set_processing_instruction_handler ?
  • PHP Manual
  • XML 解析器函数
  • 在对象中使用 XML 解析器

xml_set_object

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_object — 在对象中使用 XML 解析器

描述

xml_set_object ( resource $parser , object &$object ) : pool

该函数使得 parser 指定的解析器可以被用在 object 对象中。所有的回叫函数（callback function）都可以由 xml_set_element_handler() 等函数来设置，它们被假定为 object 对象的方法。

Example #1 xml_set_object() 示例

<?php
class xml  {
    var $parser;

    function xml()
    {
        $this->parser = xml_parser_create();

        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
    }

     function parse($data)
    {
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($parser, $tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($parser, $cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($parser, $tag);
    }

} // end of class xml

$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

User Contributed Notes

joey at gimo dot co dot uk 10-Aug-2016 10:32
This function seems to be of very limited use when [$object_instance, "method_name"] is a callable.
wake dot shinigami at gmail dot com 23-Nov-2005 08:28
I finally managed to get xml_set_object() to work, after much documentation searching.  As the solution I found has been hinted at, the focus has been wrong.

There have been many problems getting class contained XML parsers to make changes to the members of an instance.  This is because, from what I'm guessing, the functions are using a either a new annonymous instance of the class or an uninstanced version of the class.

What we want to make sure it does it that the parser is accessing its handlers as member methods of a particular instance of a class.  This can be done using the array method for passing a callback, setting the object as a reference to this instance.  This way, you know that the parser is going to call the function properly.

Ex:
<?php
class Parser {

 private $parser;
 private $data;

 public function __construct() {
  $this->parser = NULL;
  $this->data = '';
 }

 private function ParseElementStart($parser, $name, $attrs) {
  // Code
 }
 private function ParseElementEnd($parser, $name) {
  // Code
 }

 public function Parse($XMLdata) {
  $this->parser = xml_parser_create();
  xml_set_object($this->parser, $this);
  xml_set_element_handler($this->parser,
                          array(&$this, 'ParseElementStart'),
                          array(&$this, 'ParseElementEnd'));
  xml_parse($this->parser, $XMLdata);
  xml_parser_free($this->parser);
 }
}
?>

With this, when you call the Parse method, the data in that instance can be modified.  I'm not sure if xml_set_object becomes unneccissary when using the array callbacks, but I leave it in just to make sure that the xml_parse function knows it's in the object.

As above, I'd recommend for memory sake, that the XML parser be created, used, and freed all in the same function, to ensure that everything is cleaned up correctly.
bettmenn at gmx dot de 16-Oct-2004 02:03
Adding to 'lmfe at mega dot ist dot utl dot pt' contribution below, I have to say that this behaviour is very usual for PHP if MemberVars of an Object arent initialized from the constructor.
What worked best for me so far was something like this:
<?php
class foo {
  var $bar
  // the constructor
  function foo() {
    unset($this->bar);  // with every instanciation, the variable is cleared for the object
  }
}
?>
lmfe at mega dot ist dot utl dot pt 29-Sep-2004 10:51
Using PHP 4.3.0, I got this strange behaviour:

<?php
class xml  {

     /* (as specified in the documentation above) */

} // end of class xml

/* This code works */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");

/* This code works */
$xml_parser2 = new xml();
$xml_parser2->parse("<A ID='hallo2'>PHP2</A>");

/* This code DON'T work */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo3'>PHP3</A>");
?>

In the third block of code, php complains it can't find the handlers it needs.
It seems this problem only happens if the variable is used more than once.
Calling xml_parser_free doesn't help
hwheinzen at t-online dot de 14-Aug-2004 03:38
(Adding to zitan's note)
It seems easy enough to provide output functions for callback handler classes too.

Example:

<?php
class CallBack {
    var $name = 'Callback';
    var $info = 'Information!';
    function toString() {
        return $this->name.': '.$this->info;
    }
}
class Main {
    var $name = 'Main';
    var $callBackObject;
    function setCallBack(&$cBIn) { $this->callBackObject = $cBIn; }
    function toString() {
        return $this->name.': '.$this->callBackObject->toString();
    }
}

$cb = & new CallBack;
$m = & new Main;
$m->setCallBack(&$cb);
echo $cb->toString();
echo $m->toString();
?>

So, after collecting information during the parse operation within the callback handler class, e.g. in tag_close(), retrieving them is possible.
zitan at mediasculpt dot net 01-Sep-2003 09:05
Just a note about creating abstract "call back handlers" as mentioned in some of the other notes.  In this case I recommend extending the base XML class and overwritting the handler methods.  The reason I wanted to do this, is that if you have a separate callback method class it causes problems, for example if you want to collect information out of the XML file and store it in an array.  You can get around it with global variables, but I prefer to use them only when required ;)

Example:

<?php
class xml_output extends xml{

  var $output = array();

   function xml_output(){
    $this->xml();
   }

    //overwrite base methods
    function tag_open($parser, $tag, $attributes)
    {
        array_push($this->output, "<$tag, attributes>");
    }

    function cdata($parser, $cdata)
    {
         array_push($this->output, "$cdata");
    }

    function tag_close($parser, $tag)
    {
         array_push($this->output, "</$tag>");
    }

}

$xml_parser = & new xml_output();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
echo("$xml_parser->output");
?>
sbeam at syxyz dot net 12-Nov-2002 09:34
passing the object as a call-time ref (&$this) as in the example will create a warning in php 4.1+. Pass xml_set_object($xp,$this); instead. This does not seem to break anything - but I dont know for sure.
chiefgeek at ecodedesign.com 04-Aug-2002 10:37
Just adding a little note about my above written example.  It needs some improvements.

Because PHP passes by VALUE by default, when you pass an array like this:
array($callback_handler, 'handler_method')
PHP makes a copy of the callback_handler object and uses the handler_method in the copy.

This is not an ideal situation for many reasons...which I will not get into here...but you should have an idea by now.

The best way to fix this is to change a few things. In the function declaration change the parameter from $callback_handler to &$callback_handler. So now your declaration should look like this

function set_callback_handler(&$callback_handler)
{
  ...
}

Now each time you reference $callback_handler change it to &$callback_handler.  For example:

xml_set_element_handler(
          $this->xml_parser,
          array(&$callback_handler, 'start_element'),
          array(&$callback_handler, 'close_Element' ));

This ensures that PHP will always use the same object.
chiefgeek at ecodedesign.com 03-Aug-2002 08:25
xml_set_object is great, if you want to hard code your start_element, end_element, etc functions within your xml class.

But what if you want to increase the modularity of your application?

Solution, create one generic XMLParser class that handles everything *except* the callback funtions.  Then create an abstract XMLCallbackHandler class which you can extend to provide any customization you want.

So how do you tell the php's xml_parser that you want to use this other class to handle the callback functions.

xml_set_object?  This only works if the functions are *within* the object you called this method from.

The solution lies in the xml_set_element_handler() function.
Take a look at this sample source...

class XMLParser
{

  ...

  function set_callback_handler($callback_handler)
  {
    // Assign the startElement endElement functions
    xml_set_element_handler(
          $this->xml_parser,
          array($callback_handler, 'start_element'),
          array($callback_handler, 'close_Element' ));

    /* By passing an array with this ($object, 'function_name') structure
       to the 2nd and 3rd parameters.  We are able to tell the parser to
       look in another object for these callback functions.
    */

    // Assign the character data function
    xml_set_character_data_handler(
          $this->xml_parser,
          array($callback_handler, 'character_data'));
    }
}

class myCallBackHandler
{
  function start_element(...)
  {
    //code goes here
  }

  function end_element(...)
  {
    //code goes here
  }

  function character_data(...)
  {
    //code goes here
  }
}

Now all thats left to do is use these classes..

$parser = new XMLParser();
$parser->set_callback_handler(new myCallbackHandler());
dfoesch at cs dot nmsu dot edu 12-Apr-2002 05:38
English explaination of why you do: $xml = & new xml();

Ok, when PHP executes "new xml()" it creates an anonymous variable (one that you can't reference with any name) which it then runs the constructor function on.  Ok, now once that's done, it then assigns by VALUE in the example above.  This means that that lovely pointer to your parser is pointing to the anonymous instance of your class, and not the used instance of your class... thus making a "shadow" of all your variables, where assignments inside the parser access different variables than outside the parser.  What PHP _SHOULD_ be doing (similar to C++) is have this statement execute such that the assignment is done by REFERENCE, so that you assign the new name to the class that actually got constructed, and not just a copy of the class that you constructed.

If they did it right, this code wouldn't be broken.
14-Feb-2002 11:10
Call-time pass-by-reference has been deprecated, so the example is buggy as was already mentionned. However since 4.04 (I think) "new" can return objects by reference. So the clean way to have both the parser initialised in the constructor, and to save the result in your object is to do

$xml_parser = & new xml();

see http://www.php.net/manual/en/language.oop.newref.php

Ivan
pete dot nelson at serverSXPYAZMsolved dot com 27-Aug-2001 10:15
<p>in reply to jon9mm's question, I have found the same problem (function 'startElement' does not exist).  I finally found the way around this, by re-reading this doc for xml_set_object.  You HAVE to use the xml_set_object($this->parser, &$this) within your parser function.</p> <p>When that function is called, your object temporarily becomes the parser object and shares scope (so it can see 'startElement', etc).   Once that function is done, the xml_set_object(...) call goes out of scope, and your object is no longer bound to the parser.  So the simplist solution is to call xml_set_object(...), do any parsing, and then call xml_parser_free(...) all within the same function.</p>
<p>And remember, don't call xml_set_object(...) in your object's constructor - your object will be forever bound to the parser object and you'll loose all access to your object's member functions.</p>
<p>This is all explained in the examples above, but it took me reading it a couple of times to grok how it all works.</p>
nick at category4 dot com 14-May-2001 01:45
If you're using the XML parser within an object, be careful not to accidentally call any methods that don't exist within the object. Instead of complaining that the missing method doesn't exist, PHP will say it's not able to find the handler routines, even if you've indicated them correctly. (PHP version 4.0.5 on FreeBSD).
williams at cse dot unl dot edu 06-Dec-2000 12:42
If xml_set_object is not called in the constructor of an object, the values that the parser modifies will be saved. Else, the values do not seem to be saved as stated by "i_sofer" above.
--- Start Example Code ---
class foo {
var xmlparser;
function foo() { \\the constructor
$this->xmlparser=xmlparser_create();
}
function parse() {
xml_set_object($this->xmlparser,&$this);
\\also include data handler
\\and element handlers here
}
}
--- End Example Code ---
i_sofer at yahoo dot com 18-Nov-2000 04:15
Using xml parser in objects seem to have a problem that values modified(even of the object itself) get lost as soon as parsing ends...
malcontent at msgto dot com 20-Aug-2000 12:11
The example will generate a warning unless allow_call_time_pass_reference is set to true in your INI file. It also will not accept a call by value.
robert at webmotion dot com 18-Apr-2000 10:58
While true that there is no automatic destructor for PHP class objects, it is quite simple to create a method called destroy and perform the destruction manually. In the example above it may not be necessary to free the xml parser immediately... it would appear from the example that the object is re-useable.


建立处理指令（PI）处理器

  • ? xml_set_object
  • xml_set_start_namespace_decl_handler ?
  • PHP Manual
  • XML 解析器函数
  • 建立处理指令（PI）处理器

xml_set_processing_instruction_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_processing_instruction_handler — 建立处理指令（PI）处理器

说明

xml_set_processing_instruction_handler ( resource $parser , callable $handler ) : bool

为 parser 参数指定的 XML 解析器建立处理指令（PI）处理器函数。

处理指令有如下格式：

<?
target data
?>
您可以将 PHP 代码放置在类似的标识符中，但要注意一个限制：在 XML 处理指令（PI）中，PI 的终止符（?>）不能被引号引用，因此该字符序列不应该在您用 PI 嵌入到 XML 文档中的 PHP 代码中出现。否则，剩下的 PHP 代码，包括"真正"的 PI 终止符将被当作字符数据处理。

参数

parser

XML 解析器的引用，用于建立处理指令（PI）处理器。

handler

参数 handler 为表示函数名称的字符串，函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受三个参数：

handler ( resource $parser , string $target , string $data )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
target
第二个参数 target 为 PI 对象（PI target）。
data
第三个参数 data 包含了 PI 数据。

如果处理器函数名被设置为空字符串或者 false，则该有问题的处理器将被屏蔽。

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


建立起始命名空间声明处理器

  • ? xml_set_processing_instruction_handler
  • xml_set_unparsed_entity_decl_handler ?
  • PHP Manual
  • XML 解析器函数
  • 建立起始命名空间声明处理器

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

xml_set_start_namespace_decl_handler — 建立起始命名空间声明处理器

说明

xml_set_start_namespace_decl_handler ( resource $parser , callable $handler ) : bool

Set a handler to be called when a namespace is declared. Namespace declarations occur inside start tags. But the namespace declaration start handler is called before the start tag handler for each namespace declared in that start tag.

参数

parser

A reference to the XML parser.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept three parameters, and should return an integer value. If the value returned from the handler is false (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix , string $uri )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
prefix
The prefix is a string used to reference the namespace within an XML object.
uri
Uniform Resource Identifier (URI) of namespace.

If a handler function is set to an empty string, or false, the handler in question is disabled.

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • xml_set_end_namespace_decl_handler() - 建立终止命名空间声明处理器

User Contributed Notes

There are no user contributed notes for this page.


建立未解析实体定义声明处理器

  • ? xml_set_start_namespace_decl_handler
  • XMLReader ?
  • PHP Manual
  • XML 解析器函数
  • 建立未解析实体定义声明处理器

xml_set_unparsed_entity_decl_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_unparsed_entity_decl_handler — 建立未解析实体定义声明处理器

说明

xml_set_unparsed_entity_decl_handler ( resource $parser , callable $handler ) : bool

为 parser 参数指定的 XML 解析器建立未解析实体定义声明处理器函数。

当 XML 解析器遇到如下含有 NDATA 声明的外部实体定义声明时，该 handler 处理器将被调用：

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

请参阅 » XML 1.0 参考的第 4.2.2 节以获取有关已声明外部实体注释定义的信息。

参数

parser

XML 解析器的引用，用于建立未解析实体定义声明处理器。

handler

参数handler 为表示函数名称的字符串，这个函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受六个参数：

handler ( resource $parser , string $entity_name , string $base , string $system_id , string $public_id , string $notation_name )
parser
第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。
entity_name
将被定义的实体名。
base
这个参数是解析外部实体的系统标识符（system_id）的基础。当前该参数通常都被设置为空字符串。
system_id
外部实体的系统标识符。
public_id
外部实体的公共标识符。
notation_name
该实体的注释名（请参阅 xml_set_notation_decl_handler()）。

如果处理器函数名被设置为空字符串或者 false，则该有问题的处理器将被屏蔽。

Note: 除了函数名，含有对象引用的数组和方法名也可以作为参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


XMLReader

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • XMLReader — The XMLReader class
    • XMLReader::close — Close the XMLReader input
    • XMLReader::expand — Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute — Get the value of a named attribute
    • XMLReader::getAttributeNo — Get the value of an attribute by index
    • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty — Indicates if specified property has been set
    • XMLReader::isValid — Indicates if the parsed document is valid
    • XMLReader::lookupNamespace — Lookup namespace for a prefix
    • XMLReader::moveToAttribute — Move cursor to a named attribute
    • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs — Move cursor to a named attribute
    • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
    • XMLReader::next — Move cursor to next node skipping all subtrees
    • XMLReader::open — Set the URI containing the XML to parse
    • XMLReader::read — Move to next node in document
    • XMLReader::readInnerXml — Retrieve XML from current node
    • XMLReader::readOuterXml — Retrieve XML from current node, including itself
    • XMLReader::readString — Reads the contents of the current node as a string
    • XMLReader::setParserProperty — Set parser options
    • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
    • XMLReader::setSchema — Validate document against XSD
    • XMLReader::XML — Set the data containing the XML to parse

User Contributed Notes

kraussInode at yahoo dot com 27-Mar-2010 12:54
See also XMLWriter: XMLReader and XMLWriter complement each other.


简介

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

编码

It is important to note that internally, libxml uses the UTF-8 encoding and as such, the encoding of the retrieved contents will always be in UTF-8 encoding.

User Contributed Notes

There are no user contributed notes for this page.


安装

The XMLReader extension was initially a PECL extension for PHP 5. It was later moved to the PHP source (bundled) as of PHP 5.1.0, and later enabled by default as of PHP 5.1.2.

此扩展默认为启用，编译时可通过下列选项禁用： --disable-xmlreader

User Contributed Notes

Miguel Cruz 11-Jun-2012 01:06
If you are having trouble loading this extension (perhaps with a log message like 'Undefined symbol "dom_node_class_entry"'), make sure that you have xmlreader.so listed AFTER dom.so in php.ini.
alvaro at digdib dot com 02-Jan-2009 02:33
Gentoo users: emerge does not compile dev-lang/php with --enable-xmlreader by default. To enable this option, add the flag xmlreader to your USE variable and recompile php.


The XMLReader class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

类摘要

XMLReader {
/* 常量 */
const int NONE = 0 ;
const int ELEMENT = 1 ;
const int ATTRIBUTE = 2 ;
const int TEXT = 3 ;
const int CDATA = 4 ;
const int ENTITY_REF = 5 ;
const int ENTITY = 6 ;
const int PI = 7 ;
const int COMMENT = 8 ;
const int DOC = 9 ;
const int DOC_TYPE = 10 ;
const int DOC_FRAGMENT = 11 ;
const int NOTATION = 12 ;
const int WHITESPACE = 13 ;
const int SIGNIFICANT_WHITESPACE = 14 ;
const int END_ELEMENT = 15 ;
const int END_ENTITY = 16 ;
const int XML_DECLARATION = 17 ;
const int LOADDTD = 1 ;
const int DEFAULTATTRS = 2 ;
const int VALIDATE = 3 ;
const int SUBST_ENTITIES = 4 ;
/* 属性 */
public readonly int $attributeCount ;
public readonly string $baseURI ;
public readonly int $depth ;
public readonly bool $hasAttributes ;
public readonly bool $hasValue ;
public readonly bool $isDefault ;
public readonly bool $isEmptyElement ;
public readonly string $localName ;
public readonly string $name ;
public readonly string $namespaceURI ;
public readonly int $nodeType ;
public readonly string $prefix ;
public readonly string $value ;
public readonly string $xmlLang ;
/* 方法 */
public close ( ) : bool
public expand ( DOMNode|null $baseNode = null ) : DOMNode|false
public getAttribute ( string $name ) : string|null
public getAttributeNo ( int $index ) : string|null
public getAttributeNs ( string $name , string $namespace ) : string|null
public getParserProperty ( int $property ) : bool
public isValid ( ) : bool
public lookupNamespace ( string $prefix ) : string|null
public moveToAttribute ( string $name ) : bool
public moveToAttributeNo ( int $index ) : bool
public moveToAttributeNs ( string $name , string $namespace ) : bool
public moveToElement ( ) : bool
public moveToFirstAttribute ( ) : bool
public moveToNextAttribute ( ) : bool
public next ( string|null $name = null ) : bool
public static open ( string $uri , string|null $encoding = null , int $flags = 0 ) : bool|XMLReader
public read ( ) : bool
public readInnerXml ( ) : string
public readOuterXml ( ) : string
public readString ( ) : string
public setParserProperty ( int $property , bool $value ) : bool
public setRelaxNGSchema ( string|null $filename ) : bool
public setRelaxNGSchemaSource ( string|null $source ) : bool
public setSchema ( string|null $filename ) : bool
public static XML ( string $source , string|null $encoding = null , int $flags = 0 ) : bool|XMLReader
}

属性

attributeCount

The number of attributes on the node

baseURI

The base URI of the node

depth

Depth of the node in the tree, starting at 0

hasAttributes

Indicates if node has attributes

hasValue

Indicates if node has a text value

isDefault

Indicates if attribute is defaulted from DTD

isEmptyElement

Indicates if node is an empty element tag

localName

The local name of the node

name

The qualified name of the node

namespaceURI

The URI of the namespace associated with the node

nodeType

The node type for the node

prefix

The prefix of the namespace associated with the node

value

The text value of the node

xmlLang

The xml:lang scope which the node resides

预定义常量

XMLReader Node Types

XMLReader::NONE

No node type

XMLReader::ELEMENT

Start element

XMLReader::ATTRIBUTE

Attribute node

XMLReader::TEXT

Text node

XMLReader::CDATA

CDATA node

XMLReader::ENTITY_REF

Entity Reference node

XMLReader::ENTITY

Entity Declaration node

XMLReader::PI

Processing Instruction node

XMLReader::COMMENT

Comment node

XMLReader::DOC

Document node

XMLReader::DOC_TYPE

Document Type node

XMLReader::DOC_FRAGMENT

Document Fragment node

XMLReader::NOTATION

Notation node

XMLReader::WHITESPACE

Whitespace node

XMLReader::SIGNIFICANT_WHITESPACE

Significant Whitespace node

XMLReader::END_ELEMENT

End Element

XMLReader::END_ENTITY

End Entity

XMLReader::XML_DECLARATION

XML Declaration node

XMLReader Parser Options

XMLReader::LOADDTD

Load DTD but do not validate

XMLReader::DEFAULTATTRS

Load DTD and default attributes but do not validate

XMLReader::VALIDATE

Load DTD and validate while parsing

XMLReader::SUBST_ENTITIES

Substitute entities and expand references

Table of Contents

  • XMLReader::close — Close the XMLReader input
  • XMLReader::expand — Returns a copy of the current node as a DOM object
  • XMLReader::getAttribute — Get the value of a named attribute
  • XMLReader::getAttributeNo — Get the value of an attribute by index
  • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
  • XMLReader::getParserProperty — Indicates if specified property has been set
  • XMLReader::isValid — Indicates if the parsed document is valid
  • XMLReader::lookupNamespace — Lookup namespace for a prefix
  • XMLReader::moveToAttribute — Move cursor to a named attribute
  • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs — Move cursor to a named attribute
  • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
  • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
  • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
  • XMLReader::next — Move cursor to next node skipping all subtrees
  • XMLReader::open — Set the URI containing the XML to parse
  • XMLReader::read — Move to next node in document
  • XMLReader::readInnerXml — Retrieve XML from current node
  • XMLReader::readOuterXml — Retrieve XML from current node, including itself
  • XMLReader::readString — Reads the contents of the current node as a string
  • XMLReader::setParserProperty — Set parser options
  • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
  • XMLReader::setSchema — Validate document against XSD
  • XMLReader::XML — Set the data containing the XML to parse

User Contributed Notes

eef dot vreeland at gmail dot com 10-Aug-2017 05:43
Please discard my previous note; I pressed 'Add Note' too quickly

About (non-)self-closing tags:

 A) <tag></tag>
    $xmlRdr->isEmptyElement => false
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => false

 B) <tag />
    $xmlRdr->isEmptyElement => true
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => false

 C) <tag attribute="value"></tag>
    $xmlRdr->isEmptyElement => false
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => true

 D) <tag attribute="value" />
    $xmlRdr->isEmptyElement => true
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => true

... and always use the '===' operator when testing properties
eef dot vreeland at gmail dot com 10-Aug-2017 05:08
Note that when:

A) <tag></tag>
   $xmlRdr->isEmptyElement => false
   $xmlRdr->hasValue       => true
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => false

B) <tag />
   $xmlRdr->isEmptyElement => true
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => false

C) <tag attribute="value"></tag>
   $xmlRdr->isEmptyElement => false
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => true

D) <tag attribute="value" />
   $xmlRdr->isEmptyElement => true
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => true
Sean Colin Ruiz 08-Jan-2017 03:11
As japos mentioned. Take care how you use isEmptyElement. After you are done looping through the attributes: isEmptyElement will be false.  You can use moveToElement() to move the cursor back to the element and then you can use isEmptyElement like normal again.
dkrnl at yandex dot ru 04-Oct-2013 04:10
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php

<?php

/**
 * Simple XML Reader
 *
 * @license Public Domain
 * @author Dmitry Pyatkov(aka dkrnl) <dkrnl@yandex.ru>
 * @url http://github.com/dkrnl/SimpleXMLReader
 */
class SimpleXMLReader extends XMLReader
{

    /**
     * Callbacks
     *
     * @var array
     */
    protected $callback = array();

    /**
     * Add node callback
     *
     * @param  string   $name
     * @param  callback $callback
     * @param  integer  $nodeType
     * @return SimpleXMLReader
     */
    public function registerCallback($name, $callback, $nodeType = XMLREADER::ELEMENT)
    {
        if (isset($this->callback[$nodeType][$name])) {
            throw new Exception("Already exists callback $name($nodeType).");
        }
        if (!is_callable($callback)) {
            throw new Exception("Already exists parser callback $name($nodeType).");
        }
        $this->callback[$nodeType][$name] = $callback;
        return $this;
    }

    /**
     * Remove node callback
     *
     * @param  string  $name
     * @param  integer $nodeType
     * @return SimpleXMLReader
     */
    public function unRegisterCallback($name, $nodeType = XMLREADER::ELEMENT)
    {
        if (!isset($this->callback[$nodeType][$name])) {
            throw new Exception("Unknow parser callback $name($nodeType).");
        }
        unset($this->callback[$nodeType][$name]);
        return $this;
    }

    /**
     * Run parser
     *
     * @return void
     */
    public function parse()
    {
        if (empty($this->callback)) {
            throw new Exception("Empty parser callback.");
        }
        $continue = true;
        while ($continue && $this->read()) {
            if (isset($this->callback[$this->nodeType][$this->name])) {
                $continue = call_user_func($this->callback[$this->nodeType][$this->name], $this);
            }
        }
    }

    /**
     * Run XPath query on current node
     *
     * @param  string $path
     * @param  string $version
     * @param  string $encoding
     * @return array(SimpleXMLElement)
     */
    public function expandXpath($path, $version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->xpath($path);
    }

    /**
     * Expand current node to string
     *
     * @param  string $version
     * @param  string $encoding
     * @return SimpleXMLElement
     */
    public function expandString($version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->asXML();
    }

    /**
     * Expand current node to SimpleXMLElement
     *
     * @param  string $version
     * @param  string $encoding
     * @param  string $className
     * @return SimpleXMLElement
     */
    public function expandSimpleXml($version = "1.0", $encoding = "UTF-8", $className = null)
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return simplexml_import_dom($node, $className);
    }

    /**
     * Expand current node to DomDocument
     *
     * @param  string $version
     * @param  string $encoding
     * @return DomDocument
     */
    public function expandDomDocument($version = "1.0", $encoding = "UTF-8")
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return $document;
    }

}
?>
kula_shakerz 03-Apr-2013 02:27
Found this in the IXmlReader docs at msdn but it's also valid for XMLReader in PHP.

You should save the value of $isEmptyElement before processing attributes, or call moveToElement to make $isEmptyElement valid after processing attributes.

$isEmptyElement returns FALSE when XMLReader is positioned on an attribute node, even if attribute's parent element is empty.
Mike De Smet 25-Sep-2012 04:35
For those of you getting xml files that do not contain duplicate elements (in the same element), the following converter converts to arrays with key/value mapping (thus overwriting duplicate elements!):

Note this is untested with attributes although I built in support.

<?php
    function xml2assoc($xml, array &$target = array()) {
        while ($xml->read()) {
            switch ($xml->nodeType) {
                case XMLReader::END_ELEMENT:
                    return $target;
                case XMLReader::ELEMENT:
                    $name = $xml->name;
                    $target[$name] = $xml->hasAttributes ? array() : '';
                    if (!$xml->isEmptyElement) {
                        $target[$name] = array();
                        xml2assoc($xml, $target[$name]);
                    }

                    if ($xml->hasAttributes)
                        while($xml->moveToNextAttribute())
                            $target[$name]['@'.$xml->name] = $xml->value;
                    break;
                case XMLReader::TEXT:
                case XMLReader::CDATA:
                    $target = $xml->value;
            }
        }
        return $target;
    }
?>
casella dot email at google dot mail dot com 22-Sep-2012 03:59
To verify that all nodes are read without error/warning you can use this code:
<?php
$endofxml = false;
$xml_url = "example.xml";
$reader = new XMLReader();
if(!$reader->open($xml_url)){
    print "Error to open XML: $xml_url\n";
} else {
    while ($reader->read()) {
        $firstnode = (!isset($firstnode)) ? $reader->name : $firstnode;
/*
DO SOMETHING
*/
        if ($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == $firstnode) {
            $endofxml = true;
        }
    }
}
if($endofxml) {
    print "no error found";
} else {
    print "error found";
}
?>

This code is useful to trap $reader->read() error/warning.
lee8oi at gmail dot com 21-Mar-2012 01:54
Sometimes you have an unusual URL that doesn't actually point to an xml file but still returns xml as output (Like the Battlefield Heroes generated syndication urls). Using get_file_contents(url) you can retrieve the xml data from these urls and pass it as a variable for processing as an XML String.

Unfortunately simpleXML or xml DOM cannot process all xml strings. Some have error boxes added to the end of them (such as Battlefield Heroes syndicated news). These boxes cause an end of file sort of error and closes out the script. XMLReader grabs data from these strings without error.
japos dot trash at googlemail dot com 09-Oct-2010 02:17
Take care about how to use XMLReader::$isElementEmpty. I don't know if it is a bug or not, but $isElementEmpty is set for the current context and NOT just for the element. If you move your cursor to an attribute, $isElementEmpty will ALWAYS be false.

<?php
 $xml = new XMLReader();
 $xml->XML('<tag attr="value" />');
 $xml->read();
 var_dump($xml->isEmptyElement);
 $xml->moveToNextAttribute();
 var_dump($xml->isEmptyElement);
?>

will output

(bool) true
(bool) false

So be sure to store $isEmptyElement before moving the cursor.
jart (at) mail.ru 23-Sep-2010 06:59
Guys, I hope this example will help
you can erase prints showing the process-
and it will be a piece of nice code.

<?php
function xml2assoc($xml, $name)
{
    print "<ul>";

    $tree = null;
    print("I'm inside " . $name . "<br>");

    while($xml->read())
    {
        if($xml->nodeType == XMLReader::END_ELEMENT)
        {
            print "</ul>";
            return $tree;
        }

        else if($xml->nodeType == XMLReader::ELEMENT)
        {
            $node = array();

            print("Adding " . $xml->name ."<br>");
            $node['tag'] = $xml->name;

            if($xml->hasAttributes)
            {
                $attributes = array();
                while($xml->moveToNextAttribute())
                {
                    print("Adding attr " . $xml->name ." = " . $xml->value . "<br>");
                    $attributes[$xml->name] = $xml->value;
                }
                $node['attr'] = $attributes;
            }

            if(!$xml->isEmptyElement)
            {
                $childs = xml2assoc($xml, $node['tag']);
                $node['childs'] = $childs;
            }

            print($node['tag'] . " added <br>");
            $tree[] = $node;
        }

        else if($xml->nodeType == XMLReader::TEXT)
        {
            $node = array();
            $node['text'] = $xml->value;
            $tree[] = $node;
            print "text added = " . $node['text'] . "<br>";
        }
    }

    print "returning " . count($tree) . " childs<br>";
    print "</ul>";

    return $tree;
}

echo "<PRE>";

$xml = new XMLReader();
$xml->open('test.xml');
$assoc = xml2assoc($xml, "root");
$xml->close();

print_r($assoc);
echo "</PRE>";

?>

It reads this xml:

<test>
    <hallo volume="loud"> me <br/> lala </hallo>
    <hallo> me </hallo>
</test>
jnettles at inccrra dot org 02-Oct-2009 09:51
Just in case someone is confused, if you're wanting to simply pass a string of XML instead of an entire file, you would do this.

<?php
$foo = new XMLReader();
$foo->xml($STRING);
?>

.... where $STRING holds your XML. You cannot pass it like $foo = $STRING or $foo->xml = $STRING.
james dot ellis at example dot com 25-Mar-2009 03:16
The "XML2Assoc" functions noted here should be used with caution... basically they are duplicating the functionality already present in SimpleXML. They may work but they won't scale.

Their are two main uses cases for parsing XML, each suited to either XMLReader or SimpleXML.

1. SimpleXML is an excellent tool for easy access to an XML document tree using native PHP data types. It starts to flounder with massive (> 50M or so) XML documents, as it reads the entire document into memory before it can be processed. SimpleXML will just laugh at you then die when your server runs out of memory (or it will cause a load spike).

2. Aside from the reasoning behind massive XML documents, if you have to deal with massive XML documents, use XMLReader to process them. Don't try and gather an entire XML document into a PHP data structure using XMLReader and a PHP xml2assoc() function, you are reinventing the SimpleXML wheel.
When parsing massive XML documents using XMLReader, gather the data you need to perform an operation then perform it before skipping to the next node. Do not build massive data structures from a massive XML document, your server (and it's admins) will not like you.
PxL 23-Jan-2009 03:36
A basic parser

<?php
function xml2assoc($xml) {
    $arr = array();
    if (!preg_match_all('|\<\s*?(\w+).*?\>(.*)\<\/\s*\\1.*?\>|s', $xml, $m)) return $xml;
    if (is_array($m[1]))
        for ($i = 0;$i < sizeof($m[1]); $i++) $arr[$m[1][$i]] = xml2assoc($m[2][$i]);
    else $arr[$m[1]] = xml2assoc($m[2]);

    return $arr;
}
?>
boukeversteegh at gmail dot com 18-Jan-2009 02:06
XML to ASSOCIATIVE ARRAY

Improved algorithm based on Sergey Aikinkulov's. The problem was that it would overwrite nodes if they had the same tag name. Because of that <a><b/><b/><a> would be read as if <a><b/><a/>. This algorithm handles it better and outputs an easy to understand array:

<?php
function xml2assoc($xml) {
    $tree = null;
    while($xml->read())
        switch ($xml->nodeType) {
            case XMLReader::END_ELEMENT: return $tree;
            case XMLReader::ELEMENT:
                $node = array('tag' => $xml->name, 'value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
                if($xml->hasAttributes)
                    while($xml->moveToNextAttribute())
                        $node['attributes'][$xml->name] = $xml->value;
                $tree[] = $node;
            break;
            case XMLReader::TEXT:
            case XMLReader::CDATA:
                $tree .= $xml->value;
        }
    return $tree;
}

?>

Usage:

myxml.xml:
------
<PERSON>
    <NAME>John</NAME>
    <PHONE type="home">555-555-555</PHONE>
</PERSON>
----

<?
    $xml = new XMLReader();
    $xml->open('myxml.xml');
    $assoc = xml2assoc($xml);
    $xml->close();
    print_r($assoc);
?>

Outputs:
Array
(
    [0] => Array
        (
            [tag] => PERSON
            [value] => Array
                (
                    [0] => Array
                        (
                            [tag] => NAME
                            [value] => John
                        )

                    [1] => Array
                        (
                            [tag] => PHONE
                            [value] => 555-555-555
                            [attributes] => Array
                                (
                                    [type] => home
                                )

                        )

                )

        )

)

For reasons that have to do with recursion, it returns an array with the ROOT xml node as the first childNode, rather than to return only the ROOT node.
andrei_antal at yahoo dot com 08-Jan-2009 08:25
<?php
//Pull certain elements
 $reader = new XMLReader();
  $reader->open($xmlfile);
while ($reader->read()) {
 switch ($reader->nodeType) {
   case (XMLREADER::ELEMENT):

if ($reader->name == "Code")
     {
       $reader->read();
       $code = trim($reader->value);
       echo "$code\n";
       break;
     }

 if ($reader->name == "Name")
     {
       $reader->read();
       $customername = trim( $reader->value );
       echo "$name\n";
       break;
     }

 if ($reader->name == "Camp")
    {
      $camp = trim($reader->getAttribute("ID"));
       echo "$camp\n";
      break;
    }
  }
}
?>
godseth at o2 dot pl 28-Nov-2008 02:34
Thanks rein_baarsma33 AT hotmail DOT com for bugfixes.

This is my new child of XML parsing method  based on my and yours modification.

XML2ASSOC Is a complete solution for parsing ordinary XML

<?php
/**
 * XML2Assoc Class to creating
 * PHP Assoc Array from XML File
 *
 * @author godseth (AT) o2.pl & rein_baarsma33 (AT) hotmail.com (Bugfixes in parseXml Method)
 * @uses XMLReader
 *
 */

class Xml2Assoc {

    /**
     * Optimization Enabled / Disabled
     *
     * @var bool
     */
    protected $bOptimize = false;

    /**
     * Method for loading XML Data from String
     *
     * @param string $sXml
     * @param bool $bOptimize
     */

    public function parseString( $sXml , $bOptimize = false) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {

            // Set String Containing XML data
            $oXml->XML($sXml);

            // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * Method for loading Xml Data from file
     *
     * @param string $sXmlFilePath
     * @param bool $bOptimize
     */
    public function parseFile( $sXmlFilePath , $bOptimize = false ) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {
            // Open XML file
            $oXml->open($sXmlFilePath);

            // // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage(). ' | Try open file: '.$sXmlFilePath;
        }
    }

    /**
     * XML Parser
     *
     * @param XMLReader $oXml
     * @return array
     */
    protected function parseXml( XMLReader $oXml ) {

        $aAssocXML = null;
        $iDc = -1;

        while($oXml->read()){
            switch ($oXml->nodeType) {

                case XMLReader::END_ELEMENT:

                    if ($this->bOptimize) {
                        $this->optXml($aAssocXML);
                    }
                    return $aAssocXML;

                case XMLReader::ELEMENT:

                    if(!isset($aAssocXML[$oXml->name])) {
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name] = '';
                            } else {
                                $aAssocXML[$oXml->name] = $this->parseXML($oXml);
                            }
                        }
                    } elseif (is_array($aAssocXML[$oXml->name])) {
                        if (!isset($aAssocXML[$oXml->name][0]))
                        {
                            $temp = $aAssocXML[$oXml->name];
                            foreach ($temp as $sKey=>$sValue)
                            unset($aAssocXML[$oXml->name][$sKey]);
                            $aAssocXML[$oXml->name][] = $temp;
                        }

                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    } else {
                        $mOldVar = $aAssocXML[$oXml->name];
                        $aAssocXML[$oXml->name] = array($mOldVar);
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    }

                    if($oXml->hasAttributes) {
                        $mElement =& $aAssocXML[$oXml->name][count($aAssocXML[$oXml->name]) - 1];
                        while($oXml->moveToNextAttribute()) {
                            $mElement[$oXml->name] = $oXml->value;
                        }
                    }
                    break;
                case XMLReader::TEXT:
                case XMLReader::CDATA:

                    $aAssocXML[++$iDc] = $oXml->value;

            }
        }

        return $aAssocXML;
    }

    /**
     * Method to optimize assoc tree.
     * ( Deleting 0 index when element
     *  have one attribute / value )
     *
     * @param array $mData
     */
    public function optXml(&$mData) {
        if (is_array($mData)) {
            if (isset($mData[0]) && count($mData) == 1 ) {
                $mData = $mData[0];
                if (is_array($mData)) {
                    foreach ($mData as &$aSub) {
                        $this->optXml($aSub);
                    }
                }
            } else {
                foreach ($mData as &$aSub) {
                    $this->optXml($aSub);
                }
            }
        }
    }

}

?>

[EDIT BY danbrown AT php DOT net:  Fixes were also provided by "Alex" and (qdog AT qview DOT org) in user notes on this page (since removed).]
Sergey Aikinkulov 19-Jun-2008 03:51
Next version xml2assoc with some improve fixes:
 - no doubled data
 - no buffer arrays

<?php
/*
    Read XML structure to associative array
    --
    Using:
    $xml = new XMLReader();
    $xml->open([XML file]);
    $assoc = xml2assoc($xml);
    $xml->close();
*/
    function xml2assoc($xml) {
      $assoc = null;
      while($xml->read()){
        switch ($xml->nodeType) {
          case XMLReader::END_ELEMENT: return $assoc;
          case XMLReader::ELEMENT:
            $assoc[$xml->name][] = array('value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
            if($xml->hasAttributes){
              $el =& $assoc[$xml->name][count($assoc[$xml->name]) - 1];
              while($xml->moveToNextAttribute()) $el['attributes'][$xml->name] = $xml->value;
            }
            break;
          case XMLReader::TEXT:
          case XMLReader::CDATA: $assoc .= $xml->value;
        }
      }
      return $assoc;
    }
?>
desk_ocean at msn dot com 16-Mar-2008 10:03
make some modify from Sergey Aikinkulov's note

<?php
function xml2assoc(&$xml){
    $assoc = NULL;
    $n = 0;
    while($xml->read()){
        if($xml->nodeType == XMLReader::END_ELEMENT) break;
        if($xml->nodeType == XMLReader::ELEMENT and !$xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = xml2assoc($xml);
            $n++;
        }
        else if($xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = "";
            $n++;
        }
        else if($xml->nodeType == XMLReader::TEXT) $assoc = $xml->value;
    }
    return $assoc;
}
?>

add else if($xml->isEmptyElement)
may be some xml has emptyelement
itari 15-Feb-2008 08:30
<?php
function parseXML($node,$seq,$path) {
global $oldpath;
    if (!$node->read())
      return;
    if ($node->nodeType != 15) {
      print '<br/>'.$node->depth;
      print '-'.$seq++;
      print '  '.$path.'/'.($node->nodeType==3?'text() = ':$node->name);
      print $node->value;
      if ($node->hasAttributes) {
        print ' [hasAttributes: ';
        while ($node->moveToNextAttribute()) print '@'.$node->name.' = '.$node->value.' ';
        print ']';
        }
      if ($node->nodeType == 1) {
        $oldpath=$path;
        $path.='/'.$node->name;
        }
      parseXML($node,$seq,$path);
      }
    else parseXML($node,$seq,$oldpath);
}

$source = "<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>";
$xml = new XMLReader();
$xml->XML($source);
print htmlspecialchars($source).'<br/>';
parseXML($xml,0,'');
?>

Output:

<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>

0-0 /tag1
1-1 /tag1/text() = this
1-2 /tag1/tag2 [hasAttributes: @id = 4 @name = foo ]
2-3 /tag1/text() = is
1-4 /text() = a
1-5 /tag2 [hasAttributes: @id = 5 ]
2-6 /text() = common
1-7 /text() = record
orion at ftf-hq dot dk 15-Feb-2006 04:50
Some more documentation (i.e. examples) would be nice :-)

This is how I read some mysql parameters in an xml file:

<?php
    $xml = new XMLReader();
    $xml->open("config.xml");
    $xml->setParserProperty(2,true); // This seems a little unclear to me - but it worked :)

    while ($xml->read()) {
        switch ($xml->name) {
        case "mysql_host":
            $xml->read();
            $conf["mysql_host"] = $xml->value;
            $xml->read();
            break;
        case "mysql_username":
            $xml->read();
            $conf["mysql_user"] = $xml->value;
            $xml->read();
            break;
        case "mysql_password":
            $xml->read();
            $conf["mysql_pass"] = $xml->value;
            $xml->read();
            break;
        case "mysql_database":
            $xml->read();
            $conf["mysql_db"] = $xml->value;
            $xml->read();
            break;
        }
    }

    $xml->close();
?>

The XML file used:
<?xml version='1.0'?>
<MySQL_INIT>
   <mysql_host>localhost</mysql_host>
   <mysql_database>db_database</mysql_database>
   <mysql_username>root</mysql_username>
   <mysql_password>password</mysql_password>
</MySQL_INIT>


Close the XMLReader input

  • ? XMLReader
  • XMLReader::expand ?
  • PHP Manual
  • XMLReader
  • Close the XMLReader input

XMLReader::close

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::close — Close the XMLReader input

说明

public XMLReader::close ( ) : bool

Closes the input the XMLReader object is currently parsing.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::xml() - Set the data containing the XML to parse

User Contributed Notes

There are no user contributed notes for this page.


Returns a copy of the current node as a DOM object

  • ? XMLReader::close
  • XMLReader::getAttribute ?
  • PHP Manual
  • XMLReader
  • Returns a copy of the current node as a DOM object

XMLReader::expand

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::expand — Returns a copy of the current node as a DOM object

说明

public XMLReader::expand ( DOMNode|null $baseNode = null ) : DOMNode|false

This method copies the current node and returns the appropriate DOM object.

参数

baseNode

A DOMNode defining the target DOMDocument for the created DOM object.

返回值

The resulting DOMNode or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the value of a named attribute

  • ? XMLReader::expand
  • XMLReader::getAttributeNo ?
  • PHP Manual
  • XMLReader
  • Get the value of a named attribute

XMLReader::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttribute — Get the value of a named attribute

说明

public XMLReader::getAttribute ( string $name ) : string|null

Returns the value of a named attribute or null if the attribute does not exist or not positioned on an element node.

参数

name

The name of the attribute.

更新日志

版本 | 说明
8.0.0 | This function can no longer return false.

返回值

The value of the attribute, or null if no attribute with the given name is found or not positioned on an element node.

参见

  • XMLReader::getAttributeNo() - Get the value of an attribute by index
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

User Contributed Notes

Anonymous 16-Feb-2011 09:02
Or use XMLReader::ELEMENT and XMLReader::END_ELEMENT rather than the numbers 1 and 15.
Gabi 02-Jul-2007 08:15
might be obvious, but not to everyone ;-) ... when reading attributes from a node that has sub-nodes (and creating an output from this node), the output will be issued twice, once on the <ELEMENT> tag and once on the end tag </ELEMENT>. To avoid this, you can test on which part of the node you are using the property nodeType.
It'll be 1 for the element, 15 for the end element.


Get the value of an attribute by index

  • ? XMLReader::getAttribute
  • XMLReader::getAttributeNs ?
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by index

XMLReader::getAttributeNo

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttributeNo — Get the value of an attribute by index

说明

public XMLReader::getAttributeNo ( int $index ) : string|null

Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.

参数

index

The position of the attribute.

返回值

The value of the attribute, or an empty string (before PHP 5.6) or null (from PHP 5.6 onwards) if no attribute exists at index or is not positioned on the element.

更新日志

版本 | 说明
5.6.0 | XMLReader::getAttributeNo() now returns null if the attribute doesn't exist.

参见

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

User Contributed Notes

There are no user contributed notes for this page.


Get the value of an attribute by localname and URI

  • ? XMLReader::getAttributeNo
  • XMLReader::getParserProperty ?
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by localname and URI

XMLReader::getAttributeNs

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttributeNs — Get the value of an attribute by localname and URI

说明

public XMLReader::getAttributeNs ( string $name , string $namespace ) : string|null

Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.

参数

name

The local name.

namespace

The namespace URI.

返回值

The value of the attribute, or an empty string (before PHP 5.6) or null (from PHP 5.6 onwards) if no attribute with the given name and namespace is found or not positioned of element.

更新日志

版本 | 说明
8.0.0 | This function can no longer return false.
5.6.0 | XMLReader::getAttributeNS() now returns null if the attribute doesn't exist.

参见

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNo() - Get the value of an attribute by index

User Contributed Notes

There are no user contributed notes for this page.


Indicates if specified property has been set

  • ? XMLReader::getAttributeNs
  • XMLReader::isValid ?
  • PHP Manual
  • XMLReader
  • Indicates if specified property has been set

XMLReader::getParserProperty

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getParserProperty — Indicates if specified property has been set

说明

public XMLReader::getParserProperty ( int $property ) : bool

Indicates if specified property has been set.

参数

property

One of the parser option constants.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::setParserProperty() - Set parser options

User Contributed Notes

There are no user contributed notes for this page.


Indicates if the parsed document is valid

  • ? XMLReader::getParserProperty
  • XMLReader::lookupNamespace ?
  • PHP Manual
  • XMLReader
  • Indicates if the parsed document is valid

XMLReader::isValid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::isValid — Indicates if the parsed document is valid

说明

public XMLReader::isValid ( ) : bool

Returns a boolean indicating if the document being parsed is currently valid.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Validating XML

<?php
$xml = XMLReader::open('test.xml');

// The validate parser option must be enabled for
// this method to work properly
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

注释

Note: This checks the current node, not the entire document.

参见

  • XMLReader::setParserProperty() - Set parser options
  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD

User Contributed Notes

zubin at trattonuovo dot com 20-Jan-2010 03:00
I encountered some problems to use isValid method with xml2assoc function.
I use this way to validate the entire xml file and put it into an associative array.

$xml = new XMLReader();
if (!$xml->xml($xml_string, NULL, LIBXML_DTDVALID)) {
  echo "XML not valid: load error";
  exit();
}

libxml_use_internal_errors(TRUE);

$xml_array = xml2assoc($xml);

$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
  echo "XML not valid: ".$xml_errors;
  exit();
}

//all ok
remy dot damour at laposte dot net 31-Dec-2008 03:27
1. If you validate against relax-ng, no need to call $xml->setParserProperty(XMLReader::VALIDATE, true);

2. Be aware that $xml->isValid() will return validity for currently active node (ie. node currently positioned using $xml->read()). It won't check validity of your entire tree at once, but rather on a step by step basis
anzenews at volja dot net 22-Jan-2008 10:50
This comment is only partially correct:
"isValid() always returns false unless you enable checking for validity by $reader->setParserProperty(XMLReader::VALIDATE, true);"
This enables DTD checking, but you can also check by using RelaxNG (see setRelaxNGSchema() and setRelaxNGSchemaSource()).

And also, this is NOT correct:
"If you just need to check if XML file is well formed, successful loading into XMLReader object is usually enough."
It is not enough. Pull parsers operate on stream and if you have a large enough file they will not know it is well formed until it is read to the end. If you need to know if it is well formed or/and valid, read it till the end or validation error (you can use next() for fast reading if you don't care about contents).


Lookup namespace for a prefix

  • ? XMLReader::isValid
  • XMLReader::moveToAttribute ?
  • PHP Manual
  • XMLReader
  • Lookup namespace for a prefix

XMLReader::lookupNamespace

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::lookupNamespace — Lookup namespace for a prefix

说明

public XMLReader::lookupNamespace ( string $prefix ) : string|null

Lookup in scope namespace for a given prefix.

参数

prefix

String containing the prefix.

返回值

The value of the namespace, or null if no namespace exists.

更新日志

版本 | 说明
8.0.0 | This function can no longer return false.

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to a named attribute

  • ? XMLReader::lookupNamespace
  • XMLReader::moveToAttributeNo ?
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttribute — Move cursor to a named attribute

说明

public XMLReader::moveToAttribute ( string $name ) : bool

Positions cursor on the named attribute.

参数

name

The name of the attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to an attribute by index

  • ? XMLReader::moveToAttribute
  • XMLReader::moveToAttributeNs ?
  • PHP Manual
  • XMLReader
  • Move cursor to an attribute by index

XMLReader::moveToAttributeNo

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttributeNo — Move cursor to an attribute by index

说明

public XMLReader::moveToAttributeNo ( int $index ) : bool

Positions cursor on attribute based on its position.

参数

index

The position of the attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to a named attribute

  • ? XMLReader::moveToAttributeNo
  • XMLReader::moveToElement ?
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttributeNs

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttributeNs — Move cursor to a named attribute

说明

public XMLReader::moveToAttributeNs ( string $name , string $namespace ) : bool

Positions cursor on the named attribute in specified namespace.

参数

name

The local name.

namespace

The namespace URI.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Position cursor on the parent Element of current Attribute

  • ? XMLReader::moveToAttributeNs
  • XMLReader::moveToFirstAttribute ?
  • PHP Manual
  • XMLReader
  • Position cursor on the parent Element of current Attribute

XMLReader::moveToElement

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToElement — Position cursor on the parent Element of current Attribute

说明

public XMLReader::moveToElement ( ) : bool

Moves cursor to the parent Element of current Attribute.

返回值

Returns true if successful and false if it fails or not positioned on Attribute when this method is called.

参见

  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

Sean Colin Ruiz 08-Jan-2017 08:54
On an element like this: <self_closing attribute="1" /> isEmptyElement will return FALSE after you have iterated through the attributes.  So you need to use implicitly call moveToElement(), in order to move the cursor back to the parent element and use isEmptyElement again.


Position cursor on the first Attribute

  • ? XMLReader::moveToElement
  • XMLReader::moveToNextAttribute ?
  • PHP Manual
  • XMLReader
  • Position cursor on the first Attribute

XMLReader::moveToFirstAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToFirstAttribute — Position cursor on the first Attribute

说明

public XMLReader::moveToFirstAttribute ( ) : bool

Moves cursor to the first Attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute

User Contributed Notes

There are no user contributed notes for this page.


Position cursor on the next Attribute

  • ? XMLReader::moveToFirstAttribute
  • XMLReader::next ?
  • PHP Manual
  • XMLReader
  • Position cursor on the next Attribute

XMLReader::moveToNextAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToNextAttribute — Position cursor on the next Attribute

说明

public XMLReader::moveToNextAttribute ( ) : bool

Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to next node skipping all subtrees

  • ? XMLReader::moveToNextAttribute
  • XMLReader::open ?
  • PHP Manual
  • XMLReader
  • Move cursor to next node skipping all subtrees

XMLReader::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::next — Move cursor to next node skipping all subtrees

说明

public XMLReader::next ( string|null $name = null ) : bool

Positions cursor on the next node skipping all subtrees. If no such node exists, the cursor is moved to the end of the document.

参数

name

The name of the next node to move to.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | name is nullable now.

参见

  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute
  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute

User Contributed Notes

Quiet Noise 13-Apr-2019 01:39
next() without parameters will bring you to the next sibling node on the same depth as the depth where the current cursor is.
Examples:
1. If you are on an opening ELEMENT node next() will bring you to the new line node next to the closing tag of that element (i.e. if you have each tag in separate line) or it will bring you to the opening tag of next node on the same depth.
2. If you are on a TEXT node next() will bring you to the opening tag if there is one next to it.

If there are no more nodes on the given depth next() will bring you to the closing tag (END_ELEMENT) of the wrapping parent.
ppp dot BOTSNEEDNOTAPPLY at salesfloor dot net 08-Sep-2015 09:48
This method appears to follow these rules:

 - if $localName names a sibling node, the cursor is moved to that node;
 - if $localName names an ancestor node, the cursor is moved to the end of that node;
 - if $localName names a node that is a sibling of any of the current node's ancestors, the cursor is moved to that node;
 - otherwise the cursor is moved outside the document.

Note especially that this method never moves the cursor to child nodes.

For example, given this XML document

<?xml version="1.0" encoding="UTF-8"?>
<root id="root" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <aaa id="1">
    <bbb id="1.1"></bbb>
    <bbb id="1.2"></bbb>
  </aaa>
  <ccc id="2" />
  <aaa id="3">
    <ddd id="3.1">
      <aaa id="3.1.1"></aaa>
    </ddd>
    <aaa id="3.2"></aaa>
  </aaa>
  <aaa id="4">
    <eee id="4.1"></eee>
  </aaa>
</root>

going from <root id="root"> to "bbb" places the cursor outside the document;
going from <aaa id="1"> to "bbb" places the cursor outside the document;
going from <aaa id="1"> to "aaa" places the cursor on <aaa id="3">;
going from <bbb id="1.1"> to "bbb" places the cursor on <bbb id="1.2">;
going from <bbb id="1.2"> to "bbb" places the cursor outside the document;
going from <bbb id="1.1"> to "ddd" places the cursor outside the document;
going from <bbb id="1.1"> to "aaa" places the cursor on </aaa>;
going from <bbb id="1.1"> to "ccc" places the cursor on <ccc id="2">;
going from <bbb id="1.1"> to "nonsuch" places the cursor outside the document;
going from <bbb id="1.1"> to "root" places the cursor on </root>;
going from <ddd id="3.1"> to "aaa" places the cursor on <aaa id="3.2">;
going from <ddd id="3.1"> to "eee" places the cursor outside the document;

Try it yourself:

<?php

$document = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root id="root" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <aaa id="1">
    <bbb id="1.1"></bbb>
    <bbb id="1.2"></bbb>
  </aaa>
  <ccc id="2" />
  <aaa id="3">
    <ddd id="3.1">
      <aaa id="3.1.1"></aaa>
    </ddd>
    <aaa id="3.2"></aaa>
  </aaa>
  <aaa id="4">
    <eee id="4.1"></eee>
  </aaa>
</root>
XML;

$filename = "/tmp/xmlreader.php.xml";
file_put_contents($filename, $document);

echo "given this XML document\n\n$document\n\n";

showNext("root", "bbb");
showNext("1", "bbb");
showNext("1", "aaa");
showNext("1.1", "bbb");
showNext("1.2", "bbb");
showNext("1.1", "ddd");
showNext("1.1", "aaa");
showNext("1.1", "ccc");
showNext("1.1", "nonsuch");
showNext("1.1", "root");
showNext("3.1", "aaa");
showNext("3.1", "eee");

function showNext($from, $to) {
  global $filename;

  $xml = new \XmlReader();
  $xml->open("file://$filename");
  while ($xml->read()) {
    if ($xml->nodeType === \XmlReader::ELEMENT) {
      if ($xml->getAttribute("id") == $from) {
        echo "going from <$xml->name id=\"$from\">";
        break;
      }
    }
  }

  $xml->next($to);
  $destination = "";
  if($xml->nodeType === \XmlReader::NONE) {
    if(!$xml->read()) {
      $destination = "outside the document";
    }
  }

  if(!$destination) {
    if ($xml->nodeType === \XmlReader::END_ELEMENT) {
      $destination = "on </$xml->name>";
    } else if ($xml->nodeType === \XmlReader::ELEMENT) {
      $destination = "on <$xml->name id=\"" . $xml->getAttribute("id") . "\">";
    }
  }

  echo " to \"$to\" places the cursor $destination;\n";

  $xml->close();
}
?>
gholson19 at gmail dot com 13-May-2015 09:21
To skip over deletion nodes in the xml extracted from a word document, do something like this:

if ($paragraph->nodeType == XMLREADER::ELEMENT && $paragraph->name === 'w:del'){$paragraph->next();}


Set the URI containing the XML to parse

  • ? XMLReader::next
  • XMLReader::read ?
  • PHP Manual
  • XMLReader
  • Set the URI containing the XML to parse

XMLReader::open

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::open — Set the URI containing the XML to parse

说明

public static XMLReader::open ( string $uri , string|null $encoding = null , int $flags = 0 ) : bool|XMLReader

Set the URI containing the XML document to be parsed.

参数

uri

URI pointing to the document.

encoding

The document encoding or null.

flags

A bitmask of the LIBXML_* constants.

返回值

成功时返回 true， 或者在失败时返回 false。 If called statically, returns an XMLReader 或者在失败时返回 false.

错误／异常

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

更新日志

版本 | 说明
8.0.0 | XMLReader::open() is now declared as static method, but can still be called on an XMLReader instance.

参见

  • XMLReader::xml() - Set the data containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

User Contributed Notes

den at nurfuerspam dot de 29-Apr-2017 10:08
If you like to read the XML from HTTP whit a POST request, you can use libxml_set_streams_context.
Example:

<?php

$param = array('http' => array(
    'method' => 'POST',
    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
    'content' => http_build_query(array(
        'post_param1' => 'value1',
        'post_param2' => 'value2',
    )),
));
libxml_set_streams_context(stream_context_create($param));
$reader = XMLReader::open('https://example.com/get.php?get_param=value3');

?>
dave at sophoservices dot com 02-Dec-2016 07:43
When using the XmlReader to read local XML files, remember it the open function requests a URI. Add 'file://' to the front of the FULL path to the XML. Otherwise you may get:

PHP Warning:  XMLReader::open(): Unable to open source data in ...
mood(_a_)twolate.com 14-Oct-2016 11:03
For some reasons, the open() method keep throwing me this error :

PHP Warning:  XMLReader::open(): Unable to open source data in /var/www/nota/ethamap/fat_xml.php

It doesn't make sense as the xml file target hosted on my server is perfectly reachable. Adding this line before invoking open() fixed it :

libxml_disable_entity_loader(false);

Please view https://bugs.php.net/bug.php?id=62577
It is somehow related.
alvaro at demogracia dot com 14-Nov-2014 12:35
XML can optionally declare its own encoding:

    <?xml version="1.0" encoding="UTF-8"?>

You can use the $encoding parameter to provide this information (if missing) or override it (if wrong).

Output is always UTF-8 (that's how libxml works).
crungmungus at gmail dot com 15-Sep-2008 05:11
Windows users remember to enable php_openssl.dll in your php.ini if you want to be able to use this function (and others) with a HTTPS URL.


Move to next node in document

  • ? XMLReader::open
  • XMLReader::readInnerXml ?
  • PHP Manual
  • XMLReader
  • Move to next node in document

XMLReader::read

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::read — Move to next node in document

说明

public XMLReader::read ( ) : bool

Moves cursor to the next node in the document.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::next() - Move cursor to next node skipping all subtrees

User Contributed Notes

peter at 3xe dot co dot uk 13-Oct-2016 12:08
Another approach to the 'also reads closing tags' gotcha:

<?php
$reader = new XMLReader();
$reader->open('users.xml');

while ($reader->read()) {
  if ($reader->nodeType == XMLReader::END_ELEMENT) {
    continue; //skips the rest of the code in this iteration
  }
  //do something with desired node type
  if($reader->name == 'user') {
    //...
  }
}
?>
Anonymous 20-Mar-2015 09:49
> I would have liked to use the next() function instead, but as I needed to parse 2 different subtrees, I couldn't figure out how to find all the columns, reset the pointer, and then find all the rows.

I just use:

$reader->close();
$reader->open($url);

to reset the pointer.
ecziegler at gmail 29-Jan-2014 12:27
If like myself you have been turning the interwebz upside down looking for a solution for this issue:
PHP Warning:  XMLReader::read(): /tmp/xml_feed.xml:4183934: parser error : Input is not proper UTF-8, indicate encoding !

For some reason, this warning breaks the execution - is it a fatal error in disguise?

After days of frustration I found it!!!!
tidy -xml -o output.xml -utf8 -f error.log input.xml

You can invoque tidy using exec, It takes several seconds to convert a 250Mb feed, but it worthy the time.

In my case the issue was with latin1 charset, and for some reason I had to pass the xml through tidy 2 times - first time around creates new errors, second time it fixes everything.

I know invalid xml should be fixed by xml creators, but it works differently in the real world.
Nate 27-Jun-2011 10:49
It is interesting to note that this function will stop on closing tags as well.  I have an XML document similar to the following:

<root>
  <columns>
    <column>columnX</column>
    <column>columnY</column>
  </columns>
  <table>
    <row>
      <columnX>38</columnX>
      <columnY>50</columnY>
    </row>
    <row>
      <columnX>82</columnY>
      <columnY>28</columnY>
    </row>
    ...
  </table>
</root>

I need to parse the <columns> object to know what attributes to check for from each <row> node.  Therefore I was doing the following:

<?php
while ($xml->read()) {
  if ($xml->name === 'column') {
   //parse column node to into $columns array
  }
  elseif ($xml->name === 'row') {
    //parse row node, using constructed $columns array
  }
}
?>

This kind of worked in that I ended up with an array of all the data I wanted, but the array I constructed was twice as large as I expected and every other entry was empty.  Took me a while to debug, but finally figured out that checking <?php $xml->name === 'row' ?> matches both <row> and </row>, so the check should really be something more like:

<?php

if ($xml->name === 'row' && $xml->nodeType == XMLReader::ELEMENT) {
  // parse row node
}

?>

I would have liked to use the next() function instead, but as I needed to parse 2 different subtrees, I couldn't figure out how to find all the columns, reset the pointer, and then find all the rows.
andy at siliconrockstar dot com 16-May-2011 01:01
A very simple way to avoid typing $reader->read() multiple times when you want to skip some nodes:

<?php
class smartXMLReader extends XMLReader {
    public function readTimes($count) {
        $i = 0;
        while($i < $count){
            $this->read();
            $i++;
        }
    }
}
?>

Using this smartXMLReader,

<?php
$reader->readTimes(3);
?>

is equivalent to

<?php
$reader->read();
$reader->read();
$reader->read();
?>

Makes getting around in your XML document a bit easier :)
jirka at kosek dot cz 08-Feb-2006 01:01
libxml2 contains much more useful method readString() that will read and return whole text content of element. You can call it after receiving start tag (XMLReader::ELEMENT). You can use this PHP code to emulate this method until PHP will directly call underlying libxml2 implementation.

<?php
class XMLReader2 extends XMLReader
{
  function readString()
  {
        $depth = 1;
        $text = "";

        while ($this->read() && $depth != 0)
        {
            if (in_array($this->nodeType, array(XMLReader::TEXT, XMLReader::CDATA, XMLReader::WHITESPACE, XMLReader::SIGNIFICANT_WHITESPACE)))
                $text .= $this->value;
            if ($this->nodeType == XMLReader::ELEMENT) $depth++;
            if ($this->nodeType == XMLReader::END_ELEMENT) $depth--;
        }
        return $text;
    }
}
?>

Just use XMLReader2 instead of XMLReader.


Retrieve XML from current node

  • ? XMLReader::read
  • XMLReader::readOuterXml ?
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node

XMLReader::readInnerXml

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readInnerXml — Retrieve XML from current node

说明

public XMLReader::readInnerXml ( ) : string

Reads the contents of the current node, including child nodes and markup.

参数

此函数没有参数。

返回值

Returns the contents of the current node as a string. Empty string on failure.

注释

Caution

此函数仅在 PHP 与 libxml 20620 或以上版本编译时可用。

参见

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

Evert Pot 20-Mar-2015 08:26
Disregard my other comment.

readInnerXml does not advance the cursor, so you can call it more than once. I made a mistake testing this.
Evert Pot 20-Mar-2015 08:21
Note that readInnerXml() also advances the cursor.


Retrieve XML from current node, including itself

  • ? XMLReader::readInnerXml
  • XMLReader::readString ?
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node, including itself

XMLReader::readOuterXml

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readOuterXml — Retrieve XML from current node, including itself

说明

public XMLReader::readOuterXml ( ) : string

Reads the contents of the current node, including the node itself.

参数

此函数没有参数。

返回值

Returns the contents of current node, including itself, as a string. Empty string on failure.

注释

Caution

此函数仅在 PHP 与 libxml 20620 或以上版本编译时可用。

参见

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

ralf dot horlebein at web dot de 21-Jul-2014 10:57
Please note that empty tags like <span></span> will be automatically converted to the short notation <span />.  This could cause trouble in some cases.
simon at avalon dot net dot nz 16-Mar-2011 04:35
Be aware that when you extract a piece of XML from a larger XML document using the readOuterXML() function, it tries to determine the namespaces (as defined in the original XML document) that apply to the new piece, and inserts them into the appropriate tags as xmlns attributes. This can be disconcerting, but it should be a benign alteration in most cases, and I understand that it causes the new chunk of XML to be correctly formatted so it is valid in it's own right.

As far as I'm aware it's not possible to change this behaviour.


Reads the contents of the current node as a string

  • ? XMLReader::readOuterXml
  • XMLReader::setParserProperty ?
  • PHP Manual
  • XMLReader
  • Reads the contents of the current node as a string

XMLReader::readString

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readString — Reads the contents of the current node as a string

说明

public XMLReader::readString ( ) : string

Reads the contents of the current node as a string.

参数

此函数没有参数。

返回值

Returns the content of the current node as a string. Empty string on failure.

注释

Caution

此函数仅在 PHP 与 libxml 20620 或以上版本编译时可用。

参见

  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

alexander_behling at web dot de 25-Jan-2018 03:37
Important:
When using it use -> instead of ::.
You have to use :: only on static functions and then you have not to create a class object.
Lea Hayes 07-Jun-2011 01:51
I would like to reiterate that this does not work when compiled with versions of libxml lower than 20620. I found that it just presents a blank page.

<?php $string = $reader->readString(); ?>

I worked around this issue by adding the following helper function:

<?php
function read_string($reader) {
    $node = $reader->expand();
    return $node->textContent;
}
?>

And then using:

<?php $string = read_string($reader); ?>
Michael Rusch 18-May-2009 10:27
For those who, like me, are having trouble figuring out the difference between getString() an getInnerXML(), the difference is that getString() does NOT include markup.  So, for:

<foo>bar<baz>Hello, world!</baz></foo>

getString() on the <foo> node would return

bar Hello, world!

whereas getInnerXML() would return

bar<baz>Hello, world!</baz>


Set parser options

  • ? XMLReader::readString
  • XMLReader::setRelaxNGSchema ?
  • PHP Manual
  • XMLReader
  • Set parser options

XMLReader::setParserProperty

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setParserProperty — Set parser options

说明

public XMLReader::setParserProperty ( int $property , bool $value ) : bool

Set parser options. The options must be set after
XMLReader::open() or
XMLReader::xml() are called and before
the first XMLReader::read() call.

参数

property

One of the parser option constants.

value

If set to true the option will be enabled otherwise will be disabled.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set the filename or URI for a RelaxNG Schema

  • ? XMLReader::setParserProperty
  • XMLReader::setRelaxNGSchemaSource ?
  • PHP Manual
  • XMLReader
  • Set the filename or URI for a RelaxNG Schema

XMLReader::setRelaxNGSchema

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema

说明

public XMLReader::setRelaxNGSchema ( string|null $filename ) : bool

Set the filename or URI for the RelaxNG Schema to use for validation.

参数

filename

filename or URI pointing to a RelaxNG Schema.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:40
Make sure to load your data prior to calling ->setRelaxNGSchema() otherwise you will get an error.

<?php
$xml_reader = new XMLReader();
$xml_reader->setRelaxNGSchema($rng_schema);
$xml_reader->xml($xml_data);
?>
Above code generates the following warning: "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

whereas the following does not generate a warning:
<?php
$xml_reader = new XMLReader();
$xml_reader->xml($xml_data); // or $xml_reader->xml($xml_file);
$xml_reader->setRelaxNGSchema($rng_schema);
?>

cf. http://bugs.php.net/bug.php?id=46978


Set the data containing a RelaxNG Schema

  • ? XMLReader::setRelaxNGSchema
  • XMLReader::setSchema ?
  • PHP Manual
  • XMLReader
  • Set the data containing a RelaxNG Schema

XMLReader::setRelaxNGSchemaSource

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema

说明

public XMLReader::setRelaxNGSchemaSource ( string|null $source ) : bool

Set the data containing a RelaxNG Schema to use for validation.

参数

source

String containing the RelaxNG Schema.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:43
If you get the following warning message when calling ->setRelaxNGSchemaSource(): "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

Make sure to load data using XMLReader::open() or XMLReader::xml() prior to calling XMLReader::setRelaxNGSchemaSource().

Cf. comment on XMLReader::setRelaxNGSchema for more details.
anzenews at volja dot net 21-Jan-2008 12:18
This function and setRelaxNGSchema() seem picky about when they are called - right after the call to open(). For example:

<?php
  $schema="/path/to/schema.rng";
  $xmlfile="/path/to/xml.xml";

  $xml = new XMLReader();
  $xml->open($xmlfile);
  $xml->setRelaxNGSchemaSource(file_get_contents($schema));

  while ($xml->read()) {
   // ...
  }

  $xml->close();
?>


Validate document against XSD

  • ? XMLReader::setRelaxNGSchemaSource
  • XMLReader::XML ?
  • PHP Manual
  • XMLReader
  • Validate document against XSD

XMLReader::setSchema

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::setSchema — Validate document against XSD

说明

public XMLReader::setSchema ( string|null $filename ) : bool

Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read().

参数

filename

The filename of the XSD schema.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Issues E_WARNING if libxml was built without schema support, the schema contains errors or if XMLReader::read() has already been called.

注释

Caution

此函数仅在 PHP 与 libxml 20620 或以上版本编译时可用。

参见

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

There are no user contributed notes for this page.


Set the data containing the XML to parse

  • ? XMLReader::setSchema
  • XMLWriter ?
  • PHP Manual
  • XMLReader
  • Set the data containing the XML to parse

XMLReader::XML

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::XML — Set the data containing the XML to parse

说明

public static XMLReader::XML ( string $source , string|null $encoding = null , int $flags = 0 ) : bool|XMLReader

Set the data containing the XML to parse.

参数

source

String containing the XML to be parsed.

encoding

The document encoding or null.

flags

A bitmask of the LIBXML_* constants.

返回值

成功时返回 true， 或者在失败时返回 false。 If called statically, returns an XMLReader 或者在失败时返回 false.

错误／异常

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

更新日志

版本 | 说明
8.0.0 | XMLReader::XML() is now declared as static method, but can still be called on an XMLReader instance.

参见

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

User Contributed Notes

There are no user contributed notes for this page.


XMLWriter

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
    • Creating a simple XML document
    • Working with XML namespaces
    • Working with the OO API
  • XMLWriter — The XMLWriter class
    • XMLWriter::endAttribute — End attribute
    • XMLWriter::endCdata — End current CDATA
    • XMLWriter::endComment — Create end comment
    • XMLWriter::endDocument — End current document
    • XMLWriter::endDtd — End current DTD
    • XMLWriter::endDtdAttlist — End current DTD AttList
    • XMLWriter::endDtdElement — End current DTD element
    • XMLWriter::endDtdEntity — End current DTD Entity
    • XMLWriter::endElement — End current element
    • XMLWriter::endPi — End current PI
    • XMLWriter::flush — Flush current buffer
    • XMLWriter::fullEndElement — End current element
    • XMLWriter::openMemory — Create new xmlwriter using memory for string output
    • XMLWriter::openUri — Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory — Returns current buffer
    • XMLWriter::setIndent — Toggle indentation on/off
    • XMLWriter::setIndentString — Set string used for indenting
    • XMLWriter::startAttribute — Create start attribute
    • XMLWriter::startAttributeNs — Create start namespaced attribute
    • XMLWriter::startCdata — Create start CDATA tag
    • XMLWriter::startComment — Create start comment
    • XMLWriter::startDocument — Create document tag
    • XMLWriter::startDtd — Create start DTD tag
    • XMLWriter::startDtdAttlist — Create start DTD AttList
    • XMLWriter::startDtdElement — Create start DTD element
    • XMLWriter::startDtdEntity — Create start DTD Entity
    • XMLWriter::startElement — Create start element tag
    • XMLWriter::startElementNs — Create start namespaced element tag
    • XMLWriter::startPi — Create start PI tag
    • XMLWriter::text — Write text
    • XMLWriter::writeAttribute — Write full attribute
    • XMLWriter::writeAttributeNs — Write full namespaced attribute
    • XMLWriter::writeCdata — Write full CDATA tag
    • XMLWriter::writeComment — Write full comment tag
    • XMLWriter::writeDtd — Write full DTD tag
    • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
    • XMLWriter::writeDtdElement — Write full DTD element tag
    • XMLWriter::writeDtdEntity — Write full DTD Entity tag
    • XMLWriter::writeElement — Write full element tag
    • XMLWriter::writeElementNs — Write full namespaced element tag
    • XMLWriter::writePi — Writes a PI
    • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

lingtalfi 08-Oct-2015 08:35
The single quote predefined entity is not escaped.
The other predefined entities are but not the single quote, so you will have to do it yourself.

That's what you would expect:

Ampersand     &     &amp;
Single Quote     '     &apos;
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;

That's what you get with \XmlWriter:

Ampersand     &     &amp;
Single Quote     '     '
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;
Alexey Zakhlestin 09-Jun-2008 03:47
important: XMLWriter expects UTF-8 data from you. It can output xml in various encodings, but input should be strictly utf-8!


简介

This is the XMLWriter extension. It wraps the libxml xmlWriter API.

This extension represents a writer that provides a non-cached, forward-only means of generating streams or files containing XML data.

This extension can be used in an object oriented style or a procedural one. Every method documented describes the alternative procedural call.

User Contributed Notes

There are no user contributed notes for this page.


安装

The XMLWriter extension was initially a PECL extension for PHP 5. It was later added to the PHP source (bundled) as of PHP 5.1.2. This extension is enabled by default.

此扩展默认为启用，编译时可通过下列选项禁用： --disable-xmlwriter

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Prior to PHP 8.0.0, there was one resource type used by the procedural version of the XMLWriter extension: returned by xmlwriter_open_memory() or xmlwriter_open_uri().

User Contributed Notes

There are no user contributed notes for this page.


范例

Table of Contents

  • Creating a simple XML document
  • Working with XML namespaces
  • Working with the OO API

User Contributed Notes

There are no user contributed notes for this page.


Creating a simple XML document

This example shows how to use XMLWriter to create a XML document in memory.

Example #1 Creating a simple XML document

<?php

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');

xmlwriter_start_document($xw, '1.0', 'UTF-8');

// A first element
xmlwriter_start_element($xw, 'tag1');

// Attribute 'att1' for element 'tag1'
xmlwriter_start_attribute($xw, 'att1');
xmlwriter_text($xw, 'valueofatt1');
xmlwriter_end_attribute($xw);

xmlwriter_write_comment($xw, 'this is a comment.');

// Start a child element
xmlwriter_start_element($xw, 'tag11');
xmlwriter_text($xw, 'This is a sample text, ?');
xmlwriter_end_element($xw); // tag11

xmlwriter_end_element($xw); // tag1

// CDATA
xmlwriter_start_element($xw, 'testc');
xmlwriter_write_cdata($xw, "This is cdata content");
xmlwriter_end_element($xw); // testc

xmlwriter_start_element($xw, 'testc');
xmlwriter_start_cdata($xw);
xmlwriter_text($xw, "test cdata2");
xmlwriter_end_cdata($xw);
xmlwriter_end_element($xw); // testc

// A processing instruction
xmlwriter_start_pi($xw, 'php');
xmlwriter_text($xw, '$foo=2;echo $foo;');
xmlwriter_end_pi($xw);

xmlwriter_end_document($xw);

echo xmlwriter_output_memory($xw);

以上例程会输出：

<?xml version="1.0" encoding="UTF-8"?>
<tag1 att1="valueofatt1">
 <!--this is a comment.-->
 <tag11>This is a sample text, ?</tag11>
</tag1>
<testc><![CDATA[This is cdata content]]></testc>
<testc><![CDATA[test cdata2]]></testc>
<?php $foo=2;echo $foo;?>

User Contributed Notes

There are no user contributed notes for this page.


Working with XML namespaces

This example shows how to create namespaced XML elements.

Example #1 Working with XML namespaces

<?php

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');

xmlwriter_start_document($xw, '1.0', 'UTF-8');
// A first element
xmlwriter_start_element_ns($xw,'prefix', 'books', 'uri');
xmlwriter_start_attribute($xw, 'isbn');

xmlwriter_start_attribute_ns($xw, 'prefix', 'isbn', 'uri');
xmlwriter_end_attribute($xw);

xmlwriter_end_attribute($xw);

xmlwriter_text($xw, 'book1');
xmlwriter_end_element($xw);

xmlwriter_end_document($xw);

echo xmlwriter_output_memory($xw);

以上例程会输出：

<?xml version="1.0" encoding="UTF-8"?>
<prefix:books isbn="" prefix:isbn="" xmlns:prefix="uri">book1</prefix:books>

User Contributed Notes

There are no user contributed notes for this page.


Working with the OO API

This example shows how to work with XMLWriter's object oriented API.

Example #1 Working with the OO API

<?php

$xw = new XMLWriter();
$xw->openMemory();
$xw->startDocument("1.0");
$xw->startElement("book");
$xw->text("example");
$xw->endElement();
$xw->endDocument();
echo $xw->outputMemory();

以上例程会输出：

<?xml version="1.0"?>
<book>example</book>

User Contributed Notes

There are no user contributed notes for this page.


The XMLWriter class

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

简介

类摘要

XMLWriter {
/* 方法 */
public endAttribute ( ) : bool
public endCdata ( ) : bool
public endComment ( ) : bool
public endDocument ( ) : bool
public endDtd ( ) : bool
public endDtdAttlist ( ) : bool
public endDtdElement ( ) : bool
public endDtdEntity ( ) : bool
public endElement ( ) : bool
public endPi ( ) : bool
public flush ( bool $empty = true ) : string|int
public fullEndElement ( ) : bool
public openMemory ( ) : bool
public openUri ( string $uri ) : bool
public outputMemory ( bool $flush = true ) : string
public setIndent ( bool $enable ) : bool
public setIndentString ( string $indentation ) : bool
public startAttribute ( string $name ) : bool
public startAttributeNs ( string|null $prefix , string $name , string|null $namespace ) : bool
public startCdata ( ) : bool
public startComment ( ) : bool
public startDocument ( string|null $version = "1.0" , string|null $encoding = null , string|null $standalone = null ) : bool
public startDtd ( string $qualifiedName , string|null $publicId = null , string|null $systemId = null ) : bool
public startDtdAttlist ( string $name ) : bool
public startDtdElement ( string $qualifiedName ) : bool
public startDtdEntity ( string $name , bool $isParam ) : bool
public startElement ( string $name ) : bool
public startElementNs ( string|null $prefix , string $name , string|null $namespace ) : bool
public startPi ( string $target ) : bool
public text ( string $content ) : bool
public writeAttribute ( string $name , string $value ) : bool
public writeAttributeNs ( string|null $prefix , string $name , string|null $namespace , string $value ) : bool
public writeCdata ( string $content ) : bool
public writeComment ( string $content ) : bool
public writeDtd ( string $name , string|null $publicId = null , string|null $systemId = null , string|null $content = null ) : bool
public writeDtdAttlist ( string $name , string $content ) : bool
public writeDtdElement ( string $name , string $content ) : bool
public writeDtdEntity ( string $name , string $content , bool $isParam = false , string|null $publicId = null , string|null $systemId = null , string|null $notationData = null ) : bool
public writeElement ( string $name , string|null $content = null ) : bool
public writeElementNs ( string|null $prefix , string $name , string|null $namespace , string|null $content = null ) : bool
public writePi ( string $target , string $content ) : bool
public writeRaw ( string $content ) : bool
}

Table of Contents

  • XMLWriter::endAttribute — End attribute
  • XMLWriter::endCdata — End current CDATA
  • XMLWriter::endComment — Create end comment
  • XMLWriter::endDocument — End current document
  • XMLWriter::endDtd — End current DTD
  • XMLWriter::endDtdAttlist — End current DTD AttList
  • XMLWriter::endDtdElement — End current DTD element
  • XMLWriter::endDtdEntity — End current DTD Entity
  • XMLWriter::endElement — End current element
  • XMLWriter::endPi — End current PI
  • XMLWriter::flush — Flush current buffer
  • XMLWriter::fullEndElement — End current element
  • XMLWriter::openMemory — Create new xmlwriter using memory for string output
  • XMLWriter::openUri — Create new xmlwriter using source uri for output
  • XMLWriter::outputMemory — Returns current buffer
  • XMLWriter::setIndent — Toggle indentation on/off
  • XMLWriter::setIndentString — Set string used for indenting
  • XMLWriter::startAttribute — Create start attribute
  • XMLWriter::startAttributeNs — Create start namespaced attribute
  • XMLWriter::startCdata — Create start CDATA tag
  • XMLWriter::startComment — Create start comment
  • XMLWriter::startDocument — Create document tag
  • XMLWriter::startDtd — Create start DTD tag
  • XMLWriter::startDtdAttlist — Create start DTD AttList
  • XMLWriter::startDtdElement — Create start DTD element
  • XMLWriter::startDtdEntity — Create start DTD Entity
  • XMLWriter::startElement — Create start element tag
  • XMLWriter::startElementNs — Create start namespaced element tag
  • XMLWriter::startPi — Create start PI tag
  • XMLWriter::text — Write text
  • XMLWriter::writeAttribute — Write full attribute
  • XMLWriter::writeAttributeNs — Write full namespaced attribute
  • XMLWriter::writeCdata — Write full CDATA tag
  • XMLWriter::writeComment — Write full comment tag
  • XMLWriter::writeDtd — Write full DTD tag
  • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
  • XMLWriter::writeDtdElement — Write full DTD element tag
  • XMLWriter::writeDtdEntity — Write full DTD Entity tag
  • XMLWriter::writeElement — Write full element tag
  • XMLWriter::writeElementNs — Write full namespaced element tag
  • XMLWriter::writePi — Writes a PI
  • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

There are no user contributed notes for this page.


End attribute

  • ? XMLWriter
  • XMLWriter::endCdata ?
  • PHP Manual
  • XMLWriter
  • End attribute

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — End attribute

说明

面向对象风格

public XMLWriter::endAttribute ( ) : bool

过程化风格

xmlwriter_end_attribute ( XMLWriter $writer ) : bool

Ends the current attribute.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


End current CDATA

  • ? XMLWriter::endAttribute
  • XMLWriter::endComment ?
  • PHP Manual
  • XMLWriter
  • End current CDATA

XMLWriter::endCdata

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endCdata -- xmlwriter_end_cdata — End current CDATA

说明

面向对象风格

public XMLWriter::endCdata ( ) : bool

过程化风格

xmlwriter_end_cdata ( XMLWriter $writer ) : bool

Ends the current CDATA section.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create end comment

  • ? XMLWriter::endCdata
  • XMLWriter::endDocument ?
  • PHP Manual
  • XMLWriter
  • Create end comment

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Create end comment

说明

面向对象风格

public XMLWriter::endComment ( ) : bool

过程化风格

xmlwriter_end_comment ( XMLWriter $writer ) : bool

Ends the current comment.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


End current document

  • ? XMLWriter::endComment
  • XMLWriter::endDtd ?
  • PHP Manual
  • XMLWriter
  • End current document

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — End current document

说明

面向对象风格

public XMLWriter::endDocument ( ) : bool

过程化风格

xmlwriter_end_document ( XMLWriter $writer ) : bool

Ends the current document.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDocument() - Create document tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD

  • ? XMLWriter::endDocument
  • XMLWriter::endDtdAttlist ?
  • PHP Manual
  • XMLWriter
  • End current DTD

XMLWriter::endDtd

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtd -- xmlwriter_end_dtd — End current DTD

说明

面向对象风格

public XMLWriter::endDtd ( ) : bool

过程化风格

xmlwriter_end_dtd ( XMLWriter $writer ) : bool

Ends the DTD of the document.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD AttList

  • ? XMLWriter::endDtd
  • XMLWriter::endDtdElement ?
  • PHP Manual
  • XMLWriter
  • End current DTD AttList

XMLWriter::endDtdAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdAttlist -- xmlwriter_end_dtd_attlist — End current DTD AttList

说明

面向对象风格

public XMLWriter::endDtdAttlist ( ) : bool

过程化风格

xmlwriter_end_dtd_attlist ( XMLWriter $writer ) : bool

Ends the current DTD attribute list.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD element

  • ? XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity ?
  • PHP Manual
  • XMLWriter
  • End current DTD element

XMLWriter::endDtdElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdElement -- xmlwriter_end_dtd_element — End current DTD element

说明

面向对象风格

public XMLWriter::endDtdElement ( ) : bool

过程化风格

xmlwriter_end_dtd_element ( XMLWriter $writer ) : bool

Ends the current DTD element.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD Entity

  • ? XMLWriter::endDtdElement
  • XMLWriter::endElement ?
  • PHP Manual
  • XMLWriter
  • End current DTD Entity

XMLWriter::endDtdEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdEntity -- xmlwriter_end_dtd_entity — End current DTD Entity

说明

面向对象风格

public XMLWriter::endDtdEntity ( ) : bool

过程化风格

xmlwriter_end_dtd_entity ( XMLWriter $writer ) : bool

Ends the current DTD entity.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


End current element

  • ? XMLWriter::endDtdEntity
  • XMLWriter::endPi ?
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — End current element

说明

面向对象风格

public XMLWriter::endElement ( ) : bool

过程化风格

xmlwriter_end_element ( XMLWriter $writer ) : bool

Ends the current element.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


End current PI

  • ? XMLWriter::endElement
  • XMLWriter::flush ?
  • PHP Manual
  • XMLWriter
  • End current PI

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — End current PI

说明

面向对象风格

public XMLWriter::endPi ( ) : bool

过程化风格

xmlwriter_end_pi ( XMLWriter $writer ) : bool

Ends the current processing instruction.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Flush current buffer

  • ? XMLWriter::endPi
  • XMLWriter::fullEndElement ?
  • PHP Manual
  • XMLWriter
  • Flush current buffer

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Flush current buffer

说明

面向对象风格

public XMLWriter::flush ( bool $empty = true ) : string|int

过程化风格

xmlwriter_flush ( XMLWriter $writer , bool $empty = true ) : string|int

Flushes the current buffer.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

empty

Whether to empty the buffer or not. Default is true.

返回值

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes.

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
8.0.0 | This function can no longer return false.

User Contributed Notes

There are no user contributed notes for this page.


End current element

  • ? XMLWriter::flush
  • XMLWriter::openMemory ?
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — End current element

说明

面向对象风格

public XMLWriter::fullEndElement ( ) : bool

过程化风格

xmlwriter_full_end_element ( XMLWriter $writer ) : bool

End the current xml element. Writes an end tag even if the element is empty.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endElement() - End current element

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using memory for string output

  • ? XMLWriter::fullEndElement
  • XMLWriter::openUri ?
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using memory for string output

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Create new xmlwriter using memory for string output

说明

面向对象风格

public XMLWriter::openMemory ( ) : bool

过程化风格

xmlwriter_open_memory ( ) : XMLWriter|false

Creates a new XMLWriter using memory for string output.

参数

返回值

面向对象风格: 成功时返回 true， 或者在失败时返回 false。

过程化风格: Returns a new XMLWriter for later use with the xmlwriter functions on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a 资源(resource) has been returned in this case.

参见

  • XMLWriter::openUri() - Create new xmlwriter using source uri for output

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using source uri for output

  • ? XMLWriter::openMemory
  • XMLWriter::outputMemory ?
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using source uri for output

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

说明

面向对象风格

public XMLWriter::openUri ( string $uri ) : bool

过程化风格

xmlwriter_open_uri ( string $uri ) : XMLWriter|false

Creates a new XMLWriter using uri for the output.

参数

uri

The URI of the resource for the output.

返回值

面向对象风格: 成功时返回 true， 或者在失败时返回 false。

过程化风格: Returns a new XMLWriter instance for later use with the xmlwriter functions on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a 资源(resource) has been returned in this case.

范例

Example #1 Direct output of XML

It is possible to directly output XML by using the php://output stream wrapper.

<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>

注释

Note:

On Windows, files opened with this function are locked until the writer is released.

参见

  • XMLWriter::openMemory() - Create new xmlwriter using memory for string output

User Contributed Notes

There are no user contributed notes for this page.


Returns current buffer

  • ? XMLWriter::openUri
  • XMLWriter::setIndent ?
  • PHP Manual
  • XMLWriter
  • Returns current buffer

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Returns current buffer

说明

面向对象风格

public XMLWriter::outputMemory ( bool $flush = true ) : string

过程化风格

xmlwriter_output_memory ( XMLWriter $writer , bool $flush = true ) : string

Returns the current buffer.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

flush

Whether to flush the output buffer or not. Default is true.

返回值

Returns the current buffer as a string.

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::flush() - Flush current buffer

User Contributed Notes

There are no user contributed notes for this page.


Toggle indentation on/off

  • ? XMLWriter::outputMemory
  • XMLWriter::setIndentString ?
  • PHP Manual
  • XMLWriter
  • Toggle indentation on/off

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Toggle indentation on/off

说明

面向对象风格

public XMLWriter::setIndent ( bool $enable ) : bool

过程化风格

xmlwriter_set_indent ( XMLWriter $writer , bool $enable ) : bool

Toggles indentation on or off.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

enable

Whether indentation is enabled.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

范例

Example #1 XMLWriter::setIndent() and mixed Content

Enabling indentation is not suitable for mixed content, because the indent string is also inserted before inline elements.

<?php
$writer = new XMLWriter();
$writer->openMemory();
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('p');
$writer->text('before');
$writer->writeElement('a', 'element');
$writer->text('after');
$writer->endElement();
$writer->endDocument();
echo $writer->outputMemory();
?>

以上例程会输出：

<?xml version="1.0"?>
<p>before <a>element</a>
after</p>

注释

Note:

The indent is reset when an xmlwriter is opened.

参见

  • XMLWriter::setIndentString() - Set string used for indenting

User Contributed Notes

There are no user contributed notes for this page.


Set string used for indenting

  • ? XMLWriter::setIndent
  • XMLWriter::startAttribute ?
  • PHP Manual
  • XMLWriter
  • Set string used for indenting

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Set string used for indenting

说明

面向对象风格

public XMLWriter::setIndentString ( string $indentation ) : bool

过程化风格

xmlwriter_set_indent_string ( XMLWriter $writer , string $indentation ) : bool

Sets the string which will be used to indent each element/attribute of the resulting xml.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

indentation

The indentation string.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

注释

Note:

The indent is reset when an xmlwriter is opened.

参见

  • XMLWriter::setIndent() - Toggle indentation on/off

User Contributed Notes

There are no user contributed notes for this page.


Create start attribute

  • ? XMLWriter::setIndentString
  • XMLWriter::startAttributeNs ?
  • PHP Manual
  • XMLWriter
  • Create start attribute

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Create start attribute

说明

面向对象风格

public XMLWriter::startAttribute ( string $name ) : bool

过程化风格

xmlwriter_start_attribute ( XMLWriter $writer , string $name ) : bool

Starts an attribute.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The attribute name.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

范例

Example #1 Basic XMLWriter::startAttribute() Usage

<?php
$writer = new XMLWriter;
$writer->openURI('php://output');
$writer->startDocument('1.0', 'UTF-8');?>
$writer->startElement('element');
$writer->startAttribute('attribute');
$writer->text('value');
$writer->endAttribute();
$writer->endElement();
$writer->endDocument();

以上例程的输出类似于：

<?xml version="1.0" encoding="UTF-8"?>
<element attribute="value"/>

参见

  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced attribute

  • ? XMLWriter::startAttribute
  • XMLWriter::startCdata ?
  • PHP Manual
  • XMLWriter
  • Create start namespaced attribute

XMLWriter::startAttributeNs

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNs -- xmlwriter_start_attribute_ns — Create start namespaced attribute

说明

面向对象风格

public XMLWriter::startAttributeNs ( string|null $prefix , string $name , string|null $namespace ) : bool

过程化风格

xmlwriter_start_attribute_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace ) : bool

Starts a namespaced attribute.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

prefix

The namespace prefix.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
8.0.0 | prefix is nullable now.

参见

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start CDATA tag

  • ? XMLWriter::startAttributeNs
  • XMLWriter::startComment ?
  • PHP Manual
  • XMLWriter
  • Create start CDATA tag

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — Create start CDATA tag

说明

面向对象风格

public XMLWriter::startCdata ( ) : bool

过程化风格

xmlwriter_start_cdata ( XMLWriter $writer ) : bool

Starts a CDATA.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endCdata() - End current CDATA
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create start comment

  • ? XMLWriter::startCdata
  • XMLWriter::startDocument ?
  • PHP Manual
  • XMLWriter
  • Create start comment

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Create start comment

说明

面向对象风格

public XMLWriter::startComment ( ) : bool

过程化风格

xmlwriter_start_comment ( XMLWriter $writer ) : bool

Starts a comment.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endComment() - Create end comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


Create document tag

  • ? XMLWriter::startComment
  • XMLWriter::startDtd ?
  • PHP Manual
  • XMLWriter
  • Create document tag

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Create document tag

说明

面向对象风格

public XMLWriter::startDocument ( string|null $version = "1.0" , string|null $encoding = null , string|null $standalone = null ) : bool

过程化风格

xmlwriter_start_document ( XMLWriter $writer , string|null $version = "1.0" , string|null $encoding = null , string|null $standalone = null ) : bool

Starts a document.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

standalone

yes or no.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endDocument() - End current document

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD tag

  • ? XMLWriter::startDocument
  • XMLWriter::startDtdAttlist ?
  • PHP Manual
  • XMLWriter
  • Create start DTD tag

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — Create start DTD tag

说明

面向对象风格

public XMLWriter::startDtd ( string $qualifiedName , string|null $publicId = null , string|null $systemId = null ) : bool

过程化风格

xmlwriter_start_dtd ( XMLWriter $writer , string $qualifiedName , string|null $publicId = null , string|null $systemId = null ) : bool

Starts a DTD.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endDtd() - End current DTD
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD AttList

  • ? XMLWriter::startDtd
  • XMLWriter::startDtdElement ?
  • PHP Manual
  • XMLWriter
  • Create start DTD AttList

XMLWriter::startDtdAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdAttlist -- xmlwriter_start_dtd_attlist — Create start DTD AttList

说明

面向对象风格

public XMLWriter::startDtdAttlist ( string $name ) : bool

过程化风格

xmlwriter_start_dtd_attlist ( XMLWriter $writer , string $name ) : bool

Starts a DTD attribute list.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The attribute list name.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endDtdAttlist() - End current DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD element

  • ? XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity ?
  • PHP Manual
  • XMLWriter
  • Create start DTD element

XMLWriter::startDtdElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdElement -- xmlwriter_start_dtd_element — Create start DTD element

说明

面向对象风格

public XMLWriter::startDtdElement ( string $qualifiedName ) : bool

过程化风格

xmlwriter_start_dtd_element ( XMLWriter $writer , string $qualifiedName ) : bool

Starts a DTD element.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

qualifiedName

The qualified name of the document type to create.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endDtdElement() - End current DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD Entity

  • ? XMLWriter::startDtdElement
  • XMLWriter::startElement ?
  • PHP Manual
  • XMLWriter
  • Create start DTD Entity

XMLWriter::startDtdEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdEntity -- xmlwriter_start_dtd_entity — Create start DTD Entity

说明

面向对象风格

public XMLWriter::startDtdEntity ( string $name , bool $isParam ) : bool

过程化风格

xmlwriter_start_dtd_entity ( XMLWriter $writer , string $name , bool $isParam ) : bool

Starts a DTD entity.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The name of the entity.

isParam

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endDtdEntity() - End current DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


Create start element tag

  • ? XMLWriter::startDtdEntity
  • XMLWriter::startElementNs ?
  • PHP Manual
  • XMLWriter
  • Create start element tag

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Create start element tag

说明

面向对象风格

public XMLWriter::startElement ( string $name ) : bool

过程化风格

xmlwriter_start_element ( XMLWriter $writer , string $name ) : bool

Starts an element.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The element name.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced element tag

  • ? XMLWriter::startElement
  • XMLWriter::startPi ?
  • PHP Manual
  • XMLWriter
  • Create start namespaced element tag

XMLWriter::startElementNs

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNs -- xmlwriter_start_element_ns — Create start namespaced element tag

说明

面向对象风格

public XMLWriter::startElementNs ( string|null $prefix , string $name , string|null $namespace ) : bool

过程化风格

xmlwriter_start_element_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace ) : bool

Starts a namespaced element.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start PI tag

  • ? XMLWriter::startElementNs
  • XMLWriter::text ?
  • PHP Manual
  • XMLWriter
  • Create start PI tag

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Create start PI tag

说明

面向对象风格

public XMLWriter::startPi ( string $target ) : bool

过程化风格

xmlwriter_start_pi ( XMLWriter $writer , string $target ) : bool

Starts a processing instruction tag.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

target

The target of the processing instruction.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::endPi() - End current PI
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Write text

  • ? XMLWriter::startPi
  • XMLWriter::writeAttribute ?
  • PHP Manual
  • XMLWriter
  • Write text

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Write text

说明

面向对象风格

public XMLWriter::text ( string $content ) : bool

过程化风格

xmlwriter_text ( XMLWriter $writer , string $content ) : bool

Writes a text.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

content

The contents of the text. The characters <, >, & and " are written as entity references (i.e. &lt;, &gt;, &amp; and &quot;, respectively). All other characters including ' are written literally. To write the special XML characters literally, or to write literal entity references, xmlwriter_write_raw() has to be used.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

User Contributed Notes

There are no user contributed notes for this page.


Write full attribute

  • ? XMLWriter::text
  • XMLWriter::writeAttributeNs ?
  • PHP Manual
  • XMLWriter
  • Write full attribute

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Write full attribute

说明

面向对象风格

public XMLWriter::writeAttribute ( string $name , string $value ) : bool

过程化风格

xmlwriter_write_attribute ( XMLWriter $writer , string $name , string $value ) : bool

Writes a full attribute.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The name of the attribute.

value

The value of the attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

范例

Example #1 Intermixing Sub-elements and Attributes

If writing sub-elements and attributes is intermixed, any attempt to write attributes after the first sub-element will fail and return false.

<?php
$xml = new XMLWriter();
$xml->openMemory();

$xml->startElement('element');
$xml->writeAttribute('attr1', '0');
$xml->writeElement('subelem', '0');
var_dump($xml->writeAttribute('attr2', '0'));
$xml->endElement();

echo $xml->flush();
?>

以上例程会输出：

bool(false)
<element attr1="0"><subelem>0</subelem></element>

参见

  • XMLWriter::writeAttributeNs() - Write full namespaced attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced attribute

  • ? XMLWriter::writeAttribute
  • XMLWriter::writeCdata ?
  • PHP Manual
  • XMLWriter
  • Write full namespaced attribute

XMLWriter::writeAttributeNs

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNs -- xmlwriter_write_attribute_ns — Write full namespaced attribute

说明

面向对象风格

public XMLWriter::writeAttributeNs ( string|null $prefix , string $name , string|null $namespace , string $value ) : bool

过程化风格

xmlwriter_write_attribute_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace , string $value ) : bool

Writes a full namespaced attribute.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

value

The attribute value.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full CDATA tag

  • ? XMLWriter::writeAttributeNs
  • XMLWriter::writeComment ?
  • PHP Manual
  • XMLWriter
  • Write full CDATA tag

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Write full CDATA tag

说明

面向对象风格

public XMLWriter::writeCdata ( string $content ) : bool

过程化风格

xmlwriter_write_cdata ( XMLWriter $writer , string $content ) : bool

Writes a full CDATA.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

content

The contents of the CDATA.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

范例

Example #1 Basic xmlwriter_write_cdata() Usage

<?php
// set up the document
$xml = new XmlWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('mydoc');
$xml->startElement('myele');

// CData output
$xml->startElement('mycdataelement');
$xml->writeCData("text for inclusion as CData");
$xml->endElement();

// end the document and output
$xml->endElement();
$xml->endElement();
echo $xml->outputMemory(true);
?>

以上例程会输出：

<mydoc>
 <myele>
  <mycdataelement><![CDATA[text for inclusion as CData]?]></mycdataelement>
 </myele>
</mydoc>

参见

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::endCdata() - End current CDATA

User Contributed Notes

There are no user contributed notes for this page.


Write full comment tag

  • ? XMLWriter::writeCdata
  • XMLWriter::writeDtd ?
  • PHP Manual
  • XMLWriter
  • Write full comment tag

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Write full comment tag

说明

面向对象风格

public XMLWriter::writeComment ( string $content ) : bool

过程化风格

xmlwriter_write_comment ( XMLWriter $writer , string $content ) : bool

Writes a full comment.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

content

The contents of the comment.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::endComment() - Create end comment

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD tag

  • ? XMLWriter::writeComment
  • XMLWriter::writeDtdAttlist ?
  • PHP Manual
  • XMLWriter
  • Write full DTD tag

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Write full DTD tag

说明

面向对象风格

public XMLWriter::writeDtd ( string $name , string|null $publicId = null , string|null $systemId = null , string|null $content = null ) : bool

过程化风格

xmlwriter_write_dtd ( XMLWriter $writer , string $name , string|null $publicId = null , string|null $systemId = null , string|null $content = null ) : bool

Writes a full DTD.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The DTD name.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

content

The content of the DTD.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::endDtd() - End current DTD

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD AttList tag

  • ? XMLWriter::writeDtd
  • XMLWriter::writeDtdElement ?
  • PHP Manual
  • XMLWriter
  • Write full DTD AttList tag

XMLWriter::writeDtdAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdAttlist -- xmlwriter_write_dtd_attlist — Write full DTD AttList tag

说明

面向对象风格

public XMLWriter::writeDtdAttlist ( string $name , string $content ) : bool

过程化风格

xmlwriter_write_dtd_attlist ( XMLWriter $writer , string $name , string $content ) : bool

Writes a DTD attribute list.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::endDtdAttlist() - End current DTD AttList

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD element tag

  • ? XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity ?
  • PHP Manual
  • XMLWriter
  • Write full DTD element tag

XMLWriter::writeDtdElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdElement -- xmlwriter_write_dtd_element — Write full DTD element tag

说明

面向对象风格

public XMLWriter::writeDtdElement ( string $name , string $content ) : bool

过程化风格

xmlwriter_write_dtd_element ( XMLWriter $writer , string $name , string $content ) : bool

Writes a full DTD element.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The name of the DTD element.

content

The content of the element.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::endDtdElement() - End current DTD element

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD Entity tag

  • ? XMLWriter::writeDtdElement
  • XMLWriter::writeElement ?
  • PHP Manual
  • XMLWriter
  • Write full DTD Entity tag

XMLWriter::writeDtdEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdEntity -- xmlwriter_write_dtd_entity — Write full DTD Entity tag

说明

面向对象风格

public XMLWriter::writeDtdEntity ( string $name , string $content , bool $isParam = false , string|null $publicId = null , string|null $systemId = null , string|null $notationData = null ) : bool

过程化风格

xmlwriter_write_dtd_entity ( XMLWriter $writer , string $name , string $content , bool $isParam = false , string|null $publicId = null , string|null $systemId = null , string|null $notationData = null ) : bool

Writes a full DTD entity.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The name of the entity.

content

The content of the entity.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
8.0.0 | publicId, systemId and notationData are nullable now.

参见

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::endDtdEntity() - End current DTD Entity

User Contributed Notes

There are no user contributed notes for this page.


Write full element tag

  • ? XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs ?
  • PHP Manual
  • XMLWriter
  • Write full element tag

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Write full element tag

说明

面向对象风格

public XMLWriter::writeElement ( string $name , string|null $content = null ) : bool

过程化风格

xmlwriter_write_element ( XMLWriter $writer , string $name , string|null $content = null ) : bool

Writes a full element tag.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

name

The element name.

content

The element contents.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced element tag

  • ? XMLWriter::writeElement
  • XMLWriter::writePi ?
  • PHP Manual
  • XMLWriter
  • Write full namespaced element tag

XMLWriter::writeElementNs

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNs -- xmlwriter_write_element_ns — Write full namespaced element tag

说明

面向对象风格

public XMLWriter::writeElementNs ( string|null $prefix , string $name , string|null $namespace , string|null $content = null ) : bool

过程化风格

xmlwriter_write_element_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace , string|null $content = null ) : bool

Writes a full namespaced element tag.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

content

The element contents.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startElementNs() - Create start namespaced element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Writes a PI

  • ? XMLWriter::writeElementNs
  • XMLWriter::writeRaw ?
  • PHP Manual
  • XMLWriter
  • Writes a PI

XMLWriter::writePi

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writePi -- xmlwriter_write_pi — Writes a PI

说明

面向对象风格

public XMLWriter::writePi ( string $target , string $content ) : bool

过程化风格

xmlwriter_write_pi ( XMLWriter $writer , string $target , string $content ) : bool

Writes a processing instruction.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

target

The target of the processing instruction.

content

The content of the processing instruction.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::endPi() - End current PI

User Contributed Notes

There are no user contributed notes for this page.


Write a raw XML text

  • ? XMLWriter::writePi
  • XSL ?
  • PHP Manual
  • XMLWriter
  • Write a raw XML text

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Write a raw XML text

说明

面向对象风格

public XMLWriter::writeRaw ( string $content ) : bool

过程化风格

xmlwriter_write_raw ( XMLWriter $writer , string $content ) : bool

Writes a raw xml text.

参数

xmlwriter

仅用于过程调用。被修改的 XMLWriter 实例对象。此资源来自于对 xmlwriter_open_uri() 或 xmlwriter_open_memory() 的调用。

content

The text string to write.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。

参见

  • XMLWriter::text() - Write text

User Contributed Notes

There are no user contributed notes for this page.


XSL

  • 简介
  • 安装／配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
    • Example collection.xml and collection.xsl files
    • Error handling with libxml error handling functions
  • XSLTProcessor — The XSLTProcessor class
    • XSLTProcessor::__construct — Creates a new XSLTProcessor object
    • XSLTProcessor::getParameter — Get value of a parameter
    • XSLTProcessor::getSecurityPrefs — Get security preferences
    • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet — Import stylesheet
    • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter — Remove parameter
    • XSLTProcessor::setParameter — Set value for a parameter
    • XSLTProcessor::setProfiling — Sets profiling output file
    • XSLTProcessor::setSecurityPrefs — Set security preferences
    • XSLTProcessor::transformToDoc — Transform to a DOMDocument
    • XSLTProcessor::transformToUri — Transform to URI
    • XSLTProcessor::transformToXml — Transform to XML

User Contributed Notes

Jaroslaw Zabiello 23-Jun-2011 07:10
This is more usefull, no files needed, it just takes XML and XSL strings as input parameters and returns transformed XML

<?php
/**
 * @param  $xml
 * @param  $xsl
 * @return string xml
 */
function transform($xml, $xsl) {
   $xslt = new XSLTProcessor();
   $xslt->importStylesheet(new  SimpleXMLElement($xsl));
   return $xslt->transformToXml(new SimpleXMLElement($xml));
}
?>
sudhir dot vis at gmail dot com 25-Apr-2009 11:40
Here is a simplest way to transform the xml from php

<?php
$sXml  = "<xml>";
$sXml .= "<sudhir>hello sudhir</sudhir>";
$sXml .= "</xml>";

# LOAD XML FILE
$XML = new DOMDocument();
$XML->loadXML( $sXml );

# START XSLT
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load( 'xsl/index.xsl', LIBXML_NOCDATA);
$xslt->importStylesheet( $XSL );
#PRINT
print $xslt->transformToXML( $XML );
?>
allens at nospam dot com 19-Apr-2009 08:45
Problem:
Getting Netbeans error message:
Fatal error: Class 'xsltprocessor' not found

Solution:
place copy of php.ini in the c:\windows directory!

by default the php.ini file has xsl disabled......search for the line

;extension=php_xsl.dll

to enable XSL....remove ; so that the extension gets included

Then if Netbeans gives you the following message:
PHP Startup: Unable to load dynamic library './php_xsl.dll'

then you need to run the php-5.2.9-1-win32-installer.msi again
this time selecting the XSL extension!
visual77 at gmail dot com 20-Sep-2008 04:35
The XSLTProcessor is kind of a pain to use to generate an entire website, mostly due to the tedious process of building an XML tree through DOMDocument's createElement and appendChild functions.

To get an entire website out of nothing but XML and XSL (which really is a superior system to just echoing out the HTML), you could use an object that does all the PHP data structure to XML data tree conversion, and combines with the XSLTProcessor for rendering. A good object like this is DOMi, which you can find at http://domi.sourceforge.net.
emilise dot victor at gmail dot com 12-Mar-2008 08:10
Here is a way to get an output without using <xml:message> : use the var_dump function of php :
- First bind the php functions with
<? $xslt->registerPHPFunctions() ?>
and xmlns:php="http://php.net/xsl" in the stylesheet
- Then you can call the var_dump function like this : <xsl:variable name="a" select="php:function('var_dump', $return)" />

I couldn't find a way to call the function and have it really print the result without creating a variable, but well, it's just for debugging...
shangxiao at php dot net 10-Jan-2008 05:38
When using the DOM api to add xsl commands to your stylesheet dynamically, be sure to use createElementNS() rather than createElement() otherwise the XSLTProcessor will not recognise these DOM nodes.

Eg:
$xsl->createElementNS('http://www.w3.org/1999/XSL/Transform', 'xsl:element');
pb at online-magazin dot at 11-Oct-2007 03:13
Calling the Saxon XSLT Processor is a very esay task to do!

You just need to do some simple task

1. Install the JavaBridge for PHP

2. Download the freeware (B) Saxon distribution from http://saxon.sourceforge.net/

3. Put the jar files in a directory whre you have access

4. Use this sample of code

// Directory where the jar files are located
define("SAXON_DIR", $_SERVER['DOCUMENT_ROOT']."/saxonb8.9.0/");

// include the jars
java_require(SAXON_DIR."saxon8.jar;".SAXON_DIR."saxon8-dom.jar");

$sXslFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xsl"; // The xsl file
$sXmlFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xml"; // The xml file

try
{
  $oXslSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXslFile);
  $oXmlSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXmlFile);

  $oFeatureKeys = new JavaClass("net.sf.saxon.FeatureKeys");

  // Create the Factory
  $oTransformerFactory = new java("net.sf.saxon.TransformerFactoryImpl");

  //Disable source document validation
  $oTransformerFactory->setAttribute($oFeatureKeys->SCHEMA_VALIDATION, 4);

  // Create a new Transformer
  $oTransFormer = $oTransformerFactory->newTransformer($oXslSource);

  // Create a StreamResult to store the output
  $oResultStringWriter = new java("java.io.StringWriter");
  $oResultStream = new java("javax.xml.transform.stream.StreamResult", $oResultStringWriter);

  // Transform
  $oTransFormer->transform($oXmlSource, $oResultStream);

  // Echo the output from the transformation
  echo java_cast($oResultStringWriter->toString(), "string");

}
catch(JavaException $e){
   echo java_cast($e->getCause()->toString(), "string");
   exit;
}

5. Enjoy

This is working quite well.
Vasil Rangelov 21-Aug-2007 07:31
@basslines at gmail dot com
"
As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).
"

Using SAXON or AltovaXML by using their JAVA bindings could prove to be a difficult task to do, and .NET seems to be buggy (at least for me). However, I've made a class that uses SAXON or AltovaXML from the command line. AltovaXML could also be used with COM, provided it's registered as a COM component.

You can download my wrapper from:
http://xslt2processor.sourceforge.net/

I still need to implement a more graceful error handling (the way the XSL extension uses the Libxml functions), and once the bug
http://bugs.php.net/bug.php?id=41577
is fixed, I'll implement the .NET interfaces too.

I'll appreciate any feedback.
geoffreyj dot lee at gmail dot com 01-Jul-2007 11:02
Here are a couple useful tips for those who care about cross-browser compatibility.

Given:

<script type="text/javascript" src="test.js"></script>

XSLT will automatically condense it to:

<script type="text/javascript" src="test.js"/>

While this is good, Internet Explorer breaks on empty script tags. So, the simple solution is to add something to prevent an empty tag. For example:

<script type="text/javascript" src="test.js"><xsl:comment/></script>

Produces:

<script type="text/javascript" src="test.js">

</script>

------------------------

Also, here is a way to use IE's conditional comments:

<xsl:comment>[if gte IE 5]&#62;
&#60;link rel="stylesheet" type="text/css" href="ie.css" /&#62;
&#60;![endif]</xsl:comment>

Produces:

<!--[if gte IE 5]>
<link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

This will let you isolate IE-related CSS without needing to use ugly CSS hacks.
gabriel dot birke at web dot de 10-May-2007 03:19
Each <xsl:message> tag will generate a PHP error (level Warning). If you want to collect and pretty-print them, you could use a custom error handling function that collects the warnings in a static variable.
mnot at mnot dot net 08-May-2007 08:59
You can set an HTTP proxy for the XSLT document() function to use (as well as DTD external references) by setting http_proxy in the environment.

E.g., in Apache configuration;

SetEnv http_proxy http://127.0.0.1:3128/
Ryan D. Hatch 02-May-2007 01:14
Looking for php_xsl.dll?

If you installed on Windows using the MSI Installer - you may not have it.

1.) Add/Remove Programs and Change PHP Installation.  Select XSL Extension.

OR

2.) Download complete .zip file of PHP and you can copy php_xsl.dll into your PHP/etc directory.

Just a note.

Ryan D. Hatch
adrian at foeder dot de 14-Sep-2006 02:45
If you want to use the document()-function inside your XSL stylesheet, please note that you have to use an absolute path there.
Important for windows users: the absolute path *has* to be with forward slashes, so subsitute windows-path-backslashes to forward slashes before you transform the document.

Examples:
This will NOT work:
<xsl:copy-of select="document('test.xml')" />

This will also NOT work:
<xsl:copy-of select="document('c:\temp\test.xml')" />

But this WILL work:
<xsl:copy-of select="document('c:/temp/test.xml')" />
27-Apr-2006 06:26
Enable libxslt library, PHP 5, under windows:

To Enable:
In your php.ini
1. Uncomment ;extension=php_xsl.dll
2. Change extension_dir to
     extension_dir = "./ext"

To Confirm:
1. In a test.php page:
<?php phpinfo() ?>
2. Run test.php
3. Search for "libxslt Version". It should return a version number in a XSL headed table.

Further info Google
"Configuring and Testing PHP Servers for XSL Support"
Fabrice Bonny 30-Mar-2006 01:34
In response to how to use entities from DTD (internal or external) in XSLT. It works if you do this way:

$xsl = new DOMDocument;
$xsl->resolveExternals = TRUE;
$xsl->substituteEntities = TRUE;
$xsl->load(...);

Hope this helps! ;-)
basslines at gmail dot com 29-Mar-2006 10:07
As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).
17-Mar-2006 09:14
In response to appletalk at gmail dot com
<snip>
As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:
Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...
There're many ways to solve this:
.....
b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
   <!DOCTYPE xsl:stylesheet [
   <!ENTITY nbsp "&#160;" >
   ]>
.......</snip>
Just wanted to let people know that option b does NOT work. I'm not sure why this isn't implemented correctly, but it isn't, so don't waste your time. It's unfortunate the DOMXSL transform is so much less capable than the old xslt function.
venkatesh at lammersmedical dot com 01-Mar-2005 06:17
Here is function to read from the XSL sheet which is saved as a text file.

function ReadExcelSheet($filename){
             $test=file($filename);
             $ar1=str_replace("~[^\t]*\t","\t",$test);
             $ar2=str_replace("~","",$ar1);
             $ar=str_replace("?","",$ar2);
             $temp=array();
             for ($i=0; $i<count($ar); $i++) {
                       if((substr($ar[$i],0,1)!= "\t")){
                           if($ar[$i]!=="\r\n"){
                           array_push($temp,$ar[$i]);
            }
        }
    }
    $name=split("\t",$temp[0]);
    $ExcelList=array();
    for($i=1;$i<count($temp);$i++){
        $split_result=split("\t",$temp[$i]);
        array_push($ExcelList,$split_result);
    }
    $result=insert_into_array($ExcelList,0,$name);
    return($result);
}
appletalk at gmail dot com 04-Feb-2005 10:32
As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:

Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...

There're many ways to solve this:
a) The hard way
<xsl:text disable-output-escaping="yes"> &amp;nbsp;</xsl:text>

b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
   <!DOCTYPE xsl:stylesheet [
    <!ENTITY nbsp "&#160;" >
    ]>

c) External Doctype
Just in case you want need other HTML entities, you can call an external doctype with the proper definitions

<!DOCTYPE page SYSTEM "http://gv.ca/dtd/character-entities.dtd">

Of course, you can download the file and place it in your server.
kekoajs at yahoo dot com 22-Dec-2004 02:07
Wow, I spent the better part of a day looking for how one could pass an entire test expression to an XSL stylesheet.  It seems that the XSLT 1.0 specification doesn't support it but PHP 5 (and maybe 4s) inclusion of  EXSLT allows one to do exactly that...

simply add these lines...

xmlns:dyn="http://exslt.org/dynamic"
extension-element-prefixes="dyn"

to the <xsl:stylesheet> element and when using an expression stored in a <xsl:param> element write

<xsl:if test="dyn:evaluate($param-name)">

and viola!  you can now use expressions generated externally in your stylesheet!

EXSLT adds many useful functions that can be integrated into your XSL in a similar fashion.  You can go to http://exslt.org/ to learn more...
rd at jerntorget dot se 24-Sep-2004 03:58
If you get the following warning message:

xsltApplyOneTemplate: _if_ was not compiled in (if can for example be apply-template or some other method), i've found that the problem seems to be an &nbsp; directly before the <xsl:if> or what ever is causing the problem.

One way to get thru the problem is to use span tags around &nbsp;  like : <span>&nbsp;</span>
jw at jwscripts dot com 06-Sep-2004 02:23
The following code is a wrapper to support calls to some of the old xslt_* functions:

<?

if (PHP_VERSION >= 5) {
    // Emulate the old xslt library functions
    function xslt_create() {
        return new XsltProcessor();
    }

    function xslt_process($xsltproc,
                          $xml_arg,
                          $xsl_arg,
                          $xslcontainer = null,
                          $args = null,
                          $params = null) {
        // Start with preparing the arguments
        $xml_arg = str_replace('arg:', '', $xml_arg);
        $xsl_arg = str_replace('arg:', '', $xsl_arg);

        // Create instances of the DomDocument class
        $xml = new DomDocument;
        $xsl = new DomDocument;

        // Load the xml document and the xsl template
        $xml->loadXML($args[$xml_arg]);
        $xsl->loadXML($args[$xsl_arg]);

        // Load the xsl template
        $xsltproc->importStyleSheet($xsl);

        // Set parameters when defined
        if ($params) {
            foreach ($params as $param => $value) {
                $xsltproc->setParameter("", $param, $value);
            }
        }

        // Start the transformation
        $processed = $xsltproc->transformToXML($xml);

        // Put the result in a file when specified
        if ($xslcontainer) {
            return @file_put_contents($xslcontainer, $processed);
        } else {
            return $processed;
        }

    }

    function xslt_free($xsltproc) {
        unset($xsltproc);
    }
}

$arguments = array(
    '/_xml' => file_get_contents("newxslt.xml"),
    '/_xsl' => file_get_contents("newxslt.xslt")
);

$xsltproc = xslt_create();
$html = xslt_process(
    $xsltproc,
    'arg:/_xml',
    'arg:/_xsl',
    null,
    $arguments
);

xslt_free($xsltproc);
print $html;

?>
rojaro 23-Jun-2004 07:43
If you're want to use XML from a variable e.g. $xmldata but the XSLT-StyleSheet from a file, you can do it also the following way:

<?php
$xslt = new xsltProcessor;
$xslt->importStyleSheet(DomDocument::load('filename.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($xmldata));
?>


简介

The XSL extension implements the XSL standard, performing » XSLT transformations using the » libxslt library

User Contributed Notes

There are no user contributed notes for this page.


需求

此扩展需要 libxml PHP 扩展。这表示需要使用 --with-libxml，或在 PHP 7.4 之前的版本中使用 --enable-libxml， 尽管这将隐式完成因为 libxml 是缺省开启的。

This extension uses libxslt which can be found at » http://xmlsoft.org/XSLT/. libxslt version 1.1.0 or greater is required.

User Contributed Notes

There are no user contributed notes for this page.


安装

PHP 5 includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line (DIR being the libxslt installation directory).

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

XSL_CLONE_AUTO (int)
XSL_CLONE_NEVER (int)
XSL_CLONE_ALWAYS (int)
LIBXSLT_VERSION (int)
libxslt version like 10117. Available as of PHP 5.1.2.
LIBXSLT_DOTTED_VERSION (string)
libxslt version like 1.1.17. Available as of PHP 5.1.2.
LIBEXSLT_VERSION (int)
libexslt version like 813. Available as of PHP 5.1.2.
LIBEXSLT_DOTTED_VERSION (string)
libexslt version like 1.1.17. Available as of PHP 5.1.2.
XSL_SECPREF_NONE (int)
Deactivate all security restrictions.
XSL_SECPREF_READ_FILE (int)
Disallows reading files.
XSL_SECPREF_WRITE_FILE (int)
Disallows writing files.
XSL_SECPREF_CREATE_DIRECTORY (int)
Disallows creating directories.
XSL_SECPREF_READ_NETWORK (int)
Disallows reading network files.
XSL_SECPREF_WRITE_NETWORK (int)
Disallows writing network files.
XSL_SECPREF_DEFAULT (int)
Disallows all write access, i.e. a bitmask of XSL_SECPREF_WRITE_NETWORK | XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE.

User Contributed Notes

There are no user contributed notes for this page.


范例

Table of Contents

  • Example collection.xml and collection.xsl files
  • Error handling with libxml error handling functions

User Contributed Notes

There are no user contributed notes for this page.


Example collection.xml and collection.xsl files

Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:

Example #1 collection.xml

<collection>
 <cd>
  <title>Fight for your mind</title>
  <artist>Ben Harper</artist>
  <year>1995</year>
 </cd>
 <cd>
  <title>Electric Ladyland</title>
  <artist>Jimi Hendrix</artist>
  <year>1997</year>
 </cd>
</collection>

Example #2 collection.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
 <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
 <xsl:template match="collection">
  Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection!
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="cd">
  <h1><xsl:value-of select="title"/></h1>
  <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
  <hr />
 </xsl:template>
</xsl:stylesheet>

User Contributed Notes

There are no user contributed notes for this page.


Error handling with libxml error handling functions

libxml offers a number of functions for handling errors, which can be employed to capture and deal with errors in XSLT processing.

Example #1 fruits.xml

A valid XML file.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Example #2 fruits.xsl

Contains an invalid select expression.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="html" encoding="utf-8" indent="no"/>
 <xsl:template match="fruits">
  <ul>
   <xsl:apply-templates/>
  </ul>
 </xsl:template>
 <xsl:template match="fruit">
  <li><xsl:value-of select="THIS IS A DELIBERATE ERROR!"/></li>
 </xsl:template>
</xsl:stylesheet>

Example #3 Collating and printing errors

The example below captures and displays libxml errors raised when calling XSLTProcessor::importStyleSheet() with a stylesheet containing an error.

<?php

$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xsl = new XSLTProcessor();

$xmldoc->loadXML('fruits.xml');
$xsldoc->loadXML('fruits.xsl');

libxml_use_internal_errors(true);
$result = $xsl->importStyleSheet($xsldoc);
if (!$result) {
    foreach (libxml_get_errors() as $error) {
        echo "Libxml error: {$error->message}\n";
    }
}
libxml_use_internal_errors(false);

if ($result) {
    echo $xsl->transformToXML($xmldoc);
}

?>

以上例程的输出类似于：

Libxml error: Invalid expression

Libxml error: compilation error: file fruits.xsl line 9 element value-of
Libxml error: xsl:value-of : could not compile select expression 'THIS IS A DELIBERATE ERROR!'

User Contributed Notes

There are no user contributed notes for this page.


The XSLTProcessor class

(PHP 5, PHP 7, PHP 8)

简介

类摘要

XSLTProcessor {
/* 方法 */
public getParameter ( string $namespace , string $name ) : string|false
public getSecurityPrefs ( ) : int
public hasExsltSupport ( ) : bool
public importStylesheet ( object $stylesheet ) : bool
public registerPHPFunctions ( array|string|null $functions = null ) : void
public removeParameter ( string $namespace , string $name ) : bool
public setParameter ( string $namespace , string $name , string $value ) : bool
public setProfiling ( string|null $filename ) : bool
public setSecurityPrefs ( int $preferences ) : int
public transformToDoc ( object $document , string|null $returnClass = null ) : DOMDocument|false
transformToURI ( DOMDocument $doc , string $uri ) : int
public transformToXml ( object $document ) : string|false|null
}

Table of Contents

  • XSLTProcessor::__construct — Creates a new XSLTProcessor object
  • XSLTProcessor::getParameter — Get value of a parameter
  • XSLTProcessor::getSecurityPrefs — Get security preferences
  • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
  • XSLTProcessor::importStylesheet — Import stylesheet
  • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
  • XSLTProcessor::removeParameter — Remove parameter
  • XSLTProcessor::setParameter — Set value for a parameter
  • XSLTProcessor::setProfiling — Sets profiling output file
  • XSLTProcessor::setSecurityPrefs — Set security preferences
  • XSLTProcessor::transformToDoc — Transform to a DOMDocument
  • XSLTProcessor::transformToUri — Transform to URI
  • XSLTProcessor::transformToXml — Transform to XML

User Contributed Notes

joandres52725lm at gmail dot com 29-Apr-2020 07:29
[Update] PHP version /.3.15 and Windows Uncomment `extension=xsl` to activate it in your php.ini. Then restart your webserver to refresh php.
tschallacka 29-Feb-2016 09:58
uncomment extension=php_xsl.dll on windows to activate it in your php.ini. Then restart your webserver to refresh php.
flavius 13-Nov-2015 05:49
It requires PHP5 XSL extension. On linux:

sudo apt-get install php5-xsl


Creates a new XSLTProcessor object

  • ? XSLTProcessor
  • XSLTProcessor::getParameter ?
  • PHP Manual
  • XSLTProcessor
  • Creates a new XSLTProcessor object

XSLTProcessor::__construct

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::__construct — Creates a new XSLTProcessor object

说明

XSLTProcessor::__construct ( )

Creates a new XSLTProcessor object.

参数

此函数没有参数。

返回值

没有返回值。

范例

Example #1 Creating an XSLTProcessor

<?php

$xsldoc = new DOMDocument();
$xsldoc->load($xsl_filename);

$xmldoc = new DOMDocument();
$xmldoc->load($xml_filename);

$xsl = new XSLTProcessor();
$xsl->importStyleSheet($xsldoc);
echo $xsl->transformToXML($xmldoc);

?>

User Contributed Notes

There are no user contributed notes for this page.


Get value of a parameter

  • ? XSLTProcessor::__construct
  • XSLTProcessor::getSecurityPrefs ?
  • PHP Manual
  • XSLTProcessor
  • Get value of a parameter

XSLTProcessor::getParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::getParameter — Get value of a parameter

说明

public XSLTProcessor::getParameter ( string $namespace , string $name ) : string|false

Gets a parameter if previously set by XSLTProcessor::setParameter().

参数

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

返回值

The value of the parameter (as a string), or false if it's not set.

参见

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::removeParameter() - Remove parameter

User Contributed Notes

There are no user contributed notes for this page.


Get security preferences

  • ? XSLTProcessor::getParameter
  • XSLTProcessor::hasExsltSupport ?
  • PHP Manual
  • XSLTProcessor
  • Get security preferences

XSLTProcessor::getSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::getSecurityPrefs — Get security preferences

说明

public XSLTProcessor::getSecurityPrefs ( ) : int

Gets the security preferences.

参数

此函数没有参数。

返回值

A bitmask consisting of XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK.

User Contributed Notes

There are no user contributed notes for this page.


Determine if PHP has EXSLT support

  • ? XSLTProcessor::getSecurityPrefs
  • XSLTProcessor::importStylesheet ?
  • PHP Manual
  • XSLTProcessor
  • Determine if PHP has EXSLT support

XSLTProcessor::hasExsltSupport

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support

说明

public XSLTProcessor::hasExsltSupport ( ) : bool

This method determines if PHP was built with the » EXSLT library.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Testing EXSLT support

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
    die('EXSLT support not available');
}

// do EXSLT stuff here ..

?>

User Contributed Notes

There are no user contributed notes for this page.


Import stylesheet

  • ? XSLTProcessor::hasExsltSupport
  • XSLTProcessor::registerPHPFunctions ?
  • PHP Manual
  • XSLTProcessor
  • Import stylesheet

XSLTProcessor::importStylesheet

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::importStylesheet — Import stylesheet

说明

public XSLTProcessor::importStylesheet ( object $stylesheet ) : bool

This method imports the stylesheet into the XSLTProcessor for transformations.

参数

stylesheet

The imported style sheet as a DOMDocument or SimpleXMLElement object.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

rbmeo at yahoo dot com 12-Jul-2012 09:52
To make your import dynamic, try this code:

<?php
$dom = new DOMDocument();
$dom->load('main.xsl');
$xpath = new DomXPath($dom);
$importnode= $questionsXsl->createElement('xsl:include');
$attr= $questionsXsl->createAttribute('href');
$attr->value = 'import.xsl';
$importnode->appendChild($attr);
$dom->documentElement->insertBefore($importnode,$ref);
$dom->loadXml($dom->saveXml());
?>

this code basically loads the main stylesheet, prepend the import xsl code then reload as xml string so the imported stylesheet will be loaded at dom.
kevin at metalaxe dot com 17-Nov-2007 03:26
Just for reference, as of this writing, this function does not support importing multiple stylesheets. The following will output only the stylesheet transformation of the second imported sheet:

<?php

# LOAD XML FILE
$XML = new DOMDocument();
$XML->load( 'data.xml' );

# START XSLT
$xslt = new XSLTProcessor();

# IMPORT STYLESHEET 1
$XSL = new DOMDocument();
$XSL->load( 'template1.xsl' );
$xslt->importStylesheet( $XSL );

#IMPORT STYLESHEET 2
$XSL = new DOMDocument();
$XSL->load( 'template2.xsl' );
$xslt->importStylesheet( $XSL );

#PRINT
print $xslt->transformToXML( $XML );
?>

This wasn't documented and quite dissapointing.
fcartegnie 21-Jul-2007 06:11
PHP5 xsl processor has a different behaviour than PHP4's one with CDATA sections. (see http://bugs.php.net/bug.php?id=29837)
Loaded XSL sheet CDATA sections does not allow, by default, output-escaping handling (everything in the CDATA is escaped by default).

So in this case you can't build your XSL Dom the usual way:
    $xsldom = DomDocument::loadXML(file_get_contents('sheet.xsl'));

and must go through this one (allowing LIBXML_NOCDATA parameter):
    $xsldom = new DomDocument;
    $xsldom->load('sheet.xsl', LIBXML_NOCDATA);

Then the CDATA output-escaping behaviour will be correct.
diesel at spbnet dot ru 19-Mar-2007 09:07
This is not a problem. You may set DOMDocument's documentURI property.
Something like this

<?php
$xsl = new DOMDocument('1.0','UTF-8');

$xsl->loadXML(file_get_contents('/foo/bar/somefile.xsl');
$xsl->documentURI = '/foo/bar/somefile.xsl';

$xslProc = new XSLTProcessor();
$xslProc->importStylesheet($xsl);
?>

and document('other.xsl') will work fine!
bbrosseau at gmail 01-Mar-2005 08:46
For those who wants to use external documents, it is important not to use the DomDocument::loadXML because the processor will not have the path to look for other files

So if you want to transform some xml with a pre-generated stylesheet $f:

<?php
$f = 'somestylesheet.xsl';
$xsl = DomDocument::loadXML(file_get_contents($f));
?>

document('other.xml') will not work with relative path and <?php $xsl = DomDocument::load($f); ?> will!


Enables the ability to use PHP functions as XSLT functions

  • ? XSLTProcessor::importStylesheet
  • XSLTProcessor::removeParameter ?
  • PHP Manual
  • XSLTProcessor
  • Enables the ability to use PHP functions as XSLT functions

XSLTProcessor::registerPHPFunctions

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions

说明

public XSLTProcessor::registerPHPFunctions ( array|string|null $functions = null ) : void

This method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

参数

functions

Use this parameter to only allow certain functions to be called from XSLT.

This parameter can be either a string (a function name) or an array of functions.

返回值

没有返回值。

范例

Example #1 Simple PHP Function call from a stylesheet

<?php
$xml = <<<EOB
<allusers>
 <user>
  <uid>bob</uid>
 </user>
 <user>
  <uid>joe</uid>
 </user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
 <xsl:template match="allusers">
  <html><body>
    <h2>Users</h2>
    <table>
    <xsl:for-each select="user">
      <tr><td>
        <xsl:value-of
             select="php:function('ucfirst',string(uid))"/>
      </td></tr>
    </xsl:for-each>
    </table>
  </body></html>
 </xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);

$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>

User Contributed Notes

Matthew, info at mathias-schaefer dot de 25-Nov-2010 08:34
=> there is no instance of your class needed, you have to take care about the namespace (using 5.3).

<!-- xsl:
<xsl:value-of select="php:function ('My\Name\Space\MyClassName::methodName',1+2)"/>
--->

<?php
namespace My\Name\Space;

   class MyClassName
   {
      static public function methodName($someArgument)
      {
         return "resultis:".$someArgument;
      }
   }
?>

<!-- result:
resultis:3
-->

=> no to-string conversion of the argument needed
=> returning numbers is also possible (maybe DOM nodes too)

Keep on hackin'
Demerit 10-Aug-2010 07:58
Let's get the terminology correct here, folks.

If you are calling a function that is residing within a class, reference it by its INSTANCE name, NOT its class name.

class.my_class.php:

<?php
class class_name {
static function function_name($in){
return ($out);
}
}
?>

calling_document.php:

<?php
require_once('class.my_class.php');
$instance_name=new class_name();
?>

my_xslt.xsl:

<xsl:value-of select="php:function ('instance_name::function_name','garbage')" />

BTW, in 5.1.6 double-colon (::) is the only thing that works when calling a function that resides within a class. However, you must declare your function as static. Using -> as some have suggested (e.g., php:function ('instance_name->function_name','garbage')) doesn't work at all, no matter how you declare your function.
Nic Luciano 22-Jul-2009 11:09
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."

Also note that the class function must be declared as static.
Ariz Jacinto 08-Jul-2008 02:21
If you want to use replace() function similar to XPath 2.0[1]  and you want to avoid a long XSLT function similar to this one[2], you can use PHP's str_replace() instead:

   <xsl:value-of select="php:functionString('str_replace','pattern', 'replacement' , . )">

Links:
  [1] http://www.w3.org/TR/2004/WD-xpath-functions-20041029/#func-replace
  [2] http://aspn.activestate.com/ASPN/Cookbook/XSLT/Recipe/65426

_
thsoft at vipmail dot hu 27-Dec-2007 02:22
Unfortunately, you can't pass arrays to PHP from XLST.
But you can pass an arbitrary number of arguments to a PHP function and then get them with func_get_args() as an array.
[There's no sense writing a function that is identical to the array() construct, because a function's return value is converted to a string when passed as an argument to another function. This means deep arrays cannot be handled this way.]
thsoft at vipmail dot hu 31-Jan-2007 03:20
The correct way to receive DOM nodes (let it be element, document, document fragment etc.) returned from PHP is to use <xsl:copy-of select="php:function...

I found the idea and an example here: http://bugs.php.net/bug.php?id=29409

For the technical details about the reason, see http://www.w3.org/TR/xslt#copy-of
phil at worldpoolfederation dot com 01-Dec-2006 03:22
Not true

Use :: to call static functions
Use -> to call non static functions

You must define a function as static in php 5.1 to be able to call it statically.
mark at thirst dot org 10-Oct-2006 07:25
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."   This worked in 5.0.4 but no longer works in 5.1.6.
franp at free dot fr 02-Sep-2006 01:45
Note that if you want your output to validate against some xhtml dtd, you must add the following attribute to the xsl:stylesheet element of the xslt stylesheet :
exclude-result-prefixes="php".

Otherwise, you get an "invalid attribute xmlns:php" error.
taylorbarstow at that google mail thingy 26-May-2006 05:33
Add-on to my previous note (below) about returning nodesets to XSLT from PHP functions:

You don't have to return a DOMDocument, DOMElement works just as well.  Plus, retuning a DOMElement gets around the problem of discarding the root node which I discuss below and which is also touched on by "Ingram".
heinemann dot juergen at hjcms dot de 08-Mar-2006 02:23
You can find mor Examples at PHP Sources php-5.*/ext/xsl/tests
<?php

$xform = <<<EOT
<?xml version = '1.0' encoding = 'utf-8' ?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:php="http://php.net/xsl"
    xsl:extension-element-prefixes="php"
>
<xsl:output method="xml" indent="yes" encoding="utf-8" />
<xsl:namespace-alias stylesheet-prefix="php" result-prefix="xsl" />
<xsl:template match="root">
<html>
<head>
    <title>Dateformat</title>
</head>
<body>
<xsl:for-each select="datenode">
    <li>
        <xsl:value-of select="php:functionString('convertDate', . )" />
    </li>
    </xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
EOT;

function convertDate( $i )
{
    setlocale( LC_TIME, 'de_DE' );
    return utf8_encode( strftime( '%B %d %A %Y %H:%M:%S CET', $i ) );
}

$xsl = new XSLTProcessor;
$xsl->registerPHPFunctions();
$xsl->setParameter( 'DOCTYPE', 'PUBLIC', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' );
$xsl->setParameter( 'html', 'xmlns', 'http://www.w3.org/1999/xhtml' );

$xdom = new DomDocument( '1.0', 'utf-8' );
$xdom->loadXML( $xform );

$xsl->importStyleSheet( $xdom );
unset( $xdom );

$dom = new DomDocument( '1.0', 'utf-8' );
$r = $dom->appendChild( $dom->createElement( 'root' ) );
foreach ( range( 1, 12 ) AS $i ) {
    $r->appendChild( $dom->createElement( 'datenode', mktime( date('G'), date('i'), date('s'), $i, date('d'), date('Y') ) ) );
}

header( "Content-Type: text/html; CHARSET=gb2312;" );
header( "Content-Encoding: utf-8" );
echo $xsl->transformToXML( $dom );

?>
Ingram 28-Feb-2006 12:33
Upon testing returning of a nodeset contributed by

taylorbarstow at that google mail thingy

(which works excellently, TY!)

I found that with using:

===
"Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" /> "
===

I could only output the text and not any of the tags after applying templates - i.e. it stripped all elements around text.

Instead using:

===
<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
     <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.
===

Worked fine and allowed me to apply-templates without problem on the returned nodeset.
hopeseekr at gmail dot com 01-Feb-2006 12:17
One of the peskiest things I had problems with was encoding URL parameters.  I mean, pretend you want to populate a link with "search+terms" instead of just "search terms".  I was including two seperate URLs in the XML and that was ludicrous.

Below is a far more elegant PHP+XSLT solution.  You will also see it uses two *undocumented* features of registerPHPFunctions(), namely php:functionString() and the passing of parameters to the function.  I figured this out by trial and error; I really hope this note helps you as it *greatly* expands the power of php functions in XSLT!

<?php
/* --- XML input --- */
<search_results>
   <query>concert tickets</query>
</search_results>

/* --- XSL code --- */
<!-- Display query -->
<xsl:template match="search_results">
   <!-- Get URL-encoded string via PHP -->
   <xsl:variable name="safeurl" as="xs:string" select="php:functionString('urlencode', query)" />
   <p>Your search for <em><xsl:value-of select="query"/></em> can be continued at <a href="http://www.tixtix.com/search.php?q={$safeurl}">our search engine</a></p>
</xsl:template>

/* --- XHTML output --- */
<p>Your search for <em>concert tickets</em> can be continued at <a href="http://www.tixtix.com/search.php?q=space+cowboy">our search engine</a></p>
?>

Cool, huh?
taylorbarstow at that google mail thingy 01-Dec-2005 07:14
From a PHP function, you can pass a nodeset back to XSL using a DOMDocument.  For example:

<?php

function getNodeSet() {
   $xml =
       "<test>" .
       "<a-node>This is a node</a-node>" .
       "<a-node>This is another node</a-node>" .
       "</test>";
   $doc = new DOMDocument;
   $doc->loadXml($xml);
   return $doc;
}

?>

The only problem I've found is that the root level node in your returned DOM document acts like the root level node of your original.   SO, it's easy to introduce an infinite loop like so:

<xsl:template match="/">
   <xsl:apply-templates select="php:function('getNodeSet')" />
</xsl:template>

To avoid this, I've been using a construct like:

<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
      <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.  Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" />
Ritch at Bugsoftware dot co dot uk 22-Jun-2005 03:18
If you wish to use a function from inside a class use the double colon (::) notation, for example;

php:functionString('classname::function')

The funtion is fired off as a static and as such acts like a function in the global namespace.
benbarnett 04-Mar-2005 04:34
You can use the php:functionString() in the XSL, which will automatically convert output to a string!
zac at zacbowling dot com 27-Oct-2004 01:48
One thing I have told a lot of people to do if they are having
issues with this function is to check for any 'xmlns' attributes
that get generated and added to your xml pages by some
types of popular software.

<?php
$file = "http://data.map***.net/m***ck.asmx/GetMessages?IMEI=$id";

$docxml = file_get_contents($file);

//You may have to do something like this where
//I remove any instance of xmlns tags that get
//returned by my ASP.NET SOAP responses.

$docxml =
 str_replace("xmlns=\"http://data.map***.net/m***ck.asmx?WSDL\"",
  "",$docxml);

$xslt = new xsltProcessor;

//You don't remove them then this function will blow up.
$xslt->registerPHPFunctions();
$xslt->importStyleSheet(DomDocument::load('../xsl/message.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($docxml));

?>

Also a few cool tricks with this function is that you can call
built in PHP functions. For example:

<xsl:value-of
  select="php:function('nl2br',string(MessageContent/Message))"
  disable-output-escaping="yes"/>

That XSL value will now return your normal string but replace
all your new line charactors in your xml with '<br />'s.

Also note the 'disable-output-escaping="yes"' statement. If
you don't call this, then the output of that bind will be ran
thru basicly a "htmlencode()" type function.

Last but not least, take a look at the 'string()' function I
called in XSL before passing it back. That is because without
calling that, when it runs it will try and pass the node object,
and not its value (which is what you most likely only want).

This function is very awsome and could lead to some very
interesting code development. Skins could be loaded
remotely. You could write an RSS viewer in PHP without much
code. You could parse XHTML pages into another view (either
localy or remotely). Then you can take that same XML
content and throw it against ASP.NET, Java, or even a
command line processing tool using that same exact XSL
style sheet and generate the front ends for you page without
much change. I'm very excited.

Happy codding.
junkmail at eighteyes dot com 08-Oct-2004 02:52
When writing a stylesheet that uses a callback function be sure to include a namespace declaration for php, as follows:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl" version='1.0'>
begemot at php dot com dot ua 28-Sep-2004 06:24
I think it help  your.
<?php

function dateLang () {
        return strftime("%A");
}

$xsl = new DomDocument();
$xsl->load("datetime.xsl");
$inputdom = new DomDocument();
$inputdom->load("today.xml");

$proc = new XsltProcessor();
$proc->registerPhpFunctions();

// Load the documents and process using $xslt
$xsl = $proc->importStylesheet($xsl);

/* transform and output the xml document */
$newdom = $proc->transformToDoc($inputdom);

print $newdom->saveXML();

?>

Here's the XSLT stylesheet, datetime.xsl, that will call that function:

<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<xsl:template match="/">
  <xsl:value-of select="php:function('dateLang')" />
</xsl:template>
</xsl:stylesheet>

And here's an absolute minimal XML file, today.xml, to pass through the stylesheet (although articles.xml would achieve the same result):

<?xml version="1.0" encoding="iso-8859-1" ?>
<today></today>
zac at zacbowling dot com 26-Aug-2004 09:48
One thing to note about this function. A lot of values need to be converted to a XSLT string using the "string()" function in XLS before you pass them to your functions, and when you return them make sure that if they are strings that you call the "strval()" in php before doing so. This saved me hours.

Hope that helps.

Zac Bowling


Remove parameter

  • ? XSLTProcessor::registerPHPFunctions
  • XSLTProcessor::setParameter ?
  • PHP Manual
  • XSLTProcessor
  • Remove parameter

XSLTProcessor::removeParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::removeParameter — Remove parameter

说明

public XSLTProcessor::removeParameter ( string $namespace , string $name ) : bool

Removes a parameter, if set. This will make the processor use the default value for the parameter as specified in the stylesheet.

参数

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::getParameter() - Get value of a parameter

User Contributed Notes

There are no user contributed notes for this page.


Set value for a parameter

  • ? XSLTProcessor::removeParameter
  • XSLTProcessor::setProfiling ?
  • PHP Manual
  • XSLTProcessor
  • Set value for a parameter

XSLTProcessor::setParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::setParameter — Set value for a parameter

说明

public XSLTProcessor::setParameter ( string $namespace , string $name , string $value ) : bool
public XSLTProcessor::setParameter ( string $namespace , array $options ) : bool

Sets the value of one or more parameters to be used in subsequent transformations with XSLTProcessor. If the parameter doesn't exist in the stylesheet it will be ignored.

参数

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

value

The new value of the XSLT parameter.

options

An array of name => value pairs.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Changing the owner before the transformation

<?php

$collections = array(
    'Marc Rutkowski' => 'marc',
    'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

foreach ($collections as $name => $file) {
    // Load the XML source
    $xml = new DOMDocument;
    $xml->load('collection_' . $file . '.xml');

    $proc->setParameter('', 'owner', $name);
    $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

参见

  • XSLTProcessor::getParameter() - Get value of a parameter
  • XSLTProcessor::removeParameter() - Remove parameter

User Contributed Notes

richard at aggmedia dot net 04-Mar-2009 07:47
Note that there is no way to remove a parameter from an XSLTProcessor unless you know its name, and there is no way (that I can find) to get a list of the current parameters.

This means that you cannot reuse an XSLTProcessor with different parameters unless you call XSLTProcessor->removeParameter() on every parameter, and to do that you need to know the names of all the currently set parameters.

I bumped into this because we were caching XSLTProcessors for reuse, and they were spitting out content based on phantom parameters (they were still there from previous uses).
Lennaert van der Linden 13-Feb-2008 06:28
The parameter will not be set if the value contains both single and double quotes. Instead a warning will be shown when transforming the document:

PHP Warning:  XSLTProcessor::transformToXml(): Cannot create XPath expression (string contains both quote and double-quotes)
brettz9 08-May-2007 08:27
It seems heinemann's usage is not correct and does not achieve the intended result.

This method's purpose is to change a global <xsl:param> value in the XSL stylesheet--not to change an attribute of any other element.  <xsl:param> basically lets you set up a stylesheet which can be customized (as from PHP) externally (without needing to tamper with the original XSL file).

Here's an example of usage (that will work):

Stylesheet:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="print_something" select="defaultstring"/>
    <xsl:template match="/mydoc">
        <p style="color:red;">Printed parameter: <xsl:value-of select="$print_something"/></p>
    </xsl:template>
</xsl:stylesheet>

Script:

<?php
$dom = new DOMDocument();
$xsl = new XSLTProcessor;
$xsl->setParameter( '', 'print_something', "Now I've overridden the default!");
$style = realpath( "./my_stylesheet.xslt" );
$dom->load($style);
$xsl->importStyleSheet($dom);
$dom->loadXML('<mydoc></mydoc>');

$out = $xsl->transformToXML( $dom );

var_dump( '<pre>',
    htmlentities( $out, ENT_QUOTES, 'utf-8' ),
    $xsl->getParameter('', 'print_something'),
'</pre>' );
?>

gives:

string(5) "

"
string(143) "<?xml version="1.0"?>
<p style="color:red;">Printed parameter: Now I've overridden the default!</p>
"
string(32) "Now I've overridden the default!"
string(6) "

"

Notice that at present adding a namespace will not work. The only option at present is to set the first parameter for namespace to an empty string (though you can add the prefix with colon to the second argument for name in order to set the parameter for a namespace-prefixed parameter name).

See http://bugs.php.net/bug.php?id=30622
OrionI 01-May-2007 07:19
After looking at this a little further (see http://bugs.php.net/bug.php?id=41248), it appears that it's a shortcoming of libxslt, not PHP, that prevents passing in DOMDocuments or DOMNodes as parameters.
Orion I 30-Apr-2007 08:46
I've been trying to pass in a DOMDocument object as a parameter so I can stuff a bunch of data into XML nodes, but it appears that this function is not capable of it. I was hoping to get it to work like it does in the .NET 2.0 framework. (See http://msdn2.microsoft.com/en-us/library/
system.xml.xsl.xsltargumentlist.addparam.aspx)
But after looking at the PHP 5.2.1 source code, /php-5.2.1/ext/xsl/xsltprocessor.c line 604-650, it appears that it's not possible to do so in PHP even though it appears that libxslt supports it (see http://xmlsoft.org/XSLT/html/libxslt-variables.html
#xsltParseGlobalParam)

In fact, if the parameters aren't exactly what's expected, you'll always get a warning like this:

Wrong parameter count for XSLTProcessor::setParameter()
heinemann dot juergen at hjcms dot de 07-Mar-2006 03:39
Example for how it works.

<?xml version = '1.0' encoding = 'utf-8' ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"
    indent="yes"
    encoding="ISO-8859-15"
    doctype-system = "-//W3C//DTD XHTML 1.0 Transitional//EN"
    doctype-public = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
/>
<xsl:template match="docs">
<html>
<head>
    <title>
        <xsl:text>Example</xsl:text>
    </title>
</head>
<body>
    <xsl:for-each select="block">
        <div>
            <xsl:value-of select="." />
        </div>
    </xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

------------------

<?php
$dom = new DomDocument( '1.0', 'utf-8' );
$xsl = new XSLTProcessor;
$xsl->setParameter( 'block', 'xmlns', 'http://www.w3.org/1999/xhtml' );

$style = realpath( "./my_stylesheet.xslt" );
$dom->load( $style );
$xsl->importStyleSheet( $dom );

$dom->loadXML( '<docs>
    <block>Howto set xhtml Transitional Namespaces width php</block>
    <block>see http://www.php.net</block>
</docs>' );

$out = $xsl->transformToXML( $dom );

var_dump( '<pre>',
    htmlentities( $out, ENT_QUOTES, 'utf-8' ),
    $xsl->getParameter( 'block', 'xmlns' ),
    $xsl->getParameter( 'docs', 'xmlns' ),
'</pre>' );

?>
Stoke A 11-Aug-2005 03:40
XSLTProcessor::removeParameter() won't work on parameters set via XSLTProcessor::setParameter(string namespace, array options) in 5.1+ -- they need to be set and removed one by one.


Sets profiling output file

  • ? XSLTProcessor::setParameter
  • XSLTProcessor::setSecurityPrefs ?
  • PHP Manual
  • XSLTProcessor
  • Sets profiling output file

XSLTProcessor::setProfiling

(PHP >= 5.3.0, PHP 7, PHP 8)

XSLTProcessor::setProfiling — Sets profiling output file

说明

public XSLTProcessor::setProfiling ( string|null $filename ) : bool

Sets the file to output profiling information when processing a stylesheet.

参数

filename

Path to the file to dump profiling information.

返回值

成功时返回 true， 或者在失败时返回 false。

范例

Example #1 Example profiling output

<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

The above code will produce the following information in the profiling file:

number               match                name      mode  Calls Tot 100us Avg

    0                   cd                                    2      3      1
    1           collection                                    1      1      1

                         Total                                3      4

User Contributed Notes

There are no user contributed notes for this page.


Set security preferences

  • ? XSLTProcessor::setProfiling
  • XSLTProcessor::transformToDoc ?
  • PHP Manual
  • XSLTProcessor
  • Set security preferences

XSLTProcessor::setSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::setSecurityPrefs — Set security preferences

说明

public XSLTProcessor::setSecurityPrefs ( int $preferences ) : int

Sets the security preferences.

参数

preferences

The new security preferences. The following constants can be ORed: XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK. Alternatively, XSL_SECPREF_NONE or XSL_SECPREF_DEFAULT can be passed.

返回值

Returns the old security preferences.

User Contributed Notes

There are no user contributed notes for this page.


Transform to a DOMDocument

  • ? XSLTProcessor::setSecurityPrefs
  • XSLTProcessor::transformToUri ?
  • PHP Manual
  • XSLTProcessor
  • Transform to a DOMDocument

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDoc — Transform to a DOMDocument

说明

public XSLTProcessor::transformToDoc ( object $document , string|null $returnClass = null ) : DOMDocument|false

Transforms the source node to a DOMDocument applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

参数

document

The node to be transformed.

返回值

The resulting DOMDocument or false on error.

范例

Example #1 Transforming to a DOMDocument

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

以上例程会输出：

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

参见

  • XSLTProcessor::transformToUri() - Transform to URI
  • XSLTProcessor::transformToXml() - Transform to XML

User Contributed Notes

franp at free dot fr 30-Aug-2006 05:16
In most cases if you expect XML (or XHTML) as output you better use transformToXML() directly. You gain better control over xsl:output attributes, notably omit-xml-declaration.

Instead of :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$dom = $proc->transformToDoc($xml);
echo $dom->saveXML();

do use :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$newXml = $proc->transformToXML($xml);
echo $newXml;

In the first case, <?xml version="1.0" encoding="utf-8"?> is added whatever you set the omit-xml-declaration while transformToXML() take the attribute into account.


Transform to URI

  • ? XSLTProcessor::transformToDoc
  • XSLTProcessor::transformToXml ?
  • PHP Manual
  • XSLTProcessor
  • Transform to URI

XSLTProcessor::transformToUri

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToUri — Transform to URI

说明

XSLTProcessor::transformToURI ( DOMDocument $doc , string $uri ) : int

Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

参数

doc

The document to transform.

uri

The target URI for the transformation.

返回值

Returns the number of bytes written or false if an error occurred.

范例

Example #1 Transforming to a HTML file

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

参见

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToXml() - Transform to XML

User Contributed Notes

jonbarnett at gmail dot com 13-Jul-2007 12:32
Sometimes you don't want to transform to a file, an XML string (because you're using text or html), or a DOMDocument.

To transform to standard output, you can use php://output

<?php
$proc->transformToURI($xml, 'php://output');
?>

To transform to a string (of HTML or text, instead of XML), you can use the above in conjunction with output buffering.
<?php
ob_start();
$proc->transformToURI($xml, 'php://output');
$outputString = ob_get_flush();
?>


Transform to XML

  • ? XSLTProcessor::transformToUri
  • 图形用户界面(GUI) 扩展 ?
  • PHP Manual
  • XSLTProcessor
  • Transform to XML

XSLTProcessor::transformToXml

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToXml — Transform to XML

说明

public XSLTProcessor::transformToXml ( object $document ) : string|false|null

Transforms the source node to a string applying the stylesheet given by the xsltprocessor::importStylesheet() method.

参数

document

The DOMDocument or SimpleXMLElement object to be transformed.

返回值

The result of the transformation as a string or false on error.

范例

Example #1 Transforming to a string

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo $proc->transformToXML($xml);

?>

以上例程会输出：

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

<h1>Fight for your mind</h1><h2>by Ben Harper - 1995</h2><hr>
<h1>Electric Ladyland</h1><h2>by Jimi Hendrix - 1997</h2><hr>

参见

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToUri() - Transform to URI

User Contributed Notes

Josef Hornych 04-Mar-2015 07:42
Note that the method's name is sort of deceiving, because it does not only output XML, but any string that is generated by the processor. It should rather be called transformToString. So if your output method is  "text/plain", for example, this is the way to receive the resulting string.
zweibieren at yahoo dot com 15-Sep-2010 11:15
Entities are omitted from the output with the code above.
The symptom was that &nbsp;
-- which should work with UTF-8 encoding --
did not even get to XSLTProcessor, let alone through it.
After too much hacking I discovered the simple fix:
set substituteEntities to true in the DOMDocument for the XSL file.
That is, replace the loading of the xsl document with

<?php
   $xsl = new DOMDocument;
   $xsl->substituteEntities = true;    // <===added line
   $xsl->load('collection.xsl');
?>

However, this fails when data entries have HTML entity references. (Some database entries may even contain user generated text.) libxml has the pedantic habit of throwing a FATAL error for any undefined entitiy. Solution: hide the entities so libxml doesn't see them.

<?php
function hideEntities($data) {
        return str_replace("&", "&amp;", $data);
}
?>

You could just add this to the example, but it is tidier to define a function to load data into a DOMDocument. This way you don't need entity declarations in catalog.xsl, either.

<?php
// Added function for  Example #1

/** Load an XML file and create a DOMDocument.
Handles arbitrary entities, even undefined ones.
*/
function fileToDOMDoc($filename) {
    $dom= new DOMDocument;
    $xmldata = file_get_contents($filename);
    $xmldata = str_replace("&", "&amp;", $xmldata);  // disguise &s going IN to loadXML()
    $dom->substituteEntities = true;  // collapse &s going OUT to transformToXML()
    $dom->loadXML($xmldata);
    return $dom;
}

// Compare with  Example #1 Transforming to a string

// Load the XML sources
$xml = fileToDOMDoc('collection.xml');
$xsl = fileToDOMDoc('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);

// transform $xml according to the stylesheet $xsl
echo $proc->transformToXML($xml); // transform the data
?>
michael dot weibel at tilllate dot com 03-Dec-2009 01:33
If you retrieve "false" from the transformToXML method, use libxml_get_last_error() or libxml_get_errors() to retrieve the errors.
Charlie Murder 29-Nov-2009 07:43
To prevent your xsl file from automatically prepending

<?xml version="1.0"?>

whilst keeping the output as xml, which is preferable for a validated strict xhtml file, rather specify output as

<xsl:output method="xml" omit-xml-declaration="yes" />
john 05-Feb-2008 11:09
If your xsl doesn't have <html> tags. The output will contain <?xml version="1.0"?>. To fix this you can add the following to your xsl stylesheet:

<xsl:output
method="html" />
smubldg4 at hotmail dot com 02-Oct-2007 08:58
How to fix:: *Fatal error: Call to undefined method domdocument::load()*

If you get this error, visit the php.ini file and try commenting out the following, like this:

;[PHP_DOMXML]
;extension=php_domxml.dll

Suddenly, the wonderfully simple example above works as advertised.
jeandenis dot boivin at gmail dot com 13-Mar-2007 04:59
$domTranObj = $xslProcessor->transformToDoc($domXmlObj);
$domHtmlText = $domTranObj->saveHTML();

Do fix the <meta> for valid XHTML but do not correctly end empty node like <br /> which ouput like this : <br></br>

Some browser note this as 2 different <br /> ...

To fix this use

$domTranObj = $xslProcessor->transformToDoc($domXmlObj);
$domHtmlText = $domTranObj->saveXML();
Thomas Praxl 22-Jan-2007 01:36
I noticed an incompatibility between libxslt (php4) and the transformation through XSLTProcessor.
Php5 and the XSLTProcessor seem to add implicit CDATA-Section-Elements.
If you have an xslt like

<script type="text/javascript">
foo('<xsl:value-of select="bar" />');
</script>

It will result in

<script type="text/javascript"><![CDATA[
foo('xpath-result-of-bar');
]]></script>

(at least for output method="xml" in order to produce strict xhtml with xslt1)

That brings up an error (at least) in Firefox 1.5 as it is no valid javascript.
It should look like that:

<script type="text/javascript">//<![CDATA[
foo('xpath-result-of-bar');
]]></script>

As the CDATA-Section is implicit, I was not able to disable the output or to put a '//' before it.

I tried everything about xsl:text disable-output-escaping="yes"

I also tried to disable implicit adding of CDATA with <output cdata-section-elements="" />
(I thought that would exclude script-tags. It didn't).

The solution:

<xsl:text disable-output-escaping="yes">&lt;script type="text/javascript"&gt;
  foo('</xsl:text><xsl:value-of select="bar" /><xsl:text disable-output-escaping="yes">');
            &lt;/script&gt;</xsl:text>

Simple, but it took me a while.
werner@mollentze 15-Aug-2006 01:53
The transformToXML function can produce valid XHTML output - it honours the <xsl:output> element's attributes, which defines the format of the output document.

For instance, if you want valid XHTML 1.0 Strict output, you can provide the following attribute values for the <xsl:output> element in your XSL stylesheet:

<xsl:output
method="xml"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" />
lsoethout at hotmail dot com 19-Feb-2006 02:35
The function transformToXML has a problem with the meta content type tag. It outputs it like this:

    <meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312">

which is not correct X(HT)ML, because it closes with '>' instead of with '/>'.

A way to get the output correct is to use instead of transformToXML first transformToDoc anf then saveHTML:

    $domTranObj = $xslProcessor->transformToDoc($domXmlObj);
    $domHtmlText = $domTranObj->saveHTML();
jlipps at mac 06-Jan-2005 08:05
transformToXML, if you have registered PHP functions previously, does indeed attempt to execute these functions when it finds them in a php:function() pseudo-XSL function. It even finds static functions within classes, for instance:

<xsl:value-of select="php:function('MyClass::MyFunction', string(@attr), string(.))" disable-output-escaping="yes"/>

However, in this situation transformToXML does not try to execute "MyClass::MyFunction()". Instead, it executes "myclass:myfunction()". In PHP, since classes and functions are (I think) case-insensitive, this causes no problems.

A problem arises when you are combining these features with the __autoload() feature. So, say I have MyClass.php which contains the MyFunction definition. Generally, if I call MyClass::MyFunction, PHP will pass "MyClass" to __autoload(), and __autoload() will open up "MyClass.php".

What we have just seen, however, means that transformToXML will pass "myclass" to __autoload(), not "MyClass", with the consequence that PHP will try to open "myclass.php", which doesn't exist, instead of "MyClass.php", which does. On case-insensitive operating systems, this is not significant, but on my RedHat server, it is--PHP will give a file not found error.

The only solution I have found is to edit the __autoload() function to look for class names which are used in my XSL files, and manually change them to the correct casing.

Another solution, obviously, is to use all-lowercase class and file names.


图形用户界面(GUI) 扩展

  • UI
    • 简介
    • 安装／配置
    • UI\Point — Represents a position (x,y)
    • UI\Size — Represents dimenstions (width, height)
    • UI\Window — Window
    • UI\Control — Control
    • UI\Menu — Menu
    • UI\MenuItem — Menu Item
    • UI\Area — Area
    • UI\Executor — Execution Scheduler
    • UI\Controls\Tab — Tab Control
    • UI\Controls\Check — Check Control
    • UI\Controls\Button — Button Control
    • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\Label — Label Control
    • UI\Controls\Entry — Entry Control
    • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\Spin — Spin Control
    • UI\Controls\Slider — Slider Control
    • UI\Controls\Progress — Progress Control
    • UI\Controls\Separator — Control Separator
    • UI\Controls\Combo — Combo Control
    • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\Radio — Radio Control
    • UI\Controls\Picker — Picker Control
    • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Box — Control Box (Arrangement)
    • UI\Draw\Pen — Draw Pen
    • UI\Draw\Path — Draw Path
    • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Color — Color Representation
    • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Brush — Brushes
    • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI 函数
    • UI\Draw\Text\Font\Weight — Font Weight Settings
    • UI\Draw\Text\Font\Italic — Italic Font Settings
    • UI\Draw\Text\Font\Stretch — Font Stretch Settings
    • UI\Draw\Line\Cap — Line Cap Settings
    • UI\Draw\Line\Join — Line Join Settings
    • UI\Key — Key Identifiers
    • UI\Exception\InvalidArgumentException — InvalidArgumentException
    • UI\Exception\RuntimeException — RuntimeException

User Contributed Notes

There are no user contributed notes for this page.


UI

  • 简介
  • 安装／配置
    • 需求
    • 安装
  • UI\Point — Represents a position (x,y)
    • UI\Point::at — Size Coercion
    • UI\Point::__construct — Construct a new Point
    • UI\Point::getX — Retrieves X
    • UI\Point::getY — Retrieves Y
    • UI\Point::setX — Set X
    • UI\Point::setY — Set Y
  • UI\Size — Represents dimenstions (width, height)
    • UI\Size::__construct — Construct a new Size
    • UI\Size::getHeight — Retrieves Height
    • UI\Size::getWidth — Retrives Width
    • UI\Size::of — Point Coercion
    • UI\Size::setHeight — Set Height
    • UI\Size::setWidth — Set Width
  • UI\Window — Window
    • UI\Window::add — Add a Control
    • UI\Window::__construct — Construct a new Window
    • UI\Window::error — Show Error Box
    • UI\Window::getSize — Get Window Size
    • UI\Window::getTitle — Get Title
    • UI\Window::hasBorders — Border Detection
    • UI\Window::hasMargin — Margin Detection
    • UI\Window::isFullScreen — Full Screen Detection
    • UI\Window::msg — Show Message Box
    • UI\Window::onClosing — Closing Callback
    • UI\Window::open — Open Dialog
    • UI\Window::save — Save Dialog
    • UI\Window::setBorders — Border Use
    • UI\Window::setFullScreen — Full Screen Use
    • UI\Window::setMargin — Margin Use
    • UI\Window::setSize — Set Size
    • UI\Window::setTitle — Window Title
  • UI\Control — Control
    • UI\Control::destroy — Destroy Control
    • UI\Control::disable — Disable Control
    • UI\Control::enable — Enable Control
    • UI\Control::getParent — Get Parent Control
    • UI\Control::getTopLevel — Get Top Level
    • UI\Control::hide — Hide Control
    • UI\Control::isEnabled — Determine if Control is enabled
    • UI\Control::isVisible — Determine if Control is visible
    • UI\Control::setParent — Set Parent Control
    • UI\Control::show — Control Show
  • UI\Menu — Menu
    • UI\Menu::append — Append Menu Item
    • UI\Menu::appendAbout — Append About Menu Item
    • UI\Menu::appendCheck — Append Checkable Menu Item
    • UI\Menu::appendPreferences — Append Preferences Menu Item
    • UI\Menu::appendQuit — Append Quit Menu Item
    • UI\Menu::appendSeparator — Append Menu Item Separator
    • UI\Menu::__construct — Construct a new Menu
  • UI\MenuItem — Menu Item
    • UI\MenuItem::disable — Disable Menu Item
    • UI\MenuItem::enable — Enable Menu Item
    • UI\MenuItem::isChecked — Detect Checked
    • UI\MenuItem::onClick — On Click Callback
    • UI\MenuItem::setChecked — Set Checked
  • UI\Area — Area
    • UI\Area::onDraw — Draw Callback
    • UI\Area::onKey — Key Callback
    • UI\Area::onMouse — Mouse Callback
    • UI\Area::redraw — Redraw Area
    • UI\Area::scrollTo — Area Scroll
    • UI\Area::setSize — Set Size
  • UI\Executor — Execution Scheduler
    • UI\Executor::__construct — Construct a new Executor
    • UI\Executor::kill — Stop Executor
    • UI\Executor::onExecute — Execution Callback
    • UI\Executor::setInterval — Interval Manipulation
  • UI\Controls\Tab — Tab Control
    • UI\Controls\Tab::append — Append Page
    • UI\Controls\Tab::delete — Delete Page
    • UI\Controls\Tab::hasMargin — Margin Detection
    • UI\Controls\Tab::insertAt — Insert Page
    • UI\Controls\Tab::pages — Page Count
    • UI\Controls\Tab::setMargin — Set Margin
  • UI\Controls\Check — Check Control
    • UI\Controls\Check::__construct — Construct a new Check
    • UI\Controls\Check::getText — Get Text
    • UI\Controls\Check::isChecked — Checked Detection
    • UI\Controls\Check::onToggle — Toggle Callback
    • UI\Controls\Check::setChecked — Set Checked
    • UI\Controls\Check::setText — Set Text
  • UI\Controls\Button — Button Control
    • UI\Controls\Button::__construct — Construct a new Button
    • UI\Controls\Button::getText — Get Text
    • UI\Controls\Button::onClick — Click Handler
    • UI\Controls\Button::setText — Set Text
  • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\ColorButton::getColor — Get Color
    • UI\Controls\ColorButton::onChange — Change Handler
    • UI\Controls\ColorButton::setColor — Set Color
  • UI\Controls\Label — Label Control
    • UI\Controls\Label::__construct — Construct a new Label
    • UI\Controls\Label::getText — Get Text
    • UI\Controls\Label::setText — Set Text
  • UI\Controls\Entry — Entry Control
    • UI\Controls\Entry::__construct — Construct a new Entry
    • UI\Controls\Entry::getText — Get Text
    • UI\Controls\Entry::isReadOnly — Detect Read Only
    • UI\Controls\Entry::onChange — Change Handler
    • UI\Controls\Entry::setReadOnly — Set Read Only
    • UI\Controls\Entry::setText — Set Text
  • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\MultilineEntry::append — Append Text
    • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
    • UI\Controls\MultilineEntry::getText — Get Text
    • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
    • UI\Controls\MultilineEntry::onChange — Change Handler
    • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
    • UI\Controls\MultilineEntry::setText — Set Text
  • UI\Controls\Spin — Spin Control
    • UI\Controls\Spin::__construct — Construct a new Spin
    • UI\Controls\Spin::getValue — Get Value
    • UI\Controls\Spin::onChange — Change Handler
    • UI\Controls\Spin::setValue — Set Value
  • UI\Controls\Slider — Slider Control
    • UI\Controls\Slider::__construct — Construct a new Slider
    • UI\Controls\Slider::getValue — Get Value
    • UI\Controls\Slider::onChange — Change Handler
    • UI\Controls\Slider::setValue — Set Value
  • UI\Controls\Progress — Progress Control
    • UI\Controls\Progress::getValue — Get Value
    • UI\Controls\Progress::setValue — Set Value
  • UI\Controls\Separator — Control Separator
    • UI\Controls\Separator::__construct — Construct a new Separator
  • UI\Controls\Combo — Combo Control
    • UI\Controls\Combo::append — Append Option
    • UI\Controls\Combo::getSelected — Get Selected Option
    • UI\Controls\Combo::onSelected — Selected Handler
    • UI\Controls\Combo::setSelected — Set Selected Option
  • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\EditableCombo::append — Append Option
    • UI\Controls\EditableCombo::getText — Get Text
    • UI\Controls\EditableCombo::onChange — Change Handler
    • UI\Controls\EditableCombo::setText — Set Text
  • UI\Controls\Radio — Radio Control
    • UI\Controls\Radio::append — Append Option
    • UI\Controls\Radio::getSelected — Get Selected Option
    • UI\Controls\Radio::onSelected — Selected Handler
    • UI\Controls\Radio::setSelected — Set Selected Option
  • UI\Controls\Picker — Picker Control
    • UI\Controls\Picker::__construct — Construct a new Picker
  • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Form::append — Append Control
    • UI\Controls\Form::delete — Delete Control
    • UI\Controls\Form::isPadded — Padding Detection
    • UI\Controls\Form::setPadded — Set Padding
  • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Grid::append — Append Control
    • UI\Controls\Grid::isPadded — Padding Detection
    • UI\Controls\Grid::setPadded — Set Padding
  • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Group::append — Append Control
    • UI\Controls\Group::__construct — Construct a new Group
    • UI\Controls\Group::getTitle — Get Title
    • UI\Controls\Group::hasMargin — Margin Detection
    • UI\Controls\Group::setMargin — Set Margin
    • UI\Controls\Group::setTitle — Set Title
  • UI\Controls\Box — Control Box (Arrangement)
    • UI\Controls\Box::append — Append Control
    • UI\Controls\Box::__construct — Construct a new Box
    • UI\Controls\Box::delete — Delete Control
    • UI\Controls\Box::getOrientation — Get Orientation
    • UI\Controls\Box::isPadded — Padding Detection
    • UI\Controls\Box::setPadded — Set Padding
  • UI\Draw\Pen — Draw Pen
    • UI\Draw\Pen::clip — Clip a Path
    • UI\Draw\Pen::fill — Fill a Path
    • UI\Draw\Pen::restore — Restore
    • UI\Draw\Pen::save — Save
    • UI\Draw\Pen::stroke — Stroke a Path
    • UI\Draw\Pen::transform — Matrix Transform
    • UI\Draw\Pen::write — Draw Text at Point
  • UI\Draw\Path — Draw Path
    • UI\Draw\Path::addRectangle — Draw a Rectangle
    • UI\Draw\Path::arcTo — Draw an Arc
    • UI\Draw\Path::bezierTo — Draw Bezier Curve
    • UI\Draw\Path::closeFigure — Close Figure
    • UI\Draw\Path::__construct — Construct a new Path
    • UI\Draw\Path::end — Finalize Path
    • UI\Draw\Path::lineTo — Draw a Line
    • UI\Draw\Path::newFigure — Draw Figure
    • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc
  • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Matrix::invert — Invert Matrix
    • UI\Draw\Matrix::isInvertible — Invertible Detection
    • UI\Draw\Matrix::multiply — Multiply Matrix
    • UI\Draw\Matrix::rotate — Rotate Matrix
    • UI\Draw\Matrix::scale — Scale Matrix
    • UI\Draw\Matrix::skew — Skew Matrix
    • UI\Draw\Matrix::translate — Translate Matrix
  • UI\Draw\Color — Color Representation
    • UI\Draw\Color::__construct — Construct new Color
    • UI\Draw\Color::getChannel — Color Manipulation
    • UI\Draw\Color::setChannel — Color Manipulation
  • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Stroke::__construct — Construct a new Stroke
    • UI\Draw\Stroke::getCap — Get Line Cap
    • UI\Draw\Stroke::getJoin — Get Line Join
    • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
    • UI\Draw\Stroke::getThickness — Get Thickness
    • UI\Draw\Stroke::setCap — Set Line Cap
    • UI\Draw\Stroke::setJoin — Set Line Join
    • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
    • UI\Draw\Stroke::setThickness — Set Thickness
  • UI\Draw\Brush — Brushes
    • UI\Draw\Brush::__construct — Construct a new Brush
    • UI\Draw\Brush::getColor — Get Color
    • UI\Draw\Brush::setColor — Set Color
  • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop — Stop Manipulation
  • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient
  • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient
  • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
    • UI\Draw\Text\Layout::setColor — Set Color
    • UI\Draw\Text\Layout::setWidth — Set Width
  • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font::__construct — Construct a new Font
    • UI\Draw\Text\Font::getAscent — Font Metrics
    • UI\Draw\Text\Font::getDescent — Font Metrics
    • UI\Draw\Text\Font::getLeading — Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics
  • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
    • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection
  • UI 函数
    • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
    • UI\quit — Quit UI Loop
    • UI\run — Enter UI Loop
  • UI\Draw\Text\Font\Weight — Font Weight Settings
  • UI\Draw\Text\Font\Italic — Italic Font Settings
  • UI\Draw\Text\Font\Stretch — Font Stretch Settings
  • UI\Draw\Line\Cap — Line Cap Settings
  • UI\Draw\Line\Join — Line Join Settings
  • UI\Key — Key Identifiers
  • UI\Exception\InvalidArgumentException — InvalidArgumentException
  • UI\Exception\RuntimeException — RuntimeException

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension wraps libui to provide an OO API for the cross platform development of native look-and-feel user interfaces .

User Contributed Notes

There are no user contributed notes for this page.


安装／配置

Table of Contents

  • 需求
  • 安装

User Contributed Notes

shevegen at gmail dot com 14-Feb-2021 09:01
I believe this example is not correct; for example it shows "cmake" in
use but after you git clone the above URL, there are no cmake files.

So this can not possibly have worked; and I actually don't think there
ever was cmake used in the above repository, which makes you wonder
why the above code used cmake to begin with. Did it ever work? I am not sure;
I tend to assume it did not work.
whirlwind110 at 163 dot com 18-Apr-2017 04:04
Requirements:
    PHP 7
    libui (use current master)
    Windows/MacOSX/Linux (GTK-3)

Install re2c:
    sudo apt install re2c

Install libui:

    git clone https://github.com/andlabs/libui.git
    cd libui
    sudo cp *.h /usr/local/include/
    cmake .
    cd out
    sudo cp * /usr/lib/

Install ui:

    Method one: use pecl:
        sudo pecl install channel://pecl.php.net/ui-2.0.0

    Method two:build source code:
        git clone https://github.com/krakjoe/ui.git
        cd ui
        phpize
        make
        sudo make install

Enable ui.so:
    sudo echo 'extension=ui.so' > /etc/php/7.0/mods-available/ui.ini
    sudo ln -s /etc/php/7.0/mods-available/ui.ini 20-ui.ini

Test:
    php -m
    git clone https://github.com/krakjoe/ui.git
    cd ui/examples/
    php snake.php


需求

Installation requires the libui library, and PHP 7 or newer.

This extension requires the » libui library version 0.1.0 or higher to be installed. See the libui documentation for a list of prerequisites.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/ui.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


Represents a position (x,y)

(UI 0.9.9)

简介

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

类摘要

final UI\Point {
/* 属性 */
public $x ;
public $y ;
/* Constructor */
public __construct ( float $x , float $y )
/* 方法 */
public static at ( float $point ) : UI\Point
public static at ( UI\Size $size ) : UI\Point
public getX ( ) : float
public getY ( ) : float
public setX ( float $point )
public setY ( float $point )
}

属性

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Table of Contents

  • UI\Point::at — Size Coercion
  • UI\Point::__construct — Construct a new Point
  • UI\Point::getX — Retrieves X
  • UI\Point::getY — Retrieves Y
  • UI\Point::setX — Set X
  • UI\Point::setY — Set Y

User Contributed Notes

There are no user contributed notes for this page.


Size Coercion

  • ? UI\Point
  • UI\Point::__construct ?
  • PHP Manual
  • UI\Point
  • Size Coercion

UI\Point::at

(UI 1.0.2)

UI\Point::at — Size Coercion

说明

public static UI\Point::at ( float $point ) : UI\Point
public static UI\Point::at ( UI\Size $size ) : UI\Point

Shall return a UI\Point object where x and y are equal to those supplied, either in float or UI\Size form

参数

point

The value for x and y

size

The Size to convert

返回值

The resulting Point

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Point

  • ? UI\Point::at
  • UI\Point::getX ?
  • PHP Manual
  • UI\Point
  • Construct a new Point

UI\Point::__construct

(UI 0.9.9)

UI\Point::__construct — Construct a new Point

说明

public UI\Point::__construct ( float $x , float $y )

Construct a new Point using new co-ordinates

参数

x

The new X co-ordinate

y

The new Y co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Retrieves X

  • ? UI\Point::__construct
  • UI\Point::getY ?
  • PHP Manual
  • UI\Point
  • Retrieves X

UI\Point::getX

(UI 0.9.9)

UI\Point::getX — Retrieves X

说明

public UI\Point::getX ( ) : float

Retrieves the X co-ordinate

参数

此函数没有参数。

返回值

The current X co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Retrieves Y

  • ? UI\Point::getX
  • UI\Point::setX ?
  • PHP Manual
  • UI\Point
  • Retrieves Y

UI\Point::getY

(UI 0.9.9)

UI\Point::getY — Retrieves Y

说明

public UI\Point::getY ( ) : float

Retrieves the Y co-ordinate

参数

此函数没有参数。

返回值

The current Y co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Set X

  • ? UI\Point::getY
  • UI\Point::setY ?
  • PHP Manual
  • UI\Point
  • Set X

UI\Point::setX

(UI 0.9.9)

UI\Point::setX — Set X

说明

public UI\Point::setX ( float $point )

Set the X co-ordinate

参数

point

The new X co-ordinate

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set Y

  • ? UI\Point::setX
  • UI\Size ?
  • PHP Manual
  • UI\Point
  • Set Y

UI\Point::setY

(UI 0.9.9)

UI\Point::setY — Set Y

说明

public UI\Point::setY ( float $point )

Set the Y co-ordinate

参数

point

The new Y co-ordinate

返回值

User Contributed Notes

There are no user contributed notes for this page.


Represents dimenstions (width, height)

(UI 0.9.9)

简介

Sizes are used throughout UI to represent the size of a screen, control, or area.

类摘要

final UI\Size {
/* 属性 */
public $width ;
public $height ;
/* Constructor */
public __construct ( float $width , float $height )
/* 方法 */
public getHeight ( ) : float
public getWidth ( ) : float
public static of ( float $size ) : UI\Size
public static of ( UI\Point $point ) : UI\Size
public setHeight ( float $size )
public setWidth ( float $size )
}

属性

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Table of Contents

  • UI\Size::__construct — Construct a new Size
  • UI\Size::getHeight — Retrieves Height
  • UI\Size::getWidth — Retrives Width
  • UI\Size::of — Point Coercion
  • UI\Size::setHeight — Set Height
  • UI\Size::setWidth — Set Width

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Size

  • ? UI\Size
  • UI\Size::getHeight ?
  • PHP Manual
  • UI\Size
  • Construct a new Size

UI\Size::__construct

(UI 0.9.9)

UI\Size::__construct — Construct a new Size

说明

public UI\Size::__construct ( float $width , float $height )

Construct a new Size using new width and height

参数

width

The new width

height

The new height

User Contributed Notes

There are no user contributed notes for this page.


Retrieves Height

  • ? UI\Size::__construct
  • UI\Size::getWidth ?
  • PHP Manual
  • UI\Size
  • Retrieves Height

UI\Size::getHeight

(UI 0.9.9)

UI\Size::getHeight — Retrieves Height

说明

public UI\Size::getHeight ( ) : float

Retrieves the Height

参数

此函数没有参数。

返回值

The current Height

User Contributed Notes

There are no user contributed notes for this page.


Retrives Width

  • ? UI\Size::getHeight
  • UI\Size::of ?
  • PHP Manual
  • UI\Size
  • Retrives Width

UI\Size::getWidth

(UI 0.9.9)

UI\Size::getWidth — Retrives Width

说明

public UI\Size::getWidth ( ) : float

Retrieves the Width

参数

此函数没有参数。

返回值

The current Width

User Contributed Notes

There are no user contributed notes for this page.


Point Coercion

  • ? UI\Size::getWidth
  • UI\Size::setHeight ?
  • PHP Manual
  • UI\Size
  • Point Coercion

UI\Size::of

(UI 1.0.2)

UI\Size::of — Point Coercion

说明

public static UI\Size::of ( float $size ) : UI\Size
public static UI\Size::of ( UI\Point $point ) : UI\Size

Shall return a UI\Size object where width and height are equal to those supplied, either in float or UI\Point form

参数

size

The value for width and height

point

The Point to convert

返回值

The resulting Size

User Contributed Notes

There are no user contributed notes for this page.


Set Height

  • ? UI\Size::of
  • UI\Size::setWidth ?
  • PHP Manual
  • UI\Size
  • Set Height

UI\Size::setHeight

(UI 0.9.9)

UI\Size::setHeight — Set Height

说明

public UI\Size::setHeight ( float $size )

Set new Height

参数

size

The new Height

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set Width

  • ? UI\Size::setHeight
  • UI\Window ?
  • PHP Manual
  • UI\Size
  • Set Width

UI\Size::setWidth

(UI 0.9.9)

UI\Size::setWidth — Set Width

说明

public UI\Size::setWidth ( float $size )

Set new Width

参数

size

The new Width

返回值

User Contributed Notes

There are no user contributed notes for this page.


Window

(UI 0.9.9)

简介

Represents a UI Window

类摘要

UI\Window extends UI\Control {
/* 属性 */
protected $controls ;
/* Constructor */
public __construct ( string $title , Size $size , bool $menu = false )
/* 方法 */
public add ( UI\Control $control )
public error ( string $title , string $msg )
public getSize ( ) : UI\Size
public getTitle ( ) : string
public hasBorders ( ) : bool
public hasMargin ( ) : bool
public isFullScreen ( ) : bool
public msg ( string $title , string $msg )
protected onClosing ( ) : int
public open ( ) : string
public save ( ) : string
public setBorders ( bool $borders )
public setFullScreen ( bool $full )
public setMargin ( bool $margin )
public setSize ( UI\Size $size )
public setTitle ( string $title )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

属性

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Window::add — Add a Control
  • UI\Window::__construct — Construct a new Window
  • UI\Window::error — Show Error Box
  • UI\Window::getSize — Get Window Size
  • UI\Window::getTitle — Get Title
  • UI\Window::hasBorders — Border Detection
  • UI\Window::hasMargin — Margin Detection
  • UI\Window::isFullScreen — Full Screen Detection
  • UI\Window::msg — Show Message Box
  • UI\Window::onClosing — Closing Callback
  • UI\Window::open — Open Dialog
  • UI\Window::save — Save Dialog
  • UI\Window::setBorders — Border Use
  • UI\Window::setFullScreen — Full Screen Use
  • UI\Window::setMargin — Margin Use
  • UI\Window::setSize — Set Size
  • UI\Window::setTitle — Window Title

User Contributed Notes

everton3x at gmail dot com 03-Feb-2017 12:58
This is a example to wizard layout in UI library:

<?php

/*
 * Wizard sample layout builded with PHP UI
 */

use UI\Window;
use UI\Size;
use UI\Controls\Button;
use UI\Controls\Grid;
use UI\Controls\Box;
use UI\Controls\Form;
use UI\Controls\Entry;
use UI\Controls\Label;

/*
 * The window
 */
$window = new Window('Wizard Sample Layout', new Size(640, 480), TRUE);
$window->setMargin(true);

/*
 * Wizard content (sample)
 */
$content = new Form();
$content->setPadded(true);
$content->append('User:', new Entry());
$content->append('Password:', new Entry(Entry::Password));

/*
 * Layout to title, content and buttons
 */
$grid = new Grid();
$grid->setPadded(false);

/*
 * Title
 */
$grid->append(new Label('Wizard Sample'), 0, 0, 6, 1, true, Grid::Fill, false, Grid::Fill);

/*
 * Append content
 */
$grid->append($content, 0, 1, 6, 1, false, Grid::Fill, true, Grid::Fill);

/*
 * Left buttons
 */
$left_box = new Box(Box::Horizontal);
$left_box->append(new Button('&About'));
$left_box->append(new Button('&Help'));

/*
 * Right buttons
 */
$right_box = new Box(Box::Horizontal);
$right_box->append(new Button('&Back'));
$right_box->append(new Button('&Forward'));
$right_box->append(new Button('&Close'));

/**
 * Append buttons
 */
$grid->append($left_box, 0, 2, 1, 1, true, Grid::Start, false, Grid::Fill);
$grid->append($right_box, 5, 2, 1, 1, true, Grid::End, false, Grid::Fill);

/*
 * Append layout and show.
 */
$window->add($grid);

$window->show();

UI\run();

?>


Add a Control

  • ? UI\Window
  • UI\Window::__construct ?
  • PHP Manual
  • UI\Window
  • Add a Control

UI\Window::add

(UI 0.9.9)

UI\Window::add — Add a Control

说明

public UI\Window::add ( UI\Control $control )

Shall add a Control to this Window

参数

control

The Control to add

返回值

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Window

  • ? UI\Window::add
  • UI\Window::error ?
  • PHP Manual
  • UI\Window
  • Construct a new Window

UI\Window::__construct

(UI 0.9.9)

UI\Window::__construct — Construct a new Window

说明

public UI\Window::__construct ( string $title , Size $size , bool $menu = false )

Shall construct a new Window

参数

title

The title of the Window

size

The size of the Window

menu

Menu switch

User Contributed Notes

There are no user contributed notes for this page.


Show Error Box

  • ? UI\Window::__construct
  • UI\Window::getSize ?
  • PHP Manual
  • UI\Window
  • Show Error Box

UI\Window::error

(UI 0.9.9)

UI\Window::error — Show Error Box

说明

public UI\Window::error ( string $title , string $msg )

Shall show an error box

参数

title

The title of the error box

msg

The message for the error box

User Contributed Notes

There are no user contributed notes for this page.


Get Window Size

  • ? UI\Window::error
  • UI\Window::getTitle ?
  • PHP Manual
  • UI\Window
  • Get Window Size

UI\Window::getSize

(UI 0.9.9)

UI\Window::getSize — Get Window Size

说明

public UI\Window::getSize ( ) : UI\Size

Shall return the size of this Window

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get Title

  • ? UI\Window::getSize
  • UI\Window::hasBorders ?
  • PHP Manual
  • UI\Window
  • Get Title

UI\Window::getTitle

(UI 0.9.9)

UI\Window::getTitle — Get Title

说明

public UI\Window::getTitle ( ) : string

Shall retrieve the title of this Window

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Border Detection

  • ? UI\Window::getTitle
  • UI\Window::hasMargin ?
  • PHP Manual
  • UI\Window
  • Border Detection

UI\Window::hasBorders

(UI 0.9.9)

UI\Window::hasBorders — Border Detection

说明

public UI\Window::hasBorders ( ) : bool

Shall detect if borders are used on this Window

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Margin Detection

  • ? UI\Window::hasBorders
  • UI\Window::isFullScreen ?
  • PHP Manual
  • UI\Window
  • Margin Detection

UI\Window::hasMargin

(UI 0.9.9)

UI\Window::hasMargin — Margin Detection

说明

public UI\Window::hasMargin ( ) : bool

Shall detect if margins are used on this Window

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Full Screen Detection

  • ? UI\Window::hasMargin
  • UI\Window::msg ?
  • PHP Manual
  • UI\Window
  • Full Screen Detection

UI\Window::isFullScreen

(UI 0.9.9)

UI\Window::isFullScreen — Full Screen Detection

说明

public UI\Window::isFullScreen ( ) : bool

Shall detect if this Window us using the whole screen

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Show Message Box

  • ? UI\Window::isFullScreen
  • UI\Window::onClosing ?
  • PHP Manual
  • UI\Window
  • Show Message Box

UI\Window::msg

(UI 0.9.9)

UI\Window::msg — Show Message Box

说明

public UI\Window::msg ( string $title , string $msg )

Shall show a message box

参数

title

The title of the message box

msg

The message

User Contributed Notes

There are no user contributed notes for this page.


Closing Callback

  • ? UI\Window::msg
  • UI\Window::open ?
  • PHP Manual
  • UI\Window
  • Closing Callback

UI\Window::onClosing

(UI 0.9.9)

UI\Window::onClosing — Closing Callback

说明

protected UI\Window::onClosing ( ) : int

Should gracefully destroy this Window

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Open Dialog

  • ? UI\Window::onClosing
  • UI\Window::save ?
  • PHP Manual
  • UI\Window
  • Open Dialog

UI\Window::open

(UI 0.9.9)

UI\Window::open — Open Dialog

说明

public UI\Window::open ( ) : string

Shall show an open file dialog

参数

此函数没有参数。

返回值

Returns the name of the file selected for opening

User Contributed Notes

There are no user contributed notes for this page.


Save Dialog

  • ? UI\Window::open
  • UI\Window::setBorders ?
  • PHP Manual
  • UI\Window
  • Save Dialog

UI\Window::save

(UI 0.9.9)

UI\Window::save — Save Dialog

说明

public UI\Window::save ( ) : string

Shall show a save dialog

参数

此函数没有参数。

返回值

Returns the file name selecting for saving

User Contributed Notes

There are no user contributed notes for this page.


Border Use

  • ? UI\Window::save
  • UI\Window::setFullScreen ?
  • PHP Manual
  • UI\Window
  • Border Use

UI\Window::setBorders

(UI 0.9.9)

UI\Window::setBorders — Border Use

说明

public UI\Window::setBorders ( bool $borders )

Shall enable or disable the use of borders on this Window

参数

borders

User Contributed Notes

There are no user contributed notes for this page.


Full Screen Use

  • ? UI\Window::setBorders
  • UI\Window::setMargin ?
  • PHP Manual
  • UI\Window
  • Full Screen Use

UI\Window::setFullScreen

(UI 0.9.9)

UI\Window::setFullScreen — Full Screen Use

说明

public UI\Window::setFullScreen ( bool $full )

Shall enable or disable the use of the full screen for this Window

Warning

本函数还未编写文档，仅有参数列表。

参数

full

User Contributed Notes

There are no user contributed notes for this page.


Margin Use

  • ? UI\Window::setFullScreen
  • UI\Window::setSize ?
  • PHP Manual
  • UI\Window
  • Margin Use

UI\Window::setMargin

(UI 0.9.9)

UI\Window::setMargin — Margin Use

说明

public UI\Window::setMargin ( bool $margin )

Shall enable or disable the use of margins for this Window

参数

margin

User Contributed Notes

There are no user contributed notes for this page.


Set Size

  • ? UI\Window::setMargin
  • UI\Window::setTitle ?
  • PHP Manual
  • UI\Window
  • Set Size

UI\Window::setSize

(UI 0.9.9)

UI\Window::setSize — Set Size

说明

public UI\Window::setSize ( UI\Size $size )

Shall set the size of this Window

参数

size

返回值

User Contributed Notes

There are no user contributed notes for this page.


Window Title

  • ? UI\Window::setSize
  • UI\Control ?
  • PHP Manual
  • UI\Window
  • Window Title

UI\Window::setTitle

(UI 0.9.9)

UI\Window::setTitle — Window Title

说明

public UI\Window::setTitle ( string $title )

Shall set the title for this Window

参数

title

The new title

User Contributed Notes

There are no user contributed notes for this page.


Control

(UI 0.9.9)

简介

This is the closed base class for all UI Controls.

类摘要

final UI\Control {
/* 方法 */
public destroy ( )
public disable ( )
public enable ( )
public getParent ( ) : UI\Control
public getTopLevel ( ) : int
public hide ( )
public isEnabled ( ) : bool
public isVisible ( ) : bool
public setParent ( UI\Control $parent )
public show ( )
}

Table of Contents

  • UI\Control::destroy — Destroy Control
  • UI\Control::disable — Disable Control
  • UI\Control::enable — Enable Control
  • UI\Control::getParent — Get Parent Control
  • UI\Control::getTopLevel — Get Top Level
  • UI\Control::hide — Hide Control
  • UI\Control::isEnabled — Determine if Control is enabled
  • UI\Control::isVisible — Determine if Control is visible
  • UI\Control::setParent — Set Parent Control
  • UI\Control::show — Control Show

User Contributed Notes

There are no user contributed notes for this page.


Destroy Control

  • ? UI\Control
  • UI\Control::disable ?
  • PHP Manual
  • UI\Control
  • Destroy Control

UI\Control::destroy

(UI 0.9.9)

UI\Control::destroy — Destroy Control

说明

public UI\Control::destroy ( )

Shall destroy this Control

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Disable Control

  • ? UI\Control::destroy
  • UI\Control::enable ?
  • PHP Manual
  • UI\Control
  • Disable Control

UI\Control::disable

(UI 0.9.9)

UI\Control::disable — Disable Control

说明

public UI\Control::disable ( )

Shall disable this Control

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Enable Control

  • ? UI\Control::disable
  • UI\Control::getParent ?
  • PHP Manual
  • UI\Control
  • Enable Control

UI\Control::enable

(UI 0.9.9)

UI\Control::enable — Enable Control

说明

public UI\Control::enable ( )

Shall enable this Control

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get Parent Control

  • ? UI\Control::enable
  • UI\Control::getTopLevel ?
  • PHP Manual
  • UI\Control
  • Get Parent Control

UI\Control::getParent

(UI 0.9.9)

UI\Control::getParent — Get Parent Control

说明

public UI\Control::getParent ( ) : UI\Control

Shall return the parent Control

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get Top Level

  • ? UI\Control::getParent
  • UI\Control::hide ?
  • PHP Manual
  • UI\Control
  • Get Top Level

UI\Control::getTopLevel

(UI 0.9.9)

UI\Control::getTopLevel — Get Top Level

说明

public UI\Control::getTopLevel ( ) : int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Hide Control

  • ? UI\Control::getTopLevel
  • UI\Control::isEnabled ?
  • PHP Manual
  • UI\Control
  • Hide Control

UI\Control::hide

(UI 0.9.9)

UI\Control::hide — Hide Control

说明

public UI\Control::hide ( )

Shall hide this Control

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Determine if Control is enabled

  • ? UI\Control::hide
  • UI\Control::isVisible ?
  • PHP Manual
  • UI\Control
  • Determine if Control is enabled

UI\Control::isEnabled

(UI 0.9.9)

UI\Control::isEnabled — Determine if Control is enabled

说明

public UI\Control::isEnabled ( ) : bool

Shall detect if this Control is enabled

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Determine if Control is visible

  • ? UI\Control::isEnabled
  • UI\Control::setParent ?
  • PHP Manual
  • UI\Control
  • Determine if Control is visible

UI\Control::isVisible

(UI 0.9.9)

UI\Control::isVisible — Determine if Control is visible

说明

public UI\Control::isVisible ( ) : bool

Shall detect if this Control is visible

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set Parent Control

  • ? UI\Control::isVisible
  • UI\Control::show ?
  • PHP Manual
  • UI\Control
  • Set Parent Control

UI\Control::setParent

(UI 0.9.9)

UI\Control::setParent — Set Parent Control

说明

public UI\Control::setParent ( UI\Control $parent )

Shall set the parent Control of this Control

参数

parent

The parent Control

返回值

User Contributed Notes

There are no user contributed notes for this page.


Control Show

  • ? UI\Control::setParent
  • UI\Menu ?
  • PHP Manual
  • UI\Control
  • Control Show

UI\Control::show

(UI 0.9.9)

UI\Control::show — Control Show

说明

public UI\Control::show ( )

Shall show this Control

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Menu

(UI 0.9.9)

简介

Menus must be constructed before the first Window, and can be shown on any Window

类摘要

UI\Menu {
/* Constructor */
public __construct ( string $name )
/* 方法 */
public append ( string $name , string $type = UI\MenuItem::class ) : UI\MenuItem
public appendAbout ( string $type = UI\MenuItem::class ) : UI\MenuItem
public appendCheck ( string $name , string $type = UI\MenuItem::class ) : UI\MenuItem
public appendPreferences ( string $type = UI\MenuItem::class ) : UI\MenuItem
public appendQuit ( string $type = UI\MenuItem::class ) : UI\MenuItem
public appendSeparator ( )
}

Table of Contents

  • UI\Menu::append — Append Menu Item
  • UI\Menu::appendAbout — Append About Menu Item
  • UI\Menu::appendCheck — Append Checkable Menu Item
  • UI\Menu::appendPreferences — Append Preferences Menu Item
  • UI\Menu::appendQuit — Append Quit Menu Item
  • UI\Menu::appendSeparator — Append Menu Item Separator
  • UI\Menu::__construct — Construct a new Menu

User Contributed Notes

There are no user contributed notes for this page.


Append Menu Item

  • ? UI\Menu
  • UI\Menu::appendAbout ?
  • PHP Manual
  • UI\Menu
  • Append Menu Item

UI\Menu::append

(UI 0.9.9)

UI\Menu::append — Append Menu Item

说明

public UI\Menu::append ( string $name , string $type = UI\MenuItem::class ) : UI\MenuItem

Shall append a new Menu Item

参数

name

The name (text) for the new item

type

The type for the new item

返回值

A constructed object of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append About Menu Item

  • ? UI\Menu::append
  • UI\Menu::appendCheck ?
  • PHP Manual
  • UI\Menu
  • Append About Menu Item

UI\Menu::appendAbout

(UI 0.9.9)

UI\Menu::appendAbout — Append About Menu Item

说明

public UI\Menu::appendAbout ( string $type = UI\MenuItem::class ) : UI\MenuItem

Shall append an About menu item

参数

type

The type for the new item

返回值

A constructed About menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Checkable Menu Item

  • ? UI\Menu::appendAbout
  • UI\Menu::appendPreferences ?
  • PHP Manual
  • UI\Menu
  • Append Checkable Menu Item

UI\Menu::appendCheck

(UI 0.9.9)

UI\Menu::appendCheck — Append Checkable Menu Item

说明

public UI\Menu::appendCheck ( string $name , string $type = UI\MenuItem::class ) : UI\MenuItem

Shall append a checkable menu item

参数

name

The name (text) for the new item

type

The type for the new item

返回值

A constructed checkable menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Preferences Menu Item

  • ? UI\Menu::appendCheck
  • UI\Menu::appendQuit ?
  • PHP Manual
  • UI\Menu
  • Append Preferences Menu Item

UI\Menu::appendPreferences

(UI 0.9.9)

UI\Menu::appendPreferences — Append Preferences Menu Item

说明

public UI\Menu::appendPreferences ( string $type = UI\MenuItem::class ) : UI\MenuItem

Shall append a Preferences menu item

参数

type

The type for the new item

返回值

A constructed Preferences menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Quit Menu Item

  • ? UI\Menu::appendPreferences
  • UI\Menu::appendSeparator ?
  • PHP Manual
  • UI\Menu
  • Append Quit Menu Item

UI\Menu::appendQuit

(UI 0.9.9)

UI\Menu::appendQuit — Append Quit Menu Item

说明

public UI\Menu::appendQuit ( string $type = UI\MenuItem::class ) : UI\MenuItem

Shall append a Quit menu item

参数

type

The type for the new item

返回值

A constructed Quit menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Menu Item Separator

  • ? UI\Menu::appendQuit
  • UI\Menu::__construct ?
  • PHP Manual
  • UI\Menu
  • Append Menu Item Separator

UI\Menu::appendSeparator

(UI 0.9.9)

UI\Menu::appendSeparator — Append Menu Item Separator

说明

public UI\Menu::appendSeparator ( )

Shall append a separator

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Menu

  • ? UI\Menu::appendSeparator
  • UI\MenuItem ?
  • PHP Manual
  • UI\Menu
  • Construct a new Menu

UI\Menu::__construct

(UI 0.9.9)

UI\Menu::__construct — Construct a new Menu

说明

public UI\Menu::__construct ( string $name )

Shall construct a new Menu

参数

name

The name (text) for the menu

User Contributed Notes

There are no user contributed notes for this page.


Menu Item

(UI 0.9.9)

简介

Menu Items should only be created by the Menu

类摘要

UI\MenuItem {
/* 方法 */
public disable ( )
public enable ( )
public isChecked ( ) : bool
protected onClick ( )
public setChecked ( bool $checked )
}

Table of Contents

  • UI\MenuItem::disable — Disable Menu Item
  • UI\MenuItem::enable — Enable Menu Item
  • UI\MenuItem::isChecked — Detect Checked
  • UI\MenuItem::onClick — On Click Callback
  • UI\MenuItem::setChecked — Set Checked

User Contributed Notes

There are no user contributed notes for this page.


Disable Menu Item

  • ? UI\MenuItem
  • UI\MenuItem::enable ?
  • PHP Manual
  • UI\MenuItem
  • Disable Menu Item

UI\MenuItem::disable

(UI 0.9.9)

UI\MenuItem::disable — Disable Menu Item

说明

public UI\MenuItem::disable ( )

Shall disable this Menu Item

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Enable Menu Item

  • ? UI\MenuItem::disable
  • UI\MenuItem::isChecked ?
  • PHP Manual
  • UI\MenuItem
  • Enable Menu Item

UI\MenuItem::enable

(UI 0.9.9)

UI\MenuItem::enable — Enable Menu Item

说明

public UI\MenuItem::enable ( )

Shall enable this Menu Item

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Detect Checked

  • ? UI\MenuItem::enable
  • UI\MenuItem::onClick ?
  • PHP Manual
  • UI\MenuItem
  • Detect Checked

UI\MenuItem::isChecked

(UI 0.9.9)

UI\MenuItem::isChecked — Detect Checked

说明

public UI\MenuItem::isChecked ( ) : bool

Shall detect if this Menu Item is checked

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


On Click Callback

  • ? UI\MenuItem::isChecked
  • UI\MenuItem::setChecked ?
  • PHP Manual
  • UI\MenuItem
  • On Click Callback

UI\MenuItem::onClick

(UI 0.9.9)

UI\MenuItem::onClick — On Click Callback

说明

protected UI\MenuItem::onClick ( )

Shall be executed when this Menu Item is clicked

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Checked

  • ? UI\MenuItem::onClick
  • UI\Area ?
  • PHP Manual
  • UI\MenuItem
  • Set Checked

UI\MenuItem::setChecked

(UI 0.9.9)

UI\MenuItem::setChecked — Set Checked

说明

public UI\MenuItem::setChecked ( bool $checked )

Shall set the checked status of this Menu Item

参数

checked

The new status

User Contributed Notes

There are no user contributed notes for this page.


Area

(UI 0.9.9)

简介

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

类摘要

UI\Area extends UI\Control {
/* Constants */
const int Ctrl ;
const int Alt ;
const int Shift ;
const int Super ;
const int Down ;
const int Up ;
/* 方法 */
protected onDraw ( UI\Draw\Pen $pen , UI\Size $areaSize , UI\Point $clipPoint , UI\Size $clipSize )
protected onKey ( string $key , int $ext , int $flags )
protected onMouse ( UI\Point $areaPoint , UI\Size $areaSize , int $flags )
public redraw ( )
public scrollTo ( UI\Point $point , UI\Size $size )
public setSize ( UI\Size $size )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

预定义常量

UI\Area::Ctrl

Shall be set in the modifiers passed to key and mouse events when the CTRL key is active

UI\Area::Alt

Shall be set in the modifiers passed to key and mouse events when the ALT key is active

UI\Area::Shift

Shall be set in the modifiers passed to key and mouse events when the SHIFT key is active

UI\Area::Super

UI\Area::Down

Shall be set in the modifiers passed to key and mouse events

UI\Area::Up

Shall be set in the modifiers passed to key and mouse events

Table of Contents

  • UI\Area::onDraw — Draw Callback
  • UI\Area::onKey — Key Callback
  • UI\Area::onMouse — Mouse Callback
  • UI\Area::redraw — Redraw Area
  • UI\Area::scrollTo — Area Scroll
  • UI\Area::setSize — Set Size

User Contributed Notes

There are no user contributed notes for this page.


Draw Callback

  • ? UI\Area
  • UI\Area::onKey ?
  • PHP Manual
  • UI\Area
  • Draw Callback

UI\Area::onDraw

(UI 0.9.9)

UI\Area::onDraw — Draw Callback

说明

protected UI\Area::onDraw ( UI\Draw\Pen $pen , UI\Size $areaSize , UI\Point $clipPoint , UI\Size $clipSize )

Shall be invoked when this Area requires redrawing

参数

pen

A Pen suitable for drawing in this Area

areaSize

The size of the Area

clipPoint

The clip point of the Area

clipSize

The clip size of the Area

User Contributed Notes

There are no user contributed notes for this page.


Key Callback

  • ? UI\Area::onDraw
  • UI\Area::onMouse ?
  • PHP Manual
  • UI\Area
  • Key Callback

UI\Area::onKey

(UI 0.9.9)

UI\Area::onKey — Key Callback

说明

protected UI\Area::onKey ( string $key , int $ext , int $flags )

Shall be executed on key events

参数

key

The key pressed

ext

The extended key pressed

flags

Event modifiers

返回值

User Contributed Notes

There are no user contributed notes for this page.


Mouse Callback

  • ? UI\Area::onKey
  • UI\Area::redraw ?
  • PHP Manual
  • UI\Area
  • Mouse Callback

UI\Area::onMouse

(UI 0.9.9)

UI\Area::onMouse — Mouse Callback

说明

protected UI\Area::onMouse ( UI\Point $areaPoint , UI\Size $areaSize , int $flags )

Shall be executed on mouse events

参数

areaPoint

The co-ordinates of the event

areaSize

The size of the area of the event

flags

Event modifiers

User Contributed Notes

There are no user contributed notes for this page.


Redraw Area

  • ? UI\Area::onMouse
  • UI\Area::scrollTo ?
  • PHP Manual
  • UI\Area
  • Redraw Area

UI\Area::redraw

(UI 0.9.9)

UI\Area::redraw — Redraw Area

说明

public UI\Area::redraw ( )

Requests that this Area is redrawn

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Area Scroll

  • ? UI\Area::redraw
  • UI\Area::setSize ?
  • PHP Manual
  • UI\Area
  • Area Scroll

UI\Area::scrollTo

(UI 0.9.9)

UI\Area::scrollTo — Area Scroll

说明

public UI\Area::scrollTo ( UI\Point $point , UI\Size $size )

Scroll this Area

参数

point

The point to scroll to

size

The size of the scroll pane

User Contributed Notes

There are no user contributed notes for this page.


Set Size

  • ? UI\Area::scrollTo
  • UI\Executor ?
  • PHP Manual
  • UI\Area
  • Set Size

UI\Area::setSize

(UI 0.9.9)

UI\Area::setSize — Set Size

说明

public UI\Area::setSize ( UI\Size $size )

Sets the size of this Area

参数

size

The new size

User Contributed Notes

There are no user contributed notes for this page.


Execution Scheduler

(UI 2.0.0)

简介

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

类摘要

abstract UI\Executor {
/* Constructor */
public __construct ( )
public __construct ( int $microseconds )
public __construct ( int $seconds , int $microseconds )
/* 方法 */
public kill ( ) : void
abstract protected onExecute ( ) : void
public setInterval ( int $microseconds ) : bool
public setInterval ( int $seconds , int $microseconds ) : bool
}

Table of Contents

  • UI\Executor::__construct — Construct a new Executor
  • UI\Executor::kill — Stop Executor
  • UI\Executor::onExecute — Execution Callback
  • UI\Executor::setInterval — Interval Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Executor

  • ? UI\Executor
  • UI\Executor::kill ?
  • PHP Manual
  • UI\Executor
  • Construct a new Executor

UI\Executor::__construct

(UI 2.0.0)

UI\Executor::__construct — Construct a new Executor

说明

public UI\Executor::__construct ( )
public UI\Executor::__construct ( int $microseconds )
public UI\Executor::__construct ( int $seconds , int $microseconds )

Shall construct an executor with the given interval, will not start executing until main loop is entered

参数

seconds

Seconds between executions

microseconds

Microseconds between executions

User Contributed Notes

There are no user contributed notes for this page.


Stop Executor

  • ? UI\Executor::__construct
  • UI\Executor::onExecute ?
  • PHP Manual
  • UI\Executor
  • Stop Executor

UI\Executor::kill

(UI 2.0.0)

UI\Executor::kill — Stop Executor

说明

public UI\Executor::kill ( ) : void

Shall stop an executor, the executor cannot be restarted

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Execution Callback

  • ? UI\Executor::kill
  • UI\Executor::setInterval ?
  • PHP Manual
  • UI\Executor
  • Execution Callback

UI\Executor::onExecute

(UI 2.0.0)

UI\Executor::onExecute — Execution Callback

说明

abstract protected UI\Executor::onExecute ( ) : void

Shall be repetitively queued for execution in the main thread

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Interval Manipulation

  • ? UI\Executor::onExecute
  • UI\Controls\Tab ?
  • PHP Manual
  • UI\Executor
  • Interval Manipulation

UI\Executor::setInterval

(UI 2.0.0)

UI\Executor::setInterval — Interval Manipulation

说明

public UI\Executor::setInterval ( int $microseconds ) : bool
public UI\Executor::setInterval ( int $seconds , int $microseconds ) : bool

Shall set the new interval. An interval of 0 will pause the executor until a new interval has been set

参数

seconds

microseconds

返回值

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Tab Control

(UI 0.9.9)

简介

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

类摘要

UI\Controls\Tab extends UI\Control {
/* 属性 */
protected $controls ;
/* 方法 */
public append ( string $name , UI\Control $control ) : int
public delete ( int $index ) : bool
public hasMargin ( int $page ) : bool
public insertAt ( string $name , int $page , UI\Control $control )
public pages ( ) : int
public setMargin ( int $page , bool $margin )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

属性

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Tab::append — Append Page
  • UI\Controls\Tab::delete — Delete Page
  • UI\Controls\Tab::hasMargin — Margin Detection
  • UI\Controls\Tab::insertAt — Insert Page
  • UI\Controls\Tab::pages — Page Count
  • UI\Controls\Tab::setMargin — Set Margin

User Contributed Notes

There are no user contributed notes for this page.


Append Page

  • ? UI\Controls\Tab
  • UI\Controls\Tab::delete ?
  • PHP Manual
  • UI\Controls\Tab
  • Append Page

UI\Controls\Tab::append

(UI 0.9.9)

UI\Controls\Tab::append — Append Page

说明

public UI\Controls\Tab::append ( string $name , UI\Control $control ) : int

Append a new page to this Tab

参数

name

The name for the new page

control

The control for the new page

返回值

Shall return the index of the appended control, may be 0

User Contributed Notes

There are no user contributed notes for this page.


Delete Page

  • ? UI\Controls\Tab::append
  • UI\Controls\Tab::hasMargin ?
  • PHP Manual
  • UI\Controls\Tab
  • Delete Page

UI\Controls\Tab::delete

(UI 0.9.9)

UI\Controls\Tab::delete — Delete Page

说明

public UI\Controls\Tab::delete ( int $index ) : bool

Shall remove the selected page from this Tab

参数

index

The index of the page to remove

返回值

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Margin Detection

  • ? UI\Controls\Tab::delete
  • UI\Controls\Tab::insertAt ?
  • PHP Manual
  • UI\Controls\Tab
  • Margin Detection

UI\Controls\Tab::hasMargin

(UI 0.9.9)

UI\Controls\Tab::hasMargin — Margin Detection

说明

public UI\Controls\Tab::hasMargin ( int $page ) : bool

Shall detect if the given page has a margin.

参数

page

The index of the page

返回值

User Contributed Notes

There are no user contributed notes for this page.


Insert Page

  • ? UI\Controls\Tab::hasMargin
  • UI\Controls\Tab::pages ?
  • PHP Manual
  • UI\Controls\Tab
  • Insert Page

UI\Controls\Tab::insertAt

(UI 0.9.9)

UI\Controls\Tab::insertAt — Insert Page

说明

public UI\Controls\Tab::insertAt ( string $name , int $page , UI\Control $control )

Shall insert a new page into this Tab

参数

name

The name for the new page

page

The index to perform the insertion before

control

The control for the new page

User Contributed Notes

There are no user contributed notes for this page.


Page Count

  • ? UI\Controls\Tab::insertAt
  • UI\Controls\Tab::setMargin ?
  • PHP Manual
  • UI\Controls\Tab
  • Page Count

UI\Controls\Tab::pages

(UI 0.9.9)

UI\Controls\Tab::pages — Page Count

说明

public UI\Controls\Tab::pages ( ) : int

Shall return the number of pages in this Tab

参数

此函数没有参数。

返回值

The number of pages in this Tab

User Contributed Notes

There are no user contributed notes for this page.


Set Margin

  • ? UI\Controls\Tab::pages
  • UI\Controls\Check ?
  • PHP Manual
  • UI\Controls\Tab
  • Set Margin

UI\Controls\Tab::setMargin

(UI 0.9.9)

UI\Controls\Tab::setMargin — Set Margin

说明

public UI\Controls\Tab::setMargin ( int $page , bool $margin )

Shall enable or disable margins on the selected page

参数

page

The page to select

margin

Margin switch

User Contributed Notes

There are no user contributed notes for this page.


Check Control

(UI 0.9.9)

简介

A Check is a labelled checkable box

类摘要

UI\Controls\Check extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* 方法 */
public getText ( ) : string
public isChecked ( ) : bool
protected onToggle ( )
public setChecked ( bool $checked )
public setText ( string $text )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Check::__construct — Construct a new Check
  • UI\Controls\Check::getText — Get Text
  • UI\Controls\Check::isChecked — Checked Detection
  • UI\Controls\Check::onToggle — Toggle Callback
  • UI\Controls\Check::setChecked — Set Checked
  • UI\Controls\Check::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Check

  • ? UI\Controls\Check
  • UI\Controls\Check::getText ?
  • PHP Manual
  • UI\Controls\Check
  • Construct a new Check

UI\Controls\Check::__construct

(UI 0.9.9)

UI\Controls\Check::__construct — Construct a new Check

说明

public UI\Controls\Check::__construct ( string $text )

Shall construct a new Check

参数

text

The text (label) for the Check box

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • ? UI\Controls\Check::__construct
  • UI\Controls\Check::isChecked ?
  • PHP Manual
  • UI\Controls\Check
  • Get Text

UI\Controls\Check::getText

(UI 0.9.9)

UI\Controls\Check::getText — Get Text

说明

public UI\Controls\Check::getText ( ) : string

Shall return the text (label) for this Check

参数

此函数没有参数。

返回值

The current text (label)

User Contributed Notes

There are no user contributed notes for this page.


Checked Detection

  • ? UI\Controls\Check::getText
  • UI\Controls\Check::onToggle ?
  • PHP Manual
  • UI\Controls\Check
  • Checked Detection

UI\Controls\Check::isChecked

(UI 0.9.9)

UI\Controls\Check::isChecked — Checked Detection

说明

public UI\Controls\Check::isChecked ( ) : bool

Shall detect the status of this Check

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Toggle Callback

  • ? UI\Controls\Check::isChecked
  • UI\Controls\Check::setChecked ?
  • PHP Manual
  • UI\Controls\Check
  • Toggle Callback

UI\Controls\Check::onToggle

(UI 0.9.9)

UI\Controls\Check::onToggle — Toggle Callback

说明

protected UI\Controls\Check::onToggle ( )

Shall be executed when the status of this Check is changed

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Checked

  • ? UI\Controls\Check::onToggle
  • UI\Controls\Check::setText ?
  • PHP Manual
  • UI\Controls\Check
  • Set Checked

UI\Controls\Check::setChecked

(UI 0.9.9)

UI\Controls\Check::setChecked — Set Checked

说明

public UI\Controls\Check::setChecked ( bool $checked )

Shall change the status of this Check

参数

checked

The new status

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • ? UI\Controls\Check::setChecked
  • UI\Controls\Button ?
  • PHP Manual
  • UI\Controls\Check
  • Set Text

UI\Controls\Check::setText

(UI 0.9.9)

UI\Controls\Check::setText — Set Text

说明

public UI\Controls\Check::setText ( string $text )

Shall set the text (label) for this Check

参数

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


Button Control

(UI 0.9.9)

简介

Represents a labelled clickable button

类摘要

UI\Controls\Button extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* 方法 */
public getText ( ) : string
protected onClick ( )
public setText ( string $text )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Button::__construct — Construct a new Button
  • UI\Controls\Button::getText — Get Text
  • UI\Controls\Button::onClick — Click Handler
  • UI\Controls\Button::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Button

  • ? UI\Controls\Button
  • UI\Controls\Button::getText ?
  • PHP Manual
  • UI\Controls\Button
  • Construct a new Button

UI\Controls\Button::__construct

(UI 0.9.9)

UI\Controls\Button::__construct — Construct a new Button

说明

public UI\Controls\Button::__construct ( string $text )

Shall construct a new Button

参数

text

The text (label) for this Button

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • ? UI\Controls\Button::__construct
  • UI\Controls\Button::onClick ?
  • PHP Manual
  • UI\Controls\Button
  • Get Text

UI\Controls\Button::getText

(UI 0.9.9)

UI\Controls\Button::getText — Get Text

说明

public UI\Controls\Button::getText ( ) : string

Shall retrieve the text (label) for this Button

参数

此函数没有参数。

返回值

The current text (label)

User Contributed Notes

There are no user contributed notes for this page.


Click Handler

  • ? UI\Controls\Button::getText
  • UI\Controls\Button::setText ?
  • PHP Manual
  • UI\Controls\Button
  • Click Handler

UI\Controls\Button::onClick

(UI 0.9.9)

UI\Controls\Button::onClick — Click Handler

说明

protected UI\Controls\Button::onClick ( )

Shall be executed when this Button is clicked

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • ? UI\Controls\Button::onClick
  • UI\Controls\ColorButton ?
  • PHP Manual
  • UI\Controls\Button
  • Set Text

UI\Controls\Button::setText

(UI 0.9.9)

UI\Controls\Button::setText — Set Text

说明

public UI\Controls\Button::setText ( string $text )

Shall set the text (label) for this Button

参数

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


ColorButton Control

(UI 0.9.9)

简介

A Color Button is a button which displays a color picker when clicked

类摘要

UI\Controls\ColorButton extends UI\Control {
/* 方法 */
public getColor ( ) : UI\Color
protected onChange ( )
public setColor ( UI\Draw\Color $color )
public setColor ( int $color )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\ColorButton::getColor — Get Color
  • UI\Controls\ColorButton::onChange — Change Handler
  • UI\Controls\ColorButton::setColor — Set Color

User Contributed Notes

There are no user contributed notes for this page.


Get Color

  • ? UI\Controls\ColorButton
  • UI\Controls\ColorButton::onChange ?
  • PHP Manual
  • UI\Controls\ColorButton
  • Get Color

UI\Controls\ColorButton::getColor

(UI 0.9.9)

UI\Controls\ColorButton::getColor — Get Color

说明

public UI\Controls\ColorButton::getColor ( ) : UI\Color

Shall retrieve the currently selected Color

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • ? UI\Controls\ColorButton::getColor
  • UI\Controls\ColorButton::setColor ?
  • PHP Manual
  • UI\Controls\ColorButton
  • Change Handler

UI\Controls\ColorButton::onChange

(UI 0.9.9)

UI\Controls\ColorButton::onChange — Change Handler

说明

protected UI\Controls\ColorButton::onChange ( )

Shall be executed when the selected Color is changed

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Color

  • ? UI\Controls\ColorButton::onChange
  • UI\Controls\Label ?
  • PHP Manual
  • UI\Controls\ColorButton
  • Set Color

UI\Controls\ColorButton::setColor

(UI 0.9.9)

UI\Controls\ColorButton::setColor — Set Color

说明

public UI\Controls\ColorButton::setColor ( UI\Draw\Color $color )
public UI\Controls\ColorButton::setColor ( int $color )

Shall set the currently selected Color

参数

color

The new color

User Contributed Notes

There are no user contributed notes for this page.


Label Control

(UI 0.9.9)

简介

A Label is a single line of text, meant to identify, for the user, some element of the interface.

类摘要

UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* 方法 */
public getText ( ) : string
public setText ( string $text )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Label::__construct — Construct a new Label
  • UI\Controls\Label::getText — Get Text
  • UI\Controls\Label::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Label

  • ? UI\Controls\Label
  • UI\Controls\Label::getText ?
  • PHP Manual
  • UI\Controls\Label
  • Construct a new Label

UI\Controls\Label::__construct

(UI 0.9.9)

UI\Controls\Label::__construct — Construct a new Label

说明

public UI\Controls\Label::__construct ( string $text )

Shall construct a new Label

参数

text

The text for this label

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • ? UI\Controls\Label::__construct
  • UI\Controls\Label::setText ?
  • PHP Manual
  • UI\Controls\Label
  • Get Text

UI\Controls\Label::getText

(UI 0.9.9)

UI\Controls\Label::getText — Get Text

说明

public UI\Controls\Label::getText ( ) : string

Shall return the current text for this Label

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • ? UI\Controls\Label::getText
  • UI\Controls\Entry ?
  • PHP Manual
  • UI\Controls\Label
  • Set Text

UI\Controls\Label::setText

(UI 0.9.9)

UI\Controls\Label::setText — Set Text

说明

public UI\Controls\Label::setText ( string $text )

Shall set the text for this Label

参数

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Entry Control

(UI 0.9.9)

简介

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

类摘要

UI\Controls\Entry extends UI\Control {
/* Constants */
const int Normal ;
const int Password ;
const int Search ;
/* Constructor */
public __construct ( int $type = UI\Controls\Entry::Normal )
/* 方法 */
public getText ( ) : string
public isReadOnly ( ) : bool
protected onChange ( )
public setReadOnly ( bool $readOnly )
public setText ( string $text )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

预定义常量

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Table of Contents

  • UI\Controls\Entry::__construct — Construct a new Entry
  • UI\Controls\Entry::getText — Get Text
  • UI\Controls\Entry::isReadOnly — Detect Read Only
  • UI\Controls\Entry::onChange — Change Handler
  • UI\Controls\Entry::setReadOnly — Set Read Only
  • UI\Controls\Entry::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Entry

  • ? UI\Controls\Entry
  • UI\Controls\Entry::getText ?
  • PHP Manual
  • UI\Controls\Entry
  • Construct a new Entry

UI\Controls\Entry::__construct

(UI 0.9.9)

UI\Controls\Entry::__construct — Construct a new Entry

说明

public UI\Controls\Entry::__construct ( int $type = UI\Controls\Entry::Normal )

Construct a new entry of the given type

参数

type

Entry::Normal, Entry::Password, or Entry::Search

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • ? UI\Controls\Entry::__construct
  • UI\Controls\Entry::isReadOnly ?
  • PHP Manual
  • UI\Controls\Entry
  • Get Text

UI\Controls\Entry::getText

(UI 0.9.9)

UI\Controls\Entry::getText — Get Text

说明

public UI\Controls\Entry::getText ( ) : string

Shall return the current text from this Entry

参数

此函数没有参数。

返回值

The current text

User Contributed Notes

There are no user contributed notes for this page.


Detect Read Only

  • ? UI\Controls\Entry::getText
  • UI\Controls\Entry::onChange ?
  • PHP Manual
  • UI\Controls\Entry
  • Detect Read Only

UI\Controls\Entry::isReadOnly

(UI 0.9.9)

UI\Controls\Entry::isReadOnly — Detect Read Only

说明

public UI\Controls\Entry::isReadOnly ( ) : bool

Shall detect if this Entry is read only

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • ? UI\Controls\Entry::isReadOnly
  • UI\Controls\Entry::setReadOnly ?
  • PHP Manual
  • UI\Controls\Entry
  • Change Handler

UI\Controls\Entry::onChange

(UI 0.9.9)

UI\Controls\Entry::onChange — Change Handler

说明

protected UI\Controls\Entry::onChange ( )

Shall be executed when the text in this Entry changes

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Read Only

  • ? UI\Controls\Entry::onChange
  • UI\Controls\Entry::setText ?
  • PHP Manual
  • UI\Controls\Entry
  • Set Read Only

UI\Controls\Entry::setReadOnly

(UI 0.9.9)

UI\Controls\Entry::setReadOnly — Set Read Only

说明

public UI\Controls\Entry::setReadOnly ( bool $readOnly )

Shall enable or disable read only for this Entry

参数

readOnly

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • ? UI\Controls\Entry::setReadOnly
  • UI\Controls\MultilineEntry ?
  • PHP Manual
  • UI\Controls\Entry
  • Set Text

UI\Controls\Entry::setText

(UI 0.9.9)

UI\Controls\Entry::setText — Set Text

说明

public UI\Controls\Entry::setText ( string $text )

Shall set the text for this Entry

参数

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


MultilineEntry Control

(UI 0.9.9)

简介

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

类摘要

UI\Controls\MultilineEntry extends UI\Control {
/* Constants */
const int Wrap ;
const int NoWrap ;
/* Constructor */
public __construct ( int $type = ? )
/* 方法 */
public append ( string $text )
public getText ( ) : string
public isReadOnly ( ) : bool
protected onChange ( )
public setReadOnly ( bool $readOnly )
public setText ( string $text )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

预定义常量

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Table of Contents

  • UI\Controls\MultilineEntry::append — Append Text
  • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
  • UI\Controls\MultilineEntry::getText — Get Text
  • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
  • UI\Controls\MultilineEntry::onChange — Change Handler
  • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
  • UI\Controls\MultilineEntry::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Append Text

  • ? UI\Controls\MultilineEntry
  • UI\Controls\MultilineEntry::__construct ?
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Append Text

UI\Controls\MultilineEntry::append

(UI 0.9.9)

UI\Controls\MultilineEntry::append — Append Text

说明

public UI\Controls\MultilineEntry::append ( string $text )

Shall append the given text to the text in this Multiline Entry

参数

text

The text to append

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Multiline Entry

  • ? UI\Controls\MultilineEntry::append
  • UI\Controls\MultilineEntry::getText ?
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Construct a new Multiline Entry

UI\Controls\MultilineEntry::__construct

(UI 0.9.9)

UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry

说明

public UI\Controls\MultilineEntry::__construct ( int $type = ? )

Shall construct a new Multiline Entry of the given type

参数

type

MultilineEntry::Wrap or MultilineEntry::NoWrap

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • ? UI\Controls\MultilineEntry::__construct
  • UI\Controls\MultilineEntry::isReadOnly ?
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Get Text

UI\Controls\MultilineEntry::getText

(UI 0.9.9)

UI\Controls\MultilineEntry::getText — Get Text

说明

public UI\Controls\MultilineEntry::getText ( ) : string

Shall return the text in this Multiline Entry

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Read Only Detection

  • ? UI\Controls\MultilineEntry::getText
  • UI\Controls\MultilineEntry::onChange ?
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Read Only Detection

UI\Controls\MultilineEntry::isReadOnly

(UI 0.9.9)

UI\Controls\MultilineEntry::isReadOnly — Read Only Detection

说明

public UI\Controls\MultilineEntry::isReadOnly ( ) : bool

Shall detect if this Multiline Entry is read only

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • ? UI\Controls\MultilineEntry::isReadOnly
  • UI\Controls\MultilineEntry::setReadOnly ?
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Change Handler

UI\Controls\MultilineEntry::onChange

(UI 0.9.9)

UI\Controls\MultilineEntry::onChange — Change Handler

说明

protected UI\Controls\MultilineEntry::onChange ( )

Shall be executed when the text in this Multiline Entry is changed

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Read Only

  • ? UI\Controls\MultilineEntry::onChange
  • UI\Controls\MultilineEntry::setText ?
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Set Read Only

UI\Controls\MultilineEntry::setReadOnly

(UI 0.9.9)

UI\Controls\MultilineEntry::setReadOnly — Set Read Only

说明

public UI\Controls\MultilineEntry::setReadOnly ( bool $readOnly )

Shall enable or disable read only on this Multiline Entry

参数

readOnly

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • ? UI\Controls\MultilineEntry::setReadOnly
  • UI\Controls\Spin ?
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Set Text

UI\Controls\MultilineEntry::setText

(UI 0.9.9)

UI\Controls\MultilineEntry::setText — Set Text

说明

public UI\Controls\MultilineEntry::setText ( string $text )

Shall set the text in this Multiline Entry

参数

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Spin Control

(UI 0.9.9)

简介

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

类摘要

UI\Controls\Spin extends UI\Control {
/* Constructor */
public __construct ( int $min , int $max )
/* 方法 */
public getValue ( ) : int
protected onChange ( )
public setValue ( int $value )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Spin::__construct — Construct a new Spin
  • UI\Controls\Spin::getValue — Get Value
  • UI\Controls\Spin::onChange — Change Handler
  • UI\Controls\Spin::setValue — Set Value

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Spin

  • ? UI\Controls\Spin
  • UI\Controls\Spin::getValue ?
  • PHP Manual
  • UI\Controls\Spin
  • Construct a new Spin

UI\Controls\Spin::__construct

(UI 0.9.9)

UI\Controls\Spin::__construct — Construct a new Spin

说明

public UI\Controls\Spin::__construct ( int $min , int $max )

Constructs a new Spin with the given range

参数

min

The minimum value allowed

max

The maximum value allowed

User Contributed Notes

There are no user contributed notes for this page.


Get Value

  • ? UI\Controls\Spin::__construct
  • UI\Controls\Spin::onChange ?
  • PHP Manual
  • UI\Controls\Spin
  • Get Value

UI\Controls\Spin::getValue

(UI 0.9.9)

UI\Controls\Spin::getValue — Get Value

说明

public UI\Controls\Spin::getValue ( ) : int

Get the value in this Spin

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • ? UI\Controls\Spin::getValue
  • UI\Controls\Spin::setValue ?
  • PHP Manual
  • UI\Controls\Spin
  • Change Handler

UI\Controls\Spin::onChange

(UI 0.9.9)

UI\Controls\Spin::onChange — Change Handler

说明

protected UI\Controls\Spin::onChange ( )

Shall be executed when the value in this Spin changes

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Value

  • ? UI\Controls\Spin::onChange
  • UI\Controls\Slider ?
  • PHP Manual
  • UI\Controls\Spin
  • Set Value

UI\Controls\Spin::setValue

(UI 0.9.9)

UI\Controls\Spin::setValue — Set Value

说明

public UI\Controls\Spin::setValue ( int $value )

Set the value in this Spin

参数

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Slider Control

(UI 0.9.9)

简介

A Slider is a control which represents a range, and a current value in the range. The sliding element of the control (sometimes called the "thumb") reflects the value, and can be adjusted within the range.

类摘要

UI\Controls\Slider extends UI\Control {
/* Constructor */
public __construct ( int $min , int $max )
/* 方法 */
public getValue ( ) : int
protected onChange ( )
public setValue ( int $value )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Slider::__construct — Construct a new Slider
  • UI\Controls\Slider::getValue — Get Value
  • UI\Controls\Slider::onChange — Change Handler
  • UI\Controls\Slider::setValue — Set Value

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Slider

  • ? UI\Controls\Slider
  • UI\Controls\Slider::getValue ?
  • PHP Manual
  • UI\Controls\Slider
  • Construct a new Slider

UI\Controls\Slider::__construct

(UI 0.9.9)

UI\Controls\Slider::__construct — Construct a new Slider

说明

public UI\Controls\Slider::__construct ( int $min , int $max )

Construct a new Slider with the given range

参数

min

The minimum allowed value

max

The maximum allowed value

User Contributed Notes

There are no user contributed notes for this page.


Get Value

  • ? UI\Controls\Slider::__construct
  • UI\Controls\Slider::onChange ?
  • PHP Manual
  • UI\Controls\Slider
  • Get Value

UI\Controls\Slider::getValue

(UI 0.9.9)

UI\Controls\Slider::getValue — Get Value

说明

public UI\Controls\Slider::getValue ( ) : int

Get the value from this Slider

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • ? UI\Controls\Slider::getValue
  • UI\Controls\Slider::setValue ?
  • PHP Manual
  • UI\Controls\Slider
  • Change Handler

UI\Controls\Slider::onChange

(UI 0.9.9)

UI\Controls\Slider::onChange — Change Handler

说明

protected UI\Controls\Slider::onChange ( )

Shall be executed when the value of this Slider changes

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Value

  • ? UI\Controls\Slider::onChange
  • UI\Controls\Progress ?
  • PHP Manual
  • UI\Controls\Slider
  • Set Value

UI\Controls\Slider::setValue

(UI 0.9.9)

UI\Controls\Slider::setValue — Set Value

说明

public UI\Controls\Slider::setValue ( int $value )

Shall set the value for this Slider

参数

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Progress Control

(UI 0.9.9)

简介

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

类摘要

UI\Controls\Progress extends UI\Control {
/* 方法 */
public getValue ( ) : int
public setValue ( int $value )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Progress::getValue — Get Value
  • UI\Controls\Progress::setValue — Set Value

User Contributed Notes

There are no user contributed notes for this page.


Get Value

  • ? UI\Controls\Progress
  • UI\Controls\Progress::setValue ?
  • PHP Manual
  • UI\Controls\Progress
  • Get Value

UI\Controls\Progress::getValue

(UI 0.9.9)

UI\Controls\Progress::getValue — Get Value

说明

public UI\Controls\Progress::getValue ( ) : int

Shall retrieve the current value of this Progress bar

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Value

  • ? UI\Controls\Progress::getValue
  • UI\Controls\Separator ?
  • PHP Manual
  • UI\Controls\Progress
  • Set Value

UI\Controls\Progress::setValue

(UI 0.9.9)

UI\Controls\Progress::setValue — Set Value

说明

public UI\Controls\Progress::setValue ( int $value )

Shall set the value for this Progress bar

参数

value

An integer between 0 and 100 (inclusive)

User Contributed Notes

There are no user contributed notes for this page.


Control Separator

(UI 0.9.9)

简介

A Separator represents a control separator, it has no other function.

类摘要

UI\Controls\Separator extends UI\Control {
/* Constants */
const int Horizontal ;
const int Vertical ;
/* Constructor */
public __construct ( int $type = UI\Controls\Separator::Horizontal )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

预定义常量

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Table of Contents

  • UI\Controls\Separator::__construct — Construct a new Separator

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Separator

  • ? UI\Controls\Separator
  • UI\Controls\Combo ?
  • PHP Manual
  • UI\Controls\Separator
  • Construct a new Separator

UI\Controls\Separator::__construct

(UI 0.9.9)

UI\Controls\Separator::__construct — Construct a new Separator

说明

public UI\Controls\Separator::__construct ( int $type = UI\Controls\Separator::Horizontal )

Shall construct a new Separator of the given type

参数

type

Separator::Horizonal or Separator::Vertical

User Contributed Notes

There are no user contributed notes for this page.


Combo Control

(UI 0.9.9)

简介

A Combo control represents a list of options, like the familiar select HTML element.

类摘要

UI\Controls\Combo extends UI\Control {
/* 方法 */
public append ( string $text )
public getSelected ( ) : int
protected onSelected ( )
public setSelected ( int $index )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Combo::append — Append Option
  • UI\Controls\Combo::getSelected — Get Selected Option
  • UI\Controls\Combo::onSelected — Selected Handler
  • UI\Controls\Combo::setSelected — Set Selected Option

User Contributed Notes

There are no user contributed notes for this page.


Append Option

  • ? UI\Controls\Combo
  • UI\Controls\Combo::getSelected ?
  • PHP Manual
  • UI\Controls\Combo
  • Append Option

UI\Controls\Combo::append

(UI 0.9.9)

UI\Controls\Combo::append — Append Option

说明

public UI\Controls\Combo::append ( string $text )

Append an option to this Combo

参数

text

The text for the new option

User Contributed Notes

There are no user contributed notes for this page.


Get Selected Option

  • ? UI\Controls\Combo::append
  • UI\Controls\Combo::onSelected ?
  • PHP Manual
  • UI\Controls\Combo
  • Get Selected Option

UI\Controls\Combo::getSelected

(UI 0.9.9)

UI\Controls\Combo::getSelected — Get Selected Option

说明

public UI\Controls\Combo::getSelected ( ) : int

Shall retrieve the index of the option selected in this Combo

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Selected Handler

  • ? UI\Controls\Combo::getSelected
  • UI\Controls\Combo::setSelected ?
  • PHP Manual
  • UI\Controls\Combo
  • Selected Handler

UI\Controls\Combo::onSelected

(UI 0.9.9)

UI\Controls\Combo::onSelected — Selected Handler

说明

protected UI\Controls\Combo::onSelected ( )

Shall be executed when an option is selected in this Combo

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Selected Option

  • ? UI\Controls\Combo::onSelected
  • UI\Controls\EditableCombo ?
  • PHP Manual
  • UI\Controls\Combo
  • Set Selected Option

UI\Controls\Combo::setSelected

(UI 0.9.9)

UI\Controls\Combo::setSelected — Set Selected Option

说明

public UI\Controls\Combo::setSelected ( int $index )

Shall set the currently selected option in this Combo

参数

index

The index of the option to select

User Contributed Notes

There are no user contributed notes for this page.


EdiableCombo Control

(UI 0.9.9)

简介

An Editable Combo is a Combo which allows the user to enter custom options

类摘要

UI\Controls\EditableCombo extends UI\Control {
/* 方法 */
public append ( string $text )
public getText ( ) : string
protected onChange ( )
public setText ( string $text )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\EditableCombo::append — Append Option
  • UI\Controls\EditableCombo::getText — Get Text
  • UI\Controls\EditableCombo::onChange — Change Handler
  • UI\Controls\EditableCombo::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Append Option

  • ? UI\Controls\EditableCombo
  • UI\Controls\EditableCombo::getText ?
  • PHP Manual
  • UI\Controls\EditableCombo
  • Append Option

UI\Controls\EditableCombo::append

(UI 0.9.9)

UI\Controls\EditableCombo::append — Append Option

说明

public UI\Controls\EditableCombo::append ( string $text )

Shall append a new option to this Editable Combo

参数

text

The text for the new option

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • ? UI\Controls\EditableCombo::append
  • UI\Controls\EditableCombo::onChange ?
  • PHP Manual
  • UI\Controls\EditableCombo
  • Get Text

UI\Controls\EditableCombo::getText

(UI 0.9.9)

UI\Controls\EditableCombo::getText — Get Text

说明

public UI\Controls\EditableCombo::getText ( ) : string

Get the value of the currently selected option in this Editable Combo

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • ? UI\Controls\EditableCombo::getText
  • UI\Controls\EditableCombo::setText ?
  • PHP Manual
  • UI\Controls\EditableCombo
  • Change Handler

UI\Controls\EditableCombo::onChange

(UI 0.9.9)

UI\Controls\EditableCombo::onChange — Change Handler

说明

protected UI\Controls\EditableCombo::onChange ( )

Shall be executed when the value of this Editable Combobox changes

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • ? UI\Controls\EditableCombo::onChange
  • UI\Controls\Radio ?
  • PHP Manual
  • UI\Controls\EditableCombo
  • Set Text

UI\Controls\EditableCombo::setText

(UI 0.9.9)

UI\Controls\EditableCombo::setText — Set Text

说明

public UI\Controls\EditableCombo::setText ( string $text )

Shall set the text of the currently selected option in this Editable Combo

参数

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Radio Control

(UI 0.9.9)

简介

A Radio is similar to the radio input type familiar from HTML

类摘要

UI\Controls\Radio extends UI\Control {
/* 方法 */
public append ( string $text )
public getSelected ( ) : int
protected onSelected ( )
public setSelected ( int $index )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

Table of Contents

  • UI\Controls\Radio::append — Append Option
  • UI\Controls\Radio::getSelected — Get Selected Option
  • UI\Controls\Radio::onSelected — Selected Handler
  • UI\Controls\Radio::setSelected — Set Selected Option

User Contributed Notes

There are no user contributed notes for this page.


Append Option

  • ? UI\Controls\Radio
  • UI\Controls\Radio::getSelected ?
  • PHP Manual
  • UI\Controls\Radio
  • Append Option

UI\Controls\Radio::append

(UI 0.9.9)

UI\Controls\Radio::append — Append Option

说明

public UI\Controls\Radio::append ( string $text )

Shall append a new option to this Radio

参数

text

The text (label) for the option

User Contributed Notes

There are no user contributed notes for this page.


Get Selected Option

  • ? UI\Controls\Radio::append
  • UI\Controls\Radio::onSelected ?
  • PHP Manual
  • UI\Controls\Radio
  • Get Selected Option

UI\Controls\Radio::getSelected

(UI 0.9.9)

UI\Controls\Radio::getSelected — Get Selected Option

说明

public UI\Controls\Radio::getSelected ( ) : int

Shall retrieve the index of the currently selected option in this Radio

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Selected Handler

  • ? UI\Controls\Radio::getSelected
  • UI\Controls\Radio::setSelected ?
  • PHP Manual
  • UI\Controls\Radio
  • Selected Handler

UI\Controls\Radio::onSelected

(UI 0.9.9)

UI\Controls\Radio::onSelected — Selected Handler

说明

protected UI\Controls\Radio::onSelected ( )

Shall be executed when the option selected in this Radio changes

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Selected Option

  • ? UI\Controls\Radio::onSelected
  • UI\Controls\Picker ?
  • PHP Manual
  • UI\Controls\Radio
  • Set Selected Option

UI\Controls\Radio::setSelected

(UI 0.9.9)

UI\Controls\Radio::setSelected — Set Selected Option

说明

public UI\Controls\Radio::setSelected ( int $index )

Shall set the currently selected option in this Radio

参数

index

The index of the option to select

User Contributed Notes

There are no user contributed notes for this page.


Picker Control

(UI 0.9.9)

简介

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

类摘要

UI\Controls\Picker extends UI\Control {
/* Constants */
const int Date ;
const int Time ;
const int DateTime ;
/* Constructor */
public __construct ( int $type = UI\Controls\Picker::Date )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

预定义常量

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Table of Contents

  • UI\Controls\Picker::__construct — Construct a new Picker

User Contributed Notes

falcon560 at gmail dot com 05-Nov-2017 07:54
No getter method for the date/time


Construct a new Picker

  • ? UI\Controls\Picker
  • UI\Controls\Form ?
  • PHP Manual
  • UI\Controls\Picker
  • Construct a new Picker

UI\Controls\Picker::__construct

(UI 0.9.9)

UI\Controls\Picker::__construct — Construct a new Picker

说明

public UI\Controls\Picker::__construct ( int $type = UI\Controls\Picker::Date )

Construct a new Picker of the given type

参数

type

Picker::Date, Picker::Time, or Picker::DateTime

User Contributed Notes

There are no user contributed notes for this page.


Control Form (Arrangement)

(UI 0.9.9)

简介

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

类摘要

UI\Controls\Form extends UI\Control {
/* 属性 */
protected $controls ;
/* 方法 */
public append ( string $label , UI\Control $control , bool $stretchy = false ) : int
public delete ( int $index ) : bool
public isPadded ( ) : bool
public setPadded ( bool $padded )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

属性

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Form::append — Append Control
  • UI\Controls\Form::delete — Delete Control
  • UI\Controls\Form::isPadded — Padding Detection
  • UI\Controls\Form::setPadded — Set Padding

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • ? UI\Controls\Form
  • UI\Controls\Form::delete ?
  • PHP Manual
  • UI\Controls\Form
  • Append Control

UI\Controls\Form::append

(UI 0.9.9)

UI\Controls\Form::append — Append Control

说明

public UI\Controls\Form::append ( string $label , UI\Control $control , bool $stretchy = false ) : int

Shall append the control to the form, and set the label

参数

label

The text for the label

control

A control

stretchy

Should be set true to stretch the control

返回值

Shall return the index of the appended control, may be 0

User Contributed Notes

There are no user contributed notes for this page.


Delete Control

  • ? UI\Controls\Form::append
  • UI\Controls\Form::isPadded ?
  • PHP Manual
  • UI\Controls\Form
  • Delete Control

UI\Controls\Form::delete

(UI 0.9.9)

UI\Controls\Form::delete — Delete Control

说明

public UI\Controls\Form::delete ( int $index ) : bool

Shall delete the control at the given index in this Form

参数

index

The index of the control to remove

返回值

Indication of succcess

User Contributed Notes

There are no user contributed notes for this page.


Padding Detection

  • ? UI\Controls\Form::delete
  • UI\Controls\Form::setPadded ?
  • PHP Manual
  • UI\Controls\Form
  • Padding Detection

UI\Controls\Form::isPadded

(UI 0.9.9)

UI\Controls\Form::isPadded — Padding Detection

说明

public UI\Controls\Form::isPadded ( ) : bool

Shall detect if padding is enabled on this Form

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Padding

  • ? UI\Controls\Form::isPadded
  • UI\Controls\Grid ?
  • PHP Manual
  • UI\Controls\Form
  • Set Padding

UI\Controls\Form::setPadded

(UI 0.9.9)

UI\Controls\Form::setPadded — Set Padding

说明

public UI\Controls\Form::setPadded ( bool $padded )

Shall enable or disable padding on this Form

参数

padded

User Contributed Notes

There are no user contributed notes for this page.


Control Grid (Arrangement)

(UI 0.9.9)

简介

A Grid is a control which is allows the arrangement of children into a grid

类摘要

UI\Controls\Grid extends UI\Control {
/* Constants */
const int Fill ;
const int Start ;
const int Center ;
const int End ;
const int Leading ;
const int Top ;
const int Trailing ;
const int Bottom ;
/* 属性 */
protected $controls ;
/* 方法 */
public append ( UI\Control $control , int $left , int $top , int $xspan , int $yspan , bool $hexpand , int $halign , bool $vexpand , int $valign )
public isPadded ( ) : bool
public setPadded ( bool $padding )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

预定义常量

UI\Controls\Grid::Fill

UI\Controls\Grid::Start

UI\Controls\Grid::Center

UI\Controls\Grid::End

UI\Controls\Grid::Leading

UI\Controls\Grid::Top

UI\Controls\Grid::Trailing

UI\Controls\Grid::Bottom

属性

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Grid::append — Append Control
  • UI\Controls\Grid::isPadded — Padding Detection
  • UI\Controls\Grid::setPadded — Set Padding

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • ? UI\Controls\Grid
  • UI\Controls\Grid::isPadded ?
  • PHP Manual
  • UI\Controls\Grid
  • Append Control

UI\Controls\Grid::append

(UI 0.9.9)

UI\Controls\Grid::append — Append Control

说明

public UI\Controls\Grid::append ( UI\Control $control , int $left , int $top , int $xspan , int $yspan , bool $hexpand , int $halign , bool $vexpand , int $valign )

Warning

本函数还未编写文档，仅有参数列表。

参数

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

返回值

User Contributed Notes

There are no user contributed notes for this page.


Padding Detection

  • ? UI\Controls\Grid::append
  • UI\Controls\Grid::setPadded ?
  • PHP Manual
  • UI\Controls\Grid
  • Padding Detection

UI\Controls\Grid::isPadded

(UI 0.9.9)

UI\Controls\Grid::isPadded — Padding Detection

说明

public UI\Controls\Grid::isPadded ( ) : bool

Shall detect if padding is enabled on this Grid

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Padding

  • ? UI\Controls\Grid::isPadded
  • UI\Controls\Group ?
  • PHP Manual
  • UI\Controls\Grid
  • Set Padding

UI\Controls\Grid::setPadded

(UI 0.9.9)

UI\Controls\Grid::setPadded — Set Padding

说明

public UI\Controls\Grid::setPadded ( bool $padding )

Shall enable or disable padding for this Grid

参数

padding

User Contributed Notes

There are no user contributed notes for this page.


Control Group (Arrangement)

(UI 0.9.9)

简介

A Group is a titled container for child controls

类摘要

UI\Controls\Group extends UI\Control {
/* 属性 */
protected $controls ;
/* Constructor */
public __construct ( string $title )
/* 方法 */
public append ( UI\Control $control )
public getTitle ( ) : string
public hasMargin ( ) : bool
public setMargin ( bool $margin )
public setTitle ( string $title )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

属性

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Group::append — Append Control
  • UI\Controls\Group::__construct — Construct a new Group
  • UI\Controls\Group::getTitle — Get Title
  • UI\Controls\Group::hasMargin — Margin Detection
  • UI\Controls\Group::setMargin — Set Margin
  • UI\Controls\Group::setTitle — Set Title

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • ? UI\Controls\Group
  • UI\Controls\Group::__construct ?
  • PHP Manual
  • UI\Controls\Group
  • Append Control

UI\Controls\Group::append

(No version information available, might only be in Git)

UI\Controls\Group::append — Append Control

说明

public UI\Controls\Group::append ( UI\Control $control )

Shall append a control to this Group

参数

control

The control to append

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Group

  • ? UI\Controls\Group::append
  • UI\Controls\Group::getTitle ?
  • PHP Manual
  • UI\Controls\Group
  • Construct a new Group

UI\Controls\Group::__construct

(UI 0.9.9)

UI\Controls\Group::__construct — Construct a new Group

说明

public UI\Controls\Group::__construct ( string $title )

Shall construct a new Group with the given title

参数

title

The text for the title label

User Contributed Notes

There are no user contributed notes for this page.


Get Title

  • ? UI\Controls\Group::__construct
  • UI\Controls\Group::hasMargin ?
  • PHP Manual
  • UI\Controls\Group
  • Get Title

UI\Controls\Group::getTitle

(UI 0.9.9)

UI\Controls\Group::getTitle — Get Title

说明

public UI\Controls\Group::getTitle ( ) : string

Shall return the current title for this Group

参数

此函数没有参数。

返回值

The current title

User Contributed Notes

There are no user contributed notes for this page.


Margin Detection

  • ? UI\Controls\Group::getTitle
  • UI\Controls\Group::setMargin ?
  • PHP Manual
  • UI\Controls\Group
  • Margin Detection

UI\Controls\Group::hasMargin

(UI 0.9.9)

UI\Controls\Group::hasMargin — Margin Detection

说明

public UI\Controls\Group::hasMargin ( ) : bool

Shall detect if this Group has a margin

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Margin

  • ? UI\Controls\Group::hasMargin
  • UI\Controls\Group::setTitle ?
  • PHP Manual
  • UI\Controls\Group
  • Set Margin

UI\Controls\Group::setMargin

(UI 0.9.9)

UI\Controls\Group::setMargin — Set Margin

说明

public UI\Controls\Group::setMargin ( bool $margin )

Shall enable or disable margins for this Group

参数

margin

User Contributed Notes

There are no user contributed notes for this page.


Set Title

  • ? UI\Controls\Group::setMargin
  • UI\Controls\Box ?
  • PHP Manual
  • UI\Controls\Group
  • Set Title

UI\Controls\Group::setTitle

(UI 0.9.9)

UI\Controls\Group::setTitle — Set Title

说明

public UI\Controls\Group::setTitle ( string $title )

Shall set the title for this Group

参数

title

The text for the new title

User Contributed Notes

There are no user contributed notes for this page.


Control Box (Arrangement)

(UI 0.9.9)

简介

A Box allows the arrangement of other controls

类摘要

UI\Controls\Box extends UI\Control {
/* Constants */
const int Vertical ;
const int Horizontal ;
/* 属性 */
protected $controls ;
/* Constructor */
public __construct ( int $orientation = UI\Controls\Box::Horizontal )
/* 方法 */
public append ( Control $control , bool $stretchy = false ) : int
public delete ( int $index ) : bool
public getOrientation ( ) : int
public isPadded ( ) : bool
public setPadded ( bool $padded )
/* 继承的方法 */
public UI\Control::destroy ( )
public UI\Control::disable ( )
public UI\Control::enable ( )
public UI\Control::getParent ( ) : UI\Control
public UI\Control::getTopLevel ( ) : int
public UI\Control::hide ( )
public UI\Control::isEnabled ( ) : bool
public UI\Control::isVisible ( ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( )
}

属性

controls

Contains controls, should not be manipulated directly

预定义常量

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Table of Contents

  • UI\Controls\Box::append — Append Control
  • UI\Controls\Box::__construct — Construct a new Box
  • UI\Controls\Box::delete — Delete Control
  • UI\Controls\Box::getOrientation — Get Orientation
  • UI\Controls\Box::isPadded — Padding Detection
  • UI\Controls\Box::setPadded — Set Padding

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • ? UI\Controls\Box
  • UI\Controls\Box::__construct ?
  • PHP Manual
  • UI\Controls\Box
  • Append Control

UI\Controls\Box::append

(UI 0.9.9)

UI\Controls\Box::append — Append Control

说明

public UI\Controls\Box::append ( Control $control , bool $stretchy = false ) : int

Shall append the given control to this Box

参数

control

The control to append

stretchy

Set true to stretch the control

返回值

Shall return the index of the appended control, may be 0

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Box

  • ? UI\Controls\Box::append
  • UI\Controls\Box::delete ?
  • PHP Manual
  • UI\Controls\Box
  • Construct a new Box

UI\Controls\Box::__construct

(UI 0.9.9)

UI\Controls\Box::__construct — Construct a new Box

说明

public UI\Controls\Box::__construct ( int $orientation = UI\Controls\Box::Horizontal )

Shall construct a new box

参数

orientation

Box::Horizontal or Box::Vertical

User Contributed Notes

There are no user contributed notes for this page.


Delete Control

  • ? UI\Controls\Box::__construct
  • UI\Controls\Box::getOrientation ?
  • PHP Manual
  • UI\Controls\Box
  • Delete Control

UI\Controls\Box::delete

(UI 0.9.9)

UI\Controls\Box::delete — Delete Control

说明

public UI\Controls\Box::delete ( int $index ) : bool

Shall delete the control at the given index from this Box

参数

index

The index of the control to delete

返回值

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Get Orientation

  • ? UI\Controls\Box::delete
  • UI\Controls\Box::isPadded ?
  • PHP Manual
  • UI\Controls\Box
  • Get Orientation

UI\Controls\Box::getOrientation

(UI 0.9.9)

UI\Controls\Box::getOrientation — Get Orientation

说明

public UI\Controls\Box::getOrientation ( ) : int

Shall retrieve the orientation of this Box

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Padding Detection

  • ? UI\Controls\Box::getOrientation
  • UI\Controls\Box::setPadded ?
  • PHP Manual
  • UI\Controls\Box
  • Padding Detection

UI\Controls\Box::isPadded

(UI 0.9.9)

UI\Controls\Box::isPadded — Padding Detection

说明

public UI\Controls\Box::isPadded ( ) : bool

Shall detect if padding is enabled on this Box

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Set Padding

  • ? UI\Controls\Box::isPadded
  • UI\Draw\Pen ?
  • PHP Manual
  • UI\Controls\Box
  • Set Padding

UI\Controls\Box::setPadded

(UI 0.9.9)

UI\Controls\Box::setPadded — Set Padding

说明

public UI\Controls\Box::setPadded ( bool $padded )

Shall enable or disable padding on this Box

参数

padded

User Contributed Notes

There are no user contributed notes for this page.


Draw Pen

(UI 0.9.9)

简介

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

类摘要

final UI\Draw\Pen {
/* 方法 */
public clip ( UI\Draw\Path $path )
public fill ( UI\Draw\Path $path , UI\Draw\Brush $with )
public fill ( UI\Draw\Path $path , UI\Draw\Color $with )
public fill ( UI\Draw\Path $path , int $with )
public restore ( )
public save ( )
public stroke ( UI\Draw\Path $path , UI\Draw\Brush $with , UI\Draw\Stroke $stroke )
public stroke ( UI\Draw\Path $path , UI\Draw\Color $with , UI\Draw\Stroke $stroke )
public stroke ( UI\Draw\Path $path , int $with , UI\Draw\Stroke $stroke )
public transform ( UI\Draw\Matrix $matrix )
public write ( UI\Point $point , UI\Draw\Text\Layout $layout )
}

Table of Contents

  • UI\Draw\Pen::clip — Clip a Path
  • UI\Draw\Pen::fill — Fill a Path
  • UI\Draw\Pen::restore — Restore
  • UI\Draw\Pen::save — Save
  • UI\Draw\Pen::stroke — Stroke a Path
  • UI\Draw\Pen::transform — Matrix Transform
  • UI\Draw\Pen::write — Draw Text at Point

User Contributed Notes

There are no user contributed notes for this page.


Clip a Path

  • ? UI\Draw\Pen
  • UI\Draw\Pen::fill ?
  • PHP Manual
  • UI\Draw\Pen
  • Clip a Path

UI\Draw\Pen::clip

(UI 0.9.9)

UI\Draw\Pen::clip — Clip a Path

说明

public UI\Draw\Pen::clip ( UI\Draw\Path $path )

Shall clip the given Path

参数

path

The path to clip

User Contributed Notes

There are no user contributed notes for this page.


Fill a Path

  • ? UI\Draw\Pen::clip
  • UI\Draw\Pen::restore ?
  • PHP Manual
  • UI\Draw\Pen
  • Fill a Path

UI\Draw\Pen::fill

(UI 0.9.9)

UI\Draw\Pen::fill — Fill a Path

说明

public UI\Draw\Pen::fill ( UI\Draw\Path $path , UI\Draw\Brush $with )
public UI\Draw\Pen::fill ( UI\Draw\Path $path , UI\Draw\Color $with )
public UI\Draw\Pen::fill ( UI\Draw\Path $path , int $with )

Shall fill the given path

参数

path

The path to fill

with

The color or brush to fill with

User Contributed Notes

There are no user contributed notes for this page.


Restore

  • ? UI\Draw\Pen::fill
  • UI\Draw\Pen::save ?
  • PHP Manual
  • UI\Draw\Pen
  • Restore

UI\Draw\Pen::restore

(UI 0.9.9)

UI\Draw\Pen::restore — Restore

说明

public UI\Draw\Pen::restore ( )

Shall restore a previously saved Pen

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Save

  • ? UI\Draw\Pen::restore
  • UI\Draw\Pen::stroke ?
  • PHP Manual
  • UI\Draw\Pen
  • Save

UI\Draw\Pen::save

(UI 0.9.9)

UI\Draw\Pen::save — Save

说明

public UI\Draw\Pen::save ( )

Shall save the Pen

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Stroke a Path

  • ? UI\Draw\Pen::save
  • UI\Draw\Pen::transform ?
  • PHP Manual
  • UI\Draw\Pen
  • Stroke a Path

UI\Draw\Pen::stroke

(UI 0.9.9)

UI\Draw\Pen::stroke — Stroke a Path

说明

public UI\Draw\Pen::stroke ( UI\Draw\Path $path , UI\Draw\Brush $with , UI\Draw\Stroke $stroke )
public UI\Draw\Pen::stroke ( UI\Draw\Path $path , UI\Draw\Color $with , UI\Draw\Stroke $stroke )
public UI\Draw\Pen::stroke ( UI\Draw\Path $path , int $with , UI\Draw\Stroke $stroke )

Shall stroke the given path

参数

path

The path to stroke

with

The color or brush to stroke with

stroke

The configuration of the stroke

User Contributed Notes

There are no user contributed notes for this page.


Matrix Transform

  • ? UI\Draw\Pen::stroke
  • UI\Draw\Pen::write ?
  • PHP Manual
  • UI\Draw\Pen
  • Matrix Transform

UI\Draw\Pen::transform

(UI 0.9.9)

UI\Draw\Pen::transform — Matrix Transform

说明

public UI\Draw\Pen::transform ( UI\Draw\Matrix $matrix )

Shall perform matrix transformation

参数

matrix

The matrix to use

User Contributed Notes

There are no user contributed notes for this page.


Draw Text at Point

  • ? UI\Draw\Pen::transform
  • UI\Draw\Path ?
  • PHP Manual
  • UI\Draw\Pen
  • Draw Text at Point

UI\Draw\Pen::write

(UI 0.9.9)

UI\Draw\Pen::write — Draw Text at Point

说明

public UI\Draw\Pen::write ( UI\Point $point , UI\Draw\Text\Layout $layout )

Shall draw the given text layout at the given point

参数

point

The point to perform the drawing

layout

The layout of the text to draw

User Contributed Notes

There are no user contributed notes for this page.


Draw Path

(UI 0.9.9)

简介

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

类摘要

UI\Draw\Path {
/* Constants */
const int Winding ;
const int Alternate ;
/* Constructor */
public __construct ( int $mode = UI\Draw\Path::Winding )
/* 方法 */
public addRectangle ( UI\Point $point , UI\Size $size )
public arcTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public bezierTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public closeFigure ( )
public end ( )
public lineTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public newFigure ( UI\Point $point )
public newFigureWithArc ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
}

预定义常量

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Table of Contents

  • UI\Draw\Path::addRectangle — Draw a Rectangle
  • UI\Draw\Path::arcTo — Draw an Arc
  • UI\Draw\Path::bezierTo — Draw Bezier Curve
  • UI\Draw\Path::closeFigure — Close Figure
  • UI\Draw\Path::__construct — Construct a new Path
  • UI\Draw\Path::end — Finalize Path
  • UI\Draw\Path::lineTo — Draw a Line
  • UI\Draw\Path::newFigure — Draw Figure
  • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

User Contributed Notes

There are no user contributed notes for this page.


Draw a Rectangle

  • ? UI\Draw\Path
  • UI\Draw\Path::arcTo ?
  • PHP Manual
  • UI\Draw\Path
  • Draw a Rectangle

UI\Draw\Path::addRectangle

(UI 0.9.9)

UI\Draw\Path::addRectangle — Draw a Rectangle

说明

public UI\Draw\Path::addRectangle ( UI\Point $point , UI\Size $size )

Shall map the path of a rectangle of the given size, at the given point

参数

point

The point to begin the shape

size

The size of the rectangle

User Contributed Notes

There are no user contributed notes for this page.


Draw an Arc

  • ? UI\Draw\Path::addRectangle
  • UI\Draw\Path::bezierTo ?
  • PHP Manual
  • UI\Draw\Path
  • Draw an Arc

UI\Draw\Path::arcTo

(UI 0.9.9)

UI\Draw\Path::arcTo — Draw an Arc

说明

public UI\Draw\Path::arcTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall map the path for an arc

参数

point

The point to begin mapping

radius

The radius of the arc

angle

The angle of the arc

sweep

The sweep of the arc

negative

返回值

User Contributed Notes

There are no user contributed notes for this page.


Draw Bezier Curve

  • ? UI\Draw\Path::arcTo
  • UI\Draw\Path::closeFigure ?
  • PHP Manual
  • UI\Draw\Path
  • Draw Bezier Curve

UI\Draw\Path::bezierTo

(UI 0.9.9)

UI\Draw\Path::bezierTo — Draw Bezier Curve

说明

public UI\Draw\Path::bezierTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall draw a bezier curve

参数

point

The point at which to begin mapping

radius

The radius of the curve

angle

The angle of the curve

sweep

The sweep of the curve

negative

User Contributed Notes

There are no user contributed notes for this page.


Close Figure

  • ? UI\Draw\Path::bezierTo
  • UI\Draw\Path::__construct ?
  • PHP Manual
  • UI\Draw\Path
  • Close Figure

UI\Draw\Path::closeFigure

(UI 0.9.9)

UI\Draw\Path::closeFigure — Close Figure

说明

public UI\Draw\Path::closeFigure ( )

Shall close the current figure

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Path

  • ? UI\Draw\Path::closeFigure
  • UI\Draw\Path::end ?
  • PHP Manual
  • UI\Draw\Path
  • Construct a new Path

UI\Draw\Path::__construct

(UI 0.9.9)

UI\Draw\Path::__construct — Construct a new Path

说明

public UI\Draw\Path::__construct ( int $mode = UI\Draw\Path::Winding )

Shall construct a new path in the given mode

参数

mode

Path::Winding or Path::Alternate

User Contributed Notes

There are no user contributed notes for this page.


Finalize Path

  • ? UI\Draw\Path::__construct
  • UI\Draw\Path::lineTo ?
  • PHP Manual
  • UI\Draw\Path
  • Finalize Path

UI\Draw\Path::end

(UI 0.9.9)

UI\Draw\Path::end — Finalize Path

说明

public UI\Draw\Path::end ( )

Shall finalize this Path

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Draw a Line

  • ? UI\Draw\Path::end
  • UI\Draw\Path::newFigure ?
  • PHP Manual
  • UI\Draw\Path
  • Draw a Line

UI\Draw\Path::lineTo

(UI 0.9.9)

UI\Draw\Path::lineTo — Draw a Line

说明

public UI\Draw\Path::lineTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall map the path for a line

参数

point

The point to begin mapping

radius

angle

sweep

negative

返回值

User Contributed Notes

There are no user contributed notes for this page.


Draw Figure

  • ? UI\Draw\Path::lineTo
  • UI\Draw\Path::newFigureWithArc ?
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure

UI\Draw\Path::newFigure

(UI 0.9.9)

UI\Draw\Path::newFigure — Draw Figure

说明

public UI\Draw\Path::newFigure ( UI\Point $point )

Shall map a new figure at the given point

参数

point

The point to begin mapping

User Contributed Notes

There are no user contributed notes for this page.


Draw Figure with Arc

  • ? UI\Draw\Path::newFigure
  • UI\Draw\Matrix ?
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure with Arc

UI\Draw\Path::newFigureWithArc

(UI 0.9.9)

UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

说明

public UI\Draw\Path::newFigureWithArc ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

参数

point

radius

angle

sweep

negative

返回值

User Contributed Notes

There are no user contributed notes for this page.


Draw Matrix

(UI 0.9.9)

简介

类摘要

UI\Draw\Matrix {
/* 方法 */
public invert ( )
public isInvertible ( ) : bool
public multiply ( UI\Draw\Matrix $matrix ) : UI\Draw\Matrix
public rotate ( UI\Point $point , float $amount )
public scale ( UI\Point $center , UI\Point $point )
public skew ( UI\Point $point , UI\Point $amount )
public translate ( UI\Point $point )
}

Table of Contents

  • UI\Draw\Matrix::invert — Invert Matrix
  • UI\Draw\Matrix::isInvertible — Invertible Detection
  • UI\Draw\Matrix::multiply — Multiply Matrix
  • UI\Draw\Matrix::rotate — Rotate Matrix
  • UI\Draw\Matrix::scale — Scale Matrix
  • UI\Draw\Matrix::skew — Skew Matrix
  • UI\Draw\Matrix::translate — Translate Matrix

User Contributed Notes

There are no user contributed notes for this page.


Invert Matrix

  • ? UI\Draw\Matrix
  • UI\Draw\Matrix::isInvertible ?
  • PHP Manual
  • UI\Draw\Matrix
  • Invert Matrix

UI\Draw\Matrix::invert

(UI 0.9.9)

UI\Draw\Matrix::invert — Invert Matrix

说明

public UI\Draw\Matrix::invert ( )

Shall invert this matrix

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Invertible Detection

  • ? UI\Draw\Matrix::invert
  • UI\Draw\Matrix::multiply ?
  • PHP Manual
  • UI\Draw\Matrix
  • Invertible Detection

UI\Draw\Matrix::isInvertible

(UI 0.9.9)

UI\Draw\Matrix::isInvertible — Invertible Detection

说明

public UI\Draw\Matrix::isInvertible ( ) : bool

Shall detect if this Matrix may be inverted

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Multiply Matrix

  • ? UI\Draw\Matrix::isInvertible
  • UI\Draw\Matrix::rotate ?
  • PHP Manual
  • UI\Draw\Matrix
  • Multiply Matrix

UI\Draw\Matrix::multiply

(UI 0.9.9)

UI\Draw\Matrix::multiply — Multiply Matrix

说明

public UI\Draw\Matrix::multiply ( UI\Draw\Matrix $matrix ) : UI\Draw\Matrix

Shall multiply this matrix with the given matrix

参数

此函数没有参数。

返回值

The new Matrix

User Contributed Notes

There are no user contributed notes for this page.


Rotate Matrix

  • ? UI\Draw\Matrix::multiply
  • UI\Draw\Matrix::scale ?
  • PHP Manual
  • UI\Draw\Matrix
  • Rotate Matrix

UI\Draw\Matrix::rotate

(UI 0.9.9)

UI\Draw\Matrix::rotate — Rotate Matrix

说明

public UI\Draw\Matrix::rotate ( UI\Point $point , float $amount )

Shall rotate this Matrix

参数

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Scale Matrix

  • ? UI\Draw\Matrix::rotate
  • UI\Draw\Matrix::skew ?
  • PHP Manual
  • UI\Draw\Matrix
  • Scale Matrix

UI\Draw\Matrix::scale

(UI 0.9.9)

UI\Draw\Matrix::scale — Scale Matrix

说明

public UI\Draw\Matrix::scale ( UI\Point $center , UI\Point $point )

Shall scale this Matrix

参数

center

point

User Contributed Notes

There are no user contributed notes for this page.


Skew Matrix

  • ? UI\Draw\Matrix::scale
  • UI\Draw\Matrix::translate ?
  • PHP Manual
  • UI\Draw\Matrix
  • Skew Matrix

UI\Draw\Matrix::skew

(UI 0.9.9)

UI\Draw\Matrix::skew — Skew Matrix

说明

public UI\Draw\Matrix::skew ( UI\Point $point , UI\Point $amount )

Shall skew this Matrix

参数

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Translate Matrix

  • ? UI\Draw\Matrix::skew
  • UI\Draw\Color ?
  • PHP Manual
  • UI\Draw\Matrix
  • Translate Matrix

UI\Draw\Matrix::translate

(UI 0.9.9)

UI\Draw\Matrix::translate — Translate Matrix

说明

public UI\Draw\Matrix::translate ( UI\Point $point )

Shall translate this Matrix

参数

point

User Contributed Notes

There are no user contributed notes for this page.


Color Representation

(UI 0.9.9)

简介

Represents RGBA colours, individual channels are accessible via public properties.

类摘要

UI\Draw\Color {
/* Constants */
const int Red ;
const int Green ;
const int Blue ;
const int Alpha ;
/* 属性 */
public $r ;
public $g ;
public $b ;
public $a ;
/* Constructor */
public __construct ( UI\Draw\Color $color = ? )
public __construct ( int $color = ? )
/* 方法 */
public getChannel ( int $channel ) : float
public setChannel ( int $channel , float $value ) : void
}

属性

r

Provides access to the red channel

g

Provides access to the green channel

b

Provides access to the blue channel

a

Provides access to the alpha channel

预定义常量

UI\Draw\Color::Red

Identifies the red channel

UI\Draw\Color::Green

Identifies the green channel

UI\Draw\Color::Blue

Identifies the blue channel

UI\Draw\Color::Alpha

Identifies the alpha channel

Table of Contents

  • UI\Draw\Color::__construct — Construct new Color
  • UI\Draw\Color::getChannel — Color Manipulation
  • UI\Draw\Color::setChannel — Color Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Construct new Color

  • ? UI\Draw\Color
  • UI\Draw\Color::getChannel ?
  • PHP Manual
  • UI\Draw\Color
  • Construct new Color

UI\Draw\Color::__construct

(UI 0.9.9)

UI\Draw\Color::__construct — Construct new Color

说明

public UI\Draw\Color::__construct ( UI\Draw\Color $color = ? )
public UI\Draw\Color::__construct ( int $color = ? )

Shall construct a new color

参数

color

May be UI\Draw\Color or RRGGBBAA

User Contributed Notes

There are no user contributed notes for this page.


Color Manipulation

  • ? UI\Draw\Color::__construct
  • UI\Draw\Color::setChannel ?
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::getChannel

(UI 0.9.9)

UI\Draw\Color::getChannel — Color Manipulation

说明

public UI\Draw\Color::getChannel ( int $channel ) : float

Shall retrieve the value for a channel

参数

channel

Constant channel identity

返回值

The current value of the requested channel

User Contributed Notes

There are no user contributed notes for this page.


Color Manipulation

  • ? UI\Draw\Color::getChannel
  • UI\Draw\Stroke ?
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::setChannel

(UI 0.9.9)

UI\Draw\Color::setChannel — Color Manipulation

说明

public UI\Draw\Color::setChannel ( int $channel , float $value ) : void

Shall set the selected channel to the given value

参数

channel

Constant channel identity

value

The new value for the selected channel

返回值

User Contributed Notes

There are no user contributed notes for this page.


Draw Stroke

(UI 0.9.9)

简介

Holds the configuration for the Pen to perform a stroke

类摘要

UI\Draw\Stroke {
/* Constructor */
public __construct ( int $cap = UI\Draw\Line\Cap::Flat , int $join = UI\Draw\Line\Join::Miter , float $thickness = 1 , float $miterLimit = 10 )
/* 方法 */
public getCap ( ) : int
public getJoin ( ) : int
public getMiterLimit ( ) : float
public getThickness ( ) : float
public setCap ( int $cap )
public setJoin ( int $join )
public setMiterLimit ( float $limit )
public setThickness ( float $thickness )
}

Table of Contents

  • UI\Draw\Stroke::__construct — Construct a new Stroke
  • UI\Draw\Stroke::getCap — Get Line Cap
  • UI\Draw\Stroke::getJoin — Get Line Join
  • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
  • UI\Draw\Stroke::getThickness — Get Thickness
  • UI\Draw\Stroke::setCap — Set Line Cap
  • UI\Draw\Stroke::setJoin — Set Line Join
  • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
  • UI\Draw\Stroke::setThickness — Set Thickness

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Stroke

  • ? UI\Draw\Stroke
  • UI\Draw\Stroke::getCap ?
  • PHP Manual
  • UI\Draw\Stroke
  • Construct a new Stroke

UI\Draw\Stroke::__construct

(UI 0.9.9)

UI\Draw\Stroke::__construct — Construct a new Stroke

说明

public UI\Draw\Stroke::__construct ( int $cap = UI\Draw\Line\Cap::Flat , int $join = UI\Draw\Line\Join::Miter , float $thickness = 1 , float $miterLimit = 10 )

Shall construct a new Stroke

参数

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

thickness

The thickness of the stroke

miterLimit

Miter limit (default is sensible for all supported platforms)

User Contributed Notes

There are no user contributed notes for this page.


Get Line Cap

  • ? UI\Draw\Stroke::__construct
  • UI\Draw\Stroke::getJoin ?
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Cap

UI\Draw\Stroke::getCap

(UI 0.9.9)

UI\Draw\Stroke::getCap — Get Line Cap

说明

public UI\Draw\Stroke::getCap ( ) : int

Shall retrieve the line cap setting of this Stroke

参数

此函数没有参数。

返回值

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

User Contributed Notes

There are no user contributed notes for this page.


Get Line Join

  • ? UI\Draw\Stroke::getCap
  • UI\Draw\Stroke::getMiterLimit ?
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Join

UI\Draw\Stroke::getJoin

(UI 0.9.9)

UI\Draw\Stroke::getJoin — Get Line Join

说明

public UI\Draw\Stroke::getJoin ( ) : int

Shall retrieve the line join setting of this Stroke

参数

此函数没有参数。

返回值

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

User Contributed Notes

There are no user contributed notes for this page.


Get Miter Limit

  • ? UI\Draw\Stroke::getJoin
  • UI\Draw\Stroke::getThickness ?
  • PHP Manual
  • UI\Draw\Stroke
  • Get Miter Limit

UI\Draw\Stroke::getMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::getMiterLimit — Get Miter Limit

说明

public UI\Draw\Stroke::getMiterLimit ( ) : float

Shall retrieve the miter limit of this Stroke

参数

此函数没有参数。

返回值

The current miter limit

User Contributed Notes

There are no user contributed notes for this page.


Get Thickness

  • ? UI\Draw\Stroke::getMiterLimit
  • UI\Draw\Stroke::setCap ?
  • PHP Manual
  • UI\Draw\Stroke
  • Get Thickness

UI\Draw\Stroke::getThickness

(UI 0.9.9)

UI\Draw\Stroke::getThickness — Get Thickness

说明

public UI\Draw\Stroke::getThickness ( ) : float

Shall retrieve the thickness of this Stroke

参数

此函数没有参数。

返回值

The current thickness

User Contributed Notes

There are no user contributed notes for this page.


Set Line Cap

  • ? UI\Draw\Stroke::getThickness
  • UI\Draw\Stroke::setJoin ?
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Cap

UI\Draw\Stroke::setCap

(UI 0.9.9)

UI\Draw\Stroke::setCap — Set Line Cap

说明

public UI\Draw\Stroke::setCap ( int $cap )

Shall set the line cap setting for this Stroke

参数

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

User Contributed Notes

There are no user contributed notes for this page.


Set Line Join

  • ? UI\Draw\Stroke::setCap
  • UI\Draw\Stroke::setMiterLimit ?
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Join

UI\Draw\Stroke::setJoin

(UI 0.9.9)

UI\Draw\Stroke::setJoin — Set Line Join

说明

public UI\Draw\Stroke::setJoin ( int $join )

Shall set the line join setting for this Stroke

参数

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set Miter Limit

  • ? UI\Draw\Stroke::setJoin
  • UI\Draw\Stroke::setThickness ?
  • PHP Manual
  • UI\Draw\Stroke
  • Set Miter Limit

UI\Draw\Stroke::setMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::setMiterLimit — Set Miter Limit

说明

public UI\Draw\Stroke::setMiterLimit ( float $limit )

Set the miter limit for this Stroke

参数

limit

The new limit

User Contributed Notes

There are no user contributed notes for this page.


Set Thickness

  • ? UI\Draw\Stroke::setMiterLimit
  • UI\Draw\Brush ?
  • PHP Manual
  • UI\Draw\Stroke
  • Set Thickness

UI\Draw\Stroke::setThickness

(UI 0.9.9)

UI\Draw\Stroke::setThickness — Set Thickness

说明

public UI\Draw\Stroke::setThickness ( float $thickness )

Shall set the thickness for this Stroke

参数

thickness

The new thickness

User Contributed Notes

There are no user contributed notes for this page.


Brushes

(UI 0.9.9)

简介

Represents a solid color brush

类摘要

UI\Draw\Brush {
/* Constructor */
public __construct ( UI\Draw\Color $color )
public __construct ( int $color )
/* 方法 */
public getColor ( ) : UI\Draw\Color
public setColor ( UI\Draw\Color $color ) : void
public setColor ( int $color ) : void
}

Table of Contents

  • UI\Draw\Brush::__construct — Construct a new Brush
  • UI\Draw\Brush::getColor — Get Color
  • UI\Draw\Brush::setColor — Set Color

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Brush

  • ? UI\Draw\Brush
  • UI\Draw\Brush::getColor ?
  • PHP Manual
  • UI\Draw\Brush
  • Construct a new Brush

UI\Draw\Brush::__construct

(UI 0.9.9)

UI\Draw\Brush::__construct — Construct a new Brush

说明

public UI\Draw\Brush::__construct ( UI\Draw\Color $color )
public UI\Draw\Brush::__construct ( int $color )

Shall construct a solid brush using the given color

参数

color

Can be a UI\Draw\Color or RRGGBBAA

User Contributed Notes

There are no user contributed notes for this page.


Get Color

  • ? UI\Draw\Brush::__construct
  • UI\Draw\Brush::setColor ?
  • PHP Manual
  • UI\Draw\Brush
  • Get Color

UI\Draw\Brush::getColor

(UI 0.9.9)

UI\Draw\Brush::getColor — Get Color

说明

public UI\Draw\Brush::getColor ( ) : UI\Draw\Color

Shall return a UI\Draw\Color for this brush

参数

此函数没有参数。

返回值

The current color of the brush

User Contributed Notes

There are no user contributed notes for this page.


Set Color

  • ? UI\Draw\Brush::getColor
  • UI\Draw\Brush\Gradient ?
  • PHP Manual
  • UI\Draw\Brush
  • Set Color

UI\Draw\Brush::setColor

(UI 0.9.9)

UI\Draw\Brush::setColor — Set Color

说明

public UI\Draw\Brush::setColor ( UI\Draw\Color $color ) : void
public UI\Draw\Brush::setColor ( int $color ) : void

Shall set the color of this brush to the color provided

参数

color

Can be a UI\Draw\Color or RRGGBBAA

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gradient Brushes

(UI 2.0.0)

简介

Abstract for gradient brushes

类摘要

abstract UI\Draw\Brush\Gradient extends UI\Draw\Brush {
/* 方法 */
public addStop ( float $position , UI\Draw\Color $color ) : int
public addStop ( float $position , int $color ) : int
public delStop ( int $index ) : int
public setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public setStop ( int $index , float $position , int $color ) : bool
/* 继承的方法 */
public UI\Draw\Brush::getColor ( ) : UI\Draw\Color
public UI\Draw\Brush::setColor ( UI\Draw\Color $color ) : void
public UI\Draw\Brush::setColor ( int $color ) : void
}

Table of Contents

  • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::setStop — Stop Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Stop Manipulation

  • ? UI\Draw\Brush\Gradient
  • UI\Draw\Brush\Gradient::delStop ?
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::addStop

(UI 2.0.0)

UI\Draw\Brush\Gradient::addStop — Stop Manipulation

说明

public UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color ) : int
public UI\Draw\Brush\Gradient::addStop ( float $position , int $color ) : int

Shall at a stop of the given color at the given position

参数

position

The position for the new stop

color

The color for the new stop, may be UI\Draw\Color or RRGGBBAA

返回值

Total number of stops

User Contributed Notes

There are no user contributed notes for this page.


Stop Manipulation

  • ? UI\Draw\Brush\Gradient::addStop
  • UI\Draw\Brush\Gradient::setStop ?
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::delStop

(UI 2.0.0)

UI\Draw\Brush\Gradient::delStop — Stop Manipulation

说明

public UI\Draw\Brush\Gradient::delStop ( int $index ) : int

Warning

本函数还未编写文档，仅有参数列表。

参数

index

返回值

Total number of stops

User Contributed Notes

There are no user contributed notes for this page.


Stop Manipulation

  • ? UI\Draw\Brush\Gradient::delStop
  • UI\Draw\Brush\LinearGradient ?
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::setStop

(UI 2.0.0)

UI\Draw\Brush\Gradient::setStop — Stop Manipulation

说明

public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , int $color ) : bool

参数

index

The index of the stop to set

position

The position for the stop

color

The color for the stop, may be UI\Draw\Color or RRGGBBAA

返回值

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Linear Gradient

(UI 2.0.0)

简介

类摘要

UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $end )
/* 继承的方法 */
public UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color ) : int
public UI\Draw\Brush\Gradient::addStop ( float $position , int $color ) : int
public UI\Draw\Brush\Gradient::delStop ( int $index ) : int
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , int $color ) : bool
}

Table of Contents

  • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient

User Contributed Notes

There are no user contributed notes for this page.


Construct a Linear Gradient

  • ? UI\Draw\Brush\LinearGradient
  • UI\Draw\Brush\RadialGradient ?
  • PHP Manual
  • UI\Draw\Brush\LinearGradient
  • Construct a Linear Gradient

UI\Draw\Brush\LinearGradient::__construct

(UI 2.0.0)

UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient

说明

public UI\Draw\Brush\LinearGradient::__construct ( UI\Point $start , UI\Point $end )

Shall construct a new linear gradient

参数

start

end

User Contributed Notes

There are no user contributed notes for this page.


Radial Gradient

(UI 2.0.0)

简介

类摘要

UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $outer , float $radius )
/* 继承的方法 */
public UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color ) : int
public UI\Draw\Brush\Gradient::addStop ( float $position , int $color ) : int
public UI\Draw\Brush\Gradient::delStop ( int $index ) : int
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , int $color ) : bool
}

Table of Contents

  • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Radial Gradient

  • ? UI\Draw\Brush\RadialGradient
  • UI\Draw\Text\Layout ?
  • PHP Manual
  • UI\Draw\Brush\RadialGradient
  • Construct a new Radial Gradient

UI\Draw\Brush\RadialGradient::__construct

(UI 2.0.0)

UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient

说明

public UI\Draw\Brush\RadialGradient::__construct ( UI\Point $start , UI\Point $outer , float $radius )

Shall construct a new radial gradient

参数

start

outer

radius

User Contributed Notes

There are no user contributed notes for this page.


Represents Text Layout

(UI 0.9.9)

简介

A Text Layout represents the layout of text which will be drawn by the Pen

类摘要

UI\Draw\Text\Layout {
/* Constructor */
public __construct ( string $text , UI\Draw\Text\Font $font , float $width )
/* 方法 */
public setColor ( UI\Draw\Color $color , int $start = 0 , int $end = ? )
public setColor ( int $color , int $start = 0 , int $end = ? )
public setWidth ( float $width )
}

Table of Contents

  • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
  • UI\Draw\Text\Layout::setColor — Set Color
  • UI\Draw\Text\Layout::setWidth — Set Width

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Text Layout

  • ? UI\Draw\Text\Layout
  • UI\Draw\Text\Layout::setColor ?
  • PHP Manual
  • UI\Draw\Text\Layout
  • Construct a new Text Layout

UI\Draw\Text\Layout::__construct

(UI 0.9.9)

UI\Draw\Text\Layout::__construct — Construct a new Text Layout

说明

public UI\Draw\Text\Layout::__construct ( string $text , UI\Draw\Text\Font $font , float $width )

Shall construct a new Text Layout

参数

text

The text for the layout

font

The font to use for writing

width

The width of the layout

User Contributed Notes

There are no user contributed notes for this page.


Set Color

  • ? UI\Draw\Text\Layout::__construct
  • UI\Draw\Text\Layout::setWidth ?
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Color

UI\Draw\Text\Layout::setColor

(UI 0.9.9)

UI\Draw\Text\Layout::setColor — Set Color

说明

public UI\Draw\Text\Layout::setColor ( UI\Draw\Color $color , int $start = 0 , int $end = ? )
public UI\Draw\Text\Layout::setColor ( int $color , int $start = 0 , int $end = ? )

Shall set the Color for all of, or a range of the text in the Layout

参数

color

The color to use

start

The starting character

end

The ending character, by default the end of the string

User Contributed Notes

There are no user contributed notes for this page.


Set Width

  • ? UI\Draw\Text\Layout::setColor
  • UI\Draw\Text\Font ?
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Width

UI\Draw\Text\Layout::setWidth

(UI 0.9.9)

UI\Draw\Text\Layout::setWidth — Set Width

说明

public UI\Draw\Text\Layout::setWidth ( float $width )

Shall set the width of this Text Layout

参数

width

The new width

User Contributed Notes

There are no user contributed notes for this page.


Represents a Font

(UI 0.9.9)

简介

Loads a described font

类摘要

UI\Draw\Text\Font {
/* Constructor */
public __construct ( UI\Draw\Text\Font\Descriptor $descriptor )
/* 方法 */
public getAscent ( ) : float
public getDescent ( ) : float
public getLeading ( ) : float
public getUnderlinePosition ( ) : float
public getUnderlineThickness ( ) : float
}

Table of Contents

  • UI\Draw\Text\Font::__construct — Construct a new Font
  • UI\Draw\Text\Font::getAscent — Font Metrics
  • UI\Draw\Text\Font::getDescent — Font Metrics
  • UI\Draw\Text\Font::getLeading — Font Metrics
  • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
  • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Font

  • ? UI\Draw\Text\Font
  • UI\Draw\Text\Font::getAscent ?
  • PHP Manual
  • UI\Draw\Text\Font
  • Construct a new Font

UI\Draw\Text\Font::__construct

(UI 0.9.9)

UI\Draw\Text\Font::__construct — Construct a new Font

说明

public UI\Draw\Text\Font::__construct ( UI\Draw\Text\Font\Descriptor $descriptor )

Shall construct a new Font using the given descriptor

参数

descriptor

The descriptor for the Font

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • ? UI\Draw\Text\Font::__construct
  • UI\Draw\Text\Font::getDescent ?
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getAscent

(UI 1.0.3)

UI\Draw\Text\Font::getAscent — Font Metrics

说明

public UI\Draw\Text\Font::getAscent ( ) : float

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • ? UI\Draw\Text\Font::getAscent
  • UI\Draw\Text\Font::getLeading ?
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getDescent

(UI 1.0.3)

UI\Draw\Text\Font::getDescent — Font Metrics

说明

public UI\Draw\Text\Font::getDescent ( ) : float

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • ? UI\Draw\Text\Font::getDescent
  • UI\Draw\Text\Font::getUnderlinePosition ?
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getLeading

(UI 1.0.3)

UI\Draw\Text\Font::getLeading — Font Metrics

说明

public UI\Draw\Text\Font::getLeading ( ) : float

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • ? UI\Draw\Text\Font::getLeading
  • UI\Draw\Text\Font::getUnderlineThickness ?
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlinePosition

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlinePosition — Font Metrics

说明

public UI\Draw\Text\Font::getUnderlinePosition ( ) : float

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • ? UI\Draw\Text\Font::getUnderlinePosition
  • UI\Draw\Text\Font\Descriptor ?
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlineThickness

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

说明

public UI\Draw\Text\Font::getUnderlineThickness ( ) : float

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Font Descriptor

(UI 0.9.9)

简介

Describes a font

类摘要

UI\Draw\Text\Font\Descriptor {
/* Constructor */
public __construct ( string $family , float $size , int $weight = UI\Draw\Text\Font\Weight::Normal , int $italic = UI\Draw\Text\Font\Italic::Normal , int $stretch = UI\Draw\Text\Font\Stretch::Normal )
/* 方法 */
public getFamily ( ) : string
public getItalic ( ) : int
public getSize ( ) : float
public getStretch ( ) : int
public getWeight ( ) : int
}

Table of Contents

  • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
  • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
  • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
  • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
  • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
  • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Font Descriptor

  • ? UI\Draw\Text\Font\Descriptor
  • UI\Draw\Text\Font\Descriptor::getFamily ?
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Construct a new Font Descriptor

UI\Draw\Text\Font\Descriptor::__construct

(UI 0.9.9)

UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor

说明

public UI\Draw\Text\Font\Descriptor::__construct ( string $family , float $size , int $weight = UI\Draw\Text\Font\Weight::Normal , int $italic = UI\Draw\Text\Font\Italic::Normal , int $stretch = UI\Draw\Text\Font\Stretch::Normal )

Shall construct a new Font Descriptor

参数

family

The name of a valid family of fonts

size

The preferred size

weight

UI\Draw\Text\Font\Weight constant

italic

UI\Draw\Text\Font\Italic constant

stretch

UI\Draw\Text\Font\Stretch constant

User Contributed Notes

There are no user contributed notes for this page.


Get Font Family

  • ? UI\Draw\Text\Font\Descriptor::__construct
  • UI\Draw\Text\Font\Descriptor::getItalic ?
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Get Font Family

UI\Draw\Text\Font\Descriptor::getFamily

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family

说明

public UI\Draw\Text\Font\Descriptor::getFamily ( ) : string

Shall return the requested font family

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Style Detection

  • ? UI\Draw\Text\Font\Descriptor::getFamily
  • UI\Draw\Text\Font\Descriptor::getSize ?
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Style Detection

UI\Draw\Text\Font\Descriptor::getItalic

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getItalic — Style Detection

说明

public UI\Draw\Text\Font\Descriptor::getItalic ( ) : int

Shall return constant setting

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Size Detection

  • ? UI\Draw\Text\Font\Descriptor::getItalic
  • UI\Draw\Text\Font\Descriptor::getStretch ?
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Size Detection

UI\Draw\Text\Font\Descriptor::getSize

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getSize — Size Detection

说明

public UI\Draw\Text\Font\Descriptor::getSize ( ) : float

Shall return the requested size

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Style Detection

  • ? UI\Draw\Text\Font\Descriptor::getSize
  • UI\Draw\Text\Font\Descriptor::getWeight ?
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Style Detection

UI\Draw\Text\Font\Descriptor::getStretch

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getStretch — Style Detection

说明

public UI\Draw\Text\Font\Descriptor::getStretch ( ) : int

Shall return requested stretch

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Weight Detection

  • ? UI\Draw\Text\Font\Descriptor::getStretch
  • UI 函数 ?
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Weight Detection

UI\Draw\Text\Font\Descriptor::getWeight

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection

说明

public UI\Draw\Text\Font\Descriptor::getWeight ( ) : int

Shall return requested weight

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


UI 函数

Table of Contents

  • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
  • UI\quit — Quit UI Loop
  • UI\run — Enter UI Loop

User Contributed Notes

There are no user contributed notes for this page.


Retrieve Font Families

  • ? UI 函数
  • UI\quit ?
  • PHP Manual
  • UI 函数
  • Retrieve Font Families

UI\Draw\Text\Font\fontFamilies

(UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Retrieve Font Families

说明

UI\Draw\Text\Font\fontFamilies ( ) : array

Returns an array of valid font families for the current system

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Quit UI Loop

  • ? UI\Draw\Text\Font\fontFamilies
  • UI\run ?
  • PHP Manual
  • UI 函数
  • Quit UI Loop

UI\quit

(UI 2.0.0)

UI\quit — Quit UI Loop

说明

UI\quit ( ) : void

Shall cause the main loop to be exited

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Enter UI Loop

  • ? UI\quit
  • UI\Draw\Text\Font\Weight ?
  • PHP Manual
  • UI 函数
  • Enter UI Loop

UI\run

(UI 2.0.0)

UI\run — Enter UI Loop

说明

UI\run ( int $flags = ? ) : void

Shall cause PHP to enter into the main loop, by default control will not be returned to the caller

参数

flags

Set UI\Loop to return control, and UI\Wait to return control after waiting

返回值

User Contributed Notes

There are no user contributed notes for this page.


Font Weight Settings

(UI 0.9.9)

简介

类摘要

final UI\Draw\Text\Font\Weight {
/* Constants */
const int Thin ;
const int UltraLight ;
const int Light ;
const int Book ;
const int Normal ;
const int Medium ;
const int SemiBold ;
const int Bold ;
const int UltraBold ;
const int Heavy ;
const int UltraHeavy ;
}

User Contributed Notes

There are no user contributed notes for this page.


Italic Font Settings

(UI 0.9.9)

简介

类摘要

final UI\Draw\Text\Font\Italic {
/* Constants */
const int Normal = 0 ;
const int Oblique = 1 ;
const int Italic = 2 ;
}

User Contributed Notes

There are no user contributed notes for this page.


Font Stretch Settings

(UI 0.9.9)

简介

类摘要

final UI\Draw\Text\Font\Stretch {
/* Constants */
const int UltraCondensed = 0 ;
const int ExtraCondensed = 1 ;
const int Condensed = 2 ;
const int SemiCondensed = 3 ;
const int Normal = 4 ;
const int SemiExpanded = 5 ;
const int Expanded = 6 ;
const int ExtraExpanded = 7 ;
const int UltraExpanded = 8 ;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Cap Settings

(UI 0.9.9)

简介

类摘要

final UI\Draw\Line\Cap {
/* Constants */
const int Flat ;
const int Round ;
const int Square ;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Join Settings

(UI 0.9.9)

简介

类摘要

final UI\Draw\Line\Join {
/* Constants */
const int Miter ;
const int Round ;
const int Bevel ;
}

User Contributed Notes

There are no user contributed notes for this page.


Key Identifiers

(UI 1.0.0)

简介

类摘要

final UI\Key {
/* Constants */
const int Escape ;
const int Insert ;
const int Delete ;
const int Home ;
const int End ;
const int PageUp ;
const int PageDown ;
const int Up ;
const int Down ;
const int Left ;
const int Right ;
const int F1 ;
const int F2 ;
const int F3 ;
const int F4 ;
const int F5 ;
const int F6 ;
const int F7 ;
const int F8 ;
const int F9 ;
const int F10 ;
const int F11 ;
const int F12 ;
const int N0 ;
const int N1 ;
const int N2 ;
const int N3 ;
const int N4 ;
const int N5 ;
const int N6 ;
const int N7 ;
const int N8 ;
const int N9 ;
const int NDot ;
const int NEnter ;
const int NAdd ;
const int NSubtract ;
const int NMultiply ;
const int NDivide ;
}

User Contributed Notes

There are no user contributed notes for this page.


InvalidArgumentException

(UI 1.0.3)

简介

类摘要

UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

There are no user contributed notes for this page.


RuntimeException

(UI 1.0.3)

简介

类摘要

UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

There are no user contributed notes for this page.


FAQ：常见问题

  • 一般信息
  • 邮件列表
  • 获取 PHP
  • 数据库问题
  • 安装 — 安装常见问题
  • 编译问题
  • 使用 PHP
  • 密码散列 — 密码散列安全
  • PHP 和 HTML
  • PHP 和 COM
  • 其他问题

User Contributed Notes

There are no user contributed notes for this page.


一般信息

本章包括了有关 PHP 的大多数一般问题： 它是什么和它做什么。

  1. PHP是什么？
  2. PHP 这个缩写指的是什么？
  3. PHP 版本之间有什么联系？
  4. 可以同时运行几个不同版本的 PHP 吗？
  5. 我觉得自己发现了一个 bug！应该告诉谁？
PHP是什么？

根据本手册的 前言：

PHP 是一种 HTML 嵌入式的脚本语言。 它的很多语法来自 C，Java 和 Perl， 并具有几个 PHP 独有的特点。 该语言的主要目标是让 Web 开发人员快速地书写动态生成的网页。

PHP 这个缩写指的是什么？

PHP 是PHP: Hypertext Preprocessor的首字母缩写。 很多人有些糊涂了，因为缩写中的第一个字母也来自缩写。 这种方法叫做递归缩写（recursive acronyms）， 对此好奇的人可以访问 » 在线计算机词典（Free On-Line Dictionary of Computing） 或者Wikipedia上 » 递归缩写 的解释。

PHP 版本之间有什么联系？

PHP/FI 2.0 是最早的 PHP 版本，已经不再支持。 PHP 3 是 PHP/FI 2.0 的后继者，要好很多。 PHP 7 是目前一代的 PHP，内部使用了 Zend 引擎 3 代， 除了很多新功能之外还提供了许多附加的 面向对象编程（OOP） 特性。

可以同时运行几个不同版本的 PHP 吗？

可以，请参阅见 PHP 源程序发行包中的 INSTALL文件。

我觉得自己发现了一个 bug！应该告诉谁？

应该访问 PHP Bug 数据库并确认你发现的不是一个已知的 bug。 如果你在数据库中没有看到同样的， 用报告表单来报告此 bug。 使用 bug 数据库而不是给某个邮件列表发邮件非常重要， 因为该 bug 会被分配一个跟踪号码， 这样你就有可能在以后回来查看该 bug 的状态。 Bug 数据库在 » https://bugs.php.net/。

User Contributed Notes

There are no user contributed notes for this page.


邮件列表

本章包括有关如何与 PHP 团体接触的问题。最好的方法是邮件列表。

  1. 有没有 PHP 的邮件列表？
  2. 还有其它的团体吗？
  3. 我可以建立我自己的PHP邮件列表吗？
  4. 救命！我看来不能订阅／取消任何一个邮件列表！
  5. 在哪里有个邮件列表的归档吗？
  6. 我可以在邮件列表中问什么？
  7. 向邮件列表发帖子时我需要包括些什么信息？
有没有 PHP 的邮件列表？

当然有！有很多关于几个主题的邮件列表。所有邮件列表的完整列表在 » 技术支持页面。

最通用的邮件列表是 php-general。要订阅，发送一封邮件到 » php-general-subscribe@lists.php.net。不需要在邮件主题或内容中包括任何特殊单词。要取消订阅，发送一封邮件到 » php-general-unsubscribe@lists.php.net。

也可以在我们的 » 技术支持页面通过 web 界面来订阅和取消。

还有其它的团体吗？

世界上有无数 PHP 团体。我们的 » 技术支持页面上有例如一些 IRC 服务器和其它语种的邮件列表。

我可以建立我自己的PHP邮件列表吗？

百分百可以！实际上，我们不仅允许这么做，而且鼓励这么做！ 通过分享您在PHP方面的知识和经验来帮助他人， 有助于促进PHP组织和PHP语言本身的增长和发展。

救命！我看来不能订阅／取消任何一个邮件列表！

如果你在订阅或取消 php-general 邮件列表上有问题，可能是因为邮件列表软件没法确定你正确的邮件地址。如果你的 email 地址是 joeblow@example.com，可以将订阅请求发送到 php-general-subscribe-joeblow=example.com@lists.php.net，或者将取消请求发送到 php-general-unsubscribe-joeblow=example.com@lists.php.net。对其它邮件列表用类似的地址。

The most common reason folks have a hard time unsubscribing from our mailing lists is due to the use of mail forwarders. For example, if your email address is danbrown@example.com, but you subscribed to the mailing list with the forwarder php-lists@example.com and forward that to danbrown@example.com, attempting to unsubscribe danbrown@example.com will not work, as that address is not even known to our systems. Instead, you will need to unsubscribe the address to which the mail is being sent - in this example, php-lists@example.com.

在哪里有个邮件列表的归档吗？

是的，你可以在 » 技术支持页面找到归档站点的列表。 You will also find dozens of sites that archive and/or syndicate our mailing list content by using your favorite Internet search engine and searching for "php mailing list archives".

邮件列表的文章也被作为新闻组消息归档。你可以用新闻组客户端来访问位于 » news://news.php.net/的新闻组服务器。也有一个试验性质的新闻组服务器的 web 界面位于 » http://news.php.net/。

我可以在邮件列表中问什么？

由于 PHP 一天比一天更流行，php-general 邮件列表的流量增加到现在的每天 150 到 200 个帖子。由于此原因，为了每个人的利益，使用此列表是你在寻找过所有其它地方后的最后手段。

在你向列表发帖之前请先看看本 FAQ 以及手册是不是能找到帮助。如果找不到的话试试邮件列表归档（见上面）。如果你有安装或者配置 PHP 的问题请从头到尾读一遍所有包含的文档和 README 文件。如果还是不能找到任何可以帮助你的信息，那么很欢迎你使用此邮件列表。

To ensure that you receive the best responses (and to reduce the likelihood of frustrating your fellow developers), please be sure to post your question to the appropriate list. For example, if you are having difficulties installing PHP, you should send your question to the php-install mailing list. A caveat: some lists have similar names and completely different uses; a question regarding PHP scripts on Windows should be directed to the Windows PHP users list, not to the Windows Internals list.

在提问之前，阅读一下 » 怎样聪明地发问这篇文章对每个人都是个好主意。

向邮件列表发帖子时我需要包括些什么信息？

像"我不能启动运行 PHP！帮帮我！哪里出错了？"之类的贴子对任何人都完全没有用。如果你在启动和运行 PHP 上有问题你必须包括你运行的操作系统，你试图配置的 PHP 版本，你怎样得到的（预编译的，CVS，RPM 等等），目前为止你都做了些什么，卡在了何处以及确切的错误信息。

这也同样适用于其它问题。你必须包括你做了什么，卡在了哪里，你试图做什么以及，如果有的话，确切的错误信息。如果你有源代码的问题那你需要包括不起作用部分的代码。可是不要包括超出所必需的代码！这将使贴子很难读并使很多人为此而跳过它。如果你不确定应该在邮件中包括多少信息，那包括多一些比一点点更好。

另一件重要的事是记住在主题一行中概述你的问题。类似"救命！"或者"这是怎么回事？"的主题会被一大半读者忽略。

最后，我们鼓励你阅读一下 » 怎样聪明地发问这篇文章。这对每个人都有很大帮助，尤其是你自己。

User Contributed Notes

There are no user contributed notes for this page.


获取 PHP

本章包括 PHP 下载地址以及操作系统相关问题的详细资料。

  1. PHP 可以从哪里得到？
  2. 有预先编译好的可执行版本吗？
  3. 编译一些可选的 PHP 扩展库所需的库文件可以从哪里得到？
  4. 怎样使这些库起作用？
  5. 在我的 Windows 机器上通过 Git 仓库获取最新的 PHP 源码后，我应该如何去编译？
  6. 哪里可以找到 browscap.ini 文件？
PHP 可以从哪里得到？

可以从任何一个 PHP 网络成员的站点下载 PHP。这些信息在 » https://www.php.net/。还可以通过匿名 SVN 得到绝对是最新版的源程序。更多信息请访问 [broken link]。

有预先编译好的可执行版本吗？

我们只为 Windows 系统提供了预编译的可执行文件，因为我们没法为每个主流的 Linux/Unix 平台编译每一种扩展库组和的 PHP。同样注意，如今很多 Linux 的发行版本已经内置了 PHP。Windows 可执行文件可以从我们的 » 下载页面下载，至于 Linux 可执行文件，请访问你的 Linux 发布商的站点。

编译一些可选的 PHP 扩展库所需的库文件可以从哪里得到？

Note: 有 * 号标记的不是多线程的库，不应该用作多线程 Windows web 服务器（IIS，Netscape）的服务器模块。不过这在 Unix 环境下没有关系。

  • » LDAP (Unix)
  • » LDAP (Unix/Win): Mozilla Directory (LDAP) SDK
  • » 免费 LDAP 服务器
  • » Berkeley DB2 (Unix/Win): http://www.sleepycat.com/.
  • » SNMP* (Unix):
  • » GD* (Unix/Win)
  • » mSQL* (Unix)
  • » PostgreSQL (Unix)
  • » IMAP* (Win/Unix)
  • » Sybase-CT* (Linux, libc5)：内置
  • » FreeType (libttf):
  • » ZLib (Unix/Win32)
  • » expat XML parser (Unix/Win32)
  • » PDFLib
  • » mcrypt
  • » mhash
  • » t1lib
  • » dmalloc
  • » aspell
  • » readline

怎样使这些库起作用？

需要按照这些库提供的说明进行。一些库可以在运行 PHP 的"configure"时自动检测到（例如 GD 库），其它的必需用" --with-EXTENSION"选项来激活。运行" configure --help"来得到完整的列表。

在我的 Windows 机器上通过 Git 仓库获取最新的 PHP 源码后，我应该如何去编译？

参见 PHP Wiki 内的最新说明： » Step by Step Build Instructions

哪里可以找到 browscap.ini 文件？

可以从 » http://browscap.org/得到一个 browscap.ini文件。

User Contributed Notes

There are no user contributed notes for this page.


数据库问题

本节包括 PHP 和数据库之间关系的常见问题。 事实上， PHP 可以访问如今现有的任何数据库。

  1. 听说 PHP 有可能访问 Microsoft SQL Server，怎样访问？
  2. 能访问 Microsoft Access 数据库吗？
  3. 为什么我已经使用了十多年的 MySQL 扩展（ext/mysql） 不建议继续使用了？ 它被废弃了吗？我应该选择什么替代方案？如何迁移到新的方案？
  4. 为什么我得到类似如下的错误： “Warning: 0 is not a MySQL result index in <file> on line <x>” 或者 “Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>”？
听说 PHP 有可能访问 Microsoft SQL Server，怎样访问？

在 Unix 机器中，你可以使用 PDO_ODBC 或者 Unified ODBC API 来访问 Microsoft SQL Server 数据库。

在 Windows 机器中，你可以使用 PDO_SQLSRV 或 SQLSRV 来访问 Microsoft SQL Server 数据库。

同时，也可以参考下一个问题。

能访问 Microsoft Access 数据库吗？

可以。如果完全在 Windows 9x/Me/NT/2000 下运行，那已经有了所有所需的工具， 可以用 ODBC 和 Microsoft's ODBC drivers for Microsoft Access database。

如果在 Unix 下运行 PHP 而想访问 Windows 中的 MS Access， 那需要 Unix ODBC 驱动程序。 » OpenLink Software 有一个基于 Unix 的 ODBC 驱动程序可以做这件事。

另外一个替代方案是用带 Windows ODBC 驱动的 SQL Server 并用它来储存数据， 可以通过 Microsoft Access（用 ODBC）和 PHP（用内置驱动）来访问， 或者用一个 Access 和 PHP 都识别的中间文件格式， 例如 flat 文件或者 dBase 数据库。 关于这一点 OpenLink Software 的 Tim Hayes 写道：

当可以通过 ODBC 直接从 PHP 访问数据库时——例如用 OpenLink 的驱动程序， 使用其它数据库做中间媒介不是一个好主意。 如果确实需要一个中间文件格式， OpenLink 已经发布了对应于 Windows NT，Linux 和其它 Unix 平台的 Virtuoso（一个虚拟数据库引擎）。 请访问我们的 » 网站来免费下载。

还有一个已被证实有效的选择是在 Windows 下用 MySQL 和它的 MyODBC 驱动来同步数据库。 Steve Lawrence 写道：

  • 根据 MySQL 的说明在你的平台上安装 MySQL。可以从 » http://www.mysql.com/得到最新版。 除了设定数据库和配置用户帐号以外不需要特殊的配置， 应该在 host 字段中放一个 % 或者要用来访问 MySQL 的 Windows 机器名。 记下自己的服务器名， 用户名和密码。
  • 从 MySQL 网站下载 MyODBC for Windows 驱动程序。 在你的 Windows 机器中安装它。 可以用此程序中包括的工具来测试其操作。
  • 用控制面板中的 ODBC 管理器新建一个用户或系统 dsn， 设定 dsn 名称， 输入你在第一步中配置的 MySQL 数据库的主机名，用户名，密码，端口等。
  • 完整安装 Access， 这样可以确保得到适当的插件... 至少需要安装 ODBC 支持和连接表管理器。
  • 新建一个 Access 数据库。 在 Table 窗口点击右键并选择 Link Tables， 或者在 File 菜单下选择 Get External Data -> Link Tables。 当文件浏览窗口打开后，选择文件类型为：ODBC。 接着选择 System dsn 以及在第三步建立的 dsn 的名字。 再选择要连接的表，点击 OK。 现在你可以在你的 MySQL 服务器中打开表并新建／删除／编辑数据了！ 也可以构造查询，导入／导出表到 MySQL，构造表单和报告等。

提示与技巧：

  • 可以在 Access 中构造表并导出到 MySQL 中， 再把它们连接回来。 这样可以使表的建立更快。
  • 在 Access 中建立表时， 必需定义一个基本键名来取得表的写权限。 确认在把表连接到 Access 之前在 MySQL 中建立了基本键名。
  • 如果在 MySQL 中修改了表， 必须重新连接到 Access。 打开 Tools>Add-ins>Linked table manager， 找到你的 ODBC DSN，然后在这里选择要重新连接的表。 也可以在这里移动 dsn 源， 在点击 OK 之前选中 "always prompt for new location"。

为什么我已经使用了十多年的 MySQL 扩展（ext/mysql） 不建议继续使用了？ 它被废弃了吗？我应该选择什么替代方案？如何迁移到新的方案？

在 选择一种 MySQL API 一节中 描述了 3 中 MySQL 扩展。 不应该继续使用旧的 API 了，可能将来的某一天旧 API 就会被废弃甚至从 PHP 中移除。 当然，旧的 API 曾经是非常主流的，很多用户都用了它，所以这个被废弃及移除的过程不会太快。 但是仍然强烈建议使用 mysqli 或 PDO_MySQL 来访问 MySQL 数据库。

自动迁移脚本目前还没有。 mysqli API 包括了面向过程和面向对象的两种风格的调用方式，并且面向过程的版本中提供的 API 和 ext/mysql 是非常相似的。

不可以同时混合使用这几种 MySQL API。 例如，你不可以把一个 mysqli 的连接资源传入到 PDO_MySQL 或者 ext/mysql 中去使用。

为什么我得到类似如下的错误： "Warning: 0 is not a MySQL result index in <file> on line <x>" 或者 "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>"？

你试图用一个值为 0 的结果资源号。 0 表示你的查询由于某原因失败了， 需要在提交查询之后 和在使用返回结果资源号之前检查错误。 正确的方法是用类似如下的代码：

<?php

$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
?>
或者
<?php

$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: " . mysql_error());
?>

User Contributed Notes

doug at unlikelysource dot com 31-Mar-2017 08:53
To enable SQL Server access from ubuntu 16.04:

* Run these commands:
```
sudo curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > mssql-release.list
sudo mv mssql-release.list /etc/apt/sources.list.d
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql unixodbc-dev
sudo apt-get install php7.1-dev
sudo apt-get install autoconf
sudo pecl install pdo_sqlsrv-4.1.6.1
```

*  Confirm ODBC driver installation:
```
odbcinst -q -d -n "ODBC Driver 13 for SQL Server"
```

* Update the php.ini file: run` php --ini` to find the path to your php.ini file
* Add this line to /path/to/php.ini
```
extension=pdo_sqlsrv.so
```
* Run `php -i` to confirm SQLSRV support was added
* NOTE: extensions (on my computer) were installed here:
`/usr/local/lib/php/extensions/no-debug-non-zts-20160303/`

* Test user access directly on the Windows server running MSSQL:
```
sqlcmd -S ip_address -U username -P password -d database -q "select * from table_name"
```
* On the Windows server: open port 1433 in your firewall

* Install the FreeTds utils to test the connection:
```
sudo apt-get install freetds-bin
tsql -H mssql.host.ip.address -U username -P password -D database -p 1433
```

* Formulate the correct DSN (Data Source Name):
    See: http://php.net/manual/en/ref.pdo-sqlsrv.connection.php

* Sample PHP Code:
```
<?php
// Database params
$tcp  = '192.168.3.126';
$port = 1433;
$user = "test";
$password = "Password123";
$database = "test";

// Open connection
try {
    // Database connect -- use one of the two statements below
    $dsn =  'sqlsrv:Server=tcp:' . $tcp . ',' . $port . ';Database=' . $database;
    $dbh = new PDO( $dsn, $user, $password, array());
    // SQL prepare
    $sql = "SELECT * FROM prospects";
    $sth = $dbh->prepare($sql);
    // Execute
    $sth->execute();
    // Fetch results
    $row = $sth->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $output = '<pre>';
        $output .= implode("\t", array_keys($row)) . PHP_EOL;
        $output .= implode("\t", $row) . PHP_EOL;
        while ($row = $sth->fetch(PDO::FETCH_NUM)) {
            $output .= implode("\t", $row) . PHP_EOL;
        }
    }
} catch (PDOException $e) {
    $output .= $e->getMessage();
}
$output .= '</pre>';
echo $output;
```
knb at gfz-potsdam dot de 11-Oct-2004 02:53
This is a crucial piece of information for SYBASE users:

If you are using the free, but old, 11.x client libs from sybase,
 then compile with option  "--with-sybase-ct=$SYBASE"
substitute $SYBASE with the appropriate directory name.

option --with-sybase (without ct) can somehow be used to talk to old MS-SQL servers, but only with the 11.x client libs.

If you are using free, or have legally obtained, 12.x client libs from sybase, then compile with option  "--with-sybase-ct=$SYBASE/$SYBASE_OCS"
substitute $SYBASE/$SYBASE_OCS with the appropriate directory name.


安装常见问题

本章包括了安装 PHP 的常见问题。PHP 可以用于几乎任何操作系统（可能除了 OS X 之前的 MacOS 之外），以及几乎任何 web 服务器。

要安装 PHP，请按照 安装与配置一章中的指示进行。

  1. 为什么不应该在实际运作环境中的 Apache2 中使用线程化的 MPM？
  2. Unix/Windows：应该上哪儿去找我的 php.ini 文件？
  3. Unix：我安装了 PHP，但每次我打开一个页面时，只得到一条“Document Contains No Data”消息！这是怎么回事？
  4. Unix：我从 RPMS 安装了 PHP，但是 Apache 不处理 PHP 页面！这是怎么回事？
  5. Unix：我从 RPMS 安装了 PHP 3，但它没有把我需要的数据库支持编译进去！这是怎么回事？
  6. Unix：我给 Apache 加上了 FrontPage extensions 补丁，结果 PHP 突然不工作了。PHP 和 Apache FrontPage extensions 兼容吗？
  7. Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个空白页面。
  8. Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个服务器的 500 错误。
  9. 某些操作系统：我已经在不出错的情况下安装了 PHP，但当我试着启动 Apache 时得到了一个未定义符号错误： [mybox:user /src/php4] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  10. Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到如下错误： cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  11. Windows：我已经照着所有的说明做了，但还是不能让 PHP 和 IIS 一起工作！
  12. 当在 IIS，PWS，OmniHTTPD 或者 Xitami 中以 CGI 方式运行 PHP 时，出现如下错误： Security Alert! PHP CGI cannot be accessed directly..
  13. 怎样得知我的 php.ini 是否被找到和应用了？似乎我做的修改都没有生效。
  14. 怎样将 PHP 目录加入到 Windows 路径 PATH中去？
  15. 怎样使 php.ini 文件在 Windows 下被 PHP 所用？
  16. 有可能使 PHP 运作于 Apache 的 content negotiation（MultiViews 选项）吗？
  17. PHP 是否仅限于处理 GET 和 POST 请求方法？
为什么不应该在实际运作环境中的 Apache2 中使用线程化的 MPM？

PHP 是粘合剂。它将几十种第三方的库粘合到一起来创建很酷的 web 应用，并通过很直观且易于学习的语言界面使其看上去好像一个整体。PHP 的灵活与强大依赖于底层平台的稳定与耐用。起码需要将一个可运作的操作系统，一个可运作的 web 服务器以及可运作的第三方库粘合起来。其中任何一方不运作了，PHP 都需要有方法来识别出问题并且快速解决。如果没有完全独立的执行线程，完全独立的内存单元和稳定的空间对付每个请求，那底层架构就太复杂以至于不稳定因素更容易进入到 PHP 系统中。

如果必须要用线程化的 MPM，看看 FastCGI 配置，使 PHP 运行于自己独立的内存空间中。

最后需要指出，不使用线程化 MPM 的警告在 Windows 系统中没那么强烈，因为 Windows 中的大多数库都理应在多线程下安全运行。

Unix/Windows：应该上哪儿去找我的 php.ini 文件？

UNIX 中默认在 /usr/local/lib目录中，也就是 <install-path>/lib。很多人会在编译时通过 --with-config-file-path标记来改变路径。例如可以将路径设为：

--with-config-file-path=/etc
然后从发行包中将 php.ini-dist拷贝为 /etc/php.ini并编辑它来作出想要的修改。

--with-config-file-scan-dir=PATH

Windows 中 php.ini 文件的默认路径在 Windows 目录下。如果使用的是 Apache 服务器，则会首先在 Apache 的安装目录中寻找 php.ini，例如 C:\Program Files\Apache Group\Apache。这样同一台机器上不同版本的 Apache 就可以有不同的 php.ini 文件。

参见 配置文件。

Unix：我安装了 PHP，但每次我打开一个页面时，只得到一条"Document Contains No Data"消息！这是怎么回事？

这可能意味着 PHP 发生了某类错误而导致了 core dump。查看服务器的错误日志看看是不是这样，再用一个小的测试例子试着重现此问题。如果你会用"gdb"的话，那么在 bug 报告中提供回溯跟踪很有助于帮开发人员查明问题。如果你用 Apache 的模块方式使用 PHP，试着这么做：

  • 停止 httpd 进程

  • gdb httpd

  • 停止 httpd 进程

  • > run -X -f /path/to/httpd.conf

  • 然后在你的浏览器中访问导致错误的 URL

  • > run -X -f /path/to/httpd.conf

  • 如果你遇到 core dump，gdb 此时就会通知你

  • 输入：bt

  • 你应该在 bug 报告中包括回溯追踪记录。应该提交到 » https://bugs.php.net/

如果你的脚本使用了正则表达式函数（ ereg()等），应该确认在编译 PHP 和 Apache 时使用了同一个正则表达式包。在 PHP 和 Apache 1.3.x 中应该自动就是这样。

Unix：我从 RPMS 安装了 PHP，但是 Apache 不处理 PHP 页面！这是怎么回事？

假定你的 Apache 和 PHP 都是从 RPM 包中安装的，你需要在 httpd.conf 文件中取消以下部分或所有行的注释，或者把它们添加到该文件中：

# Extra Modules
AddModule mod_php.c
AddModule mod_php3.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php3_module        modules/libphp3.so     # for PHP 3
LoadModule php4_module        modules/libphp4.so     # for PHP 4
LoadModule perl_module        modules/libperl.so
并且把：
AddType application/x-httpd-php3 .php3    # for PHP 3
AddType application/x-httpd-php .php      # for PHP 4
添加到全局属性中，或者添加到你希望加入 PHP 支持的虚拟域中。

Unix：我从 RPMS 安装了 PHP 3，但它没有把我需要的数据库支持编译进去！这是怎么回事？

由于 PHP 3 构造的原因，不容易编译出一个完全灵活的 PHP RPM 包来。这个问题在 PHP 4 中解决了。对于 PHP 3 来说，我们目前建议你用 PHP 发行包中 INSTALL.REDHAT 文件中所描述的机制。如果你坚持要用 PHP 3 的 RPM 版本，请接着往下看。

为了简化安装 以及由于 RPMS 使用了 /usr/ 而不是标准的 /usr/local/ 目录来存放文件，制作 RPM 包的人设定 RPMS 不安装任何数据库支持。你需要告诉 RPM 说明文件，你想要支持哪个数据库以及你的数据库服务器最高层路径。

下面的例子解说了如何在用模块安装下的 Apache 中加入流行的 MySQL 数据库服务器支持的过程。

当然这些信息可以调整用于任何 PHP 支持的数据库服务器。本例中我们也假定你从 RPMS 中完整安装了 MySQL 和 Apache。

  • 先去掉 mod_php3：

    rpm -e mod_php3

  • 然后取得源文件的 rpm 包并安装它，而不是编译它。

    rpm -Uvh mod_php3-3.0.5-2.src.rpm

  • 接着编辑 /usr/src/redhat/SPECS/mod_php3.spec文件

    在 %build 一节加入你想要的数据库支持，以及路径。

    对应于 MySQL 你应该加入 --with-mysql=/usr。则 %build 一节看上去将类似这样：

    ./configure --prefix=/usr \ --with-apxs=/usr/sbin/apxs \ --with-config-file-path=/usr/lib \ --enable-debug=no \ --enable-safe-mode \ --with-exec-dir=/usr/bin \ --with-mysql=/usr \ --with-system-regex

  • 一旦完成了这个修改，就这样建立二进制程序的 rpm 包：

    rpm -bb /usr/src/redhat/SPECS/mod_php3.spec

  • 然后安装 rpm

    rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm

确认重新启动了 Apache，这下你就有了用 RPM 安装的并且带 MySQL 支持的 PHP 3 了。注意按照 PHP 3 发行包中 INSTALL.REDHAT文件的说明来编译其实也许更容易一些。

Unix：我给 Apache 加上了 FrontPage extensions 补丁，结果 PHP 突然不工作了。PHP 和 Apache FrontPage extensions 兼容吗？

兼容的。PHP 可以和 FrontPage extensions 一起工作，问题是 FrontPage 补丁修改了几个 PHP 依赖的 Apache 构造。在 FrontPage 补丁安装之后之后重新编译 PHP（用"make clean ; make"）可以解决此问题。

Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个空白页面。

用浏览器中的"查看源文件"，你可能会发现能看到 PHP 脚本的源程序。这意味着 web 服务器没有把脚本发送给 PHP 解释。服务器配置在某处有问题，请对照 PHP 安装说明仔细检查服务器配置。

Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个服务器的 500 错误。

当服务器尝试运行 PHP 时出了错。要想看到有意义的错误信息，在命令行中转到 PHP 可执行程序（Windows 中是 php.exe）所在目录下并运行 php -i。如果 PHP 运行有任何问题，那么会显示相应的错误信息，这将给你下一步要做什么的线索。如果你得到满屏幕 HTML 代码（ phpinfo()函数的输出）的话说明 PHP 本身工作正常，你的问题可能和你的服务器配置有关，要仔细检查。

某些操作系统：我已经在不出错的情况下安装了 PHP，但当我试着启动 Apache 时得到了一个未定义符号错误：
[mybox:user /src/php4] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress

这实际上和 PHP 没有关系，而和 MySQL 的客户端库有关。有的需要 --with-zlib，有的不需要。这个问题也包括在 MySQL 的 FAQ 中。

Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到如下错误：
cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:

这个错误信息意味着 PHP 根本就不能产生任何输出。要想看到有意义的错误信息，在命令行中转到 PHP 可执行程序（Windows 中是 php.exe）所在目录下并运行 php -i。如果 PHP 运行有任何问题，那么会显示相应的错误信息，这将给你下一步要做什么的线索。如果你得到满屏幕 HTML 代码（ phpinfo()函数的输出）的话说明 PHP 本身工作正常。

一旦 PHP 在命令行中工作正常，试着通过浏览器再次访问脚本。如果还失败的话那可能是如下原因之一：

  • 文件权限问题，你的 PHP 脚本， php.exe， php4ts.dll，php.ini 或任何你要加载的 PHP 扩展库是匿名 internet 用户 ISUR_<machinename>无权访问的。
  • 脚本文件不存在（或者有可能不在你以为的地方，注意 web 文档的目录）。注意在 IIS 中通过 Internet 服务管理器设定脚本映射时选中"检查文件是否存在"可以捕捉到此错误。这样一来如果脚本文件不存在的话服务器就会返回一个 404 错误信息。还有一个额外的好处就是 IIS 会基于 NTLanMan 权限来替你对脚本文件做任何所需要的认证。
Windows：我已经照着所有的说明做了，但还是不能让 PHP 和 IIS 一起工作！

确认需要运行 PHP 脚本的任何用户有权限运行 php.exe！IIS 使用了一个在安装 IIS 时添加的匿名用户，这个用户需要有访问 php.exe的权限。同样任何认证用户也需要执行 php.exe的权限。在 IIS4 中你还需要告诉它 PHP 是一个脚本引擎。此外，你可能还需要阅读 此常见问题。

当在 IIS，PWS，OmniHTTPD 或者 Xitami 中以 CGI 方式运行 PHP 时，出现如下错误： Security Alert! PHP CGI cannot be accessed directly..

必须将 cgi.force_redirect选项设为 0。 默认值为 1，因此要确认此选项没有被注释掉（用 ;）。和其它选项一样，是在 php.ini 中设定的。

因为默认值是 1，因此你必须百分之百确认使用了正确的 php.ini 文件。详细信息请阅读 此常见问题。

怎样得知我的 php.ini 是否被找到和应用了？似乎我做的修改都没有生效。

要确认你的 php.ini 被 PHP 使用了，调用 phpinfo()，在接近开头的位置有一项叫做 Configuration File (php.ini)。这里将告诉你 PHP 在哪里找到了 php.ini 并且是否使用了。如果只显示一个目录则 没有使用任何 php.ini 文件，你应将你的 php.ini 文件放到该目录中。如果 php.ini 包括在该路径中则它已被应用了。

如果 php.ini 被使用了并且你是以模块方式运行 PHP 的，确保在修改了 php.ini 之后重新启动你的 web server。

怎样将 PHP 目录加入到 Windows 路径 PATH中去？

在 Windows NT，2000，XP 和 2003 下：

  • 进入控制面板并打开"系统"图标（开始 -> 设置 -> 控制面板 -> 系统，Windows XP/2003 中是：开始 -> 控制面板 -> 系统）

  • 选择"高级"标签页

  • 点击"环境变量"按钮

  • 在"系统变量"栏中

  • 找到 Path 这一项（可能需要向下滚动才能找到）

  • 鼠标双击 Path 这一项

  • 在最后加入你的 PHP 目录，包括前面的";"（例如： ;C:\php）

  • 点击"确定"并重新启动电脑

在 Windows 98/Me 中需要编辑 autoexec.bat文件：

  • 打开记事本（开始 -> 运行，然后输入 notepad 并点确定）

  • 打开 C:\autoexec.bat文件

  • 找到这么一行：PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;..... 并在最后加上 ;C:\php

  • 保存文件并重新启动电脑

Note: 记住在上述修改之后重新启动，以确保对 PATH的改变生效。

PHP 手册过去提倡把文件拷贝到 Windows 系统目录中去，这是因为该目录（ C:\Windows， C:\WINNT，等等）默认就在系统路径中。但是把文件拷贝到 Windows 系统目录中这一方式早已不被提倡，还可能造成问题。

怎样使 php.ini 文件在 Windows 下被 PHP 所用？

有几种方法。如果使用 Apache，阅读专门的安装指示（ Apache 1， Apache 2），否则就必须设定 PHPRC环境变量：

在 Windows NT，2000，XP 和 2003 种：

  • 进入控制面板并打开"系统"图标（开始 -> 设置 -> 控制面板 -> 系统，Windows XP/2003 中是：开始 -> 控制面板 -> 系统）

  • 选择"高级"标签页

  • 点击"环境变量"按钮

  • 在"系统变量"栏中

  • 点击"新建"按钮并在"变量名"中输入"PHPRC"，在"变量值"中输入 php.ini 文件所在的目录（例如： C:\php）

  • 点击"确定"并重新启动电脑

在 Windows 98/Me 中需要编辑 autoexec.bat文件：

  • 打开记事本（开始 -> 运行，然后输入 notepad 并点确定）

  • 打开 C:\autoexec.bat文件

  • 在文件结尾处加入一行： set PHPRC=C:\php（将 C:\php替换为你的 php.ini 实际存在的目录）。注意路径中不能包含空格。例如将 PHP 安装到了 C:\Program Files\PHP中，你需要输入 C:\PROGRA~1\PHP替代之

  • 保存文件并重新启动电脑

有可能使 PHP 运作于 Apache 的 content negotiation（MultiViews 选项）吗？

如果到 PHP 文件的连接包含扩展名，一切都运行完美。本解答只针对到 PHP 文件的连接不包含扩展名时，而希望通过 content negotiation 来从不包含扩展名的 URL 来选择 PHP 文件的情况。在此种情况下，将 AddType application/x-httpd-php .php替换为：

# PHP 4
AddHandler php-script php
AddType text/html php

# PHP 5
AddHandler php5-script php
AddType text/html php
此方案对于 Apache 1 不适用，因为 PHP 模块不捕获 php-script。

PHP 是否仅限于处理 GET 和 POST 请求方法？

不是，PHP 有可能处理任何请求方法，例如 CONNECT。适当的回应状态可以用 header()发送。如果仅需要处理 GET 和 POST 方法，可以通过如下的 Apache 配置实现：

<LimitExcept GET POST>
Deny from all
</LimitExcept>

User Contributed Notes

ssaxena at nriol dot com 12-Mar-2010 02:28
Here are my struggle to get PHP 5.2.12 working on Windows XP SP3, IIS 5.1 (Please note Win XP SP3 has issue of FastCGI)

1. Dowloaded installer and installed in C:\Program Files\PHP as ISAPI module

---->Did not work

Added php5isapi.dll in ISAPI Filter and added the extension .php in Home Dir->Configuration
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

(And the Google was pointing to the Fast CGI issue; Don't know why microsoft has MS-FAST ! )
Uninstalled the PHP and cleaned up the folders, PATH environment variable & PHPRC, the IIS settings and registry entries and shut down(restart is different from shut down) the system to make it very clean

2. Reinstalled the PHP in C:\PHP as ISAPI and did the same as above in IIS
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

Uninstalled and cleaned up same as above and took a breath to make sure what I am doing wrong.
Shutdown the system.

3. Unzipped the php-5.2.12-Win32.zip and did the same as above (this time manually PATH variable and security permission for the PHP folder and following settings)

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system.

4. Downloaded Microsoft Web Platform Installer 2.0 and select the PHP+Fast CGI+Windows Cache for PHP extension and Web Deployment Tools
restarted the system to take effect the settings

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system

5. Took the prev version of PHP php-5.2.4-Win32.zip unzip the folder and did the following changes:

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

set the security permission as IIS_machinename with full access to the C:\PHP folder

------->IT GOT WOKRING

Hope people would be aware of php-5.2.12 and would love the php-5.2.4
john dot calder at manukau dot ac dot nz 03-May-2008 10:19
WINDOWS 2003 and IIS.  BIG LESSON FOR ME was "don't mess with the optional components".
I had lots of trouble until I tried installing without asking for extras and then it was very smooth.
I have found no need to set up paths.
I have found no need to configure IIS.
I have found no need to change security on the PHP folder.

What works for me with Windows/IIS:

1.  You need to be logged-on as "administrator"

2.  Run  "php-5.2.6-win32-installer.msi"
Your ONLY action during this wizard is to select "IIS ISAPI" as the webserver.  Do NOT CHANGE anything else!  I am guessing that the optional extras apply only to Apache because after enabling them I see Apache-related error messages.

3.  Setup a test virtual directory as you would for an ASP or ASP.NET web app.  eg "phptest"
Then use notepad to create a test page eg "test.php"
<?php
phpinfo();
?>

4.  In Internet Explorer, test with eg this address
http://localhost/phptest/test.php

IF this does not give you a beautiful page of details THEN start reading other advice on this page - especially helpful for me was the faq advice to test run "php.exe -i" from the command prompt.
charleslynch at xybersoftware dot com 17-Apr-2008 07:30
One final note to the message below if you are getting the message about not having rights to execute...You need to use IIS right click on the website and choose 'Properties/Home Directory' then on the 'Execute Permissions' combo box you need to choose 'Scripts only'...Click ok...another dialog may appear asking which directories to apply the action too...choose any directories that you intend on using php in and click ok...It should work now...
joerg at fenin dot de 02-Nov-2007 02:35
To limit HTTP Request Methods on the Apache server running PHP you should use mod_rewrite or mod_security instead of LimitExcept, to give you more control over the handling of such http errors.  Can go in .htaccess file or httpd.conf

# mod_rewrite
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST)$
  RewriteRule .* - [F,L]
</IfModule>

# mod_security
<IfModule mod_security.c>
  SecFilterSelective REQUEST_METHOD "!^(GET|HEAD|POST)$" "deny,log,status:403"
</IfModule>

You can use the php request method scanner at askapache to see exactly how your server deals with various request methods, and check that your server is configured properly..

http://www.askapache.com/online-tools/request-method-scanner/
scott at chaisson dot net 19-Sep-2007 09:18
Windows 2000 Server and IIS (SP4 and all patches):

After many frustrating hours of trying to figure out the install (again), It took a while, but here are a couple tips:

PHP working with IIS uses c:\winnt\php.ini

It doesn't matter what you set the path to, nor what you set the PHPRC environment variable to. After you get PHP running correctly in the installation folder (using php -i) copy the php.ini file into the c:\winnt folder.

Here's what worked for me:

- Add PHP path to System environment variable

- Add php5activescript.dll from http://snaps.php.net/ to the PHP folder, then Register it: "regsvr32 php5activescript.dll"

Set extension_dir and doc_root directives in PHP.INI:
  extension_dir = C:\WWW\PHP\ext
  doc_root = C:\WWW\Site
  cgi.force_redirect = 0

(the last cgi.force_redirect isn't required, but I like to set it anyway)

Copy the .INI file into WINNT folder

In IIS Manager, right-click "Default Web Site", Click "Home Directory",
  Click "Configuration", "Add" the ISAPI application:
    Executable: <your php install>\php5isapi.dll
    Extension: .php
    Limit to: GET,HEAD,POST
    Check: "Script Engine"
    Uncheck: "Check that file exists"

Finally: Set up an ISAPI filter:
  Click the "ISAPI Filters" tab,
  Filter Name: PHP
  Executable: <your php install>\php5isapi.dll

Notes: You don't have to set any of your folders as "Script source" folders. .PHP files aren't scripts, merely text files that require processing before being shipped off to the browser, which is what the ISAPI filter does.

Finally, working again.

Chase
christianfelix at laszlo dot com 16-Jul-2007 03:39
For Windows XP users

Just add php.ini to windows/system 32 and also save a copy in the setup folder e.g. c:/php/php.ini, c:/php5/php.ini,

You have to follow the suggestions, add to path, uncomment extensions and voila!!
Meiki67 skipthis at geemail 07-Jun-2007 04:41
Had a hard day to MSI install 5.2.3 on WinXP with MySQL. I use a drive substitution (subst drive: path - in my case subst d: c:\drive_d) and installed PHP in D:\PHP - which in reality is C:\DRIVE_D\PHP.  To make a long story short - only after (1) changing all substituted D:\ back to C:\DRIVE_D and (2) resolving all DOS short names to Win long names PHP started to work. The first one is clear - the substitution works only for the active console user - not for services or IUSR. For the second one I have no explanation, since DOS short names should work systemwide - maybe Win handles them correctly but PHP not ?

BTW <?php phpinfo(); ?> was of tremendeous help

Meiki
Curtis 18-May-2007 07:39
I have some additional troubleshooting tips for 53.7, which deals with getting a blank screen on your browser when running a PHP script.

In addition to server misconfiguration, it may also be that PHP isn't configured to output errors to the browser, which is the case if you or your host uses a more secure php.ini. If this is the case, you need to find out where errors are being logged to find out if any errors are preventing normal output from being delivered to the client.

If you have access to php.ini, check the 'display_errors' directive, which is, by default, located under the 'error_reporting' directive. It's helpful to have 'display_errors' on during debugging phases, but best to have it off in production environments.

Related functions: http://php.net/ini_set | http://php.net/error_reporting | http://php.net/error_log
knutw at sparhell dot no 06-Nov-2006 09:15
I recntly upgraded from PHP 5.1 to 5.2 on my Windows Server 2003 using IIS6. I selected CGI as before. My PHP folder is as always C:\Program Files\PHP. I also edited my brand new php.ini, enabling all my old extensions and recommended settings for IIS. I like not to keep my old config into a new version.

After upgrade, I just got blank pages in my browser, and the response status was 404 Not found.

I checked my installation twice, using this FAQ, but got no way.

Then I went to IIS Manager, Web Service Extensions. The php Service Extension was Allowed as it should. I deleted the Service Extension and added it. The old extension used short file names containing tilde (PROGRA~) character, but I don'?t know if that gas anything to do with the problem. Anyway, after allowing my" new" Service Extension, pointing to php-cgi.exe as before, mye web sites suddenly worked. So will revommend anyone with thos problem to delete and add the Servcie Extension. It didn't help re-allowing it, restarting IIS or the complete server.
13-Sep-2006 07:03
After setting the PHPRC environment variable, none of my PHP files would hit the preprocessor. The browser was just serving out PHP source code right there in the "view source."

The manual was telling me to set this var to "c:\php," but nothing was working. It's almost as if IIS/Win2000 wasn't reading my php.ini at all.

After I set that variable to "c:\php\php.ini," all of a sudden I was getting honest to goodness PHP pages working.
emzeperx at emzeper dot hu 01-Jan-2006 12:36
You do not have to restart the whole system make effect of changing the PATH env var. For me (sbs2003) worked automatically.
on older systems you can use

set $Path=%path%;c:\php

command to extend immediately the path var.
JUSTANOTHERUSER 14-Aug-2005 11:23
<LimitExcept GET POST>
Deny from all
</LimitExcept>

Does not work with Apache2+ & PHP5 . Apache Refuses to start
per dot fikse at ipj dot no 12-Jul-2005 01:22
Installing PHP 4 or 5 on Windows Server 2003 x64 results in http error 505. This is not a PHP bug. It is due to running a 32-bit ISAPI DLL under the 64-bit version of IIS 6, as documented here: http://support.microsoft.com/?id=895976

Solution: Flip the Metabase flag for Enable32bitAppOnWin64 as described in http://support.microsoft.com/?id=894435 ,
like this: CSCRIPT ADSUTIL.VBS SET W3SVC/AppPools/Enable32bitAppOnWin64 1

(Alternatively with full path: cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1)
barry dot fagin at usafa dot af dot mil 04-Jan-2005 09:22
Fixing 404 (file not found) errors with PHP 5.0.3 and IIS 6.0

IIS 6.0 is installed with security settings that don't permit dynamic content.  This means that even if all the hints in the FAQ are paid attention to (.ini modified correctly, security and permissions correct for IUSR_xxx user, etc), you still get 404 errors for all php files.

To fix this:  IIS Manager -> expand local computer -> Web Services Extensions -> Add web service or extension -> .php, browse to c:\php\php-cgi.exe or wherever you had the php executable installed. That plus setting the doc_root in the .ini file solved the problem.

--BF
jeff_graham at datacenterservices dot net 01-Feb-2004 01:51
As stated within the note "jimo at mail dot azhsv dot com
29-Nov-2003 04:33
PHP 4 and IIS 6.0 (Windows Server 2003)," I found the same steps were requiered for installation of PhP 5 beta 3 on my Windows 2003 server (Standard Edition)
nigel dot salt at hotmail dot com 13-Dec-2003 05:00
Finally got IIS 5 and PHP 5 to talk.

What worked for me was:

1) Set
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
W3SVC\Parameters\Script Map]
".php"="your path to php\\php.exe"

2) ensure there is not a php.ini in the windows system folder and that there is one wherever you've put PHP

3) edit php.ini and set cgi force redirect to 0 and cgi.rfc2616_headers = 1

4) Put the PHP scripts in their own folder underneath the inetpub root

5) Open the IIS console, right click your new php folder
In the Directory tab
 set application name to the name of the folder
 set executable and script as permission
 set application protection to low
Click configuration and check that .php is mapped to wherever you put
PHP

Restart IIS

Try a very simple PHP page and it should work

Nigel
jimo at mail dot azhsv dot com 29-Nov-2003 07:33
PHP 4 and IIS 6.0 (Windows Server 2003)

Had difficulty getting PHP 4.3.3 to work with Win2003 Ent Server for use with SquirrelMail.  Problem found and believed solved.  Appears to be something New with IIS 6.0 (More security by Micro$oft)  Was getting 404 error and php was not being run as a cgi even though it was in extensions and IIS user had rights to execute it. (php from command line operated correctly)

If you are installing on Windows Server 2003 (only have Enterprise Edition ? Not sure if this applies to standard edition), and you have done the normal procedures for inclusion of PHP scripts (either ISAPI or CGI) in IIS, you will still get a 404 error when attempting to execute those scripts even though IIS has rights and the extension points to the correct file.  To alleviate this problem, perform the following:

1.    Open a command prompt window
2.    Change to C:\windows\system32
3.    Execute the command:  cscript  iisext.vbs /AddFile c:\php\php.exe 1 php 0 php
4.    Execute the command:  cscript iisext.vbs /EnFile c:\php\php.exe
5.    To check for correct execution of the above,
6.    Execute the command:  cscript IisExt.vbs /ListFile ? the php extension should be listed

If you try just step 4 without step 3 you get an error that the file is not in the list (and won?t be there till you do step 3 above)

After this, IIS seems to like the php extension and work normally.

For additional reference, see the below 3 Micro$oft KB Articles:
HOWTO: Enable and Disable ISAPI Extensions and CGI Applications in IIS 6.0 (MS KB Article 328360)

HOWTO List Web Server Extensions and Extension Files in IIS 6.0 (MS KB Article 328505)

HOWTO Add and Remove Web Service Extension Files in IIS 6.0 (MS KB Article 328419)
peter dot mosinskisNOSPAM at csuci dot edu 06-Mar-2003 12:36
Running Win2K AS + IIS5.0 + PHP 4.3.1, I ran into a nasty problem that I mistakenly thought had to do with something in the php.ini configuration. When I would try to submit a form using the HTTP method GET it would work, but I would get a "404 Page Not Found" error using the POST method.

All my permissions were set correctly, the php.ini was configured correctly. It had to do with URLScan being installed on IIS (see below)

Page 404 File Not Found Error When Using POST method in PHP (and Perl, and otherwise)
-------------------------------------------

This is related to the Microsoft URLScan utility. If you have this problem, the IIS administrator has probably run the IIS Lockdown tool as well as configured URLScan to reject this type of HTTP method when sent in a URL. These tools are meant to enhance web server security.

URLScan configuration files can be found in the \WINNT\system32\inetsrv\urlscan folder on the web server. Specifically, the file to modify is urlscan.ini.

The changes to make are as follows:
1. Make sure UseAllowVerbs=1 under [options]
2. Under the [AllowVerbs] section, list your allowed HTTP methods to include:
    GET
    POST

For more information on the IIS Lockdown tool and URLScan, visit http://technet.microsoft.com
monroe at peoplego dot com 17-May-2002 10:32
INSTALLATION ON OPENBSD 3.1 VIA PORTS COLLECTION
Would have succeed but no mysql support.
I commented out the FLAVORS+= dbase filepro mysql mysql_bundled postgresql iodbc in the /usr/ports/www/php4/Makefile and in the configure options added
--with-mysql=/usr/local   and it worked.

Good Luck


编译问题

本节汇集了大多数编译时出现的常见错误。

  1. 我用匿名 GIT 服务得到了最新版的 PHP，但是里面没有 configure 脚本！
  2. 我在配置 PHP 和 Apache 一起工作时遇到了问题。说没找到 httpd.h，但这个文件明明就在那里！
  3. 当运行 PHP 配置时（ ./configure），遇到类似如下的问题： checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. 当试图启动 Apache 时，得到类似如下错误信息： fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. 当运行 configure 时，报告说找不到头文件或 GD 库或 gdbm，或其它的什么包！
  6. 当编译 language-parser.tab.c文件时，报错说 yytname undeclared。
  7. 当我运行 make时，看上去一切正常，可当连接最后的程序时报告说找不到某些文件而失败了。
  8. 当连接 PHP 时，报告说有一些未定义的引用。
  9. 我不知道怎样把 PHP 和 Apache 1.3 一起编译。
  10. 我按照所有的步骤在 UNIX 下安装了PHP 的 Apache 模块版本，但我的 PHP 脚本被显示在浏览器中或者提示保存此文件。
  11. 说要用： --activate-module=src/modules/php4/libphp4.a，但是此文件根本不存在，于是我改成了 --activate-module=src/modules/php4/libmodphp4.a，结果不行。怎么回事？
  12. 当我用 --activate-module=src/modules/php4/libphp4.a试着把 PHP 编译成 Apache 的静态模块时，报告说我的编译器不服从 ANSI 标准。
  13. 当我用 --with-apxs编译 PHP 时得到奇怪的错误信息。
  14. 在 make的过程中，在 microtime 中出错，还有很多 RUSAGE_之类的东西。
  15. 当带 MySQL 编译 PHP 时，可以正确地运行configure，但是在 make的过程中出现了类似以下的错误信息： ext/mysql/ libmysqlclient /my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/ libmysqlclient /my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp'，这是怎么回事
  16. 我想升级我的 PHP。上哪里找到我用来配置目前的 PHP 的 ./configure的参数呢？
  17. 和 GD 库一起编译 PHP 时，要么给出一个奇怪的编译错误，要么在运行时出现 segfaults。
  18. 当编译 PHP 时我看到一些随机的错误，好像死了。我用的是 Solaris，不知道有没有关系。
我用匿名 GIT 服务得到了最新版的 PHP，但是里面没有 configure 脚本！

你必须安装有 GNU autoconf 包，这样才可以从 configure.in生成 configure 脚本。从 GIT 服务中得到源程序后只要在最高层的目录中运行 ./buildconf即可。（同时要注意，除非你用了 --enable-maintainer-mode选项来运行 configure，否则即使 configure.in文件更新了，configure 脚本也不会自动重新生成。所以当你发现 configure.in文件更新了时要确保手工重新生成 configure 脚本。有一个症状是在 configure 之后或者运行 config.status时在 Makefile 中寻找类似 @VARIABLE@ 的东西。）

我在配置 PHP 和 Apache 一起工作时遇到了问题。说没找到 httpd.h，但这个文件明明就在那里！

你需要告诉 configure/setup 脚本你的 Apache 源程序最上层的目录位置。这意味着你需要这样指定 --with-apache=/path/to/apache而 不是这样 --with-apache=/path/to/apache/src。

当运行 PHP 配置时（ ./configure），遇到类似如下的问题：
checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up

请认真阅读 PHP 的 安装说明，并注意要编译 PHP 需要同时安装 flex 和 bison。根据设置的不同，可以从源代码编译 bison 和 flex，要么通过已编译好的发行包，例如 RPM。

当试图启动 Apache 时，得到类似如下错误信息：
fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found

该错误通常在 Apache 的核心程序被编译为共享用途的 DSO 库时发生。请尝试重新配置 Apache，确保至少使用了如下参数：

--enable-shared=max --enable-rule=SHARED_CORE

更多信息，请阅读 Apache 顶层目录的 INSTALL文件或者 Apache 的 » DSO 手册。

当运行 configure 时，报告说找不到头文件或 GD 库或 gdbm，或其它的什么包！

可以通过指定附加的选项让 configure 脚本在非标准的路径中寻找头文件和库并传递给 C 预处理器和连接器，例如：

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
如果用 csh 的变种作为你的登录 shell（为什么？），那就是：
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

当编译 language-parser.tab.c文件时，报错说 yytname undeclared。

需要更新 Bison 的版本。最新版本在 » http://www.gnu.org/software/bison/bison.html。

当我运行 make时，看上去一切正常，可当连接最后的程序时报告说找不到某些文件而失败了。

一些旧版本的 make 没有正确将 functions 目录下编译后的文件放到同一个目录下。试试运行 cp *.o functions然后再运行 make看看有没有什么帮助。如果成功了，那你确实需要更新到最新版的 GNU make。

当连接 PHP 时，报告说有一些未定义的引用。

看看连接的这一行命令，确认所有适当的库都包括在最后了。通常可能漏掉了"-ldl"和你包括的任何数据库支持所需要的库。

一些人也报告说在和 Apache 连接时他们不得不紧接着 libphp4.a之后加上"-ldl"。

我不知道怎样把 PHP 和 Apache 1.3 一起编译。

这其实很简单。小心地照着以下步骤来：

  • 从 » http://httpd.apache.org/download.cgi下载最新版的 Apache 1.3。
  • 解压缩到某处，例如 /usr/local/src/apache-1.3。
  • 编译 PHP，先运行 ./configure --with-apache=/<path>/apache-1.3（用你 apache-1.3 所在的真实路径替换掉 <path>。）
  • 输入 make接着是 make install来编译 PHP 并把必要的文件拷贝到 Apache 的源程序目录树中。
  • 改变当前目录到 /<path>/apache-1.3/src目录并编辑 Configuration文件。添加这一行： AddModule modules/php4/libphp4.a。
  • 输入 ./configure接着是 make。
  • 你现在应该有一个包括 PHP 支持的 httpd 可执行程序了！

注意：也可以用新的 Apache ./configure脚本。参见 Apache 发行包中 README.configure文件中的说明。也看看 PHP 发行包中的 INSTALL文件。

我按照所有的步骤在 UNIX 下安装了PHP 的 Apache 模块版本，但我的 PHP 脚本被显示在浏览器中或者提示保存此文件。

这说明 PHP 模块出于某些原因没有被调用。在寻求更多帮助前先检查三件事：

  • 确认你运行的 httpd 程序就是你刚刚编译的新 httpd 程序。运行： /path/to/binary/httpd -l 如果你没看到 mod_php4.c被列出来那你就没有运行对程序。找到并正确安装程序。
  • 确认你在 Apache .conf文件中加入了正确的 Mime 类型。应该是： AddType application/x-httpd-php .php 也确认 AddType 这一行没有隐藏在 <Virtualhost> 或者 <Directory> 块中，这可能会造成你的测试脚本所在位置没有被应用到此设置。
  • 最后，Apache 1.2 和 Apache 1.3 之间默认配置文件的位置改变了。你要确认你添加 AddType 行的文件就是实际上用的。你可以在你的 httpd.conf 中添加一个明显的语法错误或者其它明显修改，这可以告诉你是否读取了正确的文件。

说要用： --activate-module=src/modules/php4/libphp4.a，但是此文件根本不存在，于是我改成了 --activate-module=src/modules/php4/libmodphp4.a，结果不行。怎么回事？

注意 libphp4.a文件本来就不该存在，apache 进程将创建它！

当我用 --activate-module=src/modules/php4/libphp4.a试着把 PHP 编译成 Apache 的静态模块时，报告说我的编译器不服从 ANSI 标准。

这是一个 Apache 误报的错误信息，在新的版本中已经修正了。

当我用 --with-apxs编译 PHP 时得到奇怪的错误信息。

这里要检查三件事。首先，出于某些原因当 Apache 生成 apxs Perl 脚本时，有时没有正确的编译和标记变量就结束了。找到你的 apxs 脚本（用命令 which apxs），有时会在 /usr/local/apache/bin/apxs或者 /usr/sbin/apxs。打开并检查类似如下的行：

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
如果你看到这几行，那问题就在这里。它们可能包含了仅仅空格或者其它不正确的值，例如"q()"。改成这样：
my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';                   # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);              # substituted via Makefile.tmpl
第二个可能的问题仅可能在在 Red Hat 6.1 和 6.2 中发生。Red Hat 发行的 apxs 脚本坏了。查找这一行：
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
如果你看到上面这一行，改成这样：
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
最后，如果你重新配置或者重装了 Apache，在 ./configure之后和 make之前增加一个 make clean命令。

在 make的过程中，在 microtime 中出错，还有很多 RUSAGE_之类的东西。

如果 make时遇到类似这样的问题：

microtime.c: In function `php_if_getrusage':
microtime.c:94: storage size of `usg' isn't known
microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function)
microtime.c:97: (Each undeclared identifier is reported only once
microtime.c:97: for each function it appears in.)
microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function)
make[3]: *** [microtime.lo] Error 1
make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/master/php-4.0.1/ext'
make: *** [all-recursive] Error 1

你的系统坏了。你需要安装一个符合你的 glibc 的 glibc-devel 包来修复 /usr/include中的文件。这和 PHP 绝对没有任何关系。要证实这一点，试试这个简单的测试：

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
如果出现错误，那你就知道头文件坏了。

当带 MySQL 编译 PHP 时，可以正确地运行configure，但是在 make的过程中出现了类似以下的错误信息： ext/mysql/ libmysqlclient /my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/ libmysqlclient /my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp'，这是怎么回事

首先，我们需要认识到这只是个 警告，而非致命错误。由于这条信息通常是在 make的最后输出的，所以看起来它可能像是一个致命错误，但实际上不是。当然，如果将编译器设置成遇见警告信息时停止，则这也可以算是致命错误。另外值得一提的是，MySQL 的支持是默认打开的。

Note:

自 PHP 4.3.2 起，你将在编译（make）结束后看到下面的文字：

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).

我想升级我的 PHP。上哪里找到我用来配置目前的 PHP 的 ./configure的参数呢？

要么在你用来编译当前的 PHP 的源码树中查看 config.nice 文件，如果没有，只要运行此脚本：

<?php phpinfo(); ?>
在输出的顶端显示了用来配置此 PHP 的 ./configure参数。

和 GD 库一起编译 PHP 时，要么给出一个奇怪的编译错误，要么在运行时出现 segfaults。

确保你的 GD 库和 PHP 在连接时使用了用同样的支持库（例如 libpng）。

当编译 PHP 时我看到一些随机的错误，好像死了。我用的是 Solaris，不知道有没有关系。

当编译 PHP 时使用非 GNU 的工具会导致问题。确保使用 GNU 工具来确保能够正确编译 PHP。例如，在 Solaris 下面不论使用 SunOS BSD 兼容或者 Solaris 版本的 sed都不行，但是使用 GNU 或者 Sun POSIX (xpg4) 版本的 sed就可以。相关连接： » GNU sed， » GNU flex， » GNU bison。

User Contributed Notes

synnus at gmail dot com 25-Jun-2017 10:10
j'ai réalisé pour vous une machine virtuel pour compiler php 7
il suffira d'utiliser mon logiciel pour télécharger l'image disque virtuel
qui fonctionne sous virtualbox ; cette image contient une version gratuite
légale de windows 10 proposé par Microsoft lui même Réarmable .
tout le nécessaire pour compiler php 7 sera sur le bureau.

Le dossier Release pour récupérer les fichiers compiler
le lancer de compilation avec les commandes
Buildconf
Configure
nmake ...

voir la documentation https://wiki.php.net/internals/windows/stepbystepbuild
tout est déjà pré configuré vous vous trouvez à la section "Compile"
partie "4.Run : "

pour télécharger l'image c'est ici
https://github.com/Darksynx/Compiling-php7-to-a-virtual-machine

=========

I realized for you a virtual machine to compile php 7
It will suffice to use my software to download the virtual disk image
Which runs under virtualbox; This image contains a free version
Legal of Windows 10 proposed by Microsoft itself Resettable.
All necessary to compile php 7 will be on the desktop.

The Release folder to recover the compile files
The compilation run with commands
buildconf
Sets
Nmake ...

See the documentation https://wiki.php.net/internals/windows/stepbystepbuild
Everything is already preconfigured you are in the section "Compile"
Party "4.Run:"

To download the image here
https://github.com/Darksynx/Compiling-php7-to-a-virtual-machine
Fabio 22-Feb-2012 01:47
When building PHP 5.3.x for Apache 2.4.x you may get an error in the apxs query for the MPM_NAME.
This is because the apxs included in Apache 2.4.x doesn't recognize that query anymore.

To resolve this issue one should modify the PHP configure file to use the right MPM module used by Apache.

To know the used MPM you can execute this command: apachectl -t -D DUMP_MODULES | grep mpm

Then, edit the PHP configure file, search for the APXS_MPM variable and force its value to prefork, event or worker according to the value returned by the previous command.

Hope it helps.
-
Fabio
terry at mackintoshweb dot com 19-Sep-2009 08:43
The configure script of PHP 5.3.0 has some test lines that use expr with the option --, my expr (version 2.0) does not except --.  This causes a run of error messages from the shell like:

./configure: line 2xxx: test: =: unary operator expected
expr: syntax error

I used buildconf --force to see if it would fix this.
While it resulted in a quit different file, it still had the lines of code with expr -- in it.
05-May-2007 06:48
@ anca-phpdoc at anca dot tv:

You can use ./configure --with-libxml-dir=/path_to_xml2-config
anca-phpdoc at anca dot tv 08-Dec-2005 07:48
For the configure newbies among us:

If you update or reinstall any of the libraries used to compile in a different directory than they started out, you will need to make sure that you update the config.cache file (or re-generate it) so that configure will not look in the wrong place for the information.

On Mac OS X, for example, I updated my libxml using Fink.  Fink placed the files in the /sw directory.  However, php was still looking for important libxml files (such as xml2-config) in the old directory (/usr/bin/xml2-config).   After updating config.cache with the new value of the xml2-config path, I was able to compile correctly.


使用 PHP

本节汇集了你在写 PHP 脚本时可能碰到的大多数普通错误。

  1. 我忘了 PHP 函数的参数顺序，它们是随机的吗？
  2. 我想写一个可以处理任何表单来的数据的通用 PHP 脚本。我怎么知道哪个 POST 方法变量可用呢？
  3. 我需要在所有的单引号（'）前加一个反斜线（\），使它们变成（\'）。我如何能够通过正则表达式来实现？ 我同样希望能够将 " 转换成 \"，将 \ 转换成 \\。
  4.           当我这样做时，输出显示的次序是错的：

<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>

          这是怎么回事？
  5. 下面代码怎么没有分成两行显示？ <pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre>
  6. 我得到消息 “Warning: Cannot send session cookie - headers already sent...” 或者 “Cannot add header information - headers already sent...”。
  7. 我需要直接访问请求报头中的信息，怎么能办到？
  8. 当我用 IIS 进行 HTTP 认证时得到 “No Input file specified” 消息。
  9. Windows：不能访问另一台电脑上用 IIS 共享的文件。
  10. 我怎样混合使用 XML 和 PHP？它不认我的 <?xml 标记！
  11. 哪里可以找到所有可用的 PHP 预定义变量的完整列表？
  12. 怎样才能不用非免费的商业库（例如 PDFLib） 来生成 PDF 文档？我想要个免费的并且不需要再连接别的 PDF 库。
  13. 我试着在用户自定义函数中访问一个标准的 CGI 变量（例如 $DOCUMENT_ROOT 或 $HTTP_REFERER），但是找不到，哪里出了错？
  14. 有些 PHP 选项可以接受缩写的字节值，与仅能接受 int 字节值相反。都有哪些缩写字节值？
  15. 在 Windows 下，使用 localhost 访问的时候提示连接超时，但是使用 "127.0.0.1" 的时候正常，为什么？
我忘了 PHP 函数的参数顺序，它们是随机的吗？

PHP 是一个将数百个外部库连接在一起的粘合剂，尽管有时候会有一些混乱。这里有一些简单的经验法则：

数组函数 参数的顺序为 "needle, haystack"， 字符串函数 则相反，顺序为 "haystack, needle"。

我想写一个可以处理任何表单来的数据的通用 PHP 脚本。我怎么知道哪个 POST 方法变量可用呢？

PHP 提供很多" 预定义变量"，例如超全局变量 $_POST。可以遍历 $_POST变量，因为它是一个和所有通过 POST 方法传递数据相联系的数组。例如，可以用 foreach简单地遍历它，检查 empty()值，以及将它们输出。

<?php
$empty = $post = array();
foreach ($_POST as $varname => $varvalue) {
    if (empty($varvalue)) {
        $empty[$varname] = $varvalue;
    } else {
        $post[$varname] = $varvalue;
    }
}

print "<pre>";
if (empty($empty)) {
    print "None of the POSTed values are empty, posted:\n";
    var_dump($post);
} else {
    print "We have " . count($empty) . " empty values\n";
    print "Posted:\n"; var_dump($post);
    print "Empty:\n";  var_dump($empty);
    exit;
}
?>

我需要在所有的单引号（'）前加一个反斜线（\），使它们变成（\'）。我如何能够通过正则表达式来实现？ 我同样希望能够将 " 转换成 \"，将 \ 转换成 \\。

假设是针对数据库，请使用数据库自带的转义机制。比如，针对 MySQL 使用
mysql_real_escape_string() 函数，针对 PostgreSQL 则使用
pg_escape_string() 函数。还有两个标准函数
addslashes() 和
stripslashes() 可以在旧的 PHP 版本中实现类似的操作。

当我这样做时，输出显示的次序是错的：
<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
这是怎么回事？

要在一个表达式中（例如在上面的例子中和其它字符串连接）使用函数的结果，需要 return 这个值，而不是 echo 它。

下面代码怎么没有分成两行显示？
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>

在 PHP 中，一段代码的结束标记要么是"?>"要么是"?>\n"（\n 表示换行）。因此在上面的例子中，输出的句子将显示在同一行中，因为 PHP 忽略了代码结束标记后面的换行。这意味着如果要输出一个换行符，需要在每段 PHP 代码的结束标记后面多加一个换行。

PHP 为什么这么做呢？因为在格式化正常的 HTML 时，这样通常会更容易。假如输出了换行而你不需要这个换行时，就不得不用一个非常长的行来达到这样的效果，或者让产生的 HTML 页面的源文件的格式很难读。

我得到消息 "Warning: Cannot send session cookie - headers already sent..." 或者 "Cannot add header information - headers already sent..."。

函数 header()， setcookie() 和 session 函数需要在输出流中添加头信息。但是头信息只能在其它任何输出内容之前发送。在使用这些函数前不能有任何（如 HTML）的输出。函数 headers_sent() 能够检查脚本是否已经发送了头信息。请参阅 输出控制函数。

我需要直接访问请求报头中的信息，怎么能办到？

如果以 Apache 的模块方式运行 PHP，那么函数 getallheaders() 可以做这件事。因此下面的代码可以显示所有的请求报头：

<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
    echo "headers[$name] = $content<br />\n";
}
?>

请参阅函数
apache_lookup_uri()、
apache_response_headers() 和
fsockopen()。

当我用 IIS 进行 HTTP 认证时得到 "No Input file specified" 消息。

IIS 的安全模型这里有毛病。这是所有 IIS 下运行的 CGI 程序所共有的问题。一个解决办法是建立一个纯 HTML 文件（不经过 PHP 解析）作为要进入认证目录的登录页面，然后用 META 标记来重定向到 PHP 页面，或者用一个连接到 PHP 页面。然后 PHP 就可以正确识别认证信息了。如果是用 ISAPI 模块，那没有这个问题。其它 NT 下的 web 服务器不受此影响。更多信息见 » http://support.microsoft.com/kb/q160422/ 及 HTTP 认证 一章。

Windows：不能访问另一台电脑上用 IIS 共享的文件。

必须要做些修改。打开 Internet 信息服务，找到你的 PHP 文件并打开属性页，选择 文件安全性标签，点击 匿名访问和身份验证控制的"编辑"按钮。

解决此问题有两个方法，一是不要选中 匿名访问并且选中 集成 Windows 身份验证，二是选中 匿名访问并编辑匿名访问使用的帐户，改成一个有权限的。

我怎样混合使用 XML 和 PHP？它不认我的 <?xml 标记！

要能够在 PHP 代码中直接嵌入 <?xml，需要将 PHP 设置项 short_open_tags设置为 0以关闭短标记格式。无法通过函数 ini_set()来更改这项设置。不管 short_open_tags是开或者关，都可以用类似于 <?php echo '<?xml'; ?>的方法达到目的。该项设置的默认值为开。

哪里可以找到所有可用的 PHP 预定义变量的完整列表？

请阅读手册中的 预定义变量 一章，该部分的文档已经包含了一部分可以用于你的脚本的预定义变量的列表。可用变量的完整列表（及更多信息）可以通过调用 phpinfo() 函数来查阅。请务必阅读手册中 来自 PHP 之外的变量 一节，这部分文档阐述了外部变量的概念，例如来自 HTML 表单、Cookie 和 URL 的变量。

Note: register_globals 重要说明：

自 PHP 4.2.0 起，PHP 指令 register_globals 的默认值为 off。PHP 社区鼓励开发者不要依赖于此指令, 用其他手段替代，例如superglobals。

怎样才能不用非免费的商业库（例如 PDFLib） 来生成 PDF 文档？我想要个免费的并且不需要再连接别的 PDF 库。

有几个选择，例如 » FPDF 和 » TCPDF 模块。

我试着在用户自定义函数中访问一个标准的 CGI 变量（例如 $DOCUMENT_ROOT 或 $HTTP_REFERER），但是找不到，哪里出了错？

使用 $_SERVER['DOCUMENT_ROOT'] 和 $_SERVER['HTTP_REFERER'] 替代。

有些 PHP 选项可以接受缩写的字节值，与仅能接受 int 字节值相反。都有哪些缩写字节值？

可用的选择有 K（对应 Kilobytes），M（对应 Megabytes）和 G（对应 Gigabytes；自 PHP 5.1.0 起可用），区分大小写。其余的都认为是字节。 1M等于一个 Megabyte，即 1048576 字节。 1K 等于一个 Kilobyte，即 1024 字节。不能在 php.ini 之外使用这些符号，最好用整数的 int 字节值。参见 ini_get() 文档中的转换示例。要注意，数字类型为 int 会自动取整，这意味着 0.5M 与 0 是等价的。

Note: kilobyte 和 kibibyte 的区别

PHP 将一个千字节（kilobyte）描述为等于 1024 字节（bytes），而 IEC 标准则认为这是一个 kibibyte。结论：k 和 K = 1024 bytes.

在 Windows 下，使用 localhost 访问的时候提示连接超时，但是使用 "127.0.0.1" 的时候正常，为什么？

在 PHP 5.3.4 之前，如果启用了 IPv6，PHP 内部的网络解析代码有一个 bug，会导致处理 localhost 相关的地址时失败。可以通过使用 "127.0.0.1" 或在 hosts 文件中禁止 IPv6 来解决这个问题。

User Contributed Notes

robjbrain at gmail dot com 10-Oct-2016 04:37
There is no error message given if you accidentally use KB, MB or GB instead of K, M or G. From what I can tell the alphabetic characters will be ignored and it will be treated as bytes, so 1GB actually equals 1 Byte. phpinfo() and ini_get() will report what you have written e.g. 1GB, so it will not be clear that there is anything wrong with your setting even though there is.


密码散列安全

本部分解释使用散列函数对密码进行安全处理背后的原因， 以及如何有效的进行密码散列处理。

  1. 为什么需要把应用程序中用户的密码进行散列化？
  2. 为何诸如 md5 和 sha1 这样的常见散列函数不适合用在密码保护场景？
  3. 如果不建议使用常用散列函数保护密码， 那么我应该如何对密码进行散列处理？
  4. “盐”是什么？
  5. 我应该如何保存“盐”？
为什么需要把应用程序中用户的密码进行散列化？

当设计一个需要接受用户密码的应用时， 对密码进行散列是最基本的，也是必需的安全考虑。 如果不对密码进行散列处理，那么一旦应用的数据库受到攻击， 那么用户的密码将被窃取。 同时，窃取者也可以使用用户账号和密码去尝试其他的应用， 如果用户没有为每个应用单独设置密码，那么将面临风险。

通过对密码进行散列处理，然后再保存到数据库中， 这样就使得攻击者无法直接获取原始密码， 同时还可以保证你的应用可以对原始密码进行相同的散列处理， 然后比对散列结果。

需要着重提醒的是，密码散列只能保护密码 不会被从数据库中直接窃取， 但是无法保证注入到应用中的 恶意代码拦截到原始密码。

为何诸如 md5() 和 sha1() 这样的常见散列函数不适合用在密码保护场景？

MD5，SHA1 以及 SHA256 这样的散列算法是面向快速、高效 进行散列处理而设计的。随着技术进步和计算机硬件的提升， 破解者可以使用"暴力"方式来寻找散列码 所对应的原始数据。

因为现代化计算机可以快速的"反转"上述散列算法的散列值， 所以很多安全专家都强烈建议 不要在密码散列中使用这些散列算法。

如果不建议使用常用散列函数保护密码， 那么我应该如何对密码进行散列处理？

当进行密码散列处理的时候，有两个必须考虑的因素： 计算量以及"盐"。 散列算法的计算量越大， 暴力破解所需的时间就越长。

PHP 5.5 提供了 一个原生密码散列 API， 它提供一种安全的方式来完成密码 散列和 验证。 PHP 5.3.7 及后续版本中都提供了一个 » 纯 PHP 的兼容库。

PHP 5.3 及后续版本中，还可以使用 crypt() 函数， 它支持多种散列算法。 针对每种受支持的散列算法，PHP 都提供了对应的原生实现， 所以在使用此函数的时候， 你需要保证所选的散列算法是你的系统所能够支持的。

当对密码进行散列处理的时候，建议采用 Blowfish 算法， 这是密码散列 API 的默认算法。 相比 MD5 或者 SHA1，这个算法提供了更高的计算量， 同时还有具有良好的伸缩性。

如果使用 crypt() 函数来进行密码验证， 那么你需要选择一种耗时恒定的字符串比较算法来避免时序攻击。 （译注：就是说，字符串比较所消耗的时间恒定， 不随输入数据的多少变化而变化） PHP 中的 == 和 === 操作符 和 strcmp() 函数都不是耗时恒定的字符串比较， 但是 password_verify() 可以帮你完成这项工作。 我们鼓励你尽可能的使用 原生密码散列 API。

"盐"是什么？

加解密领域中的"盐"是指在进行散列处理的过程中 加入的一些数据，用来避免从已计算的散列值表 （被称作"彩虹表"）中 对比输出数据从而获取明文密码的风险。

简单而言，"盐"就是为了提高散列值被破解的难度 而加入的少量数据。 现在有很多在线服务都能够提供 计算后的散列值以及其对应的原始输入的清单， 并且数据量极其庞大。 通过加"盐"就可以避免直接从清单中查找到对应明文的风险。

如果不提供"盐"，password_hash() 函数会随机生成"盐"。 非常简单，行之有效。

我应该如何保存"盐"？

当使用 password_hash() 或者 crypt() 函数时， "盐"会被作为生成的散列值的一部分返回。 你可以直接把完整的返回值存储到数据库中， 因为这个返回值中已经包含了足够的信息， 可以直接用在 password_verify() 或 crypt() 函数来进行密码验证。

下图展示了 crypt() 或 password_hash() 函数返回值的结构。 如你所见，算法的信息以及"盐"都已经包含在返回值中， 在后续的密码验证中将会用到这些信息。

password_hash 和 crypt 函数返回值的组成部分，依次为：所选择的算法， 算法选项，所使用的

User Contributed Notes

swardx at gmail dot com 29-Jun-2016 09:36
A great read..

https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/

Serious Security: How to store your users' passwords safely

In summary, here is our minimum recommendation for safe storage of your users' passwords:

    Use a strong random number generator to create a salt of 16 bytes or longer.
    Feed the salt and the password into the PBKDF2 algorithm.
    Use HMAC-SHA-256 as the core hash inside PBKDF2.
    Perform 20,000 iterations or more. (June 2016.)
    Take 32 bytes (256 bits) of output from PBKDF2 as the final password hash.
    Store the iteration count, the salt and the final hash in your password database.
    Increase your iteration count regularly to keep up with faster cracking tools.

Whatever you do, don't try to knit your own password storage algorithm.
alf dot henrik at ascdevel dot com 12-Mar-2014 07:58
I feel like I should comment some of the clams being posted as replies here.

For starters, speed IS an issue with MD5 in particular and also SHA1. I've written my own MD5 bruteforce application just for the fun of it, and using only my CPU I can easily check a hash against about 200mill. hash per second. The main reason for this speed is that you for most attempts can bypass 19 out of 64 steps in the algorithm. For longer input (> 16 characters) it won't apply, but I'm sure there's some ways around it.

If you search online you'll see people claiming to be able to check against billions of hashes per second using GPUs. I wouldn't be surprised if it's possible to reach 100 billion per second on a single computer alone these days, and it's only going to get worse. It would require a watt monster with 4 dual high-end GPUs or something, but still possible.

Here's why 100 billion per second is an issue:
Assume most passwords contain a selection of 96 characters. A password with 8 characters would then have 96^8 = 7,21389578984e+15 combinations.
With 100 billion per second it would then take 7,21389578984e+15 / 3600 = ~20 hours to figure out what it actually says. Keep in mind that you'll need to add the numbers for 1-7 characters as well. 20 hours is not a lot if you want to target a single user.

So on essence:
There's a reason why newer hash algorithms are specifically designed not to be easily implemented on GPUs.

Oh, and I can see there's someone mentioning MD5 and rainbow tables. If you read the numbers here, I hope you realize how incredibly stupid and useless rainbow tables have become in terms of MD5. Unless the input to MD5 is really huge, you're just not going to be able to compete with GPUs here. By the time a storage media is able to produce far beyond 3TB/s, the CPUs and GPUs will have reached much higher speeds.

As for SHA1, my belief is that it's about a third slower than MD5. I can't verify this myself, but it seems to be the case judging the numbers presented for MD5 and SHA1. The issue with speeds is basically very much the same here as well.

The moral here:
Please do as told. Don't every use MD5 and SHA1 for hasing passwords ever again. We all know passwords aren't going to be that long for most people, and that's a major disadvantage. Adding long salts will help for sure, but unless you want to add some hundred bytes of salt, there's going to be fast bruteforce applications out there ready to reverse engineer your passwords or your users' passwords.
fluffy at beesbuzz dot biz 11-Jun-2012 11:33
The security issue with simple hashing (md5 et al) isn't really the speed, so much as the fact that it's idempotent; two different people with the same password will have the same hash, and so if one person's hash is brute-forced, the other one will as well.  This facilitates rainbow attacks.  Simply slowing the hash down isn't a very useful tactic for improving security.  It doesn't matter how slow and cumbersome your hash algorithm is - as soon as someone has a weak password that's in a dictionary, EVERYONE with that weak password is vulnerable.

Also, hash algorithms such as md5 are for the purpose of generating a digest and checking if two things are probably the same as each other; they are not intended to be impossible to generate a collision for.  Even if an underlying password itself requires a lot of brute forcing to determine, that doesn't mean it will be impossible to find some other bit pattern that generates the same hash in a trivial amount of time.

As such: please, please, PLEASE only use salted hashes for password storage.  There is no reason to implement your own salted hash mechanism, either, as crypt() already does an excellent job of this.


PHP 和 HTML

PHP 和 HTML 有很多相互作用：PHP 能生成 HTML，HTML 可以向 PHP 传递信息。在阅读这些常见问题之前，先学会怎样 从 PHP 之外取得变量很重要。此主题的手册页也包括很多例子。还要仔细留意 register_globals对你意味着什么。

  1. 当我通过表单／URL 传值时需要用什么编码／解码方法？
  2. 我在试用 <input type="image"> 标记，但是没有 $foo.x和 $foo.y变量，它们哪去了？
  3. 怎样在 HTML 的 <form> 中建立数组？
  4. 怎样从可多选的 HTML 的 select multiple 标记中得到所有结果？
  5. 怎样从 Javascript 传递一个变量到 PHP？
当我通过表单／URL 传值时需要用什么编码／解码方法？

在几个环节上编码方式很重要。假定有 string $data，其中包含了想通过非编码方式传递的字符串，那这是相关步骤：

  • HTML 解析。要指定一个任意的字符串， 必须将其放在双引号中，并用 htmlspecialchars()处理整个值。

  • URL：URL 由几部分组成。如果希望自己的数据被当作其中一项来解释， 必须用 urlencode()对其编码。

Example #1 隐藏的 HTML 表单单元

<?php
    echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
?>

Note: 用 urlencode()来处理 $data是错误的，因为是浏览器的责任来 urlencode()数据。所有流行的浏览器都能正确处理。注意不论何种方法（例如 GET 或 POST）都会这样。不过只会在用 GET 请求时注意到这一点，因为 POST 请求通常是隐藏的。

Example #2 等待用户编辑的数据

<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

Note: 数据会按照预期的显示在浏览器中，因为浏览器会解释 HTML 转义符号。 当提交时，不论是 GET 或者 POST 方法，数据都会被浏览器进行 urlencode 来传输，并直接被 PHP urldecode。所以最终不需要自己处理任何 urlencoding/urldecoding，全都是自动处理的。

Example #3 URL 中的例子

<?php
    echo "<a href='" . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . "'>\n";
?>

Note: 事实上这在编造一个 HTML 的 GET 请求，因此需要手工对数据进行 urlencode()。

Note: 需要对整个 URL 进行 htmlspecialchars()，因为 URL 是作为 HTML 属性的一个值出现的。在本例中，浏览器会首先对值进行 un- htmlspecialchars()，然后再传递此 URL。PHP 将能正确理解 URL，因为对数据进行了 urlencoded()。 要注意到 URL 中的 &被替换成了 &amp;。如果忘了这一步，尽管大多数浏览器都能恢复，但也不总是这样。因此即使 URL 不是动态的，也 需要对 URL 进行 htmlspecialchars()。

我在试用 <input type="image"> 标记，但是没有 $foo.x和 $foo.y变量，它们哪去了？

当提交表单时，可以用图片代替标准的提交按钮，用类似这样的标记：

<input type="image" src="image.gif" name="foo" />
当用户点击了图片的任何部分，该表单会被发送到服务器并加上两个额外的变量： foo.x和 foo.y。

因为 foo.x和 foo.y在 PHP 中会成为非法的变量名，它们被自动转换成了 foo_x和 foo_y。也就是用下划线代替了点。因此，可以按照在 来自 PHP 之外的变量这一节中说明的那样访问这些变量。例如， $_GET['foo_x']。

Note:

请求变量名中的空格被转换为下划线。

怎样在 HTML 的 <form> 中建立数组？

要使你的 <form> 结果被当成 array发送到 PHP 脚本，要对 <input>，<select> 或者 <textarea> 单元这样命名：

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
注意变量名后的方括号，这使其成为一个数组。可以通过给不同的单元分配相同的名字来把单元分组到不同的数组里：
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
这将产生两个数组，MyArray 和 MyOtherArray，并发送给 PHP 脚本。还可以给数组分配指定的键名：
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
AnotherArray 数组将包含键名 0，1，email 和 phone。

Note:

指定数组的键名是 HTML 的可选项。如果不指定键名，则数组被按照单元在表单中出现的顺序填充。第一个例子将包含键名 0，1，2 和 3。

参见 数组函数和 来自 PHP 之外的变量。

怎样从可多选的 HTML 的 select multiple 标记中得到所有结果？

可多选的 select multiple 标记是 HTML 的一个构造，允许用户从一个列表中选择多个项目。这些项目接着被传递给该表单 action 中指定的处理程序。问题是它们都会被用同样的名字传递。例如：

<select name="var" multiple="yes">
每个被选项将这样被传递到表单处理程序：
var=option1 var=option2 var=option3
每个选项将覆盖前面一个 $var变量的内容。解决方案是用 PHP 的"表单单元数组"特性。使用方法如下：
<select name="var[]" multiple="yes">
这将告诉 PHP 将 $var当成数组对待，每个对 var[] 的赋值都会给数组增加一项。第一项将成为 $var[0]，下一个是 $var[1]，等等。可以用 count()函数来测定选择了多少个项目，必要时可以用 sort()函数来对选项的数组进行排序。

注意如果在 JavaScript 中通过名字来引用单元，单元名字中的 []可能会造成问题。用表单单元中的数字序号来替代，或者将变量名用单引号括起来并用其作为单元数组的索引，例如：

variable = documents.forms[0].elements['var[]'];

怎样从 Javascript 传递一个变量到 PHP？

由于 Javascript （通常情况下）是客户端技术，而 PHP （通常情况下）是服务器端技术，而且 HTTP 是一种"无状态"协议，因此两种语言之间不能直接共享变量。

但是，有可能在二者之间传递变量。一种实现的方法是用 PHP 生成 Javascript 代码，并让浏览器自动刷新，将特定的变量传递回 PHP 脚本。以下例子显示了如何这样做——让 PHP 代码取得显示屏幕的高度和宽度，通常只能在客户端这么做。

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo "Screen width is: ". $_GET['width'] ."<br />\n";
  echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   -- post variables will need to handled differently)

  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>

User Contributed Notes

murphy 28-Jan-2020 08:58
The scenario:

1. There is a php script which (possibly complemented by a direct written HTML code) consrtucts a HTML page via its echo command, based on whatever algoritmus eventually based on supplementary data from server files or databases.

2. This php script leads to data being saved into string variable(s), which (possibly) can contain arbitrary characters, including control codes (newline, tab...), HTML special characters (&,<...) and non-ASCII (international) characters.

3. These non-ASCII characters are UTF-8 encoded, as well as the HTML page (I do highly recommend) *)

4. The values of these PHP string variables have to be transferred into javascript variables for further processing by javascript (or exposing these values in HTML directly)

The problem:

it is not safe to PHP-echo such variables into HTML (javascript) directly, because some of characters possily contained in them cause malfunction of the HTML. These strings need some encoding/escaping in order to become strings of non-conflicting characters

The solution

There may be a big lot of ways of this encoding. The following one seems to me the easiest one:
The PHP variable with unpredictable value can originate from some file, as an example (or from user input as well):

$variable=file_get_content(...)

1. Convert all bytes of that string into hex values and prepend all hex-digit-pairs with %

$variable_e=preg_replace("/(..)/","%$1",bin2hex($variable))

The new variable is now guarantied to contain only %1234567890abcdefABCDEF chracters (e.g. %61%63%0a...) and can safely be directly echoed into HTML:

var variable="<?php echo $variable_e;?>" //that's NOT all folks

But now the value is still encoded. To get the original value of the variable, it has te be decoded: *)

var variable=decodeURIComponent("<?php echo $variable_e;?>")

The value of the variable is now the same as the original value.

*) I have no idea about non-UTF-8 encoded pages/data, espetially how the decodeURIComponent works in such a case, because i have no reason to use other encodings and handle them as highly deprecatad.

WARNING: this approach is not (generally) safe against code injection. I highly recommend some further check (parsing) of the value depending on the particular case.

P.S. For very large amount of data, I would recomment to save them into file on the PHP side (file_put_content) and read them by javascript via HTTP Request.

I use this approach as it needs one line of code on server as well as client side. I do agree with arguement that not all chaeacters have to be encoded.

Do not enjoy my possibly stupid solution, if you have a better idea

murphy
starbugfourtytwo at gmail dot com 29-May-2019 11:04
Why use such a complicated example for js to php? why not do this..so we can understand:

javascript:

const variable = "A"

php:

do whatever it takes to get A from javascript
smileytechguy at smileytechguy dot com 02-Feb-2018 04:55
The (at least that I've found) best way to pass data from PHP to JS is json_encode.  Doing so will convert arrays, strings, numbers, etc. as best as possible.

<?php
$myInt = 7;
// a bunch of special characters to demonstrate proper encoding
$myString = <<<EOF
" ' ; &\ $
EOF;
$myArr = [1, "str", 2];
$myAssocArr = ["foo" => "bar"];
?>

<script>
var myInt = <?= json_encode($myInt) ?>;
var myString = <?= json_encode($myString) ?>;
var myArr = <?= json_encode($myArr) ?>;
var myAssocArr = <?= json_encode($myAssocArr) ?>;
</script>

This will render the following JS code, which correctly stores the variables:
<script>
var myInt = 7;
var myString = "\" ' ; &\\ $";
var myArr = [1,"str",2];
var myAssocArr = {"foo":"bar"};
</script>

Do note that there are no "s or anything like that around the json_encode output; json_encode handles that for you.
Jay 01-Apr-2014 09:25
If you have a really large form, be sure to check your max_input_vars setting.  Your array[] will get truncated if it exceeds this.  http://www.php.net/manual/en/info.configuration.php#ini.max-input-vars
jetboy 30-Dec-2005 07:06
While previous notes stating that square brackets in the name attribute are valid in HTML 4 are correct, according to this:

http://www.w3.org/TR/xhtml1/#C_8

the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document.


PHP 和 COM

PHP 可以在 Win32 平台中访问 COM 和 DCOM 对象。

  1. 我建立了一个 DLL 来做某种计算。有办法在 PHP 中运行这个 DLL 吗？
  2. “Unsupported variant type: xxxx (0xxxxx)”是什么意思？
  3. 在 PHP 中有可能操纵可视对象吗？
  4. 可以将一个 COM 对象保存在 session 中吗？
  5. 怎样可以捕获 COM 的错误？
  6. 我能像在 Perl 中一样从 PHP 脚本生成 DLL 文件吗？
  7. “Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”是什么意思？
  8. 怎样从远端服务器运行 COM 对象？
  9. 我得到一个“DCOM is disabled in C:\path...\scriptname.php on line 6”信息，应该怎么办？
  10. 有可能在 PHP 页面中加载／操纵 ActiveX 对象吗？
  11. 有可能得到一个组件在运行中的实例吗？
  12. 有办法处理 COM 对象中发送的事件吗？
  13. 我在尝试调用一个打开了多于一个接口的 COM 对象中的方法时碰到问题，应该怎么办？
  14. 这么说 PHP 可以和 COM 一起工作，那么 COM+ 呢？
  15. 如果 PHP 可以操纵 COM 对象，那么可以设想结合 PHP 用 MTS 来管理组件资源吗？
我建立了一个 DLL 来做某种计算。有办法在 PHP 中运行这个 DLL 吗？

如果这是个简单的 DLL 那么还没有办法在 PHP 中运行它。如果这个 DLL 中包含有一个 COM 服务器并且它实现了 IDispatch 接口，那有可能访问它。

"Unsupported variant type: xxxx (0xxxxx)"是什么意思？

有几十种 VARIANT 类型以及它们的组合。大多数已经被支持了但还有几种尚未实现。数组没有完全被支持。只有一维的仅用作索引的数组可以在 PHP 和 COM 之间传递。如果你发现其它未支持的类型，请当作一个 bug 报告（如果尚未被报告的话）并提供尽可能多的信息。

在 PHP 中有可能操纵可视对象吗？

一般来说是可以的，但是 PHP 大都用来作为 web 脚本语言并运行在 web 服务器的上下文环境中，因此可视对象决不会在服务器的桌面上显示。如果你把 PHP 用作应用程序脚本例如结合 PHP-GTK 来使用，那么访问和通过 COM 来操纵可视对象方面没有限制。

可以将一个 COM 对象保存在 session 中吗？

不行。COM 的实例被看作是资源，因此只在一个脚本的上下文中有效。

怎样可以捕获 COM 的错误？

在 PHP 5 中，COM 扩展会发出 com_exception异常信息，可以捕获并检查 code成员来决定下一步的行为。

在 PHP 4 中除了用 PHP 自己提供的办法之外（@，track_errors，..）不可能捕获 COM 的错误。

我能像在 Perl 中一样从 PHP 脚本生成 DLL 文件吗？

不行，PHP 没有这样的工具。

"Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"是什么意思？

此错误可以有多种原因：

  • 错误的 CLSID
  • 找不到所请求的 DLL
  • 所请求的组件没有实现 IDispatch 接口

怎样从远端服务器运行 COM 对象？

完全和运行本地对象一样。只须将远端服务器的 IP 作为第二个变量传递给 COM 的构造函数即可。

确认在 php.ini 中设定了 =&true;。

我得到一个"DCOM is disabled in C:\path...\scriptname.php on line 6"信息，应该怎么办？

编辑 php.ini 并设定 =&true;。

有可能在 PHP 页面中加载／操纵 ActiveX 对象吗？

这不关 PHP 的事。如果在 HTML 文档中请求的话，ActiveX 对象被加载在客户端。这和 PHP 脚本没有关系，因此也不可能和服务器端发生直接的交互作用。

有可能得到一个组件在运行中的实例吗？

在绰号的帮助下这有可能。如果你想得到同一个 word 实例的多个引用你可以这样建立此实例：

<?php
$word = new COM("C:\docs\word.doc");
?>

如果没有运行中的实例这将建立一个新的实例，否则将会返回正在运行中的实例的句柄，如果可用的话。

有办法处理 COM 对象中发送的事件吗？

可以自定义事件收报方并且用 com_event_sink()函数绑定之。可以用 com_print_typeinfo()来让 PHP 产生事件收报方类的框架。

我在尝试调用一个打开了多于一个接口的 COM 对象中的方法时碰到问题，应该怎么办？

我也不知道怎么办，我想这没办法。如果什么人有对此问题的明确信息请 » 告诉我。:)

这么说 PHP 可以和 COM 一起工作，那么 COM+ 呢？

COM+ 通过使用 MTS 和 MSMQ 来管理组件的框架扩展了 COM，但并没有什么特殊之处使 PHP 非要支持这样的组件。

如果 PHP 可以操纵 COM 对象，那么可以设想结合 PHP 用 MTS 来管理组件资源吗？

PHP 本身还并不处理事务。因而如果出错也不会发动撤回机制。如果你使用了支持事务处理的组件那你不得不自己实现事务管理。

User Contributed Notes

codeslinger at compsalot dot com 27-Jan-2007 05:18
in response to item #1 above:  "If this is a simple DLL there is no way yet to run it from PHP."

Answer: There are several different packages/add-ons to php that enable low level access to the windows api. One of the most popular of these packages is available at http://www.winbinder.org

Winbinder does have the ability to load a dll and call it's functions.  Winbinder also provides a large set of windows apis for creating windows and controls.  This is useful for creating stand-alone desktop apps.  It is a possible alternative to php-gtk.

I've had mixed results with Winbinder, some things work very well, others are buggy; source code is available.  It's worth a look, Evaluate carefully.
17-Jul-2005 04:56
Re: The Windows English CHM Sample with MS Word Automation.

I see that $Word->Release() is called after $Word->Quit().
This seems to be erroneous. Actually, $Word->Release() should not have to be called if proper COM garbage collection is taking place. Release() is a C++ construction not used in either Visual Basic or VBScript or even MS-JScript. Just to be sure, however, I ran the sample through php.exe (5.04 CLI on Windows XP SP1 with Office 2003) and got a RPC failed error on the line containing $Word->Release(). The rest of the sample works fine, and the results are as expected. So, I propose 2 scenarios:
      1.There is a problem with the documentation (more likely).
      2.There is a problem with PHP504 itself, as this problem is reproduced with any COM Automation call, not just Word.
junk.ghost@virgin dOtt net 05-Oct-2004 09:27
It may be obvious to everyone else but...

If you want to write your own COM DLL in MSVC++6 and you want to pass it a string, you need the following in your .idl file:

HRESULT function_name([in] BSTR parameter_name,
                      [retval, out] BSTR * retval);

retval is the result of your function as a string to be passed back.

BSTR is an unsigned short *, so if you want to use your string with STL string etc. you may need to convert parameters to and from char *.

The burden of my message is that from PHP

$comThing = new COM("comThing.comThing");
print $comThing->function_name("Jeremy");

Jeremy will be marshalled as wide chars, which match BSTR.


其他问题

有些问题没法归到其它类中，可以在这里找到。

  1. 在 Windows 中怎样处理 bz2 压缩的文档？
在 Windows 中怎样处理 bz2 压缩的文档？

如果没有能处理 bz2 文件的压缩工具，从 Redhat » 下载一个命令行工具（进一步信息见下面）。

如果不喜欢用命令行工具，可以试试免费工具例如 » Stuffit Expander， » UltimateZip， » 7-Zip或者 » Quick Zip。如果有像 » WinRAR或者 » Power Archiver之类的工具，可以很容易用它解压缩 bz2 文件。如果用 Total Commander（前身为 Windows Commander），可以从 » Total Commander网站免费得到一个 bz2 插件。

来自 Redhat 的 bzip2 命令行工具：

Win2K Sp2 用户下载最新版本 1.0.2，所有其它 Windows 用户应该用版本 1.00。下载后重命名可执行文件为 bzip2.exe。为方便起见将其放到一个在你路径中的目录，例如 C:\Windows，C 表示你安装 Windows 的盘符。

注意：lang 指的是你的语种，x 是想要的格式，例如：pdf。要解压缩 php_manual_lang.x.bz2，按照下面的简单说明进行：

  • 打开一个命令行窗口
  • 进入存放已下载的 php_manual_lang.x.bz2 的目录
  • 调用 bzip2 -d php_manual_lang.x.bz2，将 php_manual_lang.x 释放到同一个目录

在下载了包含很多 html 文件的 php_manual_lang.tar.bz2 的情况下，过程是一样的。唯一区别是得到了一个 php_manual_lang.tar 文件。tar 格式可以被大多数 Windows 下流行的压缩工具所处理，例如 » WinZip。

User Contributed Notes

doerr at apkk dot de 28-Dec-2010 05:41
If you only needed register_globals for get/post variables, the effictive solution for 5.3 is:
  import_request_variables("GPC", "");

But if the skripts relied on session_register() you'll have to do more:
- Replace all variables that appeared after session_register with _SESSION equivalents - so $myvar becomes $_SESSION['myvar']
- Take care if your variables appeared inside strings - 'Hello $user !' works, but 'Hello $_SESSION['user'] !' not - so you have to concatenate the string: 'Hello '.$_SESSION['user'] .' !'
- Session variables in function declarations (for whatever purpose) will not work - keeping the old (local) names will work in most cases.
- Finally, replace the session_register(..) line with session_start()
markus 18-Jun-2005 03:34
Considering the comment below. I think there's a way to avoid that "problem":

<?php
//
// $starttime is an example of a variable that we might need to define,
// even before, running the "register_globals OFF" emulator below.
//
list($msec, $sec) = explode(' ', microtime());
$starttime = ((float)$msec + (float)$sec);

//
// If register_globals is ON, ensure no unexpected globals are defined.
// ie. We'll try to emulate a register_globals OFF environment.
//
if( (bool)@ini_get('register_globals') )
{
    $superglobals = array($_ENV, $_GET, $_POST, $_COOKIE, $_FILES, $_SERVER);
    if( isset($_SESSION) )
    {
        array_unshift($superglobals, $_SESSION);
    }
    $knownglobals = array(
        //
        // Known PHP Reserved globals and superglobals:
        //
        '_ENV',        'HTTP_ENV_VARS',
        '_GET',        'HTTP_GET_VARS',
        '_POST',    'HTTP_POST_VARS',
        '_COOKIE',    'HTTP_COOKIE_VARS',
        '_FILES',    'HTTP_FILES_VARS',
        '_SERVER',    'HTTP_SERVER_VARS',
        '_SESSION',    'HTTP_SESSION_VARS',
        '_REQUEST',

        //
        // Global variables used by this code snippet:
        //
        'superglobals',
        'knownglobals',
        'superglobal',
        'global',
        'void',

        //
        // Known global variables defined before this code snippet is reached.
        //
        'starttime',
    );
    foreach( $superglobals as $superglobal )
    {
        foreach( $superglobal as $global => $void )
        {
            if( !in_array($global, $knownglobals) )
            {
                unset($GLOBALS[$global]);
            }
        }
    }
}
?>

Note the stuff related to the $_SESSION array depends on whether the PHP session has been started or not. You might want to call session_start() before this point (or set session.auto_start ON).

HTH+ :)
php at REMOVEMEkennel17 dot co dot uk 12-Apr-2005 08:22
Regarding simulating register_globals = off, note that it is impossible to adequately prevent $_SESSION variables from being globalised, as the array (and thus the globals) are created on a call to session_start().  You would therefore have to 'undo' this when you start a session as using it at the start of your script will have no effect.

To avoid potential problems, use a prefix that is unique for all session variables (e.g. 'SESS_'), and only access them via the $_SESSION array.  The prefix ensures that you don't have a naming clash (and therefore a security risk) with any non-session globals.


附录

  • PHP 及其相关工程的历史
    • PHP 的历史
    • PHP 相关工程的历史
    • PHP 相关书籍
    • PHP 相关文章
  • 从 PHP 7.4.x 移植到 PHP 8.0.x
    • 新特性
    • 不向后兼容的变更
    • PHP 8.0 废弃的功能
    • 其他变更
  • 从 PHP 7.3.x 移植到 PHP 7.4.x
    • 新特性
    • 新的类和接口
    • 新函数
    • 新的全局常量
    • 不向后兼容的变更
    • PHP 7.4.x 废弃的功能
    • 移除的扩展
    • 其他变更
    • Windows 支持
  • 从 PHP 7.2.x 移植到 PHP 7.3.x
    • 新特性
    • 新函数
    • 新的全局常量
    • 不向下兼容的变更
    • PHP 7.3.x 中废弃的功能
    • 其它变更
    • Windows 支持
  • 从 PHP 7.1.x 移植到 PHP 7.2.x
    • 新特性
    • 新函数
    • 新全局常量
    • 不向下兼容的变更
    • PHP 7.2.x 中废弃的功能
    • 其他变更
  • 从 PHP 7.0.x 移植到 PHP 7.1.x
    • 新特性
    • 新的函数
    • 新增的全局常量
    • 不向后兼容的变更
    • PHP 7.1.x 中废弃的特性
    • 变动的函数
    • 其它改动
    • Windows 支持
  • 从 PHP 5.6.x 移植到 PHP 7.0.x
    • 不向后兼容的变更
    • 新特性
    • PHP 7.0.x 弃用的功能
    • 变更的函数
    • 新函数
    • 新的类和接口
    • 新的全局常量
    • SAPI 模块的变化
    • 移除的扩展和 SAPI
    • Other Changes
  • 从 PHP 5.5.x 移植到 PHP 5.6.x
    • 向后不兼容
    • 新特性
    • PHP 5.6.x 中已废止的特性
    • 函数的变化
    • 新加函数
    • OpenSSL changes in PHP 5.6.x
    • 扩展中的变动
    • 新加的全局常量
  • PHP 的调试
    • 关于调试器
  • 配置选项
    • 核心配置选项列表
  • php.ini 配置
    • php.ini 配置选项列表
    • php.ini 配置段列表
    • php.ini 核心配置选项说明
  • 扩展库列表／归类
    • 按字母顺序
    • 按归属分
    • 按状态分
  • 函数别名列表
  • 保留字列表
    • 关键词列表
    • 预定义类
    • 预定义常量
    • 其他保留字列表
  • 资源类型列表
  • 可用过滤器列表
    • 字符串过滤器
    • string.strip_tags
    • 转换过滤器
    • 压缩过滤器
    • 加密过滤器
  • 所支持的套接字传输器（Socket Transports）列表
    • Internet 领域：TCP，UDP，SSL 和 TLS
    • Unix 领域：Unix 和 UDG
  • PHP 类型比较表
  • 解析器代号列表
  • 用户空间命名指南
    • 全局命名空间
    • 规则
    • 提示
  • 关于本手册
    • 手册的格式
    • 关于用户注释
    • 如何阅读函数的定义（函数原型）
    • 本手册中所涉及的 PHP 版本
    • 如何得到关于 PHP 更多的信息
    • 如何帮助改进本文档
    • 如何生成手册的各种格式
    • 手册译文
  • Creative Commons Attribution 3.0
  • 索引
    • 函数和方法列表
    • 示例列表
  • 更新日志

User Contributed Notes

There are no user contributed notes for this page.


PHP 及其相关工程的历史

Table of Contents

  • PHP 的历史
  • PHP 相关工程的历史
  • PHP 相关书籍
  • PHP 相关文章

PHP 在过去的几年里走过了漫长的道路。成长为处理 web 的最卓越的语言并非易事。如果对 PHP 如何发展到今天很感兴趣，那么请继续读下去吧。以前的 PHP 发行版可以在 » PHP 博物馆找到。

User Contributed Notes

tarlepp 21-Jul-2017 12:01
It seems like PHP7 is missing here totally, also some comment about why skip PHP6 version would be nice.


PHP 的历史

PHP/FI

PHP 继承自一个老的工程，名叫 PHP/FI。PHP/FI 在 1995 年由 Rasmus Lerdorf 创建，最初只是一套简单的 Perl 脚本，用来跟踪访问他主页的人们的信息。它给这一套脚本取名为"Personal Home Page Tools"。随着更多功能需求的增加，Rasmus 写了一个更大的 C 语言的实现，它可以访问数据库，可以让用户开发简单的动态 Web 程序。Rasmus » 发布了 PHP/FI 的源代码，以便每个人都可以使用它，同时大家也可以修正它的 Bug 并且改进它的源代码。

PHP/FI，一个专为个人主页／表单提供解释程序的程序，已经包含了今天 PHP 的一些基本功能。它有着 Perl 样式的变量，自动解释表单变量，并可以嵌入 HTML。语法本身与 Perl 很相似，但是它很有限，很简单，还稍微有些不协调。

到1997年，PHP/FI 2.0，也就是它的 C 语言实现的第二版在全世界已经有几千个用户（估计）和大约 50,000 个域名安装，大约是 Internet 所有域名的 1%。但是那时只有几个人在为该工程撰写少量当代码，它仍然只是一个人的工程。

PHP/FI 2.0 在经历了数个 beta 版本的发布后于 1997 年 11 月发布了官方正式版本。不久，PHP 3.0 的第一个 alpha 版本的发布，PHP 从此走向了成功。

PHP 3

PHP 3.0 是类似于当今 PHP 语法结构的第一个版本。Andi Gutmans 和 Zeev Suraski 在为一所大学的项目中开发电子商务程序时发现 PHP/FI 2.0 功能明显不足，于是他们重写了代码。这就是 PHP 3.0。经过Andi，Rasmus 和 Zeev 一系列的努力，考虑到 PHP/FI 已存在的用户群，他们决定联合发布 PHP 3.0 作为 PHP/FI 2.0 的官方后继版本。而 PHP/FI 2.0 的进一步开发几乎终止了。

PHP 3.0 的一个最强大的功能是它的可扩展性。除了给最终用户提供数据库、协议和 API 的基础结构，它的可扩展性还吸引了大量的开发人员加入并提交新的模块。后来证实，这是 PHP 3.0 取得巨大成功的关键。PHP 3.0 中的其它关键功能包括面向对象的支持和更强大和协调的语法结构。

这个全新的语言伴随着一个新的名称发布。它从 PHP/FI 2.0 的名称中移去了暗含"本语言只限于个人使用"的部分。它被命名为简单的缩写"PHP"。这是一种递归的缩写，它的全称是——PHP: Hypertext Preprocessor。

1998 年末，PHP 的安装人数几近 10,000，有大约 100,000 个网站报告他们使用了 PHP。在 PHP 3.0 的顶峰，Internet 上 10% 的 web 服务器上都安装了它。

约九个月的公开测试后，官方于 1998 年 6 月正式发布 PHP 3.0。

PHP 4

1998 年的冬天，PHP 3.0 官方发布不久，Andi Gutmans 和 Zeev Suraski 开始重新编写 PHP 代码。设计目标是增强复杂程序运行时的性能和 PHP 自身代码的模块性。PHP 3.0 的新功能和广泛的第三方数据库、API的支持使得这样程序的编写成为可能，但是 PHP 3.0 没有高效处理如此复杂程序的能力。

新的被称为"Zend Engine"（这是 Zeev 和 Andi 的缩写）的引擎，成功的实现了设计目标，并在 1999 年中期首次引入 PHP。基于该引擎并结合了更多新功能的 PHP 4.0，在 PHP 3.0 发布两年后，于2000年5月发布了官方正式版本。除了更高的性能以外，PHP 4.0 还包含了其它一些关键功能，比如：支持更多的 web 服务器；HTTP Sessions 支持；输出缓冲；更安全的处理用户输入的方法；一些新的语言结构。

今天，已经有 10,000 名开发人员（估计）和几百万网站报告已安装了 PHP，占整个 Internet 域名的 20%。

PHP 的开发小组有很多优秀的开发人员，同时还有大量的优秀人才在进行 PHP 相关工程的开发工作，如 PEAR 和 PHP 文档的工程。

PHP 5

PHP 5 在长时间的开发及多个预发布版本后，于 2004 年 7 月发布正式版本。它的核心是 Zend 引擎 2 代，引入了新的对象模型和大量新功能。

User Contributed Notes

There are no user contributed notes for this page.


PHP 相关工程的历史

PEAR

» PEAR，PHP 扩展与应用资源库（PHP Extension and Application Repository，原为 PHP Extension and Add-on Repository）是 PHP 程序的基础类，并可能在将来增强为在开发人员间分发 PHP 和 C 语言编写的 PHP 扩展的关键方法。

PEAR 在 2000 年 1 月于 Tel Aviv 举行的 PHP 开发者会议（PDM）中诞生。这个工程由 Stig S. Bakken 创建。现在，他正专注于他的第一个小女儿，Malin Bakken。

2000 年早些时候，PEAR 已经成长为一个巨大的，有意义的工程。大量的开发人员在为实现普通的、可重用的、功能强大的代码而努力工作着。这给整个 PHP 团体都带来极大的益处。今天 PEAR 包含了大量的基础类，包括数据库访问、内容缓存、数学计算、电子商务等等。

有关 PEAR 的更多信息见其» 手册。

PHP 质量保证体系（QA）

» PHP 质量保证体系于2000年夏设立，因为用户批评 PHP 在发布前没有进行足够的针对产品环境的测试。质量保证小组由精通 PHP 基础代码的核心人员组成。这些开发人员将精力花费在本地化和修复 PHP 的 bug 上。除此之外，其他小组成员也在各种不同的平台上对这些修复进行测试并提供反馈信息。

PHP-GTK

» PHP-GTK 是编写客户端图形用户界面（GUI）程序的 PHP 解决方案。Andrei Zmievski 回忆了 PHP-GTK 计划和创建的过程：

"我总是对 GUI 编程有着浓厚的兴趣。我发现 Gtk+ 是一个非常好的工具包，除了一点——它使用的 C 语言很令人乏味。目睹了 PyGtk 和 GTK-Perl 的实现，我决定尝试 PHP 是否也能够被做成 Gtk+ 的接口。2000 年 8 月，我有了更多的业余时间，于是我开始试验。我参考了 PyGtk 的实现方法，因为它有着相当完全的实现和漂亮的面向对象的接口。James Henstridge，PyG 的作者，在最初的筹备阶段提供了极大的帮助。

"手工写 Gtk+ 函数全部的接口几乎是不可能的事情，所以我把重点放在了代码生成上，就像 PyGtk 做的一样。代码生成器是一个PHP 程序，它可以读取包含 Gtk+ 类、常量和方法信息的一系列的 .defs 文件并生成与 PHP 相接口的 C 代码。无法自动生成的部分可以提交到 .overrides 文件。

"代码生成器和基础结构的工作花了我一定的时间，因为我在 2000 年秋天这段时间里只能花很少的时间在 PHP-GTK 上。在我把 PHP-GTK 给 Frank Kromann 演示过后，他产生了浓厚的兴趣，并开始帮助我完成代码生成器和 Win32 的实现。当我们写了第一个 Hello World 程序并设法使之工作之时，我们的喜悦之情溢于言表。两个多月后，这个工程初见成效，并于 2001 年 3 月 1 日发布了内部版本。这个故事迅速的打击了 SlashDot。

"感到 PHP-GTK 前景广阔，我便为它专门设置了邮件列表和 CVS 知识库。同时，gtk.php.net 网站也在 Colin Viebrock 的帮助下建立起来。文档的工作也由 James Moore 承担起来。

"PHP-GTK 发布之后，它愈加流行。我们有自己的文档小组，手册持续更新。人们开始为 PHP-GTK 编写扩展。越来越多的程序已经开始使用它了。"

User Contributed Notes

There are no user contributed notes for this page.


PHP 相关书籍

随着 PHP 的成长，人们越来越认识到它是一个世界流行的开发平台。看到这种趋势的最有趣方法之一就是：这些年 PHP 相关书籍越来越多。

据我们所知，最早的 PHP 专业书籍是"php- dynamische webauftritte professionell realisieren"——一本 1999 年出版的德国书籍，作者是 Egon Schmid、Christian Cartus 和 Richard Blume。第一本关于 PHP 的英文书随后出版，书名是"Core PHP Programming"，作者为：Leon Atkinson。这两本书都是写 PHP 3.0 的。

这两本书是这类图书的第一本——随后，大量的 PHP 相关图书上市。英文版本超过 40 种，德文 50 种，法文 20 种！除此之外，你可以发现西班牙文、韩文、日文、中文和希伯来文等等语言版本的 PHP 相关图书。

这么大量的图书，这么多作者的写作，这么多出版商的出版，并出现了这么多语言的版本——这强烈的证明 PHP 在世界范围内的成功！

User Contributed Notes

There are no user contributed notes for this page.


PHP 相关文章

据我们所知，关于 PHP 的在杂志上的第一篇文章于 1998 年末在法国的"Informatiques Magazine"杂志上发表，是描述 PHP 3.0 的。据记载，这是大量出版在杂志上 PHP 相关文章的第一篇。

关于 PHP 的文章出现在 Dr. Dobbs、Linux Enterprise、Linux Magazine 等等出版物上。关于在 Windows 下如何转换 ASP 程序到 PHP 的文章甚至出现在了微软自己的 MSDN 上！

User Contributed Notes

There are no user contributed notes for this page.


从 PHP 7.4.x 移植到 PHP 8.0.x

Table of Contents

  • 新特性
  • 不向后兼容的变更
  • PHP 8.0 废弃的功能
  • 其他变更

新的主版本号带来了一些 新特性 和 不兼容处， 在生产环境上切换 PHP 版本前需要做测试。

参见 PHP 版本迁移指南 7.0.x、 7.1.x、 7.2.x、 7.3.x、 7.4.x。

User Contributed Notes

There are no user contributed notes for this page.


新特性

PHP 核心中的新特性

命名参数

注解（Attributes）

新增注解的功能。

构造器属性提升（Constructor Property Promotion）

新增构造器属性提升功能（在构造函数中声明类的属性）。

联合类型

新增 联合类型。

Match 表达式

新增 match 表达式。

Nullsafe 运算符

新增 Nullsafe 运算符(?->)。

其他新特性

  • 新增 WeakMap 类。

  • 新增 ValueError 类。

  • 现在，只要类型兼容，任意数量的函数参数都可以用一个可变参数替换。 例如允许编写下面的代码：

    <?php
    class A {
         public function     method(int $many, string $parameters, $here) {}
    }
    class     B extends A {
         public function     method(...$everything) {}
    }
    ?>

  • static ("后期静态绑定"中) 可以作为返回类型：

    <?php
    class Test {
         public function     create(): static {
              return new static();
         }
    }
    ?>

  • 现在可以通过 $object::class 获取类名，返回的结果和 get_class($object) 一致。

  • new、instanceof 可用于任何表达式， 用法为 new (expression)(...$args) 和 $obj instanceof (expression)。

  • 添加对一些变量语法一致性的修复，例如现在能够编写 Foo::BAR::$baz。

  • 添加 Stringable interface， 当一个类定义 __toString() 方法后会自动实现该接口。

  • Trait 可以定义私有抽象方法（abstract private method）。 类必须实现 trait 定义的该方法。

  • 可作为表达式使用 throw。 使得可以编写以下用法：

    <?php
    $fn     = fn() => throw new Exception('Exception in arrow function');
    $user = $session->user ?? throw new Exception('Must have user');

  • 参数列表中的末尾逗号为可选。

    <?php
    function functionWithLongSignature(
            Type1 $parameter1,
            Type2 $parameter2, // <-- 这个逗号也被允许了
    ) {
    }

  • 现在允许 catch (Exception) 一个 exception 而无需捕获到变量中。

  • 支持 mixed 类型。

  • Private methods declared on a parent class no longer enforce any inheritance rules on the methods of a child class (with the exception of final private constructors). The following example illustrates which restrictions have been removed:

    <?php
    class ParentClass {
        private function     method1() {}
        private function     method2() {}
        private static function     method3() {}
            // Throws a warning, as "final" no longer has an effect:
            private final function method4() {}
    }
    class     ChildClass extends ParentClass {
            // All of the following are now allowed, even though the modifiers aren't
        // the same as for the private methods in the parent class.
            public abstract function method1() {}
        public static function     method2() {}
        public function     method3() {}
        public function     method4() {}
    }
    ?>

  • get_resource_id() has been added, which returns the same value as (int) $resource. It provides the same functionality under a clearer API.

Date and Time

  • DateTime::createFromInterface() and DateTimeImmutable::createFromInterface() have been added.

  • The DateTime format specifier p has been added, which is the same as P but returns Z rather than +00:00 for UTC.

DOM

DOMParentNode and DOMChildNode with new traversal and manipulation APIs have been added.

Filter

FILTER_VALIDATE_BOOL has been added as an alias for FILTER_VALIDATE_BOOLEAN. The new name is preferred, as it uses the canonical type name.

Enchant

enchant_dict_add(), enchant_dict_is_added(), and LIBENCHANT_VERSION have been added.

FPM

Added a new option pm.status_listen that allows getting the status from different endpoint (e.g. port or UDS file) which is useful for getting the status when all children are busy with serving long running requests.

Hash

HashContext objects can now be serialized.

Internationalization Functions

The IntlDateFormatter::RELATIVE_FULL,
IntlDateFormatter::RELATIVE_LONG,
IntlDateFormatter::RELATIVE_MEDIUM, and
IntlDateFormatter::RELATIVE_SHORT
constants have been added.

LDAP

ldap_count_references() has been added, which returns the number of reference messages in a search result.

OPcache

If the opcache.record_warnings ini setting is enabled, OPcache will record compile-time warnings and replay them on the next include, even if it is served from cache.

OpenSSL

Added Cryptographic Message Syntax (CMS) (» RFC 5652) support composed of functions for encryption, decryption, signing, verifying and reading. The API is similar to the API for PKCS #7 functions with an addition of new encoding constants: OPENSSL_ENCODING_DER, OPENSSL_ENCODING_SMIME and OPENSSL_ENCODING_PEM:

  • openssl_cms_encrypt() encrypts the message in the file with the certificates and outputs the result to the supplied file.
  • openssl_cms_decrypt() that decrypts the S/MIME message in the file and outputs the results to the supplied file.
  • openssl_cms_read() that exports the CMS file to an array of PEM certificates.
  • openssl_cms_sign() that signs the MIME message in the file with a cert and key and output the result to the supplied file.
  • openssl_cms_verify() that verifies that the data block is intact, the signer is who they say they are, and returns the certs of the signers.

Regular Expressions (Perl-Compatible)

preg_last_error_msg() has been added, which returns a human-readable message for the last PCRE error. It complements preg_last_error(), which returns an integer enum value instead.

Reflection

  • The following methods can now return information about default values of parameters of internal functions:

    • ReflectionParameter::isDefaultValueAvailable()
    • ReflectionParameter::getDefaultValue()
    • ReflectionParameter::isDefaultValueConstant()
    • ReflectionParameter::getDefaultValueConstantName()

SQLite3

SQLite3::setAuthorizer() and respective class constants have been added to set a userland callback that will be used to authorize or not an action on the database.

Standard Library

  • str_contains(), str_starts_with() and str_ends_with() have been added, which check whether haystack contains, starts with or ends with needle, respectively.

  • fdiv() has been added, which performs a floating-point division under IEEE 754 semantics. Division by zero is considered well-defined and will return one of Inf, -Inf or NaN.

  • get_debug_type() has been added, which returns a type useful for error messages. Unlike gettype(), it uses canonical type names, returns class names for objects, and indicates the resource type for resources.

  • printf() and friends now support the %h and %H format specifiers. These are the same as %g and %G, but always use "." as the decimal separator, rather than determining it through the LC_NUMERIC locale.

  • printf() and friends now support using "*" as width or precision, in which case the width/precision is passed as an argument to printf. This also allows using precision -1 with %g, %G, %h and %H. For example, the following code can be used to reproduce PHP's default floating point formatting:

    <?php
    printf    ("%.*H", (int) ini_get("precision"), $float);
    printf("%.*H", (int) ini_get("serialize_precision"), $float);
    ?>

  • proc_open() now supports pseudo-terminal (PTY) descriptors. The following attaches stdin, stdout and stderr to the same PTY:

    <?php
    $proc     = proc_open($command, [['pty'], ['pty'], ['pty']], $pipes);
    ?>

  • proc_open() now supports socket pair descriptors. The following attaches a distinct socket pair to stdin, stdout and stderr:

    <?php
    $proc     = proc_open($command, [['socket'], ['socket'], ['socket']], $pipes);
    ?>

    Unlike pipes, sockets do not suffer from blocking I/O issues on Windows. However, not all programs may work correctly with stdio sockets.

  • Sorting functions are now stable, which means that equal-comparing elements will retain their original order.

  • array_diff(), array_intersect() and their variations can now be used with a single array as argument. This means that usages like the following are now possible:

    <?php
    // OK even if $excludes is empty:
    array_diff($array, ...$excludes);
    // OK even if $arrays only contains a single array:
    array_intersect(...$arrays);
    ?>

  • The flag parameter of ob_implicit_flush() was changed to accept a bool rather than an int.

Tokenizer

PhpToken adds an object-based interface to the tokenizer. It provides a more uniform and ergonomic representation, while being more memory efficient and faster.

Zip

  • The Zip extension has been updated to version 1.19.1.

  • New ZipArchive::setMtimeName() and ZipArchive::setMtimeIndex() to set the modification time of an entry.

  • New ZipArchive::registerProgressCallback() to provide updates during archive close.

  • New ZipArchive::registerCancelCallback() to allow cancellation during archive close.

  • New ZipArchive::replaceFile() to replace an entry content.

  • New ZipArchive::isCompressionMethodSupported() to check optional compression features.

  • New ZipArchive::isEncryptionMethodSupported() to check optional encryption features.

  • The ZipArchive::lastId property to get the index value of the last added entry has been added.

  • Errors can now be checked after an archive has been closed using the
ZipArchive::status and
ZipArchive::statusSys properties, or the
ZipArchive::getStatusString() method.

  • The 'remove_path' option of ZipArchive::addGlob() and ZipArchive::addPattern() is now treated as an arbitrary string prefix (for consistency with the 'add_path' option), whereas formerly it was treated as a directory name.

  • Optional compression / encryption features are now listed in phpinfo.

User Contributed Notes

There are no user contributed notes for this page.


不向后兼容的变更

PHP 核心中不向后兼容的变更

字符串与数字的比较

数字与非数字形式的字符串之间的非严格比较现在将首先将数字转为字符串，然后比较这两个字符串。 数字与数字形式的字符串之间的比较仍然像之前那样进行。 请注意，这意味着 0 == "not-a-number" 现在将被认为是 false 。

Comparison | Before | After
0 == "0" | true | true
0 == "0.0" | true | true
0 == "foo" | true | false
0 == "" | true | false
42 == " 42" | true | true
42 == "42foo" | true | false

其它不向后兼容的变更

  • match 现在是一个保留字。

  • 断言（Assertion）失败现在默认抛出异常。如果想要改回之前的行为，可以在 INI 设置中设置 assert.exception=0 。

  • 与类名相同的方法名将不再被当做构造方法。应该使用__construct() 来取代它。

  • 不再允许通过静态调用的方式去调用非静态方法。因此is_callable()在检查一个类名与非静态方法 时将返回失败（应当检查一个类的实例）。

  • (real) 和 (unset) 转换已被移除。

  • The track_errors ini directive has been removed. This means that php_errormsg is no longer available. The error_get_last() function may be used instead.

  • The ability to define case-insensitive constants has been removed. The third argument to define() may no longer be true.

  • The ability to specify an autoloader using an __autoload() function has been removed. spl_autoload_register() should be used instead.

  • The errcontext argument for custom error handlers has been removed.

  • create_function() has been removed. Anonymous functions may be used instead.

  • each() has been removed. foreach or ArrayIterator should be used instead.

  • The ability to unbind this from closures that were created from a method, using Closure::fromCallable() or ReflectionMethod::getClosure(), has been removed.

  • The ability to unbind this from proper closures that contain uses of this has also been removed.

  • The ability to use array_key_exists() with objects has been removed. isset() or property_exists() may be used instead.

  • The behavior of array_key_exists() regarding the type of the key parameter has been made consistent with isset() and normal array access. All key types now use the usual coercions and array/object keys throw a TypeError.

  • Any array that has a number n as its first numeric key will use n+1 for its next implicit key, even if n is negative.

  • The default error_reporting level is now E_ALL. Previously it excluded E_NOTICE and E_DEPRECATED.

  • display_startup_errors is now enabled by default.

  • Using parent inside a class that has no parent will now result in a fatal compile-time error.

  • The @ operator will no longer silence fatal errors (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_PARSE). Error handlers that expect error_reporting to be 0 when @ is used, should be adjusted to use a mask check instead:

    <?php
    // Replace
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
        if (    error_reporting() == 0) {
            return;     // Silenced
            }
            // ...
    }

    // With
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
        if (!(    error_reporting() & $err_no)) {
            return;     // Silenced
            }
            // ...
    }
    ?>

    Additionally, care should be taken that error messages are not displayed in production environments, which can result in information leaks. Please ensure that display_errors=Off is used in conjunction with error logging.

  • #[ is no longer interpreted as the start of a comment, as this syntax is now used for attributes.

  • Inheritance errors due to incompatible method signatures (LSP violations) will now always generate a fatal error. Previously a warning was generated in some cases.

  • The precedence of the concatenation operator has changed relative to bitshifts and addition as well as subtraction.

    <?php
    echo "Sum: " . $a + $b;
    // was previously interpreted as:
    echo ("Sum: " . $a) + $b;
    // is now interpreted as:
    echo "Sum:" . ($a + $b);
    ?>

  • Arguments with a default value that resolves to null at runtime will no longer implicitly mark the argument type as nullable. Either an explicit nullable type, or an explicit null default value has to be used instead.

    <?php
    // Replace
    function test(int $arg = CONST_RESOLVING_TO_NULL) {}
    // With
    function test(?int $arg = CONST_RESOLVING_TO_NULL) {}
    // Or
    function test(int $arg = null) {}
    ?>

  • A number of warnings have been converted into Error exceptions:

    • Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.
    • Attempting to append an element to an array for which the PHP_INT_MAX key is already used.
    • Attempting to use an invalid type (array or object) as an array key or string offset.
    • Attempting to write to an array index of a scalar value.
    • Attempting to unpack a non-array/Traversable.
    • Attempting to access unqualified constants which are undefined. Previously, unqualified constant accesses resulted in a warning and were interpreted as strings.

    A number of notices have been converted into warnings:

    • Attempting to read an undefined variable.
    • Attempting to read an undefined property.
    • Attempting to read an undefined array key.
    • Attempting to read a property of a non-object.
    • Attempting to access an array index of a non-array.
    • Attempting to convert an array to string.
    • Attempting to use a resource as an array key.
    • Attempting to use null, a boolean, or a float as a string offset.
    • Attempting to read an out-of-bounds string offset.
    • Attempting to assign an empty string to a string offset.

  • Attempting to assign multiple bytes to a string offset will now emit a warning.

  • Unexpected characters in source files (such as NUL bytes outside of strings) will now result in a ParseError exception instead of a compile warning.

  • Uncaught exceptions now go through "clean shutdown", which means that destructors will be called after an uncaught exception.

  • The compile time fatal error "Only variables can be passed by reference" has been delayed until runtime, and converted into an "Argument cannot be passed by reference" Error exception.

  • Some "Only variables should be passed by reference" notices have been converted to "Argument cannot be passed by reference" exception.

  • The generated name for anonymous classes has changed. It will now include the name of the first parent or interface:

    <?php
    new class extends ParentClass {};
    // -> ParentClass@anonymous
    new class implements FirstInterface, SecondInterface {};
    // -> FirstInterface@anonymous
    new class {};
    // -> class@anonymous
    ?>

    The name shown above is still followed by a NUL byte and a unique suffix.

  • Non-absolute trait method references in trait alias adaptations are now required to be unambiguous:

    <?php
    class X {
        use     T1, T2 {
                func as otherFunc;
        }
        function     func() {}
    }
    ?>

    If both T1::func() and T2::func() exist, this code was previously silently accepted, and func was assumed to refer to T1::func. Now it will generate a fatal error instead, and either T1::func or T2::func needs to be written explicitly.

  • The signature of abstract methods defined in traits is now checked against the implementing class method:

    <?php
    trait MyTrait {
        abstract private function     neededByTrait(): string;
    }

    class     MyClass {
        use     MyTrait;

            // Error, because of return type mismatch.
            private function neededByTrait(): int { return 42; }
    }
    ?>

  • Disabled functions are now treated exactly like non-existent functions. Calling a disabled function will report it as unknown, and redefining a disabled function is now possible.

  • data:// stream wrappers are no longer writable, which matches the documented behavior.

  • The arithmetic and bitwise operators +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++, -- will now consistently throw a TypeError when one of the operands is an array, 资源(resource) or non-overloaded object. The only exception to this is the array + array merge operation, which remains supported.

  • Float to string casting will now always behave locale-independently.

    <?php
setlocale(LC_ALL, "de_DE");
$f = 3.14;
echo $f, "\n";
// Previously: 3,14
// Now:        3.14
?>

    See printf(), number_format() and NumberFormatter() for ways to customize number formatting.

  • Support for deprecated curly braces for offset access has been removed.

    <?php
// Instead of:
$array{0};
$array{"key"};
// Write:
$array[0];
$array["key"];
?>

  • Applying the final modifier on a private method will now produce a warning unless that method is the constructor.

  • If an object constructor exit()s, the object destructor will no longer be called. This matches the behavior when the constructor throws.

  • Namespaced names can no longer contain whitespace: While Foo\Bar will be recognized as a namespaced name, Foo \ Bar will not. Conversely, reserved keywords are now permitted as namespace segments, which may also change the interpretation of code: new\x is now the same as constant('new\x'), not new \x().

  • Nested ternaries now require explicit parentheses.

  • debug_backtrace() and Exception::getTrace() will no longer provide references to arguments. It will not be possible to change function arguments through the backtrace.

  • Numeric string handling has been altered to be more intuitive and less error-prone. Trailing whitespace is now allowed in numeric strings for consistency with how leading whitespace is treated. This mostly affects:

    • The is_numeric() function
    • String-to-string comparisons
    • Type declarations
    • Increment and decrement operations

    The concept of a "leading-numeric string" has been mostly dropped; the cases where this remains exist in order to ease migration. Strings which emitted an E_NOTICE "A non well-formed numeric value encountered" will now emit an E_WARNING "A non-numeric value encountered" and all strings which emitted an E_WARNING "A non-numeric value encountered" will now throw a TypeError. This mostly affects:

    • Arithmetic operations
    • Bitwise operations

    This E_WARNING to TypeError change also affects the E_WARNING "Illegal string offset 'string'" for illegal string offsets. The behavior of explicit casts to int/float from strings has not been changed.

  • Magic Methods will now have their arguments and return types checked if they have them declared. The signatures should match the following list:

    • __call(string $name, array $arguments): mixed
    • __callStatic(string $name, array $arguments): mixed
    • __clone(): void
    • __debugInfo(): ?array
    • __get(string $name): mixed
    • __invoke(mixed $arguments): mixed
    • __isset(string $name): bool
    • __serialize(): array
    • __set(string $name, mixed $value): void
    • __set_state(array $properties): object
    • __sleep(): array
    • __unserialize(array $data): void
    • __unset(string $name): void
    • __wakeup(): void

  • call_user_func_array() array keys will now be interpreted as parameter names, instead of being silently ignored.

  • Declaring a function called assert() inside a namespace is no longer allowed, and issues E_COMPILE_ERROR. The assert() function is subject to special handling by the engine, which may lead to inconsistent behavior when defining a namespaced function with the same name.

Resource to Object Migration

Several 资源(resource)s have been migrated to objects. Return value checks using is_resource() should be replaced with checks for false.

  • curl_init() will now return a CurlHandle object rather than a 资源(resource). The curl_close() function no longer has an effect, instead the CurlHandle instance is automatically destroyed if it is no longer referenced.

  • curl_multi_init() will now return a CurlMultiHandle object rather than a 资源(resource). The curl_multi_close() function no longer has an effect, instead the CurlMultiHandle instance is automatically destroyed if it is no longer referenced.

  • curl_share_init() will now return a CurlShareHandle object rather than a 资源(resource). The curl_share_close() function no longer has an effect, instead the CurlShareHandle instance is automatically destroyed if it is no longer referenced.

  • enchant_broker_init() will now return an EnchantBroker object rather than a 资源(resource).

  • enchant_broker_request_dict() and enchant_broker_request_pwl_dict() will now return an EnchantDictionary object rather than a 资源(resource).

  • The GD extension now uses GdImage objects as the underlying data structure for images, rather than 资源(resource)s. The imagedestroy() function no longer has an effect; instead the GdImage instance is automatically destroyed if it is no longer referenced.

  • openssl_x509_read() and openssl_csr_sign() will now return an OpenSSLCertificate object rather than a 资源(resource). The openssl_x509_free() function is deprecated and no longer has an effect, instead the OpenSSLCertificate instance is automatically destroyed if it is no longer referenced.

  • openssl_csr_new() will now return an OpenSSLCertificateSigningRequest object rather than a 资源(resource).

  • openssl_pkey_new() will now return an OpenSSLAsymmetricKey object rather than a 资源(resource). The openssl_pkey_free() function is deprecated and no longer has an effect, instead the OpenSSLAsymmetricKey instance is automatically destroyed if it is no longer referenced.

  • shmop_open() will now return a Shmop object rather than a 资源(resource). The shmop_close() function no longer has an effect, and is deprecated; instead the Shmop instance is automatically destroyed if it is no longer referenced.

  • socket_create(), socket_create_listen(), socket_accept(), socket_import_stream(), socket_addrinfo_connect(), socket_addrinfo_bind(), and socket_wsaprotocol_info_import() will now return a Socket object rather than a 资源(resource). socket_addrinfo_lookup() will now return an array of AddressInfo objects rather than 资源(resource)s.

  • msg_get_queue() will now return an SysvMessageQueue object rather than a 资源(resource).

  • sem_get() will now return an SysvSemaphore object rather than a 资源(resource).

  • shm_attach() will now return an SysvSharedMemory object rather than a 资源(resource).

  • xml_parser_create() and xml_parser_create_ns() will now return an XmlParser object rather than a 资源(resource). The xml_parser_free() function no longer has an effect, instead the XmlParser instance is automatically destroyed if it is no longer referenced.

  • The XMLWriter functions now accept and return, respectively, XMLWriter objects instead of 资源(resource)s.

  • inflate_init() will now return an InflateContext object rather than a 资源(resource).

  • deflate_init() will now return a DeflateContext object rather than a 资源(resource).

COM and .Net (Windows)

The ability to import case-insensitive constants from type libraries has been removed. The second argument to com_load_typelib() may no longer be false; com.autoregister_casesensitive may no longer be disabled; case-insensitive markers in com.typelib_file are ignored.

CURL

CURLOPT_POSTFIELDS no longer accepts objects as arrays. To interpret an object as an array, perform an explicit (array) cast. The same applies to other options accepting arrays as well.

Date and Time

mktime() and gmmktime() now require at least one argument. time() can be used to get the current timestamp.

DOM

Unimplemented classes from the DOM extension that had no behavior and contained test data have been removed. These classes have also been removed in the latest version of the DOM standard:

  • DOMNameList
  • DomImplementationList
  • DOMConfiguration
  • DomError
  • DomErrorHandler
  • DOMImplementationSource
  • DOMLocator
  • DOMUserDataHandler
  • DOMTypeInfo

Enchant

  • enchant_broker_list_dicts(), enchant_broker_describe() and enchant_dict_suggest() will now return an empty array instead of null.

Exif

read_exif_data() has been removed; exif_read_data() should be used instead.

Filter

  • The FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED flags for the FILTER_VALIDATE_URL filter have been removed. The scheme and host are (and have been) always required.

  • The INPUT_REQUEST and INPUT_SESSION source for filter_input() etc. have been removed. These were never implemented and their use always generated a warning.

GD

  • The deprecated functions image2wbmp() has been removed.

  • The deprecated functions png2wbmp() and jpeg2wbmp() have been removed.

  • The default mode parameter of imagecropauto() no longer accepts -1. IMG_CROP_DEFAULT should be used instead.

  • On Windows, php_gd2.dll has been renamed to php_gd.dll.

GMP

gmp_random() has been removed. One of gmp_random_range() or gmp_random_bits() should be used instead.

Iconv

iconv implementations which do not properly set errno in case of errors are no longer supported.

IMAP

  • The unused default_host argument of imap_headerinfo() has been removed.

  • The imap_header() function which is an alias of imap_headerinfo() has been removed.

Internationalization Functions

  • The deprecated constant INTL_IDNA_VARIANT_2003 has been removed.

  • The deprecated Normalizer::NONE constant has been removed.

LDAP

  • The deprecated functions ldap_sort(),
ldap_control_paged_result() and
ldap_control_paged_result_response() have been removed.

  • The interface of ldap_set_rebind_proc() has changed; the callback parameter does not accept empty strings anymore; null should be used instead.

MBString

  • The mbstring.func_overload directive has been removed. The related MB_OVERLOAD_MAIL, MB_OVERLOAD_STRING, and MB_OVERLOAD_REGEX constants have also been removed. Finally, the "func_overload" and "func_overload_list" entries in mb_get_info() have been removed.

  • mb_parse_str() can no longer be used without specifying a result array.

  • A number of deprecated mbregex aliases have been removed. See the following list for which functions should be used instead:

    • mbregex_encoding() → mb_regex_encoding()
    • mbereg() → mb_ereg()
    • mberegi() → mb_eregi()
    • mbereg_replace() → mb_ereg_replace()
    • mberegi_replace() → mb_eregi_replace()
    • mbsplit() → mb_split()
    • mbereg_match() → mb_ereg_match()
    • mbereg_search() → mb_ereg_search()
    • mbereg_search_pos() → mb_ereg_search_pos()
    • mbereg_search_regs() → mb_ereg_search_regs()
    • mbereg_search_init() → mb_ereg_search_init()
    • mbereg_search_getregs() → mb_ereg_search_getregs()
    • mbereg_search_getpos() → mb_ereg_search_getpos()
    • mbereg_search_setpos() → mb_ereg_search_setpos()

  • The e modifier for mb_ereg_replace() has been removed. mb_ereg_replace_callback() should be used instead.

  • A non-string pattern argument to mb_ereg_replace() will now be interpreted as a string instead of an ASCII codepoint. The previous behavior may be restored with an explicit call to chr().

  • The needle argument for mb_strpos(),
mb_strrpos(), mb_stripos(),
mb_strripos(), mb_strstr(),
mb_stristr(), mb_strrchr() and
mb_strrichr() can now be empty.

  • The is_hex parameter, which was not used internally, has been removed from mb_decode_numericentity().

  • The legacy behavior of passing the encoding as the third argument instead of an offset for the mb_strrpos() function has been removed; an explicit 0 offset with the encoding should be provided as the fourth argument instead.

  • The ISO_8859-* character encoding aliases have been replaced by ISO8859-* aliases for better interoperability with the iconv extension. The mbregex ISO 8859 aliases with underscores (ISO_8859_* and ISO8859_*) have also been removed.

  • mb_ereg() and mb_eregi() will now return boolean true on a successfuly match. Previously they returned integer 1 if matches was not passed, or max(1, strlen($matches[0])) if matches was passed.

OCI8

  • The OCI-Lob class is now called OCILob, and the OCI-Collection class is now called OCICollection for name compliance enforced by PHP 8 arginfo type annotation tooling.

  • Several alias functions have been marked as deprecated.

  • oci_internal_debug() and its alias ociinternaldebug() have been removed.

ODBC

  • odbc_connect() no longer reuses connections.

  • The unused flags parameter of odbc_exec() has been removed.

OpenSSL

  • openssl_seal() and openssl_open() now require method to be passed, as the previous default of "RC4" is considered insecure.

Regular Expressions (Perl-Compatible)

When passing invalid escape sequences they are no longer interpreted as literals. This behavior previously required the X modifier - which is now ignored.

PHP Data Objects

  • The default error handling mode has been changed from "silent" to "exceptions". See Errors and error handling for details.

  • The signatures of some PDO methods have changed:

    • PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs)
    • PDOStatement::setFetchMode(int $mode, mixed ...$args)

PDO ODBC

The php.ini directive pdo_odbc.db2_instance_name has been removed.

PostgreSQL

  • The deprecated pg_connect() syntax using multiple parameters instead of a connection string is no longer supported.

  • The deprecated pg_lo_import() and pg_lo_export() signature that passes the connection as the last argument is no longer supported. The connection should be passed as first argument instead.

  • pg_fetch_all() will now return an empty array instead of false for result sets with zero rows.

Phar

Metadata associated with a phar will no longer be automatically unserialized, to fix potential security vulnerabilities due to object instantiation, autoloading, etc.

Reflection

  • The method signatures

    • ReflectionClass::newInstance($args)
    • ReflectionFunction::invoke($args)
    • ReflectionMethod::invoke($object, $args)

    have been changed to:

    • ReflectionClass::newInstance(...$args)
    • ReflectionFunction::invoke(...$args)
    • ReflectionMethod::invoke($object, ...$args)

    Code that must be compatible with both PHP 7 and PHP 8 can use the following signatures to be compatible with both versions:

    • ReflectionClass::newInstance($arg = null, ...$args)
    • ReflectionFunction::invoke($arg = null, ...$args)
    • ReflectionMethod::invoke($object, $arg = null, ...$args)

  • The ReflectionType::__toString() method will now return a complete debug representation of the type, and is no longer deprecated. In particular the result will include a nullability indicator for nullable types. The format of the return value is not stable and may change between PHP versions.

  • Reflection export() methods have been removed. Instead reflection objects can be cast to string.

  • ReflectionMethod::isConstructor() and
ReflectionMethod::isDestructor() now also return true for
__construct() and
__destruct() methods of interfaces.
Previously, this would only be true for methods of classes and traits.

  • ReflectionType::isBuiltin() method has been moved to ReflectionNamedType. ReflectionUnionType does not have it.

Sockets

  • The deprecated AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() have been removed.

Standard PHP Library (SPL)

  • SplFileObject::fgetss() has been removed.

  • SplHeap::compare() now specifies a method signature. Inheriting classes implementing this method will now have to use a compatible method signature.

  • SplDoublyLinkedList::push(), SplDoublyLinkedList::unshift() and SplQueue::enqueue() now return void instead of true.

  • spl_autoload_register() will now always throw a TypeError on invalid arguments, therefore the second argument do_throw is ignored and a notice will be emitted if it is set to false.

  • SplFixedArray is now an IteratorAggregate and not an Iterator. SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next(), and SplFixedArray::valid() have been removed. In their place, SplFixedArray::getIterator() has been added. Any code which uses explicit iteration over SplFixedArray must now obtain an Iterator through SplFixedArray::getIterator(). This means that SplFixedArray is now safe to use in nested loops.

Standard Library

  • assert() will no longer evaluate string arguments, instead they will be treated like any other argument. assert($a == $b) should be used instead of assert('$a == $b'). The assert.quiet_eval ini directive and the ASSERT_QUIET_EVAL constant have also been removed, as they would no longer have any effect.

  • parse_str() can no longer be used without specifying a result array.

  • The string.strip_tags filter has been removed.

  • The needle argument of strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr(), and stristr() will now always be interpreted as a string. Previously non-string needles were interpreted as an ASCII code point. An explicit call to chr() can be used to restore the previous behavior.

  • The needle argument for strpos(),
strrpos(), stripos(), strripos(),
strstr(), stristr() and strrchr() can
now be empty.

  • The length argument for substr(), substr_count(), substr_compare(), and iconv_substr() can now be null. null values will behave as if no length argument was provided and will therefore return the remainder of the string instead of an empty string.

  • The length argument for array_splice() can now be null. null values will behave identically to omitting the argument, thus removing everything from the offset to the end of the array.

  • The args argument of vsprintf(), vfprintf(), and vprintf() must now be an array. Previously any type was accepted.

  • The 'salt' option of password_hash() is no longer supported. If the 'salt' option is used a warning is generated, the provided salt is ignored, and a generated salt is used instead.

  • The quotemeta() function will now return an empty string if an empty string was passed. Previously false was returned.

  • The following functions have been removed:

    • hebrevc()
    • convert_cyr_string()
    • money_format()
    • ezmlm_hash()
    • restore_include_path()
    • get_magic_quotes_gpc()
    • get_magic_quotes_runtime()
    • fgetss()

  • FILTER_SANITIZE_MAGIC_QUOTES has been removed.

  • Calling implode() with parameters in a reverse order ($pieces, $glue) is no longer supported.

  • parse_url() will now distinguish absent and empty queries and fragments:

    • http://example.com/foo → query = null, fragment = null
    • http://example.com/foo? → query = "", fragment = null
    • http://example.com/foo# → query = null, fragment = ""
    • http://example.com/foo?# → query = "", fragment = ""
    Previously all cases resulted in query and fragment being null.

  • var_dump() and debug_zval_dump() will now print floating-point numbers using serialize_precision rather than precision. In a default configuration, this means that floating-point numbers are now printed with full accuracy by these debugging functions.

  • If the array returned by __sleep() contains non-existing properties, these are now silently ignored. Previously, such properties would have been serialized as if they had the value null.

  • The default locale on startup is now always "C". No locales are inherited from the environment by default. Previously, LC_ALL was set to "C", while LC_CTYPE was inherited from the environment. However, some functions did not respect the inherited locale without an explicit setlocale() call. An explicit setlocale() call is now always required if a locale component should be changed from the default.

  • The deprecated DES fallback in crypt() has been removed. If an unknown salt format is passed to crypt(), the function will fail with *0 instead of falling back to a weak DES hash now.

  • Specifying out of range rounds for SHA256/SHA512 crypt() will now fail with *0 instead of clamping to the closest limit. This matches glibc behavior.

  • The result of sorting functions may have changed, if the array contains elements that compare as equal.

  • Any functions accepting callbacks that are not explicitly specified to accept parameters by reference will now warn if a callback with reference parameters is used. Examples include array_filter() and array_reduce(). This was already the case for most, but not all, functions previously.

  • The HTTP stream wrapper as used by functions like file_get_contents() now advertises HTTP/1.1 rather than HTTP/1.0 by default. This does not change the behavior of the client, but may cause servers to respond differently. To retain the old behavior, set the 'protocol_version' stream context option, e.g.

    <?php
    $ctx     = stream_context_create(['http' => ['protocol_version' => '1.0']]);
    echo     file_get_contents('http://example.org', false, $ctx);
    ?>

  • Calling crypt() without an explicit salt is no longer supported. If you would like to produce a strong hash with an auto-generated salt, use password_hash() instead.

  • substr(), mb_substr(), iconv_substr() and grapheme_substr() now consistently clamp out-of-bounds offsets to the string boundary. Previously, false was returned instead of the empty string in some cases.

  • On Windows, the program execution functions (proc_open(), exec(), popen() etc.) using the shell, now consistently execute %comspec% /s /c "$commandline", which has the same effect as executing $commandline (without additional quotes).

Sysvsem

  • The auto_release parameter of sem_get() was changed to accept bool values rather than int.

Tidy

  • The use_include_path parameter, which was not used internally, has been removed from tidy_repair_string().

  • tidy::repairString() and tidy::repairFile() became static methods.

Tokenizer

  • T_COMMENT tokens will no longer include a trailing newline. The newline will instead be part of a following T_WHITESPACE token. It should be noted that T_COMMENT is not always followed by whitespace, it may also be followed by T_CLOSE_TAG or end-of-file.

  • Namespaced names are now represented using the T_NAME_QUALIFIED (Foo\Bar), T_NAME_FULLY_QUALIFIED (\Foo\Bar) and T_NAME_RELATIVE (namespace\Foo\Bar) tokens. T_NS_SEPARATOR is only used for standalone namespace separators, and only syntactially valid in conjunction with group use declarations.

XMLReader

XMLReader::open() and XMLReader::xml() are now static methods. They can still be called as instance methods, but inheriting classes need to declare them as static if they override these methods.

XML-RPC

The XML-RPC extension has been moved to PECL and is no longer part of the PHP distribution.

Zip

ZipArchive::OPSYS_Z_CPM has been removed (this name was a typo). Use ZipArchive::OPSYS_CPM instead.

Zlib

  • gzgetss() has been removed.

  • zlib.output_compression is no longer automatically disabled for Content-Type: image/*.

Windows PHP Test Packs

The test runner has been renamed from run-test.php to run-tests.php, to match its name in php-src.

User Contributed Notes

There are no user contributed notes for this page.


PHP 8.0 废弃的功能

PHP 核心中废弃的功能

  • 如果带有默认值的参数后面跟着一个必要的参数，那么默认值就会无效。这在 PHP 8.0.0 中已被废弃，通常可以通过删除默认值，不影响现有功能：

    <?php
    function test($a = [], $b) {} // 之前
    function test($a, $b) {}      // 之后
    ?>

    这条规则的一个例外是 Type $param = null 形式的参数，其中 null 的默认值使得类型隐式为空。这种用法仍然是允许的，但仍建议使用显式可空类型。

    <?php
    function test(A $a = null, $b) {} // 旧写法，仍可用
    function test(?A $a, $b) {}       // 推荐写法
    ?>

  • Calling get_defined_functions() with exclude_disabled explicitly set to false is deprecated and no longer has an effect. get_defined_functions() will never include disabled functions.

Enchant

  • enchant_broker_set_dict_path() and enchant_broker_get_dict_path() are deprecated, because that functionality is neither available in libenchant < 1.5 nor in libenchant-2.

  • enchant_dict_add_to_personal() is deprecated; use enchant_dict_add() instead.

  • enchant_dict_is_in_session() is deprecated; use enchant_dict_is_added() instead.

  • enchant_broker_free() and enchant_broker_free_dict() are deprecated; unset the object instead.

  • The ENCHANT_MYSPELL and ENCHANT_ISPELL constants are deprecated.

LibXML

libxml_disable_entity_loader() has been deprecated. As libxml 2.9.0 is now required, external entity loading is guaranteed to be disabled by default, and this function is no longer needed to protect against XXE attacks.

PGSQL / PDO PGSQL

  • The constant PG_VERSION_STR now has the same value as PG_VERSION, and thus is deprecated.

  • Function aliases in the pgsql extension have been deprecated. See the following list for which functions should be used instead:

    • pg_errormessage() → pg_last_error()
    • pg_numrows() → pg_num_rows()
    • pg_numfields() → pg_num_fields()
    • pg_cmdtuples() → pg_affected_rows()
    • pg_fieldname() → pg_field_name()
    • pg_fieldsize() → pg_field_size()
    • pg_fieldtype() → pg_field_type()
    • pg_fieldnum() → pg_field_num()
    • pg_result() → pg_fetch_result()
    • pg_fieldprtlen() → pg_field_prtlen()
    • pg_fieldisnull() → pg_field_is_null()
    • pg_freeresult() → pg_free_result()
    • pg_getlastoid() → pg_last_oid()
    • pg_locreate() → pg_lo_create()
    • pg_lounlink() → pg_lo_unlink()
    • pg_loopen() → pg_lo_open()
    • pg_loclose() → pg_lo_close()
    • pg_loread() → pg_lo_read()
    • pg_lowrite() → pg_lo_write()
    • pg_loreadall() → pg_lo_read_all()
    • pg_loimport() → pg_lo_import()
    • pg_loexport() → pg_lo_export()
    • pg_setclientencoding() → pg_set_client_encoding()
    • pg_clientencoding() -> pg_client_encoding()

Standard Library

  • Sort comparison functions that return true or false will now throw a deprecation warning, and should be replaced with an implementation that returns an integer less than, equal to, or greater than zero.

    <?php
    // Replace
    usort($array, fn($a, $b) => $a > $b);
    // With
    usort($array, fn($a, $b) => $a <=> $b);
    ?>

Zip

  • Using an empty file as ZipArchive is deprecated. Libzip 1.6.0 does not accept empty files as valid zip archives any longer. The existing workaround will be removed in the next version.

  • The procedural API of Zip is deprecated. Use ZipArchive instead. Iteration over all entries can be accomplished using ZipArchive::statIndex() and a for loop:

    <?php
    // iterate using the procedural API
    assert(is_resource($zip));
    while (    $entry = zip_read($zip)) {
        echo     zip_entry_name($entry);
    }

    // iterate using the object-oriented API
    assert($zip instanceof ZipArchive);
    for (    $i = 0; $entry = $zip->statIndex($i); $i++) {
        echo     $entry['name'];
    }
    ?>

Reflection

  • ReflectionFunction::isDisabled() is deprecated, as it is no longer possible to create a ReflectionFunction for a disabled function. This method now always returns false.

  • ReflectionParameter::getClass(),
ReflectionParameter::isArray(), and
ReflectionParameter::isCallable() are deprecated.
ReflectionParameter::getType() and the
ReflectionType APIs should be used instead.

User Contributed Notes

There are no user contributed notes for this page.


其他变更

SAPI 模块的变更

Apache2Handler

PHP 模块从 php7_module 重命名为 php_module。

Function 的变更

Reflection

可通过新参数 filter 来过滤 ReflectionClass::getConstants() 和 ReflectionClass::getReflectionConstants() 的返回结果。 新增三个常量，搭配使用：

  • ReflectionClassConstant::IS_PUBLIC
  • ReflectionClassConstant::IS_PROTECTED
  • ReflectionClassConstant::IS_PRIVATE

Zip

  • ZipArchive::addGlob() 和 ZipArchive::addPattern() 方法中 options 数组参数可接受更多的值：

    • flags
    • comp_method
    • comp_flags
    • env_method
    • enc_password

  • ZipArchive::addEmptyDir()、ZipArchive::addFile()、 ZipArchive::addFromString() 方法新增 flags 参数。 可用于名称编码 (ZipArchive::FL_ENC_*) 与条目（entry）替换 (ZipArchive::FL_OVERWRITE)。

  • ZipArchive::extractTo() 现在会储存文件的修改时间。

其他扩展变更

CURL

  • 现在 CURL 扩展要求 libcurl 版本至少为 7.29.0。

  • 移除了 curl_version() 废弃的参数 version。

日期/时间

现在 DatePeriod 实现（implements）了 IteratorAggregate (之前是 Traversable)。

DOM

现在 DOMNamedNodeMap 与 DOMNodeList 实现（implements）了 IteratorAggregate (之前是 Traversable)。

国际化

现在 IntlBreakIterator 与 ResourceBundle 实现（implements）了 IteratorAggregate (之前是 Traversable)。

Enchant

现在环境允许时，enchant 会默认使用 libenchant-2。 仍然支持 libenchant 1，但已经废弃，并将在未来移除。

GD

  • imagepolygon()、 imageopenpolygon()、imagefilledpolygon() 的参数 num_points 现在为可选参数。 这些函数可用三或四个参数去调用。 省略参数时，会按 count($points)/2 计算。

  • 新增函数 imagegetinterpolation()，可获取当前的插值（interpolation）。

JSON

现在无法禁用 JSON 扩展，将是任意 PHP 版本的内置功能，类似 date 扩展。

MBString

更新 Unicode 数据表版本到 13.0.0。

PDO

现在 PDOStatement 实现（implements）了 IteratorAggregate (之前是 Traversable)。

LibXML

现在要求 libxml 最小版本为 2.9.0。 这代表着确保了默认情况下禁用了外部实体加载（external entity loading）的功能。 无需额外步骤即可防范 XML 外部实体注入攻击（XXE attacks）。

MySQLi / PDO MySQL

  • 未使用 mysqlnd 时（也是默认且推荐的做法）， 支持的最小 libmysqlclient 版本为 5.5。

  • 现在 mysqli_result 实现（implements）了 IteratorAggregate (之前是 Traversable)。

PGSQL / PDO PGSQL

PGSQL 与 PDO PGSQL 扩展需要 libpq 的版本号至少为 9.1。

Readline

在交互提示开始之前调用 readline_completion_function() （例如在 auto_prepend_file 中）， 将重写默认的交互输入补全函数。 之前，只有交互提示（interactive prompt）开始后， readline_completion_function() 才会运行。

SimpleXML

现在 SimpleXMLElement 实现（implements）了 RecursiveIterator 并吸收了 SimpleXMLIterator 的功能。 SimpleXMLIterator 是 SimpleXMLElement 的一个空扩展。

INI 文件处理的变更

  • com.dotnet_version 是一个新的 INI 指令，用于选择 dotnet 对象的 .NET framework 版本。

  • zend.exception_string_param_max_len 是一个新的 INI 指令，用于设置字符串化的调用栈（stack strace）的最大字符串长度。

EBCDIC

不再支持 EBCDIC targets，虽然它不太可能还在当初的地方继续运行。

性能

  • opcache 扩展新增了即时编译(JIT) 支持。

  • array_slice() 用于没有空隙的数组时， 将不会扫描整个数组去查找开始的位移（offset）。 在 offset 较大、长度较小时，会显著减少函数的运行时间。

  • 当本地化 LC_CTYPE 为 "C" 时（也是默认值）， strtolower() 会使用 SIMD 的实现。

User Contributed Notes

There are no user contributed notes for this page.


从 PHP 7.3.x 移植到 PHP 7.4.x

Table of Contents

  • 新特性
  • 新的类和接口
  • 新函数
  • 新的全局常量
  • 不向后兼容的变更
  • PHP 7.4.x 废弃的功能
  • 移除的扩展
  • 其他变更
  • Windows 支持

这个新的小版本带来了大量的 新特性 和 少量的兼容性调整 在生产环境切换 PHP 版本前应该进行相关测试。

参见 PHP 版本迁移指南 7.0.x， 7.1.x， 7.2.x 和 7.3.x。

User Contributed Notes

There are no user contributed notes for this page.


新特性

PHP 核心中的新特性

属性添加限定类型

类的属性中现在支持添加指定的类型。

<?php
class User {
    public int $id;
    public string $name;
}
?>
上面的例子中，会强制要求 $user->id 只能为 int 类型，同时 $user->name 只能为 string 类型。

箭头函数

箭头函数 提供了一种更简洁的定义函数的方法。

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

有限返回类型协变与参数类型逆变

以下代码将不会正常工作：

<?php
class A {}
class B extends A {}

class Producer {
    public function method(): A {}
}
class ChildProducer extends Producer {
    public function method(): B {}
}
?>
只有在使用自动加载的情况下，才会有完整的差异支持。在一个文件内，只有非循环类型引用是可能的，因为在引用之前，所有的类都需要可用。

空合并运算符赋值

<?php
$array['key'] ??= computeDefault();
// 等同于以下旧写法
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}
?>

数组展开操作

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

数值文字分隔符

数字文字可以在数字之间包含下划线。

<?php
6.674_083e-11; // float
299_792_458;   // decimal
0xCAFE_F00D;   // hexadecimal
0b0101_1111;   // binary
?>

Weak references

Weak references allow the programmer to retain a reference to an object that does not prevent the object from being destroyed.

允许从 __toString() 抛出异常

现在允许从 __toString() 抛出异常。之前的版本，将会导致一个致命错误。新版本中，之前发生致命错误的代码，已经被转换为 Error 异常。

CURL

CURLFile now supports stream wrappers in addition to plain file names, if the extension has been built against libcurl >= 7.56.0.

Filter

The FILTER_VALIDATE_FLOAT filter now supports the min_range and max_range options, with the same semantics as FILTER_VALIDATE_INT.

FFI

FFI is a new extension, which provides a simple way to call native functions, access native variables, and create/access data structures defined in C libraries.

GD

Added the IMG_FILTER_SCATTER image filter to apply a scatter filter to images.

Hash

Added crc32c hash using Castagnoli's polynomial. This CRC32 variant is used by storage systems, such as iSCSI, SCTP, Btrfs and ext4.

Multibyte String

Added the mb_str_split() function, which provides the same functionality as str_split(), but operating on code points rather than bytes.

OPcache

新增 缓存预加载 特性。

Regular Expressions (Perl-Compatible)

The preg_replace_callback() and preg_replace_callback_array() functions now accept an additional flags argument, with support for the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags. This influences the format of the matches array passed to to the callback function.

PDO

The username and password can now be specified as part of the PDO DSN for the mysql, mssql, sybase, dblib, firebird and oci drivers. Previously this was only supported by the pgsql driver. If a username/password is specified both in the constructor and the DSN, the constructor takes precedence.

It is now possible to escape question marks in SQL queries to avoid them being interpreted as parameter placeholders. Writing ?? allows sending a single question mark to the database and e.g. use the PostgreSQL JSON key exists (?) operator.

PDO_OCI

PDOStatement::getColumnMeta() is now available.

PDO_SQLite

PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) allows checking whether the statement is read-only, i.e. if it doesn't modify the database.

PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) enables the use of SQLite3 extended result codes in PDO::errorInfo() and PDOStatement::errorInfo().

SQLite3

Added SQLite3::lastExtendedErrorCode() to fetch the last extended result code.

Added SQLite3::enableExtendedResultCodes($enable = true), which will make SQLite3::lastErrorCode() return extended result codes.

Standard

strip_tags() with array of tag names

strip_tags() now also accepts an array of allowed tags: instead of strip_tags($str, '<a><p>') you can now write strip_tags($str, ['a', 'p']).

Custom object serialization

A new mechanism for custom object serialization has been added, which uses two new magic methods: __serialize and __unserialize.

<?php
// Returns array containing all the necessary state of the object.
public function __serialize(): array;

// Restores the object state from the given data array.
public function __unserialize(array $data): void;
?>
The new serialization mechanism supersedes the Serializable interface, which will be deprecated in the future.

Array merge functions without arguments

array_merge() and array_merge_recursive() may now be called without any arguments, in which case they will return an empty array. This is useful in conjunction with the spread operator, e.g. array_merge(...$arrays).

proc_open() function

proc_open() now accepts an array instead of a string for the command. In this case the process will be opened directly (without going through a shell) and PHP will take care of any necessary argument escaping.

<?php
proc_open(['php', '-r', 'echo "Hello World\n";'], $descriptors, $pipes);
?>

proc_open() now supports redirect and null descriptors.

<?php
// Like 2>&1 on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['redirect', 1]], $pipes);
// Like 2>/dev/null or 2>nul on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['null']], $pipes);
?>

argon2i(d) without libargon

password_hash() now has the argon2i and argon2id implementations from the sodium extension when PHP is built without libargon.

User Contributed Notes

wow-apps.pro 26-Feb-2020 08:42
<?php

// How to get property type? For example for testing:

class Foo
{
    private int $num;
    private bool $isPositive;
    private $notes;
}

$reflection = new \ReflectionClass(Foo::class);
$classProperties = $reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
foreach ($classProperties as $classProperty) {
    var_dump((string) $classProperty->getType());
}

/**
 * Result:
 * "int"
 * "bool"
 * ""
 */
Rain 27-Jan-2020 08:44
It should be noted that typed properties internally are never initialized to a default null. Unless of course you initialize them to null yourself. That's why you will always going to encounter this error if you try to access them before initialization.

**Typed property foo::$bar must not be accessed before initialization**

<?php
class User
{
    public $id;
    public string $name; // Typed property (Uninitialized)
    public ?string $age = null; //  Typed property (Initialized)
}

$user = new User;
var_dump(is_null($user->id)); // bool(true)
var_dump(is_null($user->name)); // PHP Fatal error: Typed property User::$name must not be accessed before initialization
var_dump(is_null($user->age));// bool(true)
?>

Another thing worth noting is that it's not possible to initialize a property of type object to anything other than null.  Since the evaluation of properties happens at compile-time and object instantiation happens at runtime. One last thing, callable type is not supported due to its context-dependent behavior.


新的类和接口

Reflection

  • ReflectionReference

User Contributed Notes

There are no user contributed notes for this page.


新函数

PHP 核心中新增的函数

  • get_mangled_object_vars()
  • password_algos()
  • sapi_windows_set_ctrl_handler()

GD

  • imagecreatefromtga()

OpenSSL

  • openssl_x509_verify()

Process Control

  • pcntl_unshare()

SQLite3

  • SQLite3::backup()
  • SQLite3Stmt::getSQL()

User Contributed Notes

shaman_master at list dot ru 17-Jun-2020 11:42
Also added mb_str_split()  — given a multibyte string, return an array of its characters


新的全局常量

PHP 核心中预定义的常量

  • PHP_WINDOWS_EVENT_CTRL_C
  • PHP_WINDOWS_EVENT_CTRL_BREAK

Multibyte String

  • MB_ONIGURUMA_VERSION

Sockets

添加了 FreeBSD 系统中特有的选项：

  • SO_LABEL
  • SO_PEERLABEL
  • SO_LISTENQLIMIT
  • SO_LISTENQLEN
  • SO_USER_COOKIE

Tidy

  • TIDY_TAG_ARTICLE
  • TIDY_TAG_ASIDE
  • TIDY_TAG_AUDIO
  • TIDY_TAG_BDI
  • TIDY_TAG_CANVAS
  • TIDY_TAG_COMMAND
  • TIDY_TAG_DATALIST
  • TIDY_TAG_DETAILS
  • TIDY_TAG_DIALOG
  • TIDY_TAG_FIGCAPTION
  • TIDY_TAG_FIGURE
  • TIDY_TAG_FOOTER
  • TIDY_TAG_HEADER
  • TIDY_TAG_HGROUP
  • TIDY_TAG_MAIN
  • TIDY_TAG_MARK
  • TIDY_TAG_MENUITEM
  • TIDY_TAG_METER
  • TIDY_TAG_NAV
  • TIDY_TAG_OUTPUT
  • TIDY_TAG_PROGRESS
  • TIDY_TAG_SECTION
  • TIDY_TAG_SOURCE
  • TIDY_TAG_SUMMARY
  • TIDY_TAG_TEMPLATE
  • TIDY_TAG_TIME
  • TIDY_TAG_TRACK
  • TIDY_TAG_VIDEO

User Contributed Notes

There are no user contributed notes for this page.


不向后兼容的变更

PHP 核心中不向后兼容的变更

以数组形式访问非数组

尝试以数组方式访问 null，bool， int，float 或 resource （例如 $null["key"]）将会抛出 notice 通知。

get_declared_classes() 函数

get_declared_classes() 函数将不再返回匿名的类，假如它们没有被实例化的话。

fn 关键词

fn 成为了保留关键词。需要特别注意，它不能再做为函数名或类名使用，但是仍然可以做为方法名和常量名存在。

文件尾部的 <?php 标签

文件尾部的 <?php 标签（不包含空行）将会被解释成一个 PHP 头标签。Previously it was interpreted either as a short opening tag followed by literal php and resulted in a syntax error (with short_open_tag=1) or was interpreted as a literal <?php string (with short_open_tag=0).

Stream wrappers

When using include/require on a stream, streamWrapper::stream_set_option() will be invoked with the STREAM_OPTION_READ_BUFFER option. Custom stream wrapper implementations may need to implement the streamWrapper::stream_set_option() method to avoid a warning (always returning false is a sufficient implementation).

Serialization 序列化

序列化类型 o 被移除。因为它不是由 PHP 生成的，这可能会影响到之前项目中手动生成的序列化字符串。

密码算法常量

密码哈希算法标识符现在是可空字符串，而不再是整数。

  • PASSWORD_DEFAULT 之前是 int 1; 现在是 null
  • PASSWORD_BCRYPT 之前是 int 1; 现在是 string '2y'
  • PASSWORD_ARGON2I 之前是 int 2; 现在是 string 'argon2i'
  • PASSWORD_ARGON2ID 之前是 int 3; 现在是 string 'argon2id'

应用中如果正常使用了常量 PASSWORD_DEFAULT，PASSWORD_BCRYPT，PASSWORD_ARGON2I 和 PASSWORD_ARGON2ID 将不会受到影响。

htmlentities() 函数

htmlentities() will now raise a notice (instead of a strict standards warning) if it is used with an encoding for which only basic entity substitution is supported, in which case it is equivalent to htmlspecialchars().

fread() and fwrite() 函数

fread() 和 fwrite() 在操作失败的时候会返回 false。之前的版本中会返回空字符串或 0。EAGAIN/EWOULDBLOCK 不视为故障。

这些函数现在也会在失败时发出 NOTICE 通知，例如当试图写入一个只读文件资源时。

BCMath Arbitrary Precision Mathematics

BCMath functions will now warn if a non well-formed number is passed, such as "32foo". The argument will be interpreted as zero, as before.

CURL

Attempting to serialize a CURLFile class will now generate an exception. Previously the exception was only thrown on unserialization.

Using CURLPIPE_HTTP1 is deprecated, and is no longer supported as of cURL 7.62.0.

The $version parameter of curl_version() is deprecated. If any value not equal to the default CURLVERSION_NOW is passed, a warning is raised and the parameter is ignored.

Date and Time

Calling var_dump() or similar on a DateTime or DateTimeImmutable instance will no longer leave behind accessible properties on the object.

Comparison of DateInterval objects (using ==, <, and so on) will now generate a warning and always return false. Previously all DateInterval objects were considered equal, unless they had properties.

Intl

The default parameter value of idn_to_ascii() and idn_to_utf8() is now INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.

MySQLi

The embedded server functionality has been removed. It was broken since at least PHP 7.0.

The undocumented mysqli::$stat property has been removed in favor of mysqli::stat().

OpenSSL

The openssl_random_pseudo_bytes() function will now throw an exception in error situations, similar to random_bytes(). In particular, an Error is thrown if the number of requested bytes is less than or equal to zero, and an Exception is thrown if sufficient randomness cannot be gathered. The $crypto_strong output argument is guaranteed to always be true if the function does not throw, so explicitly checking it is not necessary.

Regular Expressions (Perl-Compatible)

When PREG_UNMATCHED_AS_NULL mode is used, trailing unmatched capturing groups will now also be set to null (or [null, -1] if offset capture is enabled). This means that the size of the $matches will always be the same.

PHP Data Objects

Attempting to serialize a PDO or PDOStatement instance will now generate an Exception rather than a PDOException, consistent with other internal classes which do not support serialization.

Reflection

Reflection objects will now generate an exception if an attempt is made to serialize them. Serialization for reflection objects was never supported and resulted in corrupted reflection objects. It has been explicitly prohibited now.

Standard PHP Library (SPL)

Calling get_object_vars() on an ArrayObject instance will now always return the properties of the ArrayObject itself (or a subclass). Previously it returned the values of the wrapped array/object unless the ArrayObject::STD_PROP_LIST flag was specified.

Other affected operations are:

  • ReflectionObject::getProperties()
  • reset(), current(), etc. Use Iterator methods instead.
  • Potentially others working on object properties as a list.

(array) casts are not affected. They will continue to return either the wrapped array, or the ArrayObject properties, depending on whether the ArrayObject::STD_PROP_LIST flag is used.

SplPriorityQueue::setExtractFlags() will throw an exception if zero is passed. Previously this would generate a recoverable fatal error on the next extraction operation.

ArrayObject, ArrayIterator, SplDoublyLinkedList and SplObjectStorage now support the __serialize() and __unserialize() mechanism in addition to the Serializable interface. This means that serialization payloads created on older PHP versions can still be unserialized, but new payloads created by PHP 7.4 will not be understood by older versions.

Tokenizer

token_get_all() will now emit a T_BAD_CHARACTER token for unexpected characters instead of leaving behind holes in the token stream.

接收到的 Cookies

从 PHP 7.4.11 开始，为了安全考虑，接受到的 Cookie 中的 names 参数不再被 URL 编码。

User Contributed Notes

happydog at kennel17 24-Jan-2021 11:23
Re: "The o serialization format has been removed. As it is never produced by PHP, this may only break unserialization of manually crafted strings."

This little-o serialisation format was used by PHP3 but was never generated by PH PHP4 or above.  The deserialization code still recognised it, though, for reasons of backwards-compatibility with PHP3.

However, based on a bit of investigation, it looks like this code has been broken for about 15 years, so although this is listed as a deprecation, in practice it wasn't.

See this Stack Overflow question for a really great answer, with a lot more detail about this: https://stackoverflow.com/questions/65289729/what-was-phps-o-serialization-format-for


PHP 7.4.x 废弃的功能

PHP 核心中废弃的功能

没有显式括号的嵌套三元运算符

嵌套的三元操作中，必须明确使用显式括号来决定操作的顺序。以前，如果不使用括号，在大多数情况下，左关联性不会导致预期的行为。

<?php
1 ? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

大括号访问数组和字符串索引

使用大括号访问数组及字符串索引的方式已被废弃。请使用 $var[$idx] 的语法来替代 $var{$idx}。

(real) 类型和 is_real() 函数

(real) 类型已被废弃，请使用 (float) 来替代。

同时被废弃的还有 is_real() 函数，请使用 is_float() 来替代。

Unbinding $this when $this is used

Unbinding $this of a non-static closure that uses $this is deprecated.

parent 关键词在没父类的类中使用

在没有父类的类中使用 parent 关键词已被废弃，并且在将来的 PHP 版本中将会抛出一个编译错误。目前只在运行时访问父类时才会产生错误。

allow_url_include INI 选项

配置文件中的 allow_url_include 选项被废弃。如果启用了该选项，将会产生一个弃用通知。

基础转换函数中的无效字符处理

在下面这些基础转换函数中，base_convert(),
bindec(), octdec() 和
hexdec()
如果传入了非法字符，将会抛出一个弃用通知。函数会忽略掉无效字符后正常返回结果。前导空格和尾部空格，以及类型为
0x (取决于基数) 被允许传入。

在对象中使用 array_key_exists()

在一个对象中使用 array_key_exists() 已被废弃。请使用 isset() 或 property_exists() 来替代。

魔术引号函数

魔术引号函数 get_magic_quotes_gpc() 和 get_magic_quotes_runtime() 已被废弃。它们将永远返回 false。

hebrevc() 函数

hebrevc() 函数已被废弃。 可以用 nl2br(hebrev($str)) 来替代，更好的方法是启用 Unicode RTL 来支持。

convert_cyr_string() 函数

convert_cyr_string() 函数已被废弃。可以用 mb_convert_string()， iconv() 或 UConverter 替代。

money_format() 函数

money_format() 函数已被废弃。 可以用更国际化的 NumberFormatter 功能来替代。

ezmlm_hash() 函数

ezmlm_hash() 函数已被废弃。

restore_include_path() 函数

restore_include_path() 函数已被废弃。可以用 ini_restore('include_path') 替代。

Implode 函数的参数顺序

implode() 允许反转参数顺序的特性已被废弃，请使用 implode($glue, $parts) 来替代 implode($parts, $glue)。

COM

导入类型库的大小写不敏感的常量注册已被废弃。

Filter

FILTER_SANITIZE_MAGIC_QUOTES 已被废弃，使用 FILTER_SANITIZE_ADD_SLASHES 来替代。

Multibyte String

Passing a non-string pattern to mb_ereg_replace() is deprecated. Currently, non-string patterns are interpreted as ASCII codepoints. In PHP 8, the pattern will be interpreted as a string instead.

Passing the encoding as 3rd parameter to mb_strrpos() is deprecated. Instead pass a 0 offset, and encoding as 4th parameter.

Lightweight Directory Access Protocol

ldap_control_paged_result_response() 和
ldap_control_paged_result() 函数已被废弃。控制页面操作可以使用
ldap_search() 替代。

Reflection

调用 ReflectionType::__toString() 现在将会抛出一个弃用通知。 该方法从 PHP 7.1 开始，在 ReflectionNamedType::getName() 的文档中已经被声明废弃，但是由于技术原因，并没有抛出弃用通知。

The export() methods on all Reflection classes are deprecated. Construct a Reflection object and convert it to string instead:

<?php
// ReflectionClass::export(Foo::class, false) is:
echo new ReflectionClass(Foo::class), "\n";

// $str = ReflectionClass::export(Foo::class, true) is:
$str = (string) new ReflectionClass(Foo::class);
?>

Socket

常量 AI_IDN_ALLOW_UNASSIGNED 和 AI_IDN_USE_STD3_ASCII_RULES 在 socket_addrinfo_lookup() 中不再可用，因为该常量在 glibc 中已被废弃。

User Contributed Notes

Techlemur 13-Nov-2020 08:58
^((?!\().*)(\?[^php]).*(\:)([\s\v]+)(?!\().*[^\/](\?)([\s\v\h]*).*(\:[^=])
Regex to find deprecated nested ternaries
Ahmad Asjad 03-Jun-2020 10:01
(\?[^php]).*(\:).*(\?).*(\:[^=])
Above regex can help others to find the nested ternary operator


移除的扩展

这些扩展已经被转移到 PECL 中，不再是 PHP 发行版的一部分。这些扩展的 PECL 包版本将根据用户的需要来自行安装。

  • Firebird/Interbase - access to an InterBase and/or Firebird based database is still available with the PDO Firebird driver.
  • Recode
  • WDDX

User Contributed Notes

There are no user contributed notes for this page.


其他变更

性能提升

PHP 核心

为 array_key_exists() 函数添加了一个专门的 VM opcache 优化，如果该函数可以被静态解析，则可以提高该函数的性能。如果你在项目中使用了命名空间，可能会需要使用 \array_key_exists() 来显性的导入该函数。

正则表达式 (Perl-Compatible)

When preg_match() in UTF-8 mode ("u" modifier) is repeatedly called on the same string (but possibly different offsets), it will only be checked for UTF-8 validity once.

INI 配置文件处理的变化

zend.exception_ignore_args is a new INI directive for including or excluding arguments from stack traces generated from exceptions.

opcache.preload_user is a new INI directive for specifying the user account under which preloading code is execute if it would otherwise be run as root (which is not allowed for security reasons).

迁移到 pkg-config

一些扩展已经迁移到只使用 pkg-config 来检测库的依赖性。一般来说，这意味着不再用 --with-foo-dir=DIR 或类似的参数，而是使用 --with-foo。自定义库的路径可以通过向 PKG_CONFIG_PATH 添加额外的目录，或通过 FOO_CFLAGS 和 FOO_LIBS 来明确指定。

以下扩展和 SAPI 会受到影响：

  • CURL:
    • --with-curl 选项不再接受一个目录。
  • Enchant:
    • --with-enchant 选项不再接受一个目录。
  • FPM:
    • --with-fpm-systemd now uses only pkg-config for libsystem checks. The libsystemd minimum required version is 209.
  • GD:
    • --with-gd 改变为 --enable-gd (whether to enable the extension at all) 和 --with-external-gd (to opt into using an external libgd, rather than the bundled one).
    • --with-png-dir 参数被移除。需要 libpng 支持。
    • --with-zlib-dir 参数被移除。需要 zlib 支持。
    • --with-freetype-dir 改变为 --with-freetype
    • --with-jpeg-dir 改变为 --with-jpeg
    • --with-webp-dir 改变为 --with-webp
    • --with-xpm-dir 改变为 --with-xpm
  • IMAP:
    • --with-kerberos-systemd 选项不再接受一个目录。
  • Intl:
    • --with-icu-dir 被移除。如果使用了 --enable-intl 参数，需要 libicu 支持。
  • LDAP:
    • --with-ldap-sasl 选项不再接受一个目录。
  • Libxml:
    • --with-libxml-dir 被移除。
    • --enable-libxml 改变为 --with-libxml。
    • --with-libexpat-dir 被重命名为 --with-expat 并且该选项不再接受一个目录。
  • Litespeed:
    • --with-litespeed 改变为 --enable-litespeed。
  • Mbstring:
    • --with-onig 被移除。如果指定了 --disable-mbregex 参数，则需要 libonig 支持。
  • ODBC:
    • --with-iodbc 选项不再接受一个目录。
    • --with-unixODBC without a directory now uses pkg-config (preferred). Directory is still accepted for old versions without libodbc.pc.
  • OpenSSL:
    • --with-openssl 选项不再接受一个目录。
  • PCRE:
    • --with-pcre-regex 被移除。Instead --with-external-pcre is provided to opt into using an external PCRE library, rather than the bundled one.
  • PDO_SQLite:
    • --with-pdo-sqlite 选项不再接受一个目录。
  • Readline:
    • --with-libedit 选项不再接受一个目录。
  • Sodium:
    • --with-sodium 选项不再接受一个目录。
  • SQLite3:
    • --with-sqlite3 选项不再接受一个目录。
  • XSL:
    • --with-xsl 选项不再接受一个目录。
  • Zip:
    • --with-libzip 被移除。
    • --enable-zip 改变为 --with-zip。

CSV escaping

fputcsv(),
fgetcsv(),
SplFileObject::fputcsv(),
SplFileObject::fgetcsv(), and
SplFileObject::setCsvControl()
now accept an empty string as $escape argument,
which disables the proprietary PHP escaping mechanism.

The behavior of str_getcsv() has been adjusted accordingly (formerly, an empty string was identical to using the default).

SplFileObject::getCsvControl() now may also return an empty string for the third array element, accordingly.

Data Filtering

The filter extension no longer exposes --with-pcre-dir for Unix builds and can now reliably be built as shared when using ./configure

GD

The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd:

  • IMG_CROP_DEFAULT is no longer falling back to IMG_CROP_SIDES
  • Threshold-cropping now uses the algorithm of system libgd

The default $mode parameter of imagecropauto() has been changed to IMG_CROP_DEFAULT; passing -1 is now deprecated.

imagescale() now supports aspect ratio preserving scaling to a fixed height by passing -1 as $new_width.

HASH Message Digest Framework

The hash extension cannot be disabled anymore and is always an integral part of any PHP build, similar to the date extension.

Intl

The intl extension now requires at least ICU 50.1.

ResourceBundle now implements Countable.

Lightweight Directory Access Protocol

Support for nsldap and umich_ldap has been removed.

Libxml

All libxml-based extensions now require libxml 2.7.6 or newer.

Multibyte String

The oniguruma library is no longer bundled with PHP, instead libonig needs to be available on the system. Alternatively --disable-mbregex can be used to disable the mbregex component.

OPcache

The --disable-opcache-file and --enable-opcache-file configure options have been removed in favor of the opcache.file_cache INI directive.

Password Hashing

The password_hash() and functions now accept nullable string and int for $algo argument.

PEAR

Installation of PEAR (including PECL) is no longer enabled by default. It can be explicitly enabled using --with-pear. This option is deprecated and may be removed in the future.

Reflection

The numeric values of the modifier constants (IS_ABSTRACT, IS_DEPRECATED, IS_EXPLICIT_ABSTRACT, IS_FINAL, IS_IMPLICIT_ABSTRACT, IS_PRIVATE, IS_PROTECTED, IS_PUBLIC, and IS_STATIC) on the ReflectionClass, ReflectionFunction, ReflectionMethod, ReflectionObject, and ReflectionProperty classes have changed.

SimpleXML

SimpleXMLElement now implements Countable.

SQLite3

The bundled libsqlite has been removed. To build the SQLite3 extension a system libsqlite3 ≥ 3.7.4 is now required. To build the PDO_SQLite extension a system libsqlite3 ≥ 3.5.0 is now required.

Serialization and unserialization of SQLite3, SQLite3Stmt and SQLite3Result is now explicitly forbidden. Formerly, serialization of instances of these classes was possible, but unserialization yielded unusable objects.

The @param notation can now also be used to denote SQL query parameters.

Zip

The bundled libzip library has been removed. A system libzip >= 0.11 is now necessary to build the zip extension.

User Contributed Notes

santi at mola dot io 31-Jul-2020 07:54
Note for internals/extensions:

Many opcode values changed between PHP 7.3 and 7.4, so most documentation resources are outdated in that regard. You can look the definitions at Zend/zend_vm_opcodes.h in php-src. For example, ZEND_ECHO changes from 40 to 136.

While opcode changes happen in a lot of PHP versions, the change in 7.4 is quite significant.
ohcc at 163 dot com 09-Jun-2020 04:56
As of PHP 7.4, an exception thrown within the user-defined shutdown function can be caught by the user-defined exception handler.

<?php
    set_error_handler(
        function($level, $error, $file, $line){
            if(0 === error_reporting()){
                return false;
            }
            throw new ErrorException($error, -1, $level, $file, $line);
        },
        E_ALL
    );

    register_shutdown_function(function(){
        $error = error_get_last();
        if($error){
            throw new ErrorException($error['message'], -1, $error['type'], $error['file'], $error['line']);
        }
    });

    set_exception_handler(function($exception){
        // ... more code ...
    });

    require 'NotExists.php';
Florent H (Sowapps) 16-Feb-2020 07:37
This version brings an important changes with the directive zend.exception_ignore_args set to On by default.
In all stack traces, the args key is now missing.
All php frameworks have to handle this to report errors & exceptions.


Windows 支持

configure flags

configure 命令现在支持 CFLAGS 和 LDFLAGS 环境变量。

CTRL handling

CTRL+C and CTRL+BREAK on console can be caught by setting a handler function with sapi_windows_set_ctrl_handler().

proc_open() on Windows can be passed a "create_process_group" option. It is required if the child process is supposed to handle CTRL events.

OPcache

OPcache now supports an arbitrary number of separate caches per user via the the INI directive opcache.cache_id. All processes with the same cache ID and user share an OPcache instance.

stat

The stat implementation has been refactored.

  • An inode number is delivered and is based on the NTFS file index.
  • The device number is now based on the volume serial number.

Note that both values are derived from the system and provided as-is on 64-bit systems. On 32-bit systems, these values might overflow the 32-bit integer in PHP, so they're fake.

libsqlite3

libsqlite3 is no longer compiled statically into php_sqlite3.dll and php_pdo_sqlite.dll, but rather available as libsqlite3.dll. Refer to the installation instructions for SQLite3 and PDO_SQLITE, respectively.

User Contributed Notes

There are no user contributed notes for this page.


从 PHP 7.2.x 移植到 PHP 7.3.x

Table of Contents

  • 新特性
  • 新函数
  • 新的全局常量
  • 不向下兼容的变更
  • PHP 7.3.x 中废弃的功能
  • 其它变更
  • Windows 支持

这个新的小版本带来了大量的 新特性和 少量的兼容性调整 在生产环境切换 PHP 版本前应该进行相关测试。

参见 PHP 版本迁移指南 7.0.x、 7.1.x、 7.2.x。

User Contributed Notes

jrg dot guzz at gmail dot com 10-Jun-2020 09:00
Como parte del aumento de la seguridad, se recomienda mantener actualizada su versión de PHP. Aquí hemos proporcionado los pasos para actualizar la versión actual de PHP 7.2 a 7.3 en las versiones de Ubuntu 14/16/18 /19/20 sin eliminar la anterior. Para que podamos volver a las versiones anteriores si hay algo incompatible con la nueva después de cambiar.
    1. Inicie sesión en el servidor a través de SSH como root.
       * Sino sabes no importa usa el comando sudo (como yo)
    2. Verifique su versión actual de PHP.
       $ php -v
PHP 7.2.36

    3. Para instalar PHP 7.3, primero debemos agregar el repositorio:
       (Mucho ojo  aquí,(PRECAUCIóN) ...Si te encuentras en la versión Ubuntu  19 / 20 no es necesario agregar repositorios , los trae por default.Puedes consultar con este comando los repositorios:

 $sudo apt-cache policy | grep http | awk '{print $2 $3}' | sort -u

 Sino se encuentran app/php o app/apache2 usa este comando:

$sudo add-apt-repository ppa: ondrej / php

    4. Luego ejecute una actualización:
$sudo apt-get update

    5. Después de completar la actualización, necesitamos instalar PHP 7.3.
$ sudo apt install php7.3

    6.  Luego instale los paquetes PHP requeridos según su instalación actual:
$sudo apt install php7.3-common php7.3-cli php7.3-bz2 php7.3-curl php7.3-gd php7.3-intl php7.3-json php7.3-readline php7.3-xml php7. 3-zip php7.3-fpm php7.3-bcmath php7.3-mbstring

      Se suman nuevos comandos para la version 7.3 de Php.En el orden que se escriben para no da?ar los modulos.

Detener el Servidor Apache
$sudo systemctl stop apache2

Desactivar el Modulo Php 7.2
 $sudo a2dismod php7.2

Activas Modulo Proxy fcgi
$sudo a2enmod proxy_fcgi setenvif

Activar Modulo fpm
$sudo a2enmod php7.3-fpm

Activar Modulo de Php 7.3
$sudo a2enmod php7.3

    7. Luego reinicie Apache:
$sudo systemctl start apache2

    8. Por último comprobamos el Status del Sercidor Apache2, apagar y  prender un par de veces el servidor.(Todo correcto):

 $sudo systenctl status apache2

    9. La nueva versión de PHP debería estar activa ahora. Puede verificarlo desde la línea de comando:

$php -v
PHP 7.3.28


新特性

PHP 核心

更灵活的 Heredoc 和 Nowdoc 语法

Heredoc 和 Nowdoc 语法变的更灵活。现在支持闭合标记符的缩进，并且不再强制闭合标记符的换行。

Array Destructuring supports Reference Assignments

Array destructuring now supports reference assignments using the syntax [&$a, [$b, &$c]] = $d. The same is also supported for list().

Instanceof Operator accepts Literals

instanceof now allows literals as the first operand, in which case the result is always false.

CompileError Exception instead of some Compilation Errors

A new CompileError exception has been added, from which ParseError inherits. A small number of compilation errors will now throw a CompileError instead of generating a fatal error. Currently this only affects compilation errors that may be thrown by token_get_all() in TOKEN_PARSE mode, but more errors may be converted in the future.

Trailing Commas are allowed in Calls

Trailing commas in function and method calls are now allowed.

Argon2id Support

The --with-password-argon2[=dir] configure argument now provides support for both Argon2i and Argon2id hashes in the password_hash(), password_verify(), password_get_info(), and password_needs_rehash() functions. Passwords may be hashed and verified using the PASSWORD_ARGON2ID constant. Support for both Argon2i and Argon2id in the password_*() functions now requires PHP be linked against libargon2 reference library ≥ 20161029.

FastCGI Process Manager

New options have been added to customize the FPM logging:

log_limit
This global option can be used for setting the log limit for the logged line which allows to log messages longer than 1024 characters without wrapping. It also fixes various wrapping issues.
log_buffering
This global option allows an experimental logging without extra buffering.
decorate_workers_output
This pool option allows to disable the output decoration for workers output when catch_workers_output is enabled.

BC Math Functions

bcscale() can now also be used as getter to retrieve the current scale in use.

Lightweight Directory Access Protocol

Full support for LDAP Controls has been added to the LDAP querying functions and ldap_parse_result():

  • A $serverctrls parameter to send controls to the
server in ldap_add(),
ldap_mod_replace(), ldap_mod_add(),
ldap_mod_del(), ldap_rename(),
ldap_compare(), ldap_delete(),
ldap_modify_batch(),
ldap_search(), ldap_list() and
ldap_read() has been added.
  • The out parameter $serverctrls to get controls from the server in ldap_parse_result() has been added.
  • Support for LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS in ldap_get_option() and ldap_set_option() has been fixed.

Multibyte String Functions

Full Case-Mapping and Case-Folding Support

Support for full case-mapping and case-folding has been added. Unlike simple case-mapping, full case-mapping may change the length of the string. For example:

<?php
mb_strtoupper("Stra?e");
// Produces STRA?E on PHP 7.2
// Produces STRASSE on PHP 7.3
?>
The different casing mapping and folding modes are available through mb_convert_case():
  • MB_CASE_LOWER (used by mb_strtolower())
  • MB_CASE_UPPER (used by mb_strtoupper())
  • MB_CASE_TITLE
  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE (used by case-insensitive operations)
Only unconditional, language agnostic full case-mapping is performed.

Case-Insensitive String Operations use Case-Folding

Case-insensitive string operations now use case-folding instead of case- mapping during comparisons. This means that more characters will be considered (case insensitively) equal now.

MB_CASE_TITLE performs Title-Case Conversion

mb_convert_case() with MB_CASE_TITLE now performs title-case conversion based on the Cased and CaseIgnorable derived Unicode properties. In particular this also improves handling of quotes and apostrophes.

Unicode 11 Support

The Multibyte String data tables have been updated for Unicode 11.

Long String Support

The Multibyte String Functions now correctly support strings larger than 2GB.

Performance Improvements

Performance of the Multibyte String extension has been significantly improved across the board. The largest improvements are in case conversion functions.

Named Captures Support

The mb_ereg_* functions now support named captures. Matching functions like mb_ereg() will now return named captures both using their group number and their name, similar to PCRE:

<?php
mb_ereg('(?<word>\w+)', '国', $matches);
// => [0 => "国", 1 => "国", "word" => "国"];
?>
Additionally, mb_ereg_replace() now supports the \k<> and \k'' notations to reference named captures in the replacement string:
<?php
mb_ereg_replace('\s*(?<word>\w+)\s*', "_\k<word>_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\k<> and \k'' can also be used for numbered references, which also works with group numbers greater than 9.

Readline

Support for the completion_append_character and completion_suppress_append options has been added to readline_info(). These options are only available if PHP is linked against libreadline (rather than libedit).

User Contributed Notes

yoander dot valdes at yahoo dot com 31-May-2019 11:34
"Trailing commas in function and method calls are now allowed" means function parameters, example:

<?php

function my1() {
        echo "xxxxxx\n";
}

function my2() {
        echo "yyyyyy\n";
}

my1(),my2(); // PHP Parse error:  syntax error

my1(,); // PHP Parse error:  syntax error

my1(1,); my2(2,); // OK

?>


新函数

PHP 内核

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()
  • net_get_interfaces()

FastCGI 进程管理器

  • fpm_get_status()

Date and Time

  • DateTime::createFromImmutable()

GNU Multiple Precision

  • gmp_binomial()
  • gmp_kronecker()
  • gmp_lcm()
  • gmp_perfect_power()

国际化相关函数

  • Normalizer::getRawDecomposition()
  • normalizer_get_raw_decomposition()
  • Spoofchecker::setRestrictionLevel()

Lightweight Directory Access Protocol

  • ldap_add_ext()
  • ldap_bind_ext()
  • ldap_delete_ext()
  • ldap_exop_refresh()
  • ldap_mod_add_ext()
  • ldap_mod_replace_ext()
  • ldap_mod_del_ext()
  • ldap_rename_ext()

OpenSSL

  • openssl_pkey_derive()

Sockets

  • socket_wsaprotocol_info_export()
  • socket_wsaprotocol_info_import()
  • socket_wsaprotocol_info_release()

User Contributed Notes

There are no user contributed notes for this page.


新的全局常量

PHP 核心中预定义的常量

  • PASSWORD_ARGON2ID

Client URL Library

  • CURLAUTH_BEARER
  • CURLAUTH_GSSAPI
  • CURLE_WEIRD_SERVER_REPLY
  • CURLINFO_APPCONNECT_TIME_T
  • CURLINFO_CONNECT_TIME_T
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T
  • CURLINFO_CONTENT_LENGTH_UPLOAD_T
  • CURLINFO_FILETIME_T
  • CURLINFO_HTTP_VERSION
  • CURLINFO_NAMELOOKUP_TIME_T
  • CURLINFO_PRETRANSFER_TIME_T
  • CURLINFO_PROTOCOL
  • CURLINFO_PROXY_SSL_VERIFYRESULT
  • CURLINFO_REDIRECT_TIME_T
  • CURLINFO_SCHEME
  • CURLINFO_SIZE_DOWNLOAD_T
  • CURLINFO_SIZE_UPLOAD_T
  • CURLINFO_SPEED_DOWNLOAD_T
  • CURLINFO_SPEED_UPLOAD_T
  • CURLINFO_STARTTRANSFER_TIME_T
  • CURLINFO_TOTAL_TIME_T
  • CURL_LOCK_DATA_CONNECT
  • CURL_LOCK_DATA_PSL
  • CURL_MAX_READ_SIZE
  • CURLOPT_ABSTRACT_UNIX_SOCKET
  • CURLOPT_DISALLOW_USERNAME_IN_URL
  • CURLOPT_DNS_SHUFFLE_ADDRESSES
  • CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS
  • CURLOPT_HAPROXYPROTOCOL
  • CURLOPT_KEEP_SENDING_ON_ERROR
  • CURLOPT_PRE_PROXY
  • CURLOPT_PROXY_CAINFO
  • CURLOPT_PROXY_CAPATH
  • CURLOPT_PROXY_CRLFILE
  • CURLOPT_PROXY_KEYPASSWD
  • CURLOPT_PROXY_PINNEDPUBLICKEY
  • CURLOPT_PROXY_SSLCERT
  • CURLOPT_PROXY_SSLCERTTYPE
  • CURLOPT_PROXY_SSL_CIPHER_LIST
  • CURLOPT_PROXY_SSLKEY
  • CURLOPT_PROXY_SSLKEYTYPE
  • CURLOPT_PROXY_SSL_OPTIONS
  • CURLOPT_PROXY_SSL_VERIFYHOST
  • CURLOPT_PROXY_SSL_VERIFYPEER
  • CURLOPT_PROXY_SSLVERSION
  • CURLOPT_PROXY_TLS13_CIPHERS
  • CURLOPT_PROXY_TLSAUTH_PASSWORD
  • CURLOPT_PROXY_TLSAUTH_TYPE
  • CURLOPT_PROXY_TLSAUTH_USERNAME
  • CURLOPT_REQUEST_TARGET
  • CURLOPT_SOCKS5_AUTH
  • CURLOPT_SSH_COMPRESSION
  • CURLOPT_SUPPRESS_CONNECT_HEADERS
  • CURLOPT_TIMEVALUE_LARGE
  • CURLOPT_TLS13_CIPHERS
  • CURLPROXY_HTTPS
  • CURLSSH_AUTH_GSSAPI
  • CURL_SSLVERSION_MAX_DEFAULT
  • CURL_SSLVERSION_MAX_NONE
  • CURL_SSLVERSION_MAX_TLSv1_0
  • CURL_SSLVERSION_MAX_TLSv1_1
  • CURL_SSLVERSION_MAX_TLSv1_2
  • CURL_SSLVERSION_MAX_TLSv1_3
  • CURL_SSLVERSION_TLSv1_3
  • CURL_VERSION_ALTSVC (as of PHP 7.3.6)
  • CURL_VERSION_ASYNCHDNS
  • CURL_VERSION_BROTLI
  • CURL_VERSION_CONV
  • CURL_VERSION_CURLDEBUG (as of PHP 7.3.6)
  • CURL_VERSION_DEBUG
  • CURL_VERSION_GSSAPI
  • CURL_VERSION_GSSNEGOTIATE
  • CURL_VERSION_HTTPS_PROXY
  • CURL_VERSION_IDN
  • CURL_VERSION_LARGEFILE
  • CURL_VERSION_MULTI_SSL
  • CURL_VERSION_NTLM
  • CURL_VERSION_NTLM_WB
  • CURL_VERSION_PSL (as of PHP 7.3.6)
  • CURL_VERSION_SPNEGO
  • CURL_VERSION_SSPI
  • CURL_VERSION_TLSAUTH_SRP

Data Filtering

  • FILTER_SANITIZE_ADD_SLASHES

JavaScript Object Notation

  • JSON_THROW_ON_ERROR

Lightweight Directory Access Protocol

  • LDAP_CONTROL_ASSERT
  • LDAP_CONTROL_MANAGEDSAIT
  • LDAP_CONTROL_PROXY_AUTHZ
  • LDAP_CONTROL_SUBENTRIES
  • LDAP_CONTROL_VALUESRETURNFILTER
  • LDAP_CONTROL_PRE_READ
  • LDAP_CONTROL_POST_READ
  • LDAP_CONTROL_SORTREQUEST
  • LDAP_CONTROL_SORTRESPONSE
  • LDAP_CONTROL_PAGEDRESULTS
  • LDAP_CONTROL_AUTHZID_REQUEST
  • LDAP_CONTROL_AUTHZID_RESPONSE
  • LDAP_CONTROL_SYNC
  • LDAP_CONTROL_SYNC_STATE
  • LDAP_CONTROL_SYNC_DONE
  • LDAP_CONTROL_DONTUSECOPY
  • LDAP_CONTROL_PASSWORDPOLICYREQUEST
  • LDAP_CONTROL_PASSWORDPOLICYRESPONSE
  • LDAP_CONTROL_X_INCREMENTAL_VALUES
  • LDAP_CONTROL_X_DOMAIN_SCOPE
  • LDAP_CONTROL_X_PERMISSIVE_MODIFY
  • LDAP_CONTROL_X_SEARCH_OPTIONS
  • LDAP_CONTROL_X_TREE_DELETE
  • LDAP_CONTROL_X_EXTENDED_DN
  • LDAP_CONTROL_VLVREQUEST
  • LDAP_CONTROL_VLVRESPONSE

Multibyte String

  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE

OpenSSL

  • STREAM_CRYPTO_PROTO_SSLv3
  • STREAM_CRYPTO_PROTO_TLSv1_0
  • STREAM_CRYPTO_PROTO_TLSv1_1
  • STREAM_CRYPTO_PROTO_TLSv1_2

PostgreSQL

  • PGSQL_DIAG_SCHEMA_NAME
  • PGSQL_DIAG_TABLE_NAME
  • PGSQL_DIAG_COLUMN_NAME
  • PGSQL_DIAG_DATATYPE_NAME
  • PGSQL_DIAG_CONSTRAINT_NAME
  • PGSQL_DIAG_SEVERITY_NONLOCALIZED

User Contributed Notes

There are no user contributed notes for this page.


不向下兼容的变更

PHP 核心

Heredoc/Nowdoc Ending Label Interpretation

Due to the introduction of flexible heredoc/nowdoc syntax, doc strings that contain the ending label inside their body may cause syntax errors or change in interpretation. For example in:

<?php
$str = <<<FOO
abcdefg
   FOO
FOO;
?>
the indented occurrence of FOO did not previously have any special meaning. Now it will be interpreted as the end of the heredoc string and the following FOO; will cause a syntax error. This issue can always be resolved by choosing an ending label that does not occur within the contents of the string.

Continue Targeting Switch issues Warning

continue statements targeting switch control flow structures will now generate a warning. In PHP such continue statements are equivalent to break, while they behave as continue 2 in other languages.

<?php
while ($foo) {
    switch ($bar) {
      case "baz":
         continue;
         // Warning: "continue" targeting switch is equivalent to
         //          "break". Did you mean to use "continue 2"?
   }
}
?>

Strict Interpretation of Integer String Keys on ArrayAccess

Array accesses of type $obj["123"], where $obj implements ArrayAccess and "123" is an integer string literal will no longer result in an implicit conversion to integer, i.e., $obj->offsetGet("123") will be called instead of $obj->offsetGet(123). This matches existing behavior for non-literals. The behavior of arrays is not affected in any way, they continue to implicitly convert integral string keys to integers.

Static Properties no longer separated by Reference Assignment

In PHP, static properties are shared between inheriting classes, unless the static property is explicitly overridden in a child class. However, due to an implementation artifact it was possible to separate the static properties by assigning a reference. This loophole has been fixed.

<?php
class Test {
    public static $x = 0;
}
class Test2 extends Test { }

Test2::$x = &$x;
$x = 1;

var_dump(Test::$x, Test2::$x);
// Previously: int(0), int(1)
// Now:        int(1), int(1)
?>

References returned by Array and Property Accesses are immediately unwrapped

References returned by array and property accesses are now unwrapped as part of the access. This means that it is no longer possible to modify the reference between the access and the use of the accessed value:

<?php
$arr = [1];
$ref =& $arr[0];
var_dump($arr[0] + ($arr[0] = 2));
// Previously: int(4), Now: int(3)
?>
This makes the behavior of references and non-references consistent. Please note that reading and writing a value inside a single expression remains undefined behavior and may change again in the future.

Argument Unpacking of Traversables with non-Integer Keys no longer supported

Argument unpacking stopped working with Traversables with non-integer keys. The following code worked in PHP 5.6-7.2 by accident.

<?php
function foo(...$args) {
    var_dump($args);
}
function gen() {
    yield 1.23 => 123;
}
foo(...gen());
?>

Miscellaneous

The ext_skel utility has been completely redesigned with new options and some old options removed. This is now written in PHP and has no external dependencies.

Support for BeOS has been dropped.

Exceptions thrown due to automatic conversion of warnings into exceptions in EH_THROW mode (e.g. some DateTime exceptions) no longer populate error_get_last() state. As such, they now work the same way as manually thrown exceptions.

TypeError now reports wrong types as int and bool instead of integer and boolean, respectively.

Undefined variables passed to compact() will now be reported as a notice.

getimagesize() and related functions now report the mime type of BMP images as image/bmp instead of image/x-ms-bmp, since the former has been registered with the IANA (see » RFC 7903).

stream_socket_get_name() will now return IPv6 addresses wrapped in brackets. For example "[::1]:1337" will be returned instead of "::1:1337".

BCMath Arbitrary Precision Mathematics

All warnings thrown by BCMath functions are now using PHP's error handling. Formerly some warnings have directly been written to stderr.

bcmul() and bcpow() now return numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.

IMAP, POP3 and NNTP

rsh/ssh logins are disabled by default. Use imap.enable_insecure_rsh if you want to enable them. Note that the IMAP library does not filter mailbox names before passing them to the rsh/ssh command, thus passing untrusted data to this function with rsh/ssh enabled is insecure.

Multibyte String

Due to added support for named captures, mb_ereg_*() patterns using named captures will behave differently. In particular named captures will be part of matches and mb_ereg_replace() will interpret additional syntax. See Named Captures for more information.

MySQL Improved Extension

Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values.

MySQL Functions (PDO_MYSQL)

Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values. Please note that this only affects the usage of PDO_MYSQL with emulated prepares turned off (e.g. using the native preparation functionality). Statements using connections having PDO::ATTR_EMULATE_PREPARES=true (which is the default) were not affected by the bug fixed and have already been getting the proper fractional seconds values from the engine.

Reflection

Reflection export to string now uses int and bool instead of integer and boolean, respectively.

Standard PHP Library (SPL)

If an SPL autoloader throws an exception, following autoloaders will not be executed. Previously all autoloaders were executed and exceptions were chained.

SimpleXML

Mathematic operations involving SimpleXML objects will now treat the text as an int or float, whichever is more appropriate. Previously values were treated as ints unconditionally.

Incoming Cookies

As of PHP 7.3.23, the names of incoming cookies are no longer url-decoded for security reasons.

User Contributed Notes

gmoreno 13-Feb-2021 09:49
Chris, that is actually mentioned here: https://www.php.net/manual/en/migration73.other-changes.php#migration73.other-changes.pcre
chris at ocproducts dot com 01-May-2020 08:17
PCRE has been updated (https://wiki.php.net/rfc/pcre2-migration#backward_incompatible_changes).
The new PCRE version is stricter in some cases.


PHP 7.3.x 中废弃的功能

PHP 核心中废弃的功能

大小写不敏感的常量

大小写不敏感的常量声明现已被废弃。将 true 作为第三个参数传递给 define() 将会导致一个废弃警告。大小写不敏感的使用（在读取时使用一个与声明时不同的大小写方式）也已被废弃。

命名空间中的 assert()

废弃：在一个命名空间中声明一个名为 assert() 的函数。 assert() 函数属于引擎特殊处理的情况，当在命名空间中使用相同名字去定义 函数时也许会导致不一致的行为。

在字符串中搜索非字符串内容

废弃：将一个非字符串内容传递给字符串搜索函数。 在将来所有待搜索的内容都将被视为字符串，而不是 ASCII 编码值。如果需要依赖这个特性，你应该 要么显示地进行类型转换（转为字符串），或者显示地调用 chr()。 以下是受到影响的方法：

  • strpos()
  • strrpos()
  • stripos()
  • strripos()
  • strstr()
  • strchr()
  • strrchr()
  • stristr()

Strip-Tags Streaming

fgetss() 函数和 string.strip_tags stream filter 已经被废弃。这同样影响了 SplFileObject::fgetss() 方法和 gzgetss() 函数。

Data Filtering

对于 FILTER_FLAG_SCHEME_REQUIRED 和 FILTER_FLAG_HOST_REQUIRED 常量的显示使用已被废弃。 总之，FILTER_VALIDATE_URL 已经隐含了这两者。

图像处理和 GD 库

image2wbmp() 已被废弃。

国际化相关函数

如果 PHP 关联的ICU ≥ 56, 那么 Normalizer::NONE 形式的使用将会导致抛出一个废弃警告。

多字节字符串

以下在文档中不存在的 mbereg_*() 别名已被废弃。请使用相应的 mb_ereg_*() 变体替代。

  • mbregex_encoding()
  • mbereg()
  • mberegi()
  • mbereg_replace()
  • mberegi_replace()
  • mbsplit()
  • mbereg_match()
  • mbereg_search()
  • mbereg_search_pos()
  • mbereg_search_regs()
  • mbereg_search_init()
  • mbereg_search_getregs()
  • mbereg_search_getpos()
  • mbereg_search_setpos()

ODBC 和 DB2 函数 (PDO_ODBC)

pdo_odbc.db2_instance_name ini 设置项在先前已被废弃。 它在文档中自 PHP 5.1.1 起被废弃

User Contributed Notes

There are no user contributed notes for this page.


其它变更

PHP 核心

Set(raw)cookie 函数接受 $option 数组参数

setcookie() and setrawcookie() now also support the following signature:

setcookie ( string $name , string $value = "" , array $options = [] ) : bool
where $options is an associative array which may have any of the keys "expires", "path", "domain", "secure", "httponly" and "samesite".

新的 Syslog ini 配置

The following ini Directives have been added to customize logging, if error_log is set to syslog:

syslog.facility
Specifies what type of program is logging the message.
syslog.filter
Specifies the filter type to filter the logged messages. There are three supported filter types - all, no-ctrl and ascii.
syslog.ident
Specifies the ident string which is prepended to every message.

垃圾回收机制

The cyclic GC has been enhanced, which may result in considerable performance improvements.

其它

var_export() now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState().

debug_zval_dump() was changed to display recursive arrays and objects in the same way as var_dump(). Now, it doesn't display them twice.

array_push() and array_unshift() can now also be called with a single argument, which is particularly convenient wrt. the spread operator.

Interactive PHP Debugger

The unused constants PHPDBG_FILE, PHPDBG_METHOD, PHPDBG_LINENO and PHPDBG_FUNC have been removed.

FastCGI 进程管理器

getallheaders() 函数现已可用。

Client URL Library

libcurl ≥ 7.15.5 is now required.

Data Filtering

FILTER_VALIDATE_FLOAT now also supports a thousand option, which defines the set of allowed thousand separator chars. The default ("',.") is fully backward compatible with former PHP versions.

FILTER_SANITIZE_ADD_SLASHES has been added as an alias of the magic_quotes filter (FILTER_SANITIZE_MAGIC_QUOTES). The magic_quotes filter is subject to removal in future versions of PHP.

FTP

The default transfer mode has been changed to binary.

国际化相关函数

Normalizer::NONE is deprecated, when PHP is linked with ICU ≥ 56.

Introduced Normalizer::FORM_KC_CF as Normalizer::normalize() argument for NFKC_Casefold normalization; available when linked with ICU ≥ 56.

JavaScript Object Notation

A new flag has been added, JSON_THROW_ON_ERROR, which can be used with json_decode() or json_encode() and causes these functions to throw the new JsonException upon an error, instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg(). JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR.

Multibyte String

The configuration option --with-libmbfl is no longer available.

ODBC (Unified)

Support for ODBCRouter and Birdstep including the birdstep.max_links ini directive has been removed.

OPcache

The opcache.inherited_hack ini directive has been removed. The value has already been ignored since PHP 5.3.0.

OpenSSL

The min_proto_version and max_proto_version ssl stream options as well as related constants for possible TLS protocol values have been added.

Regular Expressions (Perl-Compatible)

The PCRE extension has been upgraded to PCRE2, which may cause minor behavioral changes (for instance, character ranges in classes are now more strictly interpreted), and augments the existing regular expression syntax.

preg_quote() now also escapes the '#' character.

Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

The attribute PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS to enable automatic skipping of empty rowsets has been added.

The PDO::DBLIB_ATTR_TDS_VERSION attribute which exposes the TDS version has been added.

DATETIME2 columns are now treated like DATETIME columns.

SQLite Functions (PDO_SQLITE)

SQLite3 databases can now be opened in read-only mode by setting the new PDO::SQLITE_ATTR_OPEN_FLAGS attribute to PDO::SQLITE_OPEN_READONLY.

Session Handling

session_set_cookie_params() now also supports the following signature:

session_set_cookie_params ( array $options ) : bool
where $options is an associative array which may have any of the keys "lifetime", "path", "domain", "secure", "httponly" and "samesite". Accordingly, the return value of session_get_cookie_params() now also has an element with the key "samesite". Furthermore, the new session.cookie_samesite ini option to set the default of the SameSite directive for cookies has been added. It defaults to "" (empty string), so no SameSite directive is set. Can be set to "Lax" or "Strict", which sets the respective SameSite directive.

Tidy

Building against » tidyp is now also supported transparently. Since tidyp offers no API to get the release date, tidy_get_release() and tidy::getRelease() return 'unknown' in this case.

XML Parser

The return value of the xml_set_external_entity_ref_handler() callback is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop.

Zip

Building against the bundled libzip is discouraged, but still possible by adding --without-libzip to the configuration.

Zlib Compression

The zlib/level context option for the compress.zlib wrapper to facilitate setting the desired compression level has been added.

User Contributed Notes

There are no user contributed notes for this page.


Windows 支持

PHP 核心

更符合 POSIX 标准的文件删除方法

File descriptors are opened in shared read/write/delete mode by default. This effectively maps the POSIX semantics and allows to delete files with handles in use. It is not 100% same, some platform differences still persist. After the deletion, the filename entry is blocked, until all the opened handles to it are closed.

User Contributed Notes

There are no user contributed notes for this page.


从 PHP 7.1.x 移植到 PHP 7.2.x

Table of Contents

  • 新特性
  • 新函数
  • 新全局常量
  • 不向下兼容的变更
  • PHP 7.2.x 中废弃的功能
  • 其他变更

这个新的小版本带来了大量的 新特性和 少量的兼容性调整 在生产环境切换 PHP 版本前应该进行相关测试。

参见 PHP 版本迁移指南 7.0.x 和 7.1.x。

User Contributed Notes

There are no user contributed notes for this page.


新特性

新的对象类型

这种新的对象类型, object, 引进了可用于逆变（contravariant）参数输入和协变（covariant）返回任何对象类型。

<?php

function test(object $obj) : object
{
    return new SplQueue();
}

test(new StdClass());

通过名称加载扩展

扩展文件不再需要通过文件加载 (Unix下以.so为文件扩展名，在Windows下以 .dll 为文件扩展名) 进行指定。可以在php.ini配置文件进行启用, 也可以使用 dl() 函数进行启用。

允许重写抽象方法(Abstract method)

当一个抽象类继承于另外一个抽象类的时候，继承后的抽象类可以重写被继承的抽象类的抽象方法。

<?php

abstract class A
{
    abstract function test(string $s);
}
abstract class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    abstract function test($s) : int;
}

使用Argon2算法生成密码散列

Argon2 已经被加入到密码散列（password hashing） API (这些函数以 password_ 开头), 以下是暴露出来的常量:

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

新增 ext/PDO（PDO扩展） 字符串扩展类型

当你准备支持多语言字符集，PDO的字符串类型已经扩展支持国际化的字符集。以下是扩展的常量：

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

这些常量通过PDO::PARAM_STR利用位运算OR进行计算：

<?php

$db->quote('über', PDO::PARAM_STR | PDO::PARAM_STR_NATL);

为 ext/PDO新增额外的模拟调试信息

PDOStatement::debugDumpParams()方法已经更新，当发送SQL到数据库的时候，在一致性、行查询（包括替换绑定占位符）将会显示调试信息。这一特性已经加入到模拟调试中（在模拟调试打开时可用）。

ext/LDAP（LDAP扩展） 支持新的操作方式

LDAP 扩展已经新增了EXOP支持. 扩展暴露以下函数和常量:

  • ldap_parse_exop()
  • ldap_exop()
  • ldap_exop_passwd()
  • ldap_exop_whoami()
  • LDAP_EXOP_START_TLS
  • LDAP_EXOP_MODIFY_PASSWD
  • LDAP_EXOP_REFRESH
  • LDAP_EXOP_WHO_AM_I
  • LDAP_EXOP_TURN

ext/sockets（sockets扩展）添加了地址信息

sockets扩展现在具有查找地址信息的能力，且可以连接到这个地址，或者进行绑定和解析。为此添加了以下一些函数:

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

扩展了参数类型

重写方法和接口实现的参数类型现在可以省略了。不过这仍然是符合LSP，因为现在这种参数类型是逆变的。

<?php

interface A
{
    public function Test(array $input);
}

class B implements A
{
    public function Test($input){} // type omitted for $input
}

允许分组命名空间的尾部逗号

命名空间可以在PHP 7中使用尾随逗号进行分组引入。

<?php

use Foo\Bar\{
    Foo,
    Bar,
    Baz,
};

User Contributed Notes

info at ensostudio dot ru 11-Sep-2020 07:28
Note: you cant change parameter type for abstract method defined in interface.
<?php
abstract class AbstractAssocArray imlements ArrayAccess
{
    abstract public function offsetSet($offset, $value): void;
    ...
}
abstract class AbstractAssocArray2 extends AbstractAssocArray
{
    abstract public function offsetSet(string $offset, $value): void;
}
class AssocArray extends AbstractAssocArray2
{
    public function offsetSet(string $offset, $value): void
    {
         $this->{$offset} = $value;
    }
}
?>
It's throw fatal error: Declaration of AbstractAssocArray::offsetSet(string $offset, $value): void must be compatible with AbstractAssocArrayAccess::offsetSet($offset, $value).


新函数

PHP 内核

  • stream_isatty()
  • sapi_windows_vt100_support()

SPL

  • spl_object_id()

DOM

  • DomNodeList::count()
  • DOMNamedNodeMap::count()

FTP

  • ftp_append()

GD

  • imagesetclip()
  • imagegetclip()
  • imageopenpolygon()
  • imageresolution()
  • imagecreatefrombmp()
  • imagebmp()

Hash

  • hash_hmac_algos()

LDAP

  • ldap_parse_exop()
  • ldap_exop()
  • ldap_exop_passwd()
  • ldap_exop_whoami()

Multibyte String

  • mb_chr()
  • mb_ord()
  • mb_scrub()

Oracle OCI8

  • oci_register_taf_callback()
  • oci_unregister_taf_callback()

Sockets

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Sodium

  • sodium_add()
  • sodium_bin2hex()
  • sodium_compare()
  • sodium_crypto_aead_aes256gcm_decrypt()
  • sodium_crypto_aead_aes256gcm_encrypt()
  • sodium_crypto_aead_aes256gcm_is_available()
  • sodium_crypto_aead_aes256gcm_keygen()
  • sodium_crypto_aead_chacha20poly1305_decrypt()
  • sodium_crypto_aead_chacha20poly1305_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_decrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_keygen()
  • sodium_crypto_aead_chacha20poly1305_keygen()
  • sodium_crypto_auth_keygen()
  • sodium_crypto_auth_verify()
  • sodium_crypto_auth()
  • sodium_crypto_box_keypair_from_secretkey_and_publickey()
  • sodium_crypto_box_keypair()
  • sodium_crypto_box_open()
  • sodium_crypto_box_publickey_from_secretkey()
  • sodium_crypto_box_publickey()
  • sodium_crypto_box_seal_open()
  • sodium_crypto_box_seal()
  • sodium_crypto_box_secretkey()
  • sodium_crypto_box_seed_keypair()
  • sodium_crypto_box()
  • sodium_crypto_generichash_final()
  • sodium_crypto_generichash_init()
  • sodium_crypto_generichash_keygen()
  • sodium_crypto_generichash_update()
  • sodium_crypto_generichash()
  • sodium_crypto_kdf_derive_from_key()
  • sodium_crypto_kdf_keygen()
  • sodium_crypto_kx_client_session_keys()
  • sodium_crypto_kx_keypair()
  • sodium_crypto_kx_publickey()
  • sodium_crypto_kx_secretkey()
  • sodium_crypto_kx_seed_keypair()
  • sodium_crypto_kx_server_session_keys()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str()
  • sodium_crypto_pwhash_scryptsalsa208sha256()
  • sodium_crypto_pwhash_str_verify()
  • sodium_crypto_pwhash_str()
  • sodium_crypto_pwhash()
  • sodium_crypto_scalarmult_base()
  • sodium_crypto_scalarmult()
  • sodium_crypto_secretbox_keygen()
  • sodium_crypto_secretbox_open()
  • sodium_crypto_secretbox()
  • sodium_crypto_shorthash_keygen()
  • sodium_crypto_shorthash()
  • sodium_crypto_sign_detached()
  • sodium_crypto_sign_ed25519_pk_to_curve25519()
  • sodium_crypto_sign_ed25519_sk_to_curve25519()
  • sodium_crypto_sign_keypair_from_secretkey_and_publickey()
  • sodium_crypto_sign_keypair()
  • sodium_crypto_sign_open()
  • sodium_crypto_sign_publickey_from_secretkey()
  • sodium_crypto_sign_publickey()
  • sodium_crypto_sign_secretkey()
  • sodium_crypto_sign_seed_keypair()
  • sodium_crypto_sign_verify_detached()
  • sodium_crypto_sign()
  • sodium_crypto_stream_keygen()
  • sodium_crypto_stream_xor()
  • sodium_crypto_stream()
  • sodium_hex2bin()
  • sodium_increment()
  • sodium_memcmp()
  • sodium_memzero()
  • sodium_pad()
  • sodium_unpad()

ZIP

  • ZipArchive::count()
  • ZipArchive::setEncryptionName()
  • ZipArchive::setEncryptionIndex()

User Contributed Notes

There are no user contributed notes for this page.


新全局常量

PHP 内核

  • PHP_FLOAT_DIG
  • PHP_FLOAT_EPSILON
  • PHP_FLOAT_MIN
  • PHP_FLOAT_MAX
  • PHP_OS_FAMILY

文件信息

  • FILEINFO_EXTENSION

JSON

  • JSON_INVALID_UTF8_IGNORE
  • JSON_INVALID_UTF8_SUBSTITUTE

GD

  • IMG_EFFECT_MULTIPLY
  • IMG_BMP

LDAP

  • LDAP_EXOP_START_TLS
  • LDAP_EXOP_MODIFY_PASSWD
  • LDAP_EXOP_REFRESH
  • LDAP_EXOP_WHO_AM_I
  • LDAP_EXOP_TURN

密码散列

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

PCRE

  • PREG_UNMATCHED_AS_NULL

PDO

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

Sodium

  • SODIUM_LIBRARY_VERSION
  • SODIUM_LIBRARY_MAJOR_VERSION
  • SODIUM_LIBRARY_MINOR_VERSION
  • SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES
  • SODIUM_CRYPTO_AUTH_BYTES
  • SODIUM_CRYPTO_AUTH_KEYBYTES
  • SODIUM_CRYPTO_BOX_SEALBYTES
  • SODIUM_CRYPTO_BOX_SECRETKEYBYTES
  • SODIUM_CRYPTO_BOX_PUBLICKEYBYTES
  • SODIUM_CRYPTO_BOX_KEYPAIRBYTES
  • SODIUM_CRYPTO_BOX_MACBYTES
  • SODIUM_CRYPTO_BOX_NONCEBYTES
  • SODIUM_CRYPTO_BOX_SEEDBYTES
  • SODIUM_CRYPTO_KDF_BYTES_MIN
  • SODIUM_CRYPTO_KDF_BYTES_MAX
  • SODIUM_CRYPTO_KDF_CONTEXTBYTES
  • SODIUM_CRYPTO_KDF_KEYBYTES
  • SODIUM_CRYPTO_KX_SEEDBYTES
  • SODIUM_CRYPTO_KX_SESSIONKEYBYTES
  • SODIUM_CRYPTO_KX_PUBLICKEYBYTES
  • SODIUM_CRYPTO_KX_SECRETKEYBYTES
  • SODIUM_CRYPTO_KX_KEYPAIRBYTES
  • SODIUM_CRYPTO_GENERICHASH_BYTES
  • SODIUM_CRYPTO_GENERICHASH_BYTES_MIN
  • SODIUM_CRYPTO_GENERICHASH_BYTES_MAX
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX
  • SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13
  • SODIUM_CRYPTO_PWHASH_ALG_DEFAULT
  • SODIUM_CRYPTO_PWHASH_SALTBYTES
  • SODIUM_CRYPTO_PWHASH_STRPREFIX
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE
  • SODIUM_CRYPTO_SCALARMULT_BYTES
  • SODIUM_CRYPTO_SCALARMULT_SCALARBYTES
  • SODIUM_CRYPTO_SHORTHASH_BYTES
  • SODIUM_CRYPTO_SHORTHASH_KEYBYTES
  • SODIUM_CRYPTO_SECRETBOX_KEYBYTES
  • SODIUM_CRYPTO_SECRETBOX_MACBYTES
  • SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
  • SODIUM_CRYPTO_SIGN_BYTES
  • SODIUM_CRYPTO_SIGN_SEEDBYTES
  • SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES
  • SODIUM_CRYPTO_SIGN_SECRETKEYBYTES
  • SODIUM_CRYPTO_SIGN_KEYPAIRBYTES
  • SODIUM_CRYPTO_STREAM_NONCEBYTES
  • SODIUM_CRYPTO_STREAM_KEYBYTES

Zip

  • ZipArchive::EM_NONE
  • ZipArchive::EM_AES_128
  • ZipArchive::EM_AES_192
  • ZipArchive::EM_AES_256

User Contributed Notes

There are no user contributed notes for this page.


不向下兼容的变更

防止 number_format() 返回负零

之前版本中，number_format() 有可能会返回 -0。虽然这是符合 IEEE 754 规范的，但是这样会导致可读性不好，新版本中会将这样的负数去掉。

<?php

var_dump(number_format(-0.01)); // 新版本输出 string(1) "0" 旧版本输出 string(2) "-0"

转换对象和数组中的数字键

将数组转换为对象，或将对象转换为数组时，数字键现在得到了更好的处理（无论是通过显式转换还是通过 settype() 函数）。

这意味着现在可以访问数组中的整数(或者说是字符串整数)键，这些键会映射到对象中：

<?php

// array to object
$arr = [0 => 1];
$obj = (object)$arr;
var_dump(
    $obj,
    $obj->{'0'}, // 新写法
    $obj->{0} // 新写法
);

以上例程会输出：

object(stdClass)#1 (1) {
  ["0"]=>    // string key now, rather than integer key
  int(1)
}
int(1)
int(1)

从对象转换成的数组中的整数（或者说是字符串整数）键现在也可以直接访问：

<?php

// object to array
$obj = new class {
    public function __construct()
    {
        $this->{0} = 1;
    }
};
$arr = (array)$obj;
var_dump(
    $arr,
    $arr[0], // 新写法
    $arr['0'] // 新写法
);

以上例程会输出：

array(1) {
  [0]=>    // integer key now, rather than string key
  int(1)
}
int(1)
int(1)

get_class() 函数不再接受 null 参数

之前版本中，传递 null 给 get_class() 函数将返回当前类名。在新版本中，此行为会抛出一个 E_WARNING 错误。如果想实现与之前版本同样的效果，请不要传递任何参数进来。

计算非可数类型（non-countable）时发出警告

对非可数类型调用 count()（或 sizeof()）函数，会抛出一个 E_WARNING 错误。

<?php

var_dump(
    count(null), // NULL is not countable
    count(1), // integers are not countable
    count('abc'), // strings are not countable
    count(new stdclass), // objects not implementing the Countable interface are not countable
    count([1,2]) // arrays are countable
);

以上例程会输出：

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d
int(0)
int(1)
int(1)
int(1)
int(2)

ext/hash 从资源变成对象

As part of the long-term migration away from resources, the Hash extension has been updated to use objects instead of resources. The change should be seamless for PHP developers, except for where is_resource() checks have been made (which will need updating to is_object() instead).

SSL/TLS 的默认选项的改进

下列默认选项被修改：

  • tls:// 默认为 TLSv1.0 or TLSv1.1 or TLSv1.2
  • ssl:// 成为 tls:// 的别名
  • STREAM_CRYPTO_METHOD_TLS_* 常量默认为 TLSv1.0 或 TLSv1.1 + TLSv1.2，替代之前的 TLSv1.0

gettype() 在闭包资源中的返回值

之前版本中，如果在一个闭包资源中使用 gettype() 会返回字符串 "unknown type"，现在将会返回字符 "resource (closed)"。

is_object() 和 __PHP_Incomplete_Class

之前版本中，对 __PHP_Incomplete_Class 调用 is_object() 函数会返回 false，现在会返回 true。

提升未定义常量的错误级别

调用未定义的常量，现在会抛出一个 E_WARNING 错误(之前版本中为 E_NOTICE)。在下一个 PHP 大版本中，将会抛出一个 Error 错误。

Windows 支持

官方支持的最低 Windows 版本为 Windows 7/Server 2008 R2。

Checks on default property values of traits

Compatibility checks upon default trait property values will no longer perform casting.

object 保留字的变化

object 在之前的 PHP 7.0 版本 中被声明为软保留字（soft-reserved）。现在变更为强制保留字，禁止在任何类或接口中使用该名称。

NetWare 支持

NetWare 已不再被支持。

array_unique() with SORT_STRING

While array_unique() with SORT_STRING formerly copied the array and removed non-unique elements (without packing the array afterwards), now a new array is built by adding the unique elements. This can result in different numeric indexes.

bcmod() changes with floats

The bcmod() function no longer truncates fractional numbers to integers. As such, its behavior now follows fmod(), rather than the % operator. For example bcmod('4', '3.5') now returns 0.5 instead of 1.

Hashing functions and non-cryptographic hashes

The hash_hmac(), hash_hmac_file(), hash_pbkdf2(), and hash_init() (with HASH_HMAC) functions no longer accept non-cryptographic hashes.

json_decode() 函数变更

The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is null. Previously, JSON_OBJECT_AS_ARRAY was always ignored.

rand() and mt_rand() output

Sequences generated by rand() and mt_rand() for a specific seed may differ from PHP 7.1 on 64-bit machines (due to the fixing of a modulo bias bug in the implementation).

sql.safe_mode ini 选项移除

sql.safe_mode ini 设置项已被移除。

Changes to date_parse() and date_parse_from_format()

The zone element of the array returned by date_parse() and date_parse_from_format() represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.

Incoming Cookies

As of PHP 7.2.34, the names of incoming cookies are no longer url-decoded for security reasons.

User Contributed Notes

There are no user contributed notes for this page.


PHP 7.2.x 中废弃的功能

不带引号的字符串

不带引号的字符串是不存在的全局常量，转化成他们自身的字符串。 在以前，该行为会产生 E_NOTICE，但现在会产生 E_WARNING。在下一个 PHP 主版本中，将抛出 Error 异常。

<?php

var_dump(NONEXISTENT);

/* Output:
Warning: Use of undefined constant NONEXISTENT - assumed 'NONEXISTENT' (this will throw an Error in a future version of PHP) in %s on line %d
string(11) "NONEXISTENT"
*/

png2wbmp() 和 jpeg2wbmp()

GD 扩展内的 png2wbmp() 和 jpeg2wbmp() 现已被废弃，将在下一个 PHP 主版本中移除。

INTL_IDNA_VARIANT_2003 转化

Intl 扩展废弃了 INTL_IDNA_VARIANT_2003 转化，为idn_to_ascii() 和 idn_to_utf8() 的默认选项。 PHP 7.4 会把默认值设置为 INTL_IDNA_VARIANT_UTS46， 并在下一个 PHP 主版本中完全移除 INTL_IDNA_VARIANT_2003。

__autoload() 方法

__autoload() 方法已被废弃， 因为和 spl_autoload_register() 相比功能较差 (因为无法链式处理多个 autoloader)， 而且也无法在两种 autoloading 样式中配合使用。

track_errors ini 设置和 $php_errormsg 变量

当开启了 track_errors ini 设置，出现非致命错误时， 会在本地作用域创建 $php_errormsg 变量。 由于提供了更好的方式： error_get_last() 来获取此类错误信息，该功能被废弃。

create_function() 函数

考虑到此函数的安全隐患问题（它是 eval() 的瘦包装器），该过时的函数现在已被废弃。 更好的选择是匿名函数。

mbstring.func_overload ini 设置

由于此设置会影响环境中的字符串系列函数，带来相互操作中的问题，它现在已被废弃。

(unset) 类型强制转化

转化任意表达式为此类型，结果总是 null，所以这个多余的类型转化现在也就被废弃了。

parse_str() 不加第二个参数

使用 parse_str() 时，不加第二个参数会导致查询字符串参数导入当前符号表。 考虑到安全隐患问题，不加第二个参数使用 parse_str() 的行为已被废弃。 此函数的第二个选项为必填项，它使查询字符串转为 Array。

gmp_random() 函数

此函数基于未知的、取决于平台的 limb 尺寸产生随机数。因此，该函数已被废弃。 使用更好的方式产生随机数： GMP 扩展中的 gmp_random_bits() 和 gmp_random_range()。

each() 函数

使用此函数遍历时，比普通的 foreach 更慢， 并且给新语法的变化带来实现问题。因此它被废弃了。

assert() 一个字符串参数

assert() 字符串参数将要求它能被 eval() 执行。 考虑到可能被执行远程代码，废弃了字符串的 assert()，最好提供 bool 的表达式。

错误处理器内的 $errcontext 参数

$errcontext 参数包含了错误网站的所有本地变量。 考虑到它很少被用到，而且还会导致内部优化问题，它现在被废弃了。 代替用法：调试器应该自己取回错误站点的本地变量。

read_exif_data() 函数

read_exif_data() 别名已被废弃 使用 exif_read_data() 函数代替。

User Contributed Notes

Anonymous 26-Jul-2018 05:09
An empty <?php?> Codeblock in PHP 7.2.0 will put out an "Unquoted strings" warning. To prevent that, add at least one empty space into the codeblock.

Example:
<?php

<?php/*
echo "This was some useful code.\n";
*/?>

?>
Gives: PHP Warning:  Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP)

Fix via:
<?php

<?php   /*
echo "This was some useful code.\";
*/?>

?>

Don't know if that is an intentional behaviour or a side effect.
webmaster at thedigitalorchard dot ca 01-Feb-2018 05:14
Instead of __autoload(), you can use spl_autoload_register() very easily, as per the documentation:

spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

And this lets you have multiple autoloaders instead of one global one.


其他变更

移动 utf8_encode() 和 utf8_decode()

utf8_encode() 和 utf8_decode() 现在已经作为字符串处理函数移到标准扩展中， 在此之前需要启用 XML 扩展才能使用。

mail() 和 mb_sendmail() 的变更

mail() 和 mb_sendmail() 函数中的 $additional_headers 参数变更为 array，此前为 string。

支持 LMDB

DBA 扩展现在已经支持 LMDB。

PHP 构建系统的变更

  • Unix: 构建 PHP 需要 Autoconf 2.64 或更高的版本。
  • Unix: --with-pdo-oci 配置选项不再需要指定 Oracle Instant Client 的版本号数字。
  • Unix: 移除了 --enable-gd-native-ttf 配置参数。自 PHP 5.5.0 以来就已经不再使用。
  • Windows: 添加了 --with-config-profile 配置参数。 可用于保存细节配置，就像是神奇的 config.nice.bat 文件。

GD的变更

  • 当编译时使用了系统的 libgd，imageantialias() 也能生效。
  • imagegd() 以真彩色储存真彩色图像。在此之前，会转化为调色板图像。

移动 MCrypt 到 PECL

MCrypt 扩展从内核移动到 PECL。 考虑到 mcrypt 库自 2007 年以来未见任何更新，不再建议使用。 代替品即可以用 OpenSSL，也可以用 Sodium。

session_module_name()

传递给 session_module_name() 函数的模块名不允许为 "user"，将会抛出一个 E_RECOVERABLE_ERROR，之前版本会忽略这个问题。

User Contributed Notes

There are no user contributed notes for this page.


从 PHP 7.0.x 移植到 PHP 7.1.x

Table of Contents

  • 新特性
  • 新的函数
  • 新增的全局常量
  • 不向后兼容的变更
  • PHP 7.1.x 中废弃的特性
  • 变动的函数
  • 其它改动
  • Windows 支持

这个新的小版本带来了大量的 新特性和 少量的兼容性调整 在生产环境切换 PHP 版本前应该进行相关测试。

参见 PHP 版本迁移指南 7.0.x。

User Contributed Notes

There are no user contributed notes for this page.


新特性

可为空（Nullable）类型

参数以及返回值的类型现在可以通过在类型前加上一个问号使之允许为空。 当启用这个特性时，传入的参数或者函数返回的结果要么是给定的类型，要么是 null 。

<?php

function testReturn(): ?string
{
    return 'elePHPant';
}

var_dump(testReturn());

function testReturn(): ?string
{
    return null;
}

var_dump(testReturn());

function test(?string $name)
{
    var_dump($name);
}

test('elePHPant');
test(null);
test();

以上例程会输出：

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Void 函数

一个新的返回值类型void被引入。 返回值声明为 void 类型的方法要么干脆省去 return 语句，要么使用一个空的 return 语句。 对于 void 函数来说，null 不是一个合法的返回值。

<?php
function swap(&$left, &$right) : void
{
    if ($left === $right) {
        return;
    }

    $tmp = $left;
    $left = $right;
    $right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

以上例程会输出：

null
int(2)
int(1)

试图去获取一个 void 方法的返回值会得到 null ，并且不会产生任何警告。这么做的原因是不想影响更高层次的方法。

Symmetric array destructuring

短数组语法（[]）现在作为list()语法的一个备选项，可以用于将数组的值赋给一些变量（包括在foreach中）。

<?php
$data = [
    [1, 'Tom'],
    [2, 'Fred'],
];

// list() style
list($id1, $name1) = $data[0];

// [] style
[$id1, $name1] = $data[0];

// list() style
foreach ($data as list($id, $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as [$id, $name]) {
    // logic here with $id and $name
}

类常量可见性

现在起支持设置类常量的可见性。

<?php
class ConstDemo
{
    const PUBLIC_CONST_A = 1;
    public const PUBLIC_CONST_B = 2;
    protected const PROTECTED_CONST = 3;
    private const PRIVATE_CONST = 4;
}

iterable 伪类

现在引入了一个新的被称为iterable的伪类 (与callable类似)。 这可以被用在参数或者返回值类型中，它代表接受数组或者实现了Traversable接口的对象。 至于子类，当用作参数时，子类可以收紧父类的iterable类型到array 或一个实现了Traversable的对象。对于返回值，子类可以拓宽父类的 array或对象返回值类型到iterable。

<?php
function iterator(iterable $iter)
{
    foreach ($iter as $val) {
        //
    }
}

多异常捕获处理

一个catch语句块现在可以通过管道字符(|)来实现多个异常的捕获。 这对于需要同时处理来自不同类的不同异常时很有用。

<?php
try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
}

list()现在支持键名

现在list()和它的新的[]语法支持在它内部去指定键名。这意味着它可以将任意类型的数组 都赋值给一些变量（与短数组语法类似）

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];

// list() style
list("id" => $id1, "name" => $name1) = $data[0];

// [] style
["id" => $id1, "name" => $name1] = $data[0];

// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
    // logic here with $id and $name
}

支持为负的字符串偏移量

现在所有支持偏移量的字符串操作函数 都支持接受负数作为偏移量，包括通过[]或{}操作字符串下标。在这种情况下，一个负数的偏移量会被理解为一个从字符串结尾开始的偏移量。

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

以上例程会输出：

string (1) "e"
int(3)

Negative string and array offsets are now also supported in the simple variable parsing syntax inside of strings.

<?php
$string = 'bar';
echo "The last character of '$string' is '$string[-1]'.\n";
?>

以上例程会输出：

The last character of 'bar' is 'r'.

ext/openssl 支持 AEAD

通过给openssl_encrypt()和openssl_decrypt() 添加额外参数，现在支持了AEAD (模式 GCM and CCM)。

通过 Closure::fromCallable() 将callables转为闭包

Closure新增了一个静态方法，用于将callable快速地 转为一个Closure 对象。

<?php
class Test
{
    public function exposeFunction()
    {
        return Closure::fromCallable([$this, 'privateFunction']);
    }

    private function privateFunction($param)
    {
        var_dump($param);
    }
}

$privFunc = (new Test)->exposeFunction();
$privFunc('some value');

以上例程会输出：

string(10) "some value"

异步信号处理

一个新的名为 pcntl_async_signals() 的方法现在被引入， 用于启用无需 ticks （这会带来很多额外的开销）的异步信号处理。

<?php
pcntl_async_signals(true); // turn on async signals

pcntl_signal(SIGHUP,  function($sig) {
    echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

以上例程会输出：

SIGHUP

HTTP/2 server push support in ext/curl

对服务器推送的支持现在已经被加入到 CURL 扩展中（ 需要版本 7.46 或更高）。这个可以通过 curl_multi_setopt() 函数与新的常量 CURLMOPT_PUSHFUNCTION 来进行调节。常量 CURL_PUST_OK 和 CURL_PUSH_DENY 也已经被添加进来，以便服务器推送的回调函数来表明自己会同意或拒绝处理。

套接字上下文选项

新增 tcp_nodelay 选项。

User Contributed Notes

DYM 09-Apr-2018 10:36
<?php
function swap( &$a, &$b ): void
  { [ $a, $b ] = [ $b, $a ]; }
?>
unti1x 06-Apr-2018 11:20
Note that declaring nullable return type does not mean that you can skip return statement at all. For example:

php > function a(): ?string { }
php > a();
PHP Warning:  Uncaught TypeError: Return value of a() must be of the type string or null, none returned in php shell code:2

php > function b(): ?string { return; }
PHP Fatal error:  A function with return type must return a value (did you mean "return null;" instead of "return;"?) in php shell code on line 2


新的函数

PHP Core

  • sapi_windows_cp_get()
  • sapi_windows_cp_set()
  • sapi_windows_cp_conv()
  • sapi_windows_cp_is_utf8()

Closure

  • Closure::fromCallable()

CURL

  • curl_multi_errno()
  • curl_share_errno()
  • curl_share_strerror()

OpenSSL

  • openssl_get_curve_names()

Session

  • session_create_id()
  • session_gc()

SPL

  • is_iterable()

PCNTL

  • pcntl_async_signals()
  • pcntl_signal_get_handler()

User Contributed Notes

There are no user contributed notes for this page.


新增的全局常量

PHP 核心中预定义的常量

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Data Filtering

  • FILTER_FLAG_EMAIL_UNICODE

Image Processing and GD

  • IMAGETYPE_WEBP

JSON

  • JSON_UNESCAPED_LINE_TERMINATORS

LDAP

  • LDAP_OPT_X_SASL_NOCANON
  • LDAP_OPT_X_SASL_USERNAME
  • LDAP_OPT_X_TLS_CACERTDIR
  • LDAP_OPT_X_TLS_CACERTFILE
  • LDAP_OPT_X_TLS_CERTFILE
  • LDAP_OPT_X_TLS_CIPHER_SUITE
  • LDAP_OPT_X_TLS_KEYFILE
  • LDAP_OPT_X_TLS_RANDOM_FILE
  • LDAP_OPT_X_TLS_CRLCHECK
  • LDAP_OPT_X_TLS_CRL_NONE
  • LDAP_OPT_X_TLS_CRL_PEER
  • LDAP_OPT_X_TLS_CRL_ALL
  • LDAP_OPT_X_TLS_DHFILE
  • LDAP_OPT_X_TLS_CRLFILE
  • LDAP_OPT_X_TLS_PROTOCOL_MIN
  • LDAP_OPT_X_TLS_PROTOCOL_SSL2
  • LDAP_OPT_X_TLS_PROTOCOL_SSL3
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_0
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_1
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
  • LDAP_OPT_X_TLS_PACKAGE
  • LDAP_OPT_X_KEEPALIVE_IDLE
  • LDAP_OPT_X_KEEPALIVE_PROBES
  • LDAP_OPT_X_KEEPALIVE_INTERVAL

PostgreSQL

  • PGSQL_NOTICE_LAST
  • PGSQL_NOTICE_ALL
  • PGSQL_NOTICE_CLEAR

SPL

  • MT_RAND_PHP

User Contributed Notes

There are no user contributed notes for this page.


不向后兼容的变更

当传递参数过少时将抛出错误

在过去如果我们调用一个用户定义的函数时，提供的参数不足，那么将会产生一个警告(warning)。 现在，这个警告被提升为一个错误异常(Error exception)。这个变更仅对用户定义的函数生效， 并不包含内置函数。例如：

<?php
function test($param){}
test();

以上例程在 PHP 5.5 中的输出：

Uncaught Error: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

Forbid dynamic calls to scope introspection functions

Dynamic calls for certain functions have been forbidden (in the form of $func() or array_map('extract', ...), etc). These functions either inspect or modify another scope, and present with them ambiguous and unreliable behavior. The functions are as follows:

  • assert() - with a string as the first argument
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - with one arg
  • parse_str() - with one arg
<?php
(function () {
    'func_num_args'();
})();

以上例程会输出：

Warning: Cannot call func_num_args() dynamically in %s on line %d

Invalid class, interface, and trait names

The following names cannot be used to name classes, interfaces, or traits:

  • void
  • iterable

Numerical string conversions now respect scientific notation

Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().

Fixes to mt_rand() algorithm

mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_srand() was relied upon, then the MT_RAND_PHP with the ability to preserve the old (incorrect) implementation via an additional optional second parameter to mt_srand().

rand() aliased to mt_rand() and srand() aliased to mt_srand()

rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changes: rand(), shuffle(), str_shuffle(), and array_rand().

Disallow the ASCII delete control character in identifiers

The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.

error_log changes with syslog value

If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.

在不完整的对象上不再调用析构方法

析构方法在一个不完整的对象（例如在构造方法中抛出一个异常）上将不再会被调用。

call_user_func()不再支持对传址的函数的调用

call_user_func() 现在在调用一个以引用作为参数的函数时将始终失败。

字符串不再支持空索引操作符 The empty index operator is not supported for strings anymore

对字符串使用一个空索引操作符（例如$str[] = $x）将会抛出一个致命错误， 而不是静默地将其转为一个数组。

ini配置项移除

下列ini配置项已经被移除：

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

以上例程在 PHP 7.0 中的输出：

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

以上例程在 PHP 7.1 中的输出：

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Note:

Don't rely on the order of elements which compare as equal; it might change anytime.

Error message for E_RECOVERABLE errors

The error message for E_RECOVERABLE errors has been changed from "Catchable fatal error" to "Recoverable fatal error".

$options parameter of unserialize()

The allowed_classes element of the $options parameter of unserialize() is now strictly typed, i.e. if anything other than an array or a boolean is given, unserialize() returns false and issues an E_WARNING.

DateTime constructor incorporates microseconds

DateTime and DateTimeImmutable now properly incorporate microseconds when constructed from the current time, either explicitly or with a relative string (e.g. "first day of next month"). This means that naive comparisons of two newly created instances will now more likely return false instead of true:

<?php
new DateTime() == new DateTime();
?>

Fatal errors to Error exceptions conversions

In the Date extension, invalid serialization data for DateTime or DatePeriod classes, or timezone initialization failure from serialized data, will now throw an Error exception from the __wakeup() or __set_state() methods, instead of resulting in a fatal error.

In the DBA extension, data modification functions (such as dba_insert()) will now throw an Error exception instead of triggering a catchable fatal error if the key does not contain exactly two elements.

In the DOM extension, invalid schema or RelaxNG validation contexts will now throw an Error exception instead of resulting in a fatal error. Similarly, attempting to register a node class that does not extend the appropriate base class, or attempting to read an invalid property or write to a readonly property, will also now throw an Error exception.

In the IMAP extension, email addresses longer than 16385 bytes will throw an Error exception instead of resulting in a fatal error.

In the Intl extension, failing to call the parent constructor in a class extending Collator before invoking the parent methods will now throw an Error instead of resulting in a recoverable fatal error. Also, cloning a Transliterator object will now throw an Error exception on failure to clone the internal transliterator instead of resulting in a fatal error.

In the LDAP extension, providing an unknown modification type to ldap_batch_modify() will now throw an Error exception instead of resulting in a fatal error.

In the mbstring extension, the mb_ereg() and mb_eregi() functions will now throw a ParseError exception if an invalid PHP expression is provided and the 'e' option is used.

In the Mcrypt extension, the mcrypt_encrypt() and mcrypt_decrypt() will now throw an Error exception instead of resulting in a fatal error if mcrypt cannot be initialized.

In the mysqli extension, attempting to read an invalid property or write to a readonly property will now throw an Error exception instead of resulting in a fatal error.

In the Reflection extension, failing to retrieve a reflection object or retrieve an object property will now throw an Error exception instead of resulting in a fatal error.

In the Session extension, custom session handlers that do not return strings for session IDs will now throw an Error exception instead of resulting in a fatal error when a function is called that must generate a session ID.

In the SimpleXML extension, creating an unnamed or duplicate attribute will now throw an Error exception instead of resulting in a fatal error.

In the SPL extension, attempting to clone an SplDirectory object will now throw an Error exception instead of resulting in a fatal error. Similarly, calling ArrayIterator::append() when iterating over an object will also now throw an Error exception.

In the standard extension, the assert() function, when provided with a string argument as its first parameter, will now throw a ParseError exception instead of resulting in a catchable fatal error if the PHP code is invalid. Similarly, calling forward_static_call() outside of a class scope will now throw an Error exception.

In the Tidy extension, creating a tidyNode manually will now throw an Error exception instead of resulting in a fatal error.

In the WDDX extension, a circular reference when serializing will now throw an Error exception instead of resulting in a fatal error.

In the XML-RPC extension, a circular reference when serializing will now throw an instance of Error exception instead of resulting in a fatal error.

In the Zip extension, the ZipArchive::addGlob() method will now throw an Error exception instead of resulting in a fatal error if glob support is not available.

Lexically bound variables cannot reuse names

Variables bound to a closure via the use construct cannot use the same name as any superglobals, $this, or any parameter. For example, all of these function definition will result in a fatal error:

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

JSON encoding and decoding

The serialize_precision ini setting now controls the serialization precision when encoding doubles.

Decoding an empty key now results in an empty property name, rather than _empty_ as a property name.

<?php
var_dump(json_decode(json_encode(['' => 1])));

以上例程的输出类似于：

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

When supplying the JSON_UNESCAPED_UNICODE flag to json_encode(), the sequences U+2028 and U+2029 are now escaped.

Changes to mb_ereg() and mb_eregi() parameter semantics

The third paramter to the mb_ereg() and mb_eregi() functions (regs) will now be set to an empty array if nothing was matched. Formely, the parameter would not have been modified.

Drop support for the sslv2 stream

The sslv2 stream has now been dropped in OpenSSL.

User Contributed Notes

david at artefactual dot com 04-Apr-2019 05:29
Regarding the ArgumentCountError, PHP 7.1+ does still support user functions with a variable number of arguments, using the "func(...$args) {}" syntax, see: https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
mikem at gmail dot com 21-Nov-2017 12:09
ArgumentCountError - this modification is the main reason to avoid this version on older projects.
kees at twekaers dot net 21-Mar-2017 11:49
The backwards incompatible change 'The empty index operator is not supported for strings anymore' has a lot more implications than just a fatal error on the following code

<?php
$a = "";
$a[] = "hello world";
var_dump($a);
?>

This will give a fatal error in 7.1 but will work as expected in 7.0 or below and give you: (no notice, no warning)

array(1) {
  [0]=>
  string(11) "hello world"
}

However, the following is also changed:

<?php
$a = "";
$a[0] = "hello world";
var_dump($a);
// 7.1: string(1) "h"
// pre-7.1: array(1) {  [0]=>  string(11) "hello world" }

$a = "";
$a[5] = "hello world";
var_dump($a);
// 7.1: string(6) "     h"
// pre-7.1: array(1) {  [0]=>  string(11) "hello world" }

?>
m dot r dot sopacua at gmail dot com 30-Dec-2016 03:49
"OMFG! Why was session.hash_function removed?!? Dude!"

https://wiki.php.net/rfc/session-id-without-hashing

There. Saved ya a search.
love at sickpeople dot se 24-Nov-2016 07:59
For anyone migrating from 5.x to 7.1:

About "Array ordering when elements are automatically created during by reference assignments has changed" on this page

(http://php.net/manual/en/migration71.incompatible.php#migration71.incompatible.array-order)

The behaviour of 7.1 is THE SAME as of PHP 5. It is only 7.0 that differs.

See https://3v4l.org/frbUc

<?php

$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);


PHP 7.1.x 中废弃的特性

ext/mcrypt

mcrypt 扩展已经过时了大约10年，并且用起来很复杂。因此它被废弃并且被 OpenSSL 所取代。 从PHP 7.2起它将被从核心代码中移除并且移到PECL中。

mb_ereg_replace()和mb_eregi_replace()的Eval选项

对于mb_ereg_replace()和mb_eregi_replace()的 e模式修饰符现在已被废弃。

User Contributed Notes

There are no user contributed notes for this page.


变动的函数

PHP 核心

  • getopt() 函数增加了第三个参数，这是一个可选参数。 通过以引用的方式传入参数， 它可以用来存储参数列表中下一个参数的下标位置。
  • getenv() 可以不传入任何参数。 如果不传入参数，此函数会以关联数组的形式 返回所有的环境变量。
  • get_headers() 增加了一个参数， 可以用来解析自定义的流上下文。
  • output_reset_rewrite_vars() 函数不再重置会话 URL 重写变量了。
  • parse_url() 更加严格的限制， 并且提供对 RFC3986 的支持。
  • unpack() 函数增加第三个参数， 这是一个可选参数，用来指定开始解包的位置。

文件系统

  • file_get_contents() 接受负数作为搜索偏移量， 前提是流上下文必须是可搜索的。
  • tempnam() 会在退回使用系统临时目录的时候，产生警告。

JSON

  • json_encode() 增加新的选项： JSON_UNESCAPED_LINE_TERMINATORS。 这个选项可以在指定 JSON_UNESCAPED_UNICODE 选项的时候， 对于 U+2028 和 U+2029 这两个字符不再进行转义。

多子节字符

  • mb_ereg() 不接受无效的字节序列。
  • mb_ereg_replace() 不接受无效的字节序列。

PDO

  • PDO::lastInsertId() 在用于 PostgreSQL 数据库的时候， 如果当前会话（到 PostgreSQL 的数据库连接）上尚未调用过 nextval， 那么此方法会触发一个错误。

PostgreSQL

  • pg_last_notice() 增加一个用来指定操作的可选参数。 可使用以下常量作为此参数的值： PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL 或 PGSQL_NOTICE_CLEAR。
  • pg_fetch_all() 增加第二个参数，这是一个可选参数， 它用来指定返回结果的类型 （类似于 pg_fetch_array() 的第三个参数）。
  • pg_select() 增加第四个参数，这是一个可选参数， 它用来指定返回结果的类型 （类似于 pg_fetch_array() 的第三个参数）。

Session

  • session_start() 当无法成功初始化会话的时候，返回 false， 并且不会初始化超级变量 $_SESSION。

User Contributed Notes

There are no user contributed notes for this page.


其它改动

无效字符串计算的通知和警告

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

<?php
'1b' + 'something';

以上例程会输出：

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

八进制转义序列溢出时发出警告

Previously, 3-octet octal string escape sequences would overflow silently. Now, they will still overflow, but E_WARNING will be emitted.

<?php
var_dump("\500");

以上例程会输出：

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

$this 不一致的修正

Whilst $this is considered a special variable in PHP, it lacked proper checks to ensure it wasn't used as a variable name or reassigned. This has now been rectified to ensure that $this cannot be a user-defined variable, reassigned to a different value, or be globalised.

无需散列即可生成 Session ID

Session ID 将不再在生成时进行哈希。这一变化，会导致以下四个 ini 设置不再使用：

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

并增加以下两个 ini 设置：

  • session.sid_length - 定义会话 ID 的长度（为了向后兼容，默认为 32 个字符）
  • session.sid_bits_per_character - 定义了每个字符的存储位数（即增加了会话 ID 中可使用的字符范围），为了向后兼容，默认为 4

INI 文件处理的变化

precision

If the value is set to -1, then the dtoa mode 0 is used. The default value is still 14.

serialize_precision

If the value is set to -1, then the dtoa mode 0 is used. The value -1 is now used by default.

gd.jpeg_ignore_warning

The default of this php.ini setting has been changed to 1, so by default libjpeg warnings are ignored.

opcache.enable_cli

The default of this php.ini setting has been changed to 1 (enabled) in PHP 7.1.2, and back to 0 (disabled) in PHP 7.1.7.

Session ID generation with a CSPRNG only

Session IDs will now only be generated with a CSPRNG.

More informative TypeError messages when null is allowed

TypeError exceptions for arg_info type checks will now provide more informative error messages. If the parameter type or return type accepts null (by either having a default value of null or being a nullable type), then the error message will now mention this with a message of "must be ... or null" or "must ... or be null."

User Contributed Notes

Ta7To7 27-Feb-2018 05:47
Note that using Incrementing/Decrementing operators on string is legal
<?php
$str = "";
echo ++$str; // output: 1
?>


Windows 支持

Support for long and UTF-8 path

If a web application is UTF-8 conform, no further action is required. For applications depending on paths in non UTF-8 encodings for I/O, an explicit INI directive has to be set. The encoding INI settings check relies on the order in the core:

  • internal_encoding
  • default_charset
  • zend.multibyte

Several functions for codepage handling were introduced:

  • sapi_windows_cp_set() to set the default codepage
  • sapi_windows_cp_get() to retrieve the current codepage
  • sapi_windows_cp_is_utf8()
  • sapi_windows_cp_conv() to convert between codepages, using iconv() compatible signature

These functions are thread safe.

The console output codepage is adjusted depending on the encoding used in PHP. Depending on the concrete system OEM codepage, the visible output might or might be not correct. For example, in the default cmd.exe and on a system with the OEM codepage 437, outputs in codepages 1251, 1252, 1253 and some others can be shown correctly when using UTF-8. On the same system, chars in codepage like 20932 probably won't be shown correctly. This refers to the particular system rules for codepage, font compatibility and the particular console program used. PHP automatically sets the console codepage according to the encoding rules from php.ini. Using alternative consoles instead of cmd.exe directly might bring better experience in some cases.

Nevertheless be aware, runtime codepage switch after the request start might bring unexpected side effects on CLI. The preferable way is php.ini, When PHP CLI is used in a console emulator, that doesn't support Unicode, it might possibly be required, to avoid changing the console codepage. The best way to achieve it is by setting the default or internal encoding to correspond the ANSI codepage. Another method is to set the INI directives output_encoding and input_encoding to the required codepage, in which case however the difference between internal and I/O codepage is likely to cause mojibake. In rare cases, if PHP happens to crash gracefully, the original console codepage might be not restored. In this case, the chcp command can be used, to restore it manually.

Special awareness for the DBCS systems - the codepage switch on runtime using ini_set() is likely to cause display issues. The difference to the non DBCS systems is, that the extended characters require two console cells to be displayed. In certain case, only the mapping of the characters into the glyph set of the font could happen, no actual font change. This is the nature of DBCS systems, the most simple way to prevent display issues is to avoid usage of ini_set() for the codepage change.

As a result of UTF-8 support in the streams, PHP scripts are not limited to ASCII or ANSI filenames anymore. This is supported out of the box on CLI. For other SAPI, the documentation for the corresponding server is useful.

Long paths support is transparent. Paths longer than 260 bytes get automatically prefixed with \\?\. The max path length is limited to 2048 bytes. Be aware, that the path segment limit (basename length) still persists.

For the best portability, it is strongely recommended to handle filenames, I/O and other related topics UTF-8. Additionally, for the console applications, the usage of a TrueType font is preferable and the usage of ini_set() for the codepage change is discouraged.

readline

readline 扩展 现在通过 » WinEditLine 库 来实现了支持。因此，一个交互式的 CLI 命令行也得到了支持。(php.exe -a)。

PHP_FCGI_CHILDREN

PHP_FCGI_CHILDREN is now respected. If this environment variable is defined, the first php-cgi.exe process will exec the specified number of children. These will share the same TCP socket.

ftok()

Added support for ftok()

User Contributed Notes

There are no user contributed notes for this page.


从 PHP 5.6.x 移植到 PHP 7.0.x

Table of Contents

  • 不向后兼容的变更
  • 新特性
  • PHP 7.0.x 弃用的功能
  • 变更的函数
  • 新函数
  • 新的类和接口
  • 新的全局常量
  • SAPI 模块的变化
  • 移除的扩展和 SAPI
  • Other Changes

尽管 PHP 7.0 是一个新的大版本，我们仍将致力于使迁移变得平缓。 这个版本主要消除在之前版本中不推荐使用的内容，使得语言变得更加通用一致。

这儿有一些值得关注的 少量的兼容性调整 以及 新的特性，同时在生产环境切换 PHP 版本之前，应该对代码进行测试。

User Contributed Notes

There are no user contributed notes for this page.


不向后兼容的变更

错误和异常处理相关的变更

在 PHP 7 中，很多致命错误以及可恢复的致命错误，都被转换为异常来处理了。 这些异常继承自 Error 类，此类实现了 Throwable 接口 （所有异常都实现了这个基础接口）。

这也意味着，当发生错误的时候，以前代码中的一些错误处理的代码将无法被触发。 因为在 PHP 7 版本中，已经使用抛出异常的错误处理机制了。 （如果代码中没有捕获 Error 异常，那么会引发致命错误）。

PHP 7 中的错误处理的更完整的描述，请参见 PHP 7 错误处理。 本迁移指导主要是列出对兼容性有影响的变更。

set_exception_handler() 不再保证收到的一定是 Exception 对象

抛出 Error 对象时，如果 set_exception_handler() 里的异常处理代码声明了类型 Exception ，将会导致 fatal error。

想要异常处理器同时支持 PHP5 和 PHP7，应该删掉异常处理器里的类型声明。如果代码仅仅是升级到 PHP7，则可以把类型 Exception 替换成 Throwable。

<?php
// PHP 5 时代的代码将会出现问题
function handler(Exception $e) { ... }
set_exception_handler('handler');

// 兼容 PHP 5 和 7
function handler($e) { ... }

// 仅支持 PHP 7
function handler(Throwable $e) { ... }
?>

当内部构造器失败的时候，总是抛出异常

在之前版本中，如果内部类的构造器出错，会返回 null 或者一个不可用的对象。 从 PHP 7 开始，如果内部类构造器发生错误， 那么会抛出异常。

解析错误会抛出 ParseError 异常

解析错误会抛出 ParseError 异常。 对于 eval() 函数，需要将其包含到一个 catch 代码块中来处理解析错误。

E_STRICT 警告级别变更

原有的 E_STRICT 警告都被迁移到其他级别。 E_STRICT 常量会被保留，所以调用 error_reporting(E_ALL|E_STRICT) 不会引发错误。

E_STRICT 警告级别变更
场景 | 新的级别/行为
将资源类型的变量用作键来进行索引 | E_NOTICE
抽象静态方法 | 不再警告，会引发错误
重复定义构造器函数 | 不再警告，会引发错误
在继承的时候，方法签名不匹配 | E_WARNING
在两个 trait 中包含相同的（兼容的）属性 | 不再警告，会引发错误
以非静态调用的方式访问静态属性 | E_NOTICE
变量应该以引用的方式赋值 | E_NOTICE
变量应该以引用的方式传递（到函数参数中） | E_NOTICE
以静态方式调用实例方法 | E_DEPRECATED

关于变量处理的变化

PHP 7 现在使用了抽象语法树来解析源代码。这使得许多由于之前的PHP的解释器的限制所不可能实现的改进得以实现。 但出于一致性的原因导致了一些特殊例子的变动，而这些变动打破了向后兼容。 在这一章中将详细介绍这些例子。

关于间接使用变量、属性和方法的变化

对变量、属性和方法的间接调用现在将严格遵循从左到右的顺序来解析，而不是之前的混杂着几个特殊案例的情况。 下面这张表说明了这个解析顺序的变化。

间接调用的表达式的新旧解析顺序
表达式 | PHP 5 的解析方式 | PHP 7 的解析方式
$$foo['bar']['baz'] | ${$foo['bar']['baz']} | ($$foo)['bar']['baz']
$foo->$bar['baz'] | $foo->{$bar['baz']} | ($foo->$bar)['baz']
$foo->$bar['baz']() | $foo->{$bar['baz']}() | ($foo->$bar)['baz']()
Foo::$bar['baz']() | Foo::{$bar['baz']}() | (Foo::$bar)['baz']()

使用了旧的从右到左的解析顺序的代码必须被重写，明确的使用大括号来表明顺序（参见上表中间一列）。 这样使得代码既保持了与PHP 7.x的前向兼容性，又保持了与PHP 5.x的后向兼容性。

这同样影响了 global 关键字。如果需要的话可以使用大括号来模拟之前的行为。

<?php
function f() {
    // Valid in PHP 5 only.
    global $$foo->bar;

    // Valid in PHP 5 and 7.
    global ${$foo->bar};
}
?>

关于list()处理方式的变更

list() 不再以反向的顺序来进行赋值

list() 现在会按照变量定义的顺序来给他们进行赋值，而非反过来的顺序。 通常来说，这只会影响list() 与数组的[]操作符一起使用的案例，如下所示：

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

以上例程在 PHP 5 中的输出：

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

以上例程在 PHP 7 中的输出：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

总之，我们推荐不要依赖list()的赋值顺序，因为这是一个在未来也许会变更的实现细节。

空的list()赋值支持已经被移除

list() 结构现在不再能是空的。如下的例子不再被允许：

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
list()不再能解开string

list() 不再能解开字符串（string）变量。 你可以使用str_split()来代替它。

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

以上例程在 PHP 5 中的输出：

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

以上例程在 PHP 7 中的输出：

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

函数参数附近的括号不再影响行为

在 PHP 5中，在以引用方式传递函数参数时，使用冗余的括号对可以隐匿严格标准 的警告。现在，这个警告总会触发。

<?php
function getArray() {
    return [1, 2, 3];
}

function squareArray(array &$a) {
    foreach ($a as &$v) {
        $v **= 2;
    }
}

// Generates a warning in PHP 7.
squareArray((getArray()));
?>

以上例程会输出：

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

foreach的变化

foreach发生了细微的变化，控制结构， 主要围绕阵列的内部数组指针和迭代处理的修改。

foreach不再改变内部数组指针

在PHP7之前，当数组通过 foreach 迭代时，数组指针会移动。现在开始，不再如此，见下面代码

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
    var_dump(current($array));
}
?>

以上例程在 PHP 5 中的输出：

int(1)
int(2)
bool(false)

以上例程在 PHP 7 中的输出：

int(0)
int(0)
int(0)

foreach 通过值遍历时，操作的值为数组的副本

当默认使用通过值遍历数组时，foreach 实际操作的是数组的迭代副本，而非数组本身。这就意味着，foreach 中的操作不会修改原数组的值。

foreach通过引用遍历时，有更好的迭代特性

当使用引用遍历数组时，现在 foreach 在迭代中能更好的跟踪变化。例如，在迭代中添加一个迭代值到数组中，参考下面的代码：

<?php
$array = [0];
foreach ($array as &$val) {
    var_dump($val);
    $array[1] = 1;
}
?>

以上例程在 PHP 5 中的输出：

int(0)

以上例程在 PHP 7 中的输出：

int(0)
int(1)

非Traversable 对象的遍历

迭代一个非Traversable对象将会与迭代一个引用数组的行为相同。 这将导致在对象添加或删除属性时， foreach通过引用遍历时，有更好的迭代特性也能被应用

Changes to integer handling

无效的八进制字符（Invalid octal literals）

在之前，一个八进制字符如果含有无效数字，该无效数字将被静默删节(0128 将被解析为 012). 现在这样的八进制字符将产生解析错误。

负位移运算（Negative bitshifts）

以负数形式进行的位移运算将会抛出一个 ArithmeticError：

<?php
var_dump(1 >> -1);
?>

以上例程在 PHP 5 中的输出：

int(0)

以上例程在 PHP 7 中的输出：

Fatal error: Uncaught ArithmeticError: Bit shift by negative number in /tmp/test.php:2
Stack trace:
#0 {main}
  thrown in /tmp/test.php on line 2

超范围后产生位移

超出 integer 位宽的位移操作（无论哪个方向）将始终得到 0 作为结果。在从前，这一操作是结构依赖的。

除以零的变化

之前的版本中，当 0 被做为除数时，无论是除数 (/) 或取模 (%) 操作，都会抛出一个 E_WARNING 错误并返回 false。现在，除法运算符 (/) 会返回一个由 IEEE 754 指定的浮点数：+INF, -INF 或 NAN。取模操作符 (%) 则会抛出一个 DivisionByZeroError 异常，并且不再产生 E_WARNING 错误。

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

以上例程在 PHP 5 中的输出：

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

以上例程在 PHP 7 中的输出：

Warning: Division by zero in %s on line %d
float(INF)

Warning: Division by zero in %s on line %d
float(NAN)

PHP Fatal error:  Uncaught DivisionByZeroError: Modulo by zero in %s line %d

string处理上的调整

十六进制字符串不再被认为是数字

含十六进制字符串不再被认为是数字。例如：

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

以上例程在 PHP 5 中的输出：

bool(true)
bool(true)
int(15)
string(2) "oo"

以上例程在 PHP 7 中的输出：

bool(false)
bool(false)
int(0)

Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

filter_var() 函数可以用于检查一个 string 是否含有十六进制数字,并将其转换为integer:

<?php
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
    throw new Exception("Invalid integer!");
}
var_dump($int); // int(65535)
?>

\u{ 可能引起错误

由于新的 Unicode codepoint escape syntax语法， 紧连着无效序列并包含\u{ 的字串可能引起致命错误。 为了避免这一报错，应该避免反斜杠开头。

被移除的函数（Removed functions）

call_user_method() and call_user_method_array()

这两个函数从PHP 4.1.0 开始被废弃，应该使用 call_user_func() 和 call_user_func_array()。 你也可以考虑使用 变量函数 或者 ... 操作符。

所有的 ereg* 函数

所有 ereg 系列函数被删掉了。 PCRE 作为推荐的替代品。

mcrypt 别名

已废弃的 mcrypt_generic_end() 函数已被移除，请使用mcrypt_generic_deinit()代替。

此外，已废弃的 mcrypt_ecb(),
mcrypt_cbc(), mcrypt_cfb() 和
mcrypt_ofb() 函数已被移除，请配合恰当的MCRYPT_MODE_* 常量来使用 mcrypt_decrypt()进行代替。

所有 ext/mysql 函数

所有 ext/mysql 函数已被删掉了。 如何选择不同的 MySQL API，详情请见 选择 MySQL API。

所有 ext/mssql 函数

所有 ext/mssql 函数已被移除。

  • PDO_SQLSRV
  • PDO_ODBC
  • SQLSRV
  • Unified ODBC API

intl 别名

已废弃的 datefmt_set_timezone_id() 和
IntlDateFormatter::setTimeZoneID() 函数已被移除，请使用 datefmt_set_timezone() 与
IntlDateFormatter::setTimeZone()代替。

set_magic_quotes_runtime()

移除了 set_magic_quotes_runtime() 和它的别名 magic_quotes_runtime()。 它们在 PHP 5.3.0 中已经被废弃， 并由于 PHP 5.4.0 移除魔术引号（Magic Quotes）而没有用处。

set_socket_blocking()

已废弃的 set_socket_blocking() 函数已被移除，请使用stream_set_blocking()代替。

dl() in PHP-FPM

dl()在 PHP-FPM 不再可用，在 CLI 和 embed SAPIs 中仍可用。

GD Type1 functions

Support for PostScript Type1 fonts has been removed from the GD extension, resulting in the removal of the following functions:

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

推荐使用 TrueType 字体和相关的函数作为替代。

被移除掉的 INI 配置指令

被移除的功能

以下 INI 配置指令已经被移除，同时移除的还有其对应的功能

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

xsl.security_prefs 指令被移除 在预处理的时候，取而代之的方法 XsltProcessor::setSecurityPrefs() 应该被调用到

其他向后兼容相关的变更

new 操作符创建的对象不能以引用方式赋值给变量

new 语句创建的对象不能 以引用的方式赋值给变量。

<?php
class C {}
$c =& new C;
?>

以上例程在 PHP 5 中的输出：

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

以上例程在 PHP 7 中的输出：

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

无效的类、接口以及 trait 命名

不能以下列名字来命名类、接口以及 trait：

  • bool
  • int
  • float
  • string
  • null
  • true
  • false

此外，也不要使用下列的名字来命名类、接口以及 trait。虽然在 PHP 7.0 中， 这并不会引发错误， 但是这些名字是保留给将来使用的。

  • resource
  • object
  • mixed
  • numeric

移除了 ASP 和 script PHP 标签

使用类似 ASP 的标签，以及 script 标签来区分 PHP 代码的方式被移除。 受到影响的标签有：

被移除的 ASP 和 script 标签
开标签 | 闭标签
<% | %>
<%= | %>
<script language="php"> | </script>

从不匹配的上下文发起调用

在不匹配的上下文中以静态方式调用非静态方法， 在 PHP 5.6 中已经废弃， 但是在 PHP 7.0 中， 会导致被调用方法中未定义 $this 变量，以及此行为已经废弃的警告。

<?php
class A {
    public function test() { var_dump($this); }
}

// 注意：并没有从类 A 继承
class B {
    public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>

以上例程在 PHP 5.6 中的输出：

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

以上例程在 PHP 7 中的输出：

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8

Notice: Undefined variable: this in /tmp/test.php on line 3
NULL

yield 变更为右联接运算符

在使用 yield 关键字的时候，不再需要括号， 并且它变更为右联接操作符，其运算符优先级介于 print 和 => 之间。 这可能导致现有代码的行为发生改变：

<?php
echo yield -1;
// 在之前版本中会被解释为：
echo (yield) - 1;
// 现在，它将被解释为：
echo yield (-1);

yield $foo or die;
// 在之前版本中会被解释为：
yield ($foo or die);
// 现在，它将被解释为：
(yield $foo) or die;
?>

可以通过使用括号来消除歧义。

函数定义不可以包含多个同名参数

在函数定义中，不可以包含两个或多个同名的参数。 例如，下面代码中的函数定义会触发 E_COMPILE_ERROR 错误：

<?php
function foo($a, $b, $unused, $unused) {
    //
}
?>

Switch 语句不可以包含多个 default 块

在 switch 语句中，两个或者多个 default 块的代码已经不再被支持。 例如，下面代码中的 switch 语句会触发 E_COMPILE_ERROR 错误：

<?php
switch (1) {
    default:
    break;
    default:
    break;
}
?>

在函数中检视参数值会返回 当前 的值

当在函数代码中使用 func_get_arg() 或
func_get_args() 函数来检视参数值，
或者使用 debug_backtrace() 函数查看回溯跟踪，
以及在异常回溯中所报告的参数值是指参数当前的值（有可能是已经被函数内的代码改变过的值），
而不再是参数被传入函数时候的原始值了。

<?php
function foo($x) {
    $x++;
    var_dump(func_get_arg(0));
}
foo(1);?>

以上例程在 PHP 5 中的输出：

1

以上例程在 PHP 7 中的输出：

2

$HTTP_RAW_POST_DATA 被移除

不再提供 $HTTP_RAW_POST_DATA 变量。 请使用 php://input 作为替代。

INI 文件中 # 注释格式被移除

在 INI 文件中，不再支持以 # 开始的注释行， 请使用 ;（分号）来表示注释。 此变更适用于 php.ini 以及用 parse_ini_file() 和 parse_ini_string() 函数来处理的文件。

JSON 扩展已经被 JSOND 取代

JSON 扩展已经被 JSOND 扩展取代。 对于数值的处理，有以下两点需要注意的： 第一，数值不能以点号（.）结束 （例如，数值 34. 必须写作 34.0 或 34）。 第二，如果使用科学计数法表示数值，e 前面必须不是点号（.） （例如，3.e3 必须写作 3.0e3 或 3e3）。 另外，空字符串不再被视作有效的 JSON 字符串。

在数值溢出的时候，内部函数将会失败

将浮点数转换为整数的时候，如果浮点数值太大，导致无法以整数表达的情况下， 在之前的版本中，内部函数会直接将整数截断，并不会引发错误。 在 PHP 7.0 中，如果发生这种情况，会引发 E_WARNING 错误，并且返回 null。

自定义会话处理器的返回值修复

在自定义会话处理器中，如果函数的返回值不是 false，也不是 -1， 会引发致命错误。现在，如果这些函数的返回值不是布尔值，也不是 -1 或者 0，函数调用结果将被视为失败，并且引发 E_WARNING 错误。

相等的元素在排序时的顺序问题

由于内部排序算法进行了提升， 可能会导致对比时被视为相等的多个元素之间的顺序不稳定。

Note:

在对比时被视为相等的多个元素之间的排序顺序是不可信赖的，即使是相等的两个元素， 他们的位置也可能被排序算法所改变。

错误的使用 break 和 switch 语句

在循环或者 switch 语句之外使用 break 和 continue 被视为编译型错误（之前视为运行时错误），会引发 E_COMPILE_ERROR 错误。

Mhash 不再是一个单独的扩展了

Mhash 扩展已经被完全整合进 Hash 扩展了。
因此，不要再使用 extension_loaded() 函数来检测是否支持 MHash 扩展了，
建议使用 function_exists() 函数来进行检测。
另外，函数 get_loaded_extensions() 以及相关的特性中，也不再报告
和 MHash 扩展相关的信息了。

declare(ticks)

declare(ticks) 指示符不再泄漏到不同的编译单元中。

User Contributed Notes

ilya dot chase at yandex dot ru 30-Apr-2019 09:22
Take note that in preg_replace() function, flag '\e' was deleted in PHP 7.0.0. This function will return null always with this flag. Doc: https://www.php.net/manual/ru/function.preg-replace.php
tkondrashov at gmail dot com 02-Oct-2018 04:34
split() was also removed in 7.0, so be sure to check your old code for it as well as the functions listed in this doc
Ray.Paseur sometimes uses Gmail 23-Mar-2017 03:51
In the section captioned "Changes to the handling of indirect variables, properties, and methods" there are parentheses used in the table directly beneath "PHP 7 interpretation."

The parentheses are intended to show the evaluation order, but they are not part of the syntax, and should not be used in the variable definition or reference.  This juxtaposition confused one of my colleagues; hopefully this note will save someone else some time.

Examples of the correct curly-brace syntax is further down the page, in the section captioned "global only accepts simple variables."
viktor dot csiky at nospam dot nospam dot eu 21-Jul-2016 11:16
It is stated:

"foreach by-value operates on a copy of the array

When used in the default by-value mode, foreach will now operate on a copy of the array being iterated rather than the array itself. This means that changes to the array made during iteration will not affect the values that are iterated."

Please note that this is not exactly true. New foreach operates on a copy of the array, by-value or by-reference. It seems that in the latter case, the array copy is simply moved over (to) the original array before it is presumably destroyed.

As a consequence of this, you may not "dereference" an array containing values - e.g. for use with ReflectionMethod::invokeArgs() or the good ole' call_user_func().
Consider the snippet below:

<?php
function deref(Array $inputArray)
{
        $retVal = [];

        foreach ($inputArray as &$inputValue)
        {
            $retVal[] = $inputValue;
        }

        return $retVal;
}
?>

As of PHP 7.0, this *will no longer work*. You will get the usual suspect:

PHP Warning:  Parameter n to whatever() expected to be a reference, value given in baz.php on line x

You need to convert it to explicitly reference the original array:
<?php
function deref(Array $inputArray)
{
        $retVal = [];

        foreach ($inputArray as $inputKey => $inputValue)
        {
            $retVal[$inputKey] = &$inputArray[$inputKey];
        }

        return $retVal;
}
?>

PLEASE NOTE that this might have the unforeseen consequence of your code not working anymore in php versions less than 5.3 (that is, 5.2 and below).
maba at mb-systemhaus dot net 12-May-2016 09:52
NOTE:
the new variable handling in PHP 7 also has side effects on the COM .NET extension. Numeric variants (in the Windows application space) now must be quoted when passed over from PHP. This is the case when the receiving application expects a variable of type variant.

Here is an example:

<?php
  $word = new COM('Word.Application');

  // now load a document, ...

  // the following works in PHP 5 but will throw an exception in PHP 7
  $word->ActiveDocument->PrintOut(false, false, 0, $outfile);

  // the following works in PHP 7 as well, please note the quotes around the '0'
  $word->ActiveDocument->PrintOut(false, false, '0', $outfile);
?>
Frank 11-Apr-2016 03:40
[Editor's Note: that change is listed in the "Changed functions" section.]

The substr function has also been changed in a backward incompatible way.

<?php
substr("test",4);  # false in PHP 5,  "" in PHP 7
?>

In fact, this is the only thing we had to change in a number of places for our code base to run on PHP 7. It's definitely an improvement though, as the old behavior tended to cause bugs in border cases.
mossy2100 19-Dec-2015 05:29
Although $x/0 is technically not infinity in a purely mathematical sense, when you understand why the IEEE float includes a value for infinity, and returns infinity in this case, it makes sense that PHP would agree with this.

The reason is that programmers don't usually divide by 0 on purpose. A value of 0 as a divisor usually occurs due to underflow, i.e. a value which is too small to be represented as a float. So, for example, if you have values like:
$x = 1;
$y = 1e-15 * 1e-15;
$z = $x/$y;
Because $y will have underflowed to 0, the division operation will throw the division by zero warning, and $z will be set to INF. In a better computer, however, $y would not have the value 0 (it would be 1e-30) and $z would not have the value INF (it would be 1e30).

In other words, 0 is not only representative of an actual 0, but also a very small number which float cannot represent correctly (underflow), and INF does not only represent infinity, but also a very big number which float cannot represent correctly (overflow). We do the best we can within the limitations of floating point values, which are really just good approximations of the actual numbers being represented.

What does bother me is that division by zero is handled in two different ways depending on the operator. I would have preferred the new DivisionByZeroError exception to be thrown in all cases, for consistency and to enforce good programming practices.
tuxedobob 11-Dec-2015 09:23
As a programmer, I don't care whether 3/0 is INF or NaN. Both answers are (probably) equally useless, and tell me that something somewhere else is screwed up.
opitz dot alexander at googlemail dot com 04-Dec-2015 04:14
About the division by zero, please see discussion to IEEEE 754
For example: http://stackoverflow.com/questions/14682005/why-does-division-by-zero-in-ieee754-standard-results-in-infinite-value
me at fquff dot io 04-Dec-2015 06:45
[Editor's note: fixed limit on user request]

As a mathematician, 3/0 == +INF IS JUST WRONG. You can't just assume 3/0 == lim_{x->0+} 3/x, which is +INF indeed, because division IS NOT A CONTINUOUS FUNCTION in x == 0.

Also, 3/0 == +INF ("positive" infinity) while -3/0 == -INF ("negative" infinity) requires the assumption that 0 is a positive number, which is just as illogical as it looks like.

The fact that a warning is emitted is good, but it should definitely equals to NaN. ±INF is just illogical (and arithmetically wrong).

Except for this "detail", looks an amazing update, can't wait to test it even further!

Cheers,
P.


新特性

标量类型声明

标量类型声明 有两种模式: 强制 (默认) 和 严格模式。 现在可以使用下列类型参数（无论用强制模式还是严格模式）： 字符串(string), 整数 (int), 浮点数 (float), 以及布尔值 (bool)。它们扩充了PHP5中引入的其他类型：类名，接口，数组和 回调类型。

<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));

以上例程会输出：

int(9)

要使用严格模式，一个 declare 声明指令必须放在文件的顶部。这意味着严格声明标量是基于文件可配的。 这个指令不仅影响参数的类型声明，也影响到函数的返回值声明（参见 返回值类型声明, 内置的PHP函数以及扩展中加载的PHP函数）

完整的标量类型声明文档和示例参见类型声明章节。

返回值类型声明

PHP 7 增加了对返回类型声明的支持。 类似于参数类型声明，返回类型声明指明了函数返回值的类型。可用的类型与参数声明中可用的类型相同。

<?php

function arraysSum(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

以上例程会输出：

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

完整的标量类型声明文档和示例可参见 返回值类型声明.

null合并运算符

由于日常使用中存在大量同时使用三元表达式和 isset()的情况， 我们添加了null合并运算符 (??) 这个语法糖。如果变量存在且值不为null， 它就会返回自身的值，否则返回它的第二个操作数。

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalesces can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

太空船操作符（组合比较符）

太空船操作符用于比较两个表达式。当$a小于、等于或大于$b时它分别返回-1、0或1。 比较的原则是沿用 PHP 的常规比较规则进行的。

<?php
// 整数
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// 浮点数
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// 字符串
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

通过 define() 定义常量数组

Array 类型的常量现在可以通过 define() 来定义。在 PHP5.6 中仅能通过 const 定义。

<?php
define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // 输出 "cat"
?>

匿名类

现在支持通过new class 来实例化一个匿名类，这可以用来替代一些"用后即焚"的完整类定义。

<?php
interface Logger {
    public function log(string $msg);
}

class Application {
    private $logger;

    public function getLogger(): Logger {
         return $this->logger;
    }

    public function setLogger(Logger $logger) {
         $this->logger = $logger;
    }
}

$app = new Application;
$app->setLogger(new class implements Logger {
    public function log(string $msg) {
        echo $msg;
    }
});

var_dump($app->getLogger());
?>

以上例程会输出：

object(class@anonymous)#2 (0) {
}

详细文档可以参考 匿名类.

Unicode codepoint 转译语法

这接受一个以16进制形式的 Unicode codepoint，并打印出一个双引号或heredoc包围的 UTF-8 编码格式的字符串。 可以接受任何有效的 codepoint，并且开头的 0 是可以省略的。

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

以上例程会输出：

a
a (same as before but with optional leading 0's)
香

Closure::call()

Closure::call() 现在有着更好的性能，简短干练的暂时绑定一个方法到对象上闭包并调用它。

<?php
class A {private $x = 1;}

// PHP 7 之前版本的代码
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // 中间层闭包
echo $getX();

// PHP 7+ 及更高版本的代码
$getX = function() {return $this->x;};
echo $getX->call(new A);

以上例程会输出：

1
1

为unserialize()提供过滤

这个特性旨在提供更安全的方式解包不可靠的数据。它通过白名单的方式来防止潜在的代码注入。

<?php

// 将所有的对象都转换为 __PHP_Incomplete_Class 对象
$data = unserialize($foo, ["allowed_classes" => false]);

// 将除 MyClass 和 MyClass2 之外的所有对象都转换为 __PHP_Incomplete_Class 对象
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]);

// 默认情况下所有的类都是可接受的，等同于省略第二个参数
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

新增加的 IntlChar 类旨在暴露出更多的 ICU 功能。这个类自身定义了许多静态方法用于操作多字符集的 unicode 字符。

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

以上例程会输出：

10ffff
COMMERCIAL AT
bool(true)

若要使用此类，请先安装Intl扩展

预期

预期是向后兼用并增强之前的 assert() 的方法。 它使得在生产环境中启用断言为零成本，并且提供当断言失败时抛出特定异常的能力。

老版本的API出于兼容目的将继续被维护，assert()现在是一个语言结构，它允许第一个参数是一个表达式，而不仅仅是一个待计算的 string或一个待测试的boolean。

<?php
ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Some error message'));
?>

以上例程会输出：

Fatal error: Uncaught CustomError: Some error message

关于这个特性的完整说明，包括如何在开发和生产环境中配置它，可以在assert()的 expectations section章节找到。

Group use declarations

从同一 namespace 导入的类、函数和常量现在可以通过单个 use 语句 一次性导入了。

<?php

// PHP 7 之前的代码
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ 及更高版本的代码
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
?>

生成器可以返回表达式

此特性基于 PHP 5.5 版本中引入的生成器特性构建的。 它允许在生成器函数中通过使用 return 语法来返回一个表达式 （但是不允许返回引用值）， 可以通过调用 Generator::getReturn() 方法来获取生成器的返回值， 但是这个方法只能在生成器完成产生工作以后调用一次。

<?php

$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

以上例程会输出：

1
2
3

在生成器中能够返回最终的值是一个非常便利的特性， 因为它使得调用生成器的客户端代码可以直接得到生成器（或者其他协同计算）的返回值， 相对于之前版本中客户端代码必须先检查生成器是否产生了最终的值然后再进行响应处理 来得方便多了。

Generator delegation

现在，只需在最外层生成其中使用 yield from， 就可以把一个生成器自动委派给其他的生成器， Traversable 对象或者 array。

<?php

function gen()
{
    yield 1;
    yield 2;

    yield from gen2();
}

function gen2()
{
    yield 3;
    yield 4;
}

foreach (gen() as $val)
{
    echo $val, PHP_EOL;
}

?>

以上例程会输出：

1
2
3
4

整数除法函数 intdiv()

新加的函数 intdiv() 用来进行 整数的除法运算。

<?php

var_dump(intdiv(10, 3));
?>

以上例程会输出：

int(3)

会话选项

session_start() 可以接受一个 array 作为参数， 用来覆盖 php.ini 文件中设置的 会话配置选项。

在调用 session_start() 的时候， 传入的选项参数中也支持 session.lazy_write 行为， 默认情况下这个配置项是打开的。它的作用是控制 PHP 只有在会话中的数据发生变化的时候才 写入会话存储文件，如果会话中的数据没有发生改变，那么 PHP 会在读取完会话数据之后， 立即关闭会话存储文件，不做任何修改，可以通过设置 read_and_close 来实现。

例如，下列代码设置 session.cache_limiter 为 private，并且在读取完毕会话数据之后马上关闭会话存储文件。

<?php
session_start([
    'cache_limiter' => 'private',
    'read_and_close' => true,
]);
?>

preg_replace_callback_array()

在 PHP 7 之前，当使用 preg_replace_callback() 函数的时候， 由于针对每个正则表达式都要执行回调函数，可能导致过多的分支代码。 而使用新加的 preg_replace_callback_array() 函数， 可以使得代码更加简洁。

现在，可以使用一个关联数组来对每个正则表达式注册回调函数， 正则表达式本身作为关联数组的键， 而对应的回调函数就是关联数组的值。

CSPRNG Functions

新加入两个跨平台的函数： random_bytes() 和 random_int() 用来产生高安全级别的随机字符串和随机整数。

可以使用 list() 函数来展开实现了 ArrayAccess 接口的对象

在之前版本中，list() 函数不能保证 正确的展开实现了 ArrayAccess 接口的对象， 现在这个问题已经被修复。

其他特性

  • 允许在克隆表达式上访问对象成员，例如： (clone $foo)->bar()。

User Contributed Notes

Julian Sawicki 12-Sep-2020 02:30
Currying was possible in php 5.6. But in php 7.0 it is now possible to invoke a curryied function with a one liner.

<?php
// A curried function
function add($a) {
  return function($b) use ($a) {
    return $a + $b;
  };
}

// Invoking a curried function in PHP 7
$result = add(10)(15);
var_dump($result); // int 25

// Invoking a curried function in PHP 5.6
$add10 = add(10);
$result = $add10(15);
var_dump($result); // int 25
?>
Julian Sawicki 12-Sep-2020 01:52
In php 7.0 it's possible to curry functions in a way that's similar to JavaScript.

<?php

// A curried function
function add($a) {
  return function($b) use ($a) {
    return $a + $b;
  };
}

// Invoking curried function in PHP 7
$result = add(10)(15);

var_dump($result); // int 25

?>

Currying in this way is not possible in php 5.6.
nevercode at pm dot me 18-Aug-2020 09:03
It is worth nothing that the following code just works in PHP 7.4:

```
function nullOrDefault($x = null)
{
    $x ??= 3222;

    return $x;
}
```
Adrian Wiik 16-Jan-2020 01:52
A good rule of thumb for remembering what the spaceship operator expression returns is to replace the spaceship operator with a minus sign (-). If the result is negative, 0 or positive, the expression will return -1, 0 or 1 respectively.

Example:
<?php
echo 5 <=> 8; // 5 - 8 = -3, prints -1
echo 2 <=> 2; // 2 - 2 = 0, prints 0
echo 4 <=> 2; // 4 - 2 = 2, prints 1
ricasiano at gmail dot com 08-Jan-2020 12:53
Be careful on performing null coalesce on typecasted properties. Enclose them in parenthesis

<?php
$foo = new StdClass;
//(int) 23
$bar = $foo->bas ?? 23;
var_dump($bar);

$foo = new StdClass;
//(int) 23
$bar = (int) ($foo->bas ?? 23);
var_dump($bar);

$foo = new StdClass;
$bar = (int) $foo->bas ?? 23;
//Notice: Undefined property: stdClass::$bas
var_dump($bar);
TerryE 21-Jun-2017 09:13
$a = ''; // or 0 or false

$b = $a ?? 'a';
// $b is '' or 0 or false

$c = $a ?: 'a';
// $c is 'a'
PawelD 19-Jul-2016 09:23
<?php
class foo { static $bar = 'baz'; }
var_dump('foo'::$bar);
?>

if < php7.0

then we will receive a syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

but php7 returns string(3) "baz"

I think it's not documented anywhere


PHP 7.0.x 弃用的功能

PHP4 风格的构造函数

PHP4 风格的构造函数（方法名和类名一样）将被弃用，并在将来移除。 如果在类中仅使用了 PHP4 风格的构造函数，PHP7 会产生 E_DEPRECATED 警告。 如果还定义了 __construct() 方法则不受影响。

<?php
class foo {
    function foo() {
        echo 'I am the constructor';
    }
}
?>

以上例程会输出：

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo has a deprecated constructor in example.php on line 3

静态调用非静态的方法

废弃了 静态（Static） 调用未声明成 static 的方法，未来可能会彻底移除该功能。

<?php
class foo {
    function bar() {
        echo 'I am not static!';
    }
}

foo::bar();
?>

以上例程会输出：

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
I am not static!

password_hash() 盐值选项

废弃了 password_hash() 函数中的盐值选项，阻止开发者生成自己的盐值（通常更不安全）。 开发者不传该值时，该函数自己会生成密码学安全的盐值。因此再无必要传入自己自定义的盐值。

capture_session_meta SSL 上下文选项

废弃了 capture_session_meta 内的 SSL 上下文选项。 现在可以通过 stream_get_meta_data() 获取 SSL 元数据（metadata）。

LDAP 中的废弃

以下函数已被废弃：

  • ldap_sort()

User Contributed Notes

There are no user contributed notes for this page.


变更的函数

PHP 核心

  • debug_zval_dump() 现在打印 "int" 替代 "long", 打印 "float" 替代 "double"
  • dirname() 增加了可选的第二个参数, depth, 获取当前目录向上 depth 级父目录的名称。
  • getrusage() 现在支持 Windows.
  • mktime() and gmmktime() 函数不再接受 is_dst 参数。
  • preg_replace() 函数不再支持 "\e" (PREG_REPLACE_EVAL). 应当使用 preg_replace_callback() 替代。
  • setlocale() 函数不再接受 category 传入字符串。 应当使用 LC_* 常量。
  • exec(), system() and passthru() 函数对 NULL 增加了保护.
  • shmop_open() 现在返回一个资源而非一个int， 这个资源可以传给shmop_size(), shmop_write(), shmop_read(), shmop_close() 和 shmop_delete().
  • substr() 现在当 start 的值与 string 的长度相同时将返回一个空字符串。
  • xml_parser_free()不再足以释放解析器资源，如果它引用了一个对象，而这个对象又引用了那个解析器资源。在这种情况下，需要额外地取消设置 $parser。

User Contributed Notes

There are no user contributed notes for this page.


新函数

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

错误处理和日志

  • error_clear_last()

Generator

  • Generator::getReturn()

GNU 多重精度

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

PHP 选项和信息

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Zlib Compression

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()

User Contributed Notes

There are no user contributed notes for this page.


新的类和接口

Intl

  • IntlChar

Reflection

  • ReflectionGenerator
  • ReflectionType

会话（Session）管理器

  • SessionUpdateTimestampHandlerInterface

Exception 等级

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError

User Contributed Notes

There are no user contributed notes for this page.


新的全局常量

内核预定义常量

  • PHP_INT_MIN

GD

  • IMG_WEBP (自 PHP 7.0.10 起)

JSON

  • JSON_ERROR_INVALID_PROPERTY_NAME
  • JSON_ERROR_UTF16

LibXML

  • LIBXML_BIGLINES

PCRE

  • PREG_JIT_STACKLIMIT_ERROR

POSIX

  • POSIX_RLIMIT_AS
  • POSIX_RLIMIT_CORE
  • POSIX_RLIMIT_CPU
  • POSIX_RLIMIT_DATA
  • POSIX_RLIMIT_FSIZE
  • POSIX_RLIMIT_LOCKS
  • POSIX_RLIMIT_MEMLOCK
  • POSIX_RLIMIT_MSGQUEUE
  • POSIX_RLIMIT_NICE
  • POSIX_RLIMIT_NOFILE
  • POSIX_RLIMIT_NPROC
  • POSIX_RLIMIT_RSS
  • POSIX_RLIMIT_RTPRIO
  • POSIX_RLIMIT_RTTIME
  • POSIX_RLIMIT_SIGPENDING
  • POSIX_RLIMIT_STACK
  • POSIX_RLIMIT_INFINITY

Zlib

  • ZLIB_ENCODING_RAW
  • ZLIB_ENCODING_DEFLATE
  • ZLIB_ENCODING_GZIP
  • ZLIB_FILTERED
  • ZLIB_HUFFMAN_ONLY
  • ZLIB_FIXED
  • ZLIB_RLE
  • ZLIB_DEFAULT_STRATEGY
  • ZLIB_BLOCK
  • ZLIB_FINISH
  • ZLIB_FULL_FLUSH
  • ZLIB_NO_FLUSH
  • ZLIB_PARTIAL_FLUSH
  • ZLIB_SYNC_FLUSH

User Contributed Notes

There are no user contributed notes for this page.


SAPI 模块的变化

FPM

listen 端口现在同时监听 IPv4 和 IPv6 地址。

在 PHP 5 中，listen 指令如果仅带一个端口数字， 则会监听所有网络接口，但只是 IPv4。 现在 PHP 7 会同时接受来自 IPv4 和 IPv6 上的请求。

指定了 ip 地址后不受此影响；它们会继续仅仅监听在指定的地址和协议上。

User Contributed Notes

There are no user contributed notes for this page.


移除的扩展和 SAPI

移除的扩展

  • ereg
  • mssql
  • mysql
  • sybase_ct

移除的 SAPI

  • aolserver
  • apache
  • apache_hooks
  • apache2filter
  • caudium
  • continuity
  • isapi
  • milter
  • nsapi
  • phttpd
  • pi3web
  • roxen
  • thttpd
  • tux
  • webjames

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

放宽了保留词限制

现在允许全局保留词用于类/接口/Trait 中的属性、常量和方法名。 在引入新关键词时，此变更减少了对向后兼容的破坏，避免了 API 命名的限制。

使用流畅的接口实现内部 DSL 时，这非常有用：

<?php
// 以前不能用  'new'、'private' 和 'for'
Project::new('Project Name')->private()->for('purpose here')->with('username here');
?>

唯一的限制是： class关键词不能用于常量名，否则会和 类名解析语法冲突 (ClassName::class)。

移除 date.timezone 警告

调用任意 date- 开头或者其他基于时间的函数时， 未设置 date.timezone INI 设置的情况下， 之前会产生警告。 现在移除了警告（date.timezone 默认仍然是 UTC）

User Contributed Notes

There are no user contributed notes for this page.


从 PHP 5.5.x 移植到 PHP 5.6.x

Table of Contents

  • 向后不兼容
  • 新特性
  • PHP 5.6.x 中已废止的特性
  • 函数的变化
  • 新加函数
  • OpenSSL changes in PHP 5.6.x
  • 扩展中的变动
  • 新加的全局常量

PHP 5.6 中大多数的改善对旧项目没有影响。有一些 不兼容处 和 新功能 需要 注意下，并且在正式布署升级后的项目前应该测试您的代码。

User Contributed Notes

There are no user contributed notes for this page.


向后不兼容

虽然大部分 PHP 5 的代码无需修改即可正常运行， 但是有部分代码是无法向后兼容的：

使用数组标识符为类定义数组类型的属性时，数组的键不会被覆盖

在 PHP 5.6 之前的版本中，为类定义数组类型的属性时， 如果数组中同时使用了显式数组键和隐式数组键，并且显式的键和隐式的序列键相同， 那么数组的键将被覆盖。例如：

<?php
class C {
    const ONE = 1;
    public $array = [
        self::ONE => 'foo',
        'bar',
        'quux',
    ];
}

var_dump((new C)->array);
?>

以上例程在 PHP 5.5 中的输出：

array(2) {
  [0]=>
  string(3) "bar"
  [1]=>
  string(4) "quux"
}

以上例程在 PHP 5.6 中的输出：

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

严格的 json_decode()

对于 JSON 字面量 true，false 和
null，如果不采用小写格式，将会被 json_decode() 函数拒绝，
同时相应的设置 json_last_error()。
在之前的版本中，json_decode() 函数可以接受这些字面量的
全部大写或者大小写混写的格式。

此变更仅会影响传入到 json_decode() 中的 JSON 格式无效的情况， 有效的 JSON 输入不会受到影响并且能够正确解析。

当使用 SSL/TLS 的时候，流封装器默认验证端点证书和主机名

All encrypted client streams now enable peer verification by default. By default, this will use OpenSSL's default CA bundle to verify the peer certificate. In most cases, no changes will need to be made to communicate with servers with valid SSL certificates, as distributors generally configure OpenSSL to use known good CA bundles.

The default CA bundle may be overridden on a global basis by setting either the openssl.cafile or openssl.capath configuration setting, or on a per request basis by using the cafile or capath context options.

While not recommended in general, it is possible to disable peer certificate verification for a request by setting the verify_peer context option to false, and to disable peer name validation by setting the verify_peer_name context option to false.

GMP 资源现为对象

GMP 资源现为对象。 GMP 扩展中的基于函数的 API 实现不受影响， 只有在代码中使用 is_resource() 或类似函数 来显示检测是否资源类型的代码才会受到影响。

Mcrypt 函数需要有效长度的密钥和初始向量

mcrypt_encrypt()，mcrypt_decrypt()，
mcrypt_cbc()，mcrypt_cfb()，
mcrypt_ecb()，mcrypt_generic() 以及
mcrypt_ofb() 函数不再接受无效长度的密钥和初始向量，
对于需要初始向量的分组加密模式，如果不提供初始向量，函数调用将会失败。

cURL 文件上传

必须先设置 CURLOPT_SAFE_UPLOAD 为 false 才能够使用 @file 语法来上传文件。 建议使用 CURLFile 类来上传文件。

User Contributed Notes

Roger 22-Jun-2017 10:15
Another breaking change involves opening the special "php://input" stream for decompression. In PHP 5.5, the following code would allow PHP to decode a gzip'd request input stream:

<?php
// Open the input stream for requests with Content-Encoding: gzip.
$input = gzopen('php://input','r');
// This has the same effect as fopen('compress.zlib://php://input','r').

// Get the decompressed request body.
var_dump(stream_get_contents($input));
?>

However in PHP 5.6 this does not work. Instead PHP gives the following warning: gzopen(): cannot represent a stream of type Input as a File Descriptor.

It is unclear whether this is a bug or intentional, backward-incompatible change.


新特性

使用表达式定义常量

在之前的 PHP 版本中， 必须使用静态值来定义常量，声明属性以及指定函数参数默认值。 现在你可以使用包括数值、字符串字面量以及其他常量在内的数值表达式来 定义常量、声明属性以及设置函数参数默认值。

<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;

    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>

以上例程会输出：

4
The value of THREE is 3

现在可以通过 const 关键字来定义类型为 array 的常量。

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

以上例程会输出：

a

使用 ... 运算符定义变长参数函数

现在可以不依赖 func_get_args()， 使用 ... 运算符 来实现 变长参数函数。

<?php
function f($req, $opt = null, ...$params) {
    // $params 是一个包含了剩余参数的数组
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>

以上例程会输出：

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3

使用 ... 运算符进行参数展开

在调用函数的时候，使用 ... 运算符， 将 数组 和 可遍历 对象展开为函数参数。 在其他编程语言，比如 Ruby中，这被称为连接运算符，。

<?php
function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>

以上例程会输出：

6

使用 ** 进行幂运算

加入右连接运算符 ** 来进行幂运算。 同时还支持简写的 **= 运算符，表示进行幂运算并赋值。

<?php
printf("2 ** 3 ==      %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);

$a = 2;
$a **= 3;
printf("a ==           %d\n", $a);
?>

以上例程会输出：

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function 以及 use const

use 运算符 被进行了扩展以支持在类中导入外部的函数和常量。 对应的结构为 use function 和 use const。

<?php
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;

    echo FOO."\n";
    f();
}
?>

以上例程会输出：

42
Name\Space\f

phpdbg

PHP 的 SAPI 模块中实现了一个 交互式调试器，叫做 phpdbg。更多信息，请访问 phpdbg documentation。

默认字符编码

对于一些字符编码相关的函数，例如 htmlentities()， html_entity_decode() 以及 htmlspecialchars() 使用 default_charset 作为默认字符集。请注意，对于 iconv（现已废弃） 和 mbstring 相关的函数， 如果分别设置了他们的编码， 那么这些对应设置的优先级高于 default_charset。

default_charset 的默认值是 UTF-8。

php://input 是可重用的了

只要你需要，你可以多次打开并读取 php://input。 同时，这个特性使得在处理 POST 的数据的时候， 可以明显降低对于内存的需求量。

大文件上传

现在可以支持大于 2GB 的文件上传。

GMP 支持运算符重载

GMP 支持运算符重载， 并且造型成数值类型。 这使得使用 GMP 的代码更加直观。

<?php
$a = gmp_init(42);
$b = gmp_init(17);

if (version_compare(PHP_VERSION, '5.6', '<')) {
    echo gmp_intval(gmp_add($a, $b)), PHP_EOL;
    echo gmp_intval(gmp_add($a, 17)), PHP_EOL;
    echo gmp_intval(gmp_add(42, $b)), PHP_EOL;
} else {
    echo $a + $b, PHP_EOL;
    echo $a + 17, PHP_EOL;
    echo 42 + $b, PHP_EOL;
}
?>

以上例程会输出：

59
59
59

使用 hash_equals() 比较字符串避免时序攻击

加入 hash_equals() 函数， 以恒定的时间消耗来进行字符串比较， 以避免时序攻击。 比如当比较 crypt() 密码散列值的时候，就可以使用此函数。 （假定你不能使用 password_hash() 和 password_verify()， 这两个函数也可以抵抗时序攻击）

<?php
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('1234',  '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

以上例程会输出：

bool(true)
bool(false)

__debugInfo()

加入 __debugInfo()， 当使用 var_dump() 输出对象的时候， 可以用来控制要输出的属性和值。

<?php
class C {
    private $prop;

    public function __construct($val) {
        $this->prop = $val;
    }

    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new C(42));
?>

以上例程会输出：

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

gost-crypto 散列算法

加入 gost-crypto 散列算法。 它使用 » RFC 4357, 11.2 小节 定义的 CryptoPro S-box 表实现了 GOST 散列函数。

SSL/TLS 提升

在 PHP 5.6 中对 SSL/TLS 的支持进行了大幅度的提升。 这其中包括 默认启用端点验证 选项来支持证书指纹比对， 以避免 TLS 重新协商攻击。 还增加了很多 SSL 上下文选项， 以便在使用加密流的时候， 能够更好的控制协议和验证的相关设置。

这些变动在 PHP 5.6.x 中的 OpenSSL 变更 中有详细描述。

pgsql 异步支持

pgsql 扩展现在支持 异步方式连接数据库及执行查询， 也即可以使用非阻塞的方式和 PostgreSQL 数据库进行交互。 使用 PGSQL_CONNECT_ASYNC 常量可以 建立异步连接，pg_connect_poll()， pg_socket()， pg_consume_input() 和 pg_flush() 函数 可以用来处理异步连接和查询。

User Contributed Notes

stocki dot r at gmail dot com 25-Feb-2021 02:24
You can create a self-documented, named argument workaround in PHP 5.6-7 with ... operator:

<?php
htmlspecialchars($string, ...array_values([
    'flags'         => ENT_COMPAT | ENT_HTML401,
    'encoding'      => 'UTF-8',
    'double_encode' => false,
]))
?>
BernieV 04-Dec-2019 12:31
The splat operator (...) is documented everywhere with no space after it.
But it seems to work just as well with whitespace between ... and what follows.
My IDE line-wrapped, introducing white-space, immediately after the ...
ciachn 06-Sep-2014 07:20
Having 2 ** 3 ** 2 = 512 is actually that is the exact correct behavior for a right-associative operator just as specified in the "**" documentation.
Anonymous 15-Jul-2014 12:58
Remember, that

    ($a ** $b) ** $c === $a ** ($b * $c)

Thats why exponent operator** is RIGHT associative.
ashnazg at php dot net 21-Apr-2014 03:07
Note the order of operations in that exponentiation operator, as it was opposite of what my first expectation was:

<?php
// what I had expected,
// evaluating left to right,
// since no parens were used to guide the order of operations
2 ** 3 ** 2 == 64; // (2 ** 3) ** 2 = 8 ** 2 = 64

// the given example,
// which appears to evaluate right to left
2 ** 3 ** 2 == 512; // 2 ** (3 ** 2) = 2 ** 9 = 512
?>
gmblar+php at gmail dot com 31-Jan-2014 02:36
<?php

function array_zip(...$arrays) {
    return array_merge(...array_map(NULL, ...$arrays));
}

$a = array(1, 4, 7);
$b = array(2, 5, 8);
$c = array(3, 6, 9);

var_dump(implode(', ', array_zip($a, $b, $c)));

// Output
string(25) "1, 2, 3, 4, 5, 6, 7, 8, 9"
tr0y 25-Jan-2014 07:02
It is also possible ( in 5.6.0alpha ) to typehint the ...-operator

function foo (stdclass ... $inbound) {
   var_dump($inbound);
}

// ok:
foo( (object)['foo' => 'bar'], (object)['bar' => 'foo'] );

// fails:
foo( 1, 2, 3, 4 );


PHP 5.6.x 中已废止的特性

从不兼容的上下文调用方法

现在已废止从不兼容的上下文调用方法， 并且产生 E_DEPRECATED 错误 （以前是 E_STRICT）。 在 PHP 的后续版本中可能彻底移除对此特性的支持。

以下是不兼容上下文调用方法的示例：

<?php
class A {
    function f() { echo get_class($this); }
}

class B {
    function f() { A::f(); }
}

(new B)->f();
?>

以上例程会输出：

Deprecated: Non-static method A::f() should not be called statically, assuming $this from incompatible context in - on line 7
B

$HTTP_RAW_POST_DATA 和 always_populate_raw_post_data

使用 always_populate_raw_post_data 会导致在填充 $HTTP_RAW_POST_DATA 时产生 E_DEPRECATED 错误。 请使用 php://input 替代 $HTTP_RAW_POST_DATA， 因为它可能在后续的 PHP 版本中被移除。 设置 always_populate_raw_post_data 为 -1 （这样会强制 $HTTP_RAW_POST_DATA 未定义，所以也不回导致 E_DEPRECATED 的错误） 来体验新的行为。

iconv 和 mbstring 编码设置

iconv 和 mbstring 配置选项中 和编码相关的选项都已废弃， 请使用 default_charset。 废弃的选项有：

  • iconv.input_encoding
  • iconv.output_encoding
  • iconv.internal_encoding
  • mbstring.http_input
  • mbstring.http_output
  • mbstring.internal_encoding

User Contributed Notes

There are no user contributed notes for this page.


函数的变化

PHP 内核

  • 如果省略 salt 参数，crypt() 会产生 E_NOTICE错误。
  • substr_compare() 的 length 参数现在接受 0 的值。
  • unserialize() will now fail if passed serialised data that has been manipulated to attempt to instantiate an object without calling its constructor.

cURL

  • 只有设置 CURLOPT_SAFE_UPLOAD 为 false 的情况下， 才接受 @file 语法上传文件。 最好使用 CURLFile 代替。

Mcrypt

  • mcrypt_create_iv() 的 source 现在默认值是 MCRYPT_DEV_URANDOM，而非 MCRYPT_DEV_RANDOM。

OpenSSL

  • 如果 SSL 上下文选项已经提供 crypto_type 选项， stream_socket_enable_crypto() 可以忽略 crypto_type 参数。

PostgreSQL

  • pg_insert()、pg_select()、 pg_update()、pg_delete() 不再是实验性质的。
  • 如果数据库连接 socket 流设置为非阻塞（non-blocking）模式，
pg_send_execute()、
pg_send_prepare()、pg_send_query()
、pg_send_query_params() 不再会阻塞查询直到写入完成。

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() 现在允许非 Final 的内部类实例化。

XMLReader

  • 和 XMLReader::getAttribute() 一样，未找到属性的情况下，
XMLReader::getAttributeNs() 和
XMLReader::getAttributeNo() 会返回 null 。

User Contributed Notes

There are no user contributed notes for this page.


新加函数

日期和时间

  • DateTimeImmutable::createFromMutable()

GMP

  • gmp_root()
  • gmp_rootrem()

Hash

  • hash_equals()

LDAP

  • ldap_escape()
  • ldap_modify_batch()

MySQLi

  • mysqli_get_links_stats()

OCI8

  • oci_get_implicit_resultset()

OpenSSL

  • openssl_get_cert_locations()
  • openssl_x509_fingerprint()
  • openssl_spki_new()
  • openssl_spki_verify()
  • openssl_spki_export_challenge()
  • openssl_spki_export()

PostgreSQL

  • pg_connect_poll()
  • pg_consume_input()
  • pg_flush()
  • pg_socket()

PDO_PGSQL

  • PDO::pgsqlGetNotify()
  • PDO::pgsqlGetPid()

Session

  • session_abort()
  • session_reset()

Zip

  • ZipArchive::setPassword()

User Contributed Notes

There are no user contributed notes for this page.


OpenSSL changes in PHP 5.6.x

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

All encrypted client streams now enable peer verification by default. By default, this will use OpenSSL's default CA bundle to verify the peer certificate. In most cases, no changes will need to be made to communicate with servers with valid SSL certificates, as distributors generally configure OpenSSL to use known good CA bundles.

The default CA bundle may be overridden on a global basis by setting either the openssl.cafile or openssl.capath configuration setting, or on a per request basis by using the cafile or capath context options.

While not recommended in general, it is possible to disable peer certificate verification for a request by setting the verify_peer context option to false, and to disable peer name validation by setting the verify_peer_name context option to false.

Certificate fingerprints

Support has been added for extracting and verifying certificate fingerprints. openssl_x509_fingerprint() has been added to extract a fingerprint from an X.509 certificate, and two SSL stream context options have been added: capture_peer_cert to capture the peer's X.509 certificate, and peer_fingerprint to assert that the peer's certificate should match the given fingerprint.

Default ciphers updated

The default ciphers used by PHP have been updated to a more secure list based on the » Mozilla cipher recommendations, with two additional exclusions: anonymous Diffie-Hellman ciphers, and RC4.

This list can be accessed via the new OPENSSL_DEFAULT_STREAM_CIPHERS constant, and can be overridden (as in previous PHP versions) by setting the ciphers context option.

Compression disabled by default

SSL/TLS compression has been disabled by default to mitigate the CRIME attack. PHP 5.4.13 added a disable_compression context option to allow compression to be disabled: this is now set to true (that is, compression is disabled) by default.

Allow servers to prefer their cipher order

The honor_cipher_order SSL context option has been added to allow encrypted stream servers to mitigate BEAST vulnerabilities by preferring the server's ciphers to the client's.

Access the negotiated protocol and cipher

The protocol and cipher that were negotiated for an encrypted stream can now be accessed via stream_get_meta_data() or stream_context_get_options() when the capture_session_meta SSL context option is set to true.

<?php
$ctx = stream_context_create(['ssl' => [
    'capture_session_meta' => TRUE
]]);

$html = file_get_contents('https://google.com/', FALSE, $ctx);
$meta = stream_context_get_options($ctx)['ssl']['session_meta'];
var_dump($meta);
?>

以上例程会输出：

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

New options for perfect forward secrecy in encrypted stream servers

Encrypted client streams already support perfect forward secrecy, as it is generally controlled by the server. PHP encrypted server streams using certificates capable of perfect forward secrecy do not need to take any additional action to enable PFS; however a number of new SSL context options have been added to allow more control over PFS and deal with any compatibility issues that may arise.

ecdh_curve

This option allows the selection of a specific curve for use with ECDH ciphers. If not specified, prime256v1 will be used.

dh_param

A path to a file containing parametrs for Diffie-Hellman key exchange, such as that created by the following command:

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

If set to true, a new key pair will be created when using Diffie-Hellman parameters, thereby improving forward secrecy.

single_ecdh_use

If set to true, a new key pair will always be generated when ECDH cipher suites are negotiated. This improves forward secrecy.

SSL/TLS version selection

It is now possible to select specific versions of SSL and TLS via the crypto_method SSL context option or by specifying a specific transport when creating a stream wrapper (for example, by calling stream_socket_client() or stream_socket_server()).

The crypto_method SSL context option accepts a bitmask enumerating the protocols that are permitted, as does the crypto_type of stream_socket_enable_crypto().

Selected protocol versions and corresponding options
Protocol(s) | Client flag | Server flag | Transport
Any TLS or SSL version | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Any TLS version | STREAM_CRYPTO_METHOD_TLS_CLIENT | STREAM_CRYPTO_METHOD_TLS_SERVER | tls://
TLS 1.0 | STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | tlsv1.0://
TLS 1.1 | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | tlsv1.1://
TLS 1.2 | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER | tlsv1.2://
SSL 3 | STREAM_CRYPTO_METHOD_SSLv3_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_SERVER | sslv3://
<?php

// Requiring TLS 1.0 or better when using file_get_contents():
$ctx = stream_context_create([
    'ssl' => [
        'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
    ],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Requiring TLS 1.1 or 1.2:
$ctx = stream_context_create([
    'ssl' => [
        'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
                           STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
    ],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Connecting using the tlsv1.2:// stream socket transport.
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

openssl_get_cert_locations() added

The openssl_get_cert_locations() function has been added: it returns the default locations PHP will search when looking for CA bundles.

<?php
var_dump(openssl_get_cert_locations());
?>

以上例程会输出：

array(8) {
  ["default_cert_file"]=>
  string(21) "/etc/pki/tls/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/etc/pki/tls/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/etc/pki/tls/private"
  ["default_default_cert_area"]=>
  string(12) "/etc/pki/tls"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

SPKI support

Support has been added for generating, extracting and verifying signed public key and challenges (SPKAC). openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge(), and openssl_spki_export() have been added to create, verify export PEM public key and associated challenge from SPKAC's generated from a KeyGen HTML5 element.

openssl_spki_new

Generates a new SPKAC using private key, challenge string and hashing algorithm.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

以上例程会输出：

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Verifies provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
var_dump(openssl_spki_verify($spkac));
?>
openssl_spki_export_challenge

Exports associated challenge from provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge($spkac):
echo $challenge;
?>

以上例程会输出：

challenge string
openssl_spki_export

Exports the PEM formatted RSA public key from SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

以上例程会输出：

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcvQh9SKOPv4DwI8LwSaFx02h7
l9QCiDs6sF2GfsSTEUG61SnjQ/v4uJiLKBgbVOagj9rkSCwtTez23ATPeGaBj2Zg
ipv+tv5IXyqUP8ropXJQ5ELtbXPUN/gvw7cO5EbPHr/7eMhbpw8Gl+AfWxW5hLW8
MGw/+AwwjHBOwong/QIDAQAB
-----END PUBLIC KEY-----

User Contributed Notes

Victor 27-Oct-2015 09:36
To get back to the "old behavior" with self-signed ("snakeoil") certificates to possibly incorrect name, you need to set both options.

<?php
            $streamContext = stream_context_create([
                'ssl' => [
                    'verify_peer'      => false,
                    'verify_peer_name' => false
                ]
            ]);
            $contents = file_get_contents('https://url', false, $streamContext);
?>


扩展中的变动

cURL

在 cURL 库中的一些被标记为废弃的常量， 现在已经被移除：

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • 加入 oci_get_implicit_resultset() 函数 来支持 Oracle Database 12c 的隐式结果集。
  • 如果使用 oci_execute($s, OCI_NO_AUTO_COMMIT) 执行 SELECT 语句， 在连接关闭时发起内部的事物回滚不再是冗余的。
  • 通过 --enable-dtrace 配置选项 控制 DTrace 探针。
  • oci_internal_debug() 现在是无操作函数。
  • 在 phpinfo() 输出中 OCI8 的格式发生变动。

Zip

加入 --with-libzip 配置选项， 使得你可以使用系统安装的 libzip。 最低支持 libzip 0.11 版本，建议使用 0.11.2 或更高的版本。

MySQLi

新加 mysqli.rollback_on_cached_plink 选项，对于事务回滚的连接，将其返回到持久连接池中。

User Contributed Notes

There are no user contributed notes for this page.


新加的全局常量

GD

  • IMG_WEBP （自 PHP 5.6.25 起）

LDAP

  • LDAP_ESCAPE_DN
  • LDAP_ESCAPE_FILTER

OpenSSL

  • OPENSSL_DEFAULT_STREAM_CIPHERS
  • STREAM_CRYPTO_METHOD_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

PostgreSQL

  • PGSQL_CONNECT_ASYNC
  • PGSQL_CONNECTION_AUTH_OK
  • PGSQL_CONNECTION_AWAITING_RESPONSE
  • PGSQL_CONNECTION_MADE
  • PGSQL_CONNECTION_SETENV
  • PGSQL_CONNECTION_SSL_STARTUP
  • PGSQL_CONNECTION_STARTED
  • PGSQL_DML_ESCAPE
  • PGSQL_POLLING_ACTIVE
  • PGSQL_POLLING_FAILED
  • PGSQL_POLLING_OK
  • PGSQL_POLLING_READING
  • PGSQL_POLLING_WRITING

User Contributed Notes

There are no user contributed notes for this page.


PHP 的调试

Table of Contents

  • 关于调试器

User Contributed Notes

Anonymous 06-Aug-2020 08:51
I often rely on a Slack channel open that is solely dedicated to debug output in whatever project I'm working on. Then I use a PHP function called debug($obj) that takes $obj and uses the Slack API to post a message with that value to that channel. It's helped me immensely and hopefully it would help others too.
shananpk95 at gmail dot com 12-Mar-2020 04:51
I am using two ways to debug code

one is print the data and die the function in specific point.

     print_r($data);die;

second one is writing log file in specific point in code.

function write_log($log_msg)
{
    $log_filename = "logs";
    if (!file_exists($log_filename))
    {
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/debug.log';
  file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);

}

write_log("Writing Log");
$a = array(
        array('id' => '1','date' => '09-04-2018','length' => '10'),
        array('id' => '2','date' => '09-04-2018','length' => '20'),
        array('id' => '1','date' => '10-04-2018','length' => '11')
    );
write_log(print_r($a,1));
Fonstw 26-Feb-2020 08:54
For me, just outputting variables only works when I know a method should be broken.

I use Xdebug in PHP Storm (available on other IDE's and editors as well)
It allows me to use line breaks and fully inspect anything that's set and how their values are changed and allows me to call single method even at (paused) runtime to see what behaviour the method really gives at any given point, which gives me a much better insight on how my code works and how to get it to work like it should.

I wholeheartedly recomend anyone to try a fuller-fledged debugger like that!
metron19 at yandex dot ru 31-Jul-2019 12:56
A good example of data output to the console via <script> tags, I myself used this first, but he broke the captcha job, because <script> tags were inserted into the base64 code of the captcha picture. Then I began to display logs in the headers with such a function (it may help someone else, in a similar situation):

<?php

function header_log($data){
  $bt = debug_backtrace();
  $caller = array_shift($bt);
  $line = $caller['line'];
  $file = array_pop(explode('/', $caller['file']));
  header('log_'.$file.'_'.$caller['line'].': '.json_encode($data));
}

?>

Usage:
$myvar = array(1,2,3);
header_log( $myvar ); // in headers we see: log_filename_rownumber: [1,2,3]
tekintian at gmail dot com 24-Mar-2019 12:07
<?php
/**
 * 测试打印方法
 * @FileName: test_helper.php
 * @Author: TekinTian
 * @QQ: 3316872019
 * @Email: tekintian@gmail.com
 * @Supported: http://dev.yunnan.ws/
 * @Date:   2017-01-23 11:45:26
 * @Last Modified 2019-03-04
 */

if (!function_exists('dd')) {
    /**
     * 测试打印函数
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    function dd($arr) {
        if (is_array($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";
        } else if (is_object($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";

        } else {
            echo $arr;
        }
        die;
    }
}

if (!function_exists('pp')) {
    /**
     * 格式化输出
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    function pp($arr) {
        if (is_array($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";
        } else if (is_object($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";

        } else {
            echo $arr;
        }
        die;
    }
}

if (!function_exists('pr')) {
    /**
     * 打印不中断
     */
    function pr($arr) {
        if (is_array($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";
        } else if (is_object($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";

        } else {
            echo $arr;
        }
    }
}

if (!function_exists('vd')) {
    /**
     * 测试打印函数
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    function vd($arr) {
        echo "<pre>";
        var_dump($arr);
        echo "</pre>";
        die;
    }
}

if (!function_exists('vv')) {
    function vv($arr) {
        echo "<pre>";
        var_dump($arr);
        echo "</pre>";
    }
}

if (!function_exists('console_log')) {
    /**
     * console.log控制台调试函数
     * @param  [type] $data [要在控制台输出的数据 支持数组、对象和字符串]
     * @return [type]       [description]
     */
    function console_log($data) {
        if (is_array($data) || is_object($data)) {
            echo ("<script>console.log('" . json_encode($data) . "');</script>");
        } else {
            echo ("<script>console.log('" . $data . "');</script>");
        }
    }
}

/**
 * 浏览器友好的变量输出,便于调试时候使用
 *
 * @param     mixed   $var       要输出查看的内容
 * @param     bool    $echo      是否直接输出
 * @param     string  $label     加上说明标签,如果有,这显示"标签名:"这种形式
 * @param     bool    $strict    是否严格过滤
 * @return    string
 */
if (!function_exists('dump')) {
    function dump($var, $echo = true, $label = null, $strict = true) {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
            } else {
                $output = $label . " : " . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo ($output);
            return null;
        } else {
            return $output;
        }

    }
}
rajendra at skydevelopers dot net 29-Sep-2018 11:06
I also use a method to print complete data from www.skydevelopers.net company:

function dd($data) {
    echo '<pre>';
    print_r($data);
    exit;
}

well this is also very beneficial
eric at derewonko dot com 14-Jan-2018 09:08
None of the given examples here do fit my needs.
When I debug, I want to see clearly what's going on and where is the debug data. Also it has to accommodate with the current styles and not fall behind or get mixed with other text etc.
This snippet will give you real debug notices in a flashy table:
- complete backtrace of calls on the left with line numbers
- arguments content on the right, with the variable name and coloring per variable type

<?php
function wtf(){
  error_reporting(E_ALL);
  $args = func_get_args();
  $backtrace = debug_backtrace();
  $file = file($backtrace[0]['file']);
  $src  = $file[$backtrace[0]['line']-1];  // select debug($varname) line where it has been called
  $pat  = '#(.*)'.__FUNCTION__.' *?\( *?\$(.*) *?\)(.*)#i';  // search pattern for wtf(parameter)
  $arguments  = trim(preg_replace($pat, '$2', $src));  // extract arguments pattern
  $args_arr = array_map('trim', explode(',', $arguments));

  print '<style>
  div.debug {visible; clear: both; display: table; width: 100%; font-family: Courier,monospace; border: medium solid red; background-color: yellow; border-spacing: 5px; z-index: 999;}
  div.debug > div {display: unset; margin: 5px; border-spacing: 5px; padding: 5px;}
  div.debug .cell {display: inline-flex; padding: 5px; white-space: pre-wrap;}
  div.debug .left-cell {float: left; background-color: Violet;}
  div.debug .array {color: RebeccaPurple; background-color: Violet;}
  div.debug .object pre {color: DodgerBlue; background-color: PowderBlue;}
  div.debug .variable pre {color: RebeccaPurple; background-color: LightGoldenRodYellow;}
  div.debug pre {white-space: pre-wrap;}
  </style>'.PHP_EOL;
  print '<div class="debug">'.PHP_EOL;
  foreach ($args as $key => $arg) {
    print '<div><div class="left-cell cell"><b>';
    array_walk(debug_backtrace(),create_function('$a,$b','print "{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']})<br> ";'));
    print '</b></div>'.PHP_EOL;
    if (is_array($arg)) {
      print '<div class="cell array"><b>'.$args_arr[$key].' = </b>';
      print_r(htmlspecialchars(print_r($arg)), ENT_COMPAT, 'UTF-8');
      print '</div>'.PHP_EOL;
    } elseif (is_object($arg)) {
      print '<div class="cell object"><pre><b>'.$args_arr[$key].' = </b>';
      print_r(htmlspecialchars(print_r(var_dump($arg))), ENT_COMPAT, 'UTF-8');
      print '</pre></div>'.PHP_EOL;
    } else {
      print '<div class="cell variable"><pre><b>'.$args_arr[$key].' = </b>&gt;';
      print_r(htmlspecialchars($arg, ENT_COMPAT, 'UTF-8').'&lt;');
      print '</pre></div>'.PHP_EOL;
    }
    print '</div>'.PHP_EOL;
  }
  print '</div>'.PHP_EOL;
}
?>

Usage: wtf($arg1, $arg2,..);
That's it!
Bladimir 28-Sep-2017 02:24
Following example above using variable-lenght arguments to support similar Web API's console.log implementation

<?php
function console_log( ...$messages ){
  $msgs = '';
  foreach ($messages as $msg) {
    $msgs .= json_encode($msg);
  }

  echo '<script>';
  echo 'console.log('. json_encode($msgs) .')';
  echo '</script>';
}

?>
Anonymous 19-Apr-2017 08:17
I would like to add http://phpdebugbar.com/ which is also a handy tool for debugging/profiling data. and you could use it whenever framework you are using. :-)
netyou 27-Sep-2015 07:29
I find it very useful to print out to the browsers console instead of just var_dumping:

function console_log( $data ){
  echo '<script>';
  echo 'console.log('. json_encode( $data ) .')';
  echo '</script>';
}

Usage:
$myvar = array(1,2,3);
console_log( $myvar ); // [1,2,3]
skatebiker at gmail dot com 05-Dec-2014 01:24
p_r() is a function for logging variable values.

In this example the function p_r() does only log when the URL parameter d=<nonzero> is set. Reset it by d=0.
When  the parameter is a valid filename (relative to the script's path) it will be logged to that file rather than to the browser.

[code]
@session_start();
// debug
if (isset($_GET['d']))
{
  $_SESSION['d'] = $_GET['d'];
}

if (@$_SESSION['d']) {

function p_r($exp)
{
  $res = "";
  $trace = debug_backtrace();
  $level = 0;
  $e = error_reporting(E_ALL&~E_NOTICE);
  $file = strrpos($trace[$level]['file'], "/");
  $file = substr($trace[$level]['file'],$file+1);
  $line = date("H:i:s"). " " . $file . ' ' . $trace[$level]['line'] . ' ' . $trace[$level+1]['function'] . "()";
  $e = error_reporting($e);
  if (!is_string($exp)) $exp = var_export($exp,1);
  if (substr($_SESSION["d"],-4)==".log") {
    file_put_contents ($_SESSION["d"],$line . ": ". $exp . "\n",  FILE_APPEND);
  } else {
    $res = $line . "\n<pre>".htmlentities($exp). "</pre>\n";
    echo $res;
  }
  return $res;
}

    // refresh to prevent timeout
  $a = $_SESSION['d'];
  $_SESSION['d'] = $a;
  error_reporting (E_ALL);

} else {
  function  p_r() {}
}  // end if debug

[/code]
online _ use _ only == hotmail.com 15-Mar-2006 03:41
I still find that printing out variable values at problem points in the code is one of the easiest ways for me to debug.  If you're interested in knowing the full contents of an object/array/scalar, then use

var_dump($var).


关于调试器

PHP 带来了 phpdbg 交互式调试器。也可以使用外部调试器。» Zend IDE 就是其中之一，它包含一个调试器。也有一些免费的调试器，比如在 » http://www.php-debugger.com/dbg/ 上的 DBG，» Advanced PHP Debugger（APD）或者 » Xdebug。

User Contributed Notes

Marco 17-Feb-2020 06:10
Kint is an awesome debugger.
To quote the author ... Its var_dump BUT ON STEROIDS !
pegasus.is.a.geek[at]gmail 24-May-2019 07:51
NOTE: ADP hasn't been maintained since 2004


配置选项

Table of Contents

  • 核心配置选项列表

User Contributed Notes

squeeNoSpam at NoSpamAddress dot com 14-Aug-2002 12:06
[Editor's note: The reason why some general options for the "configure" scripts are not documented is that said script is part of the GNU autoconf tools, and as such its general options are documented elsewhere, e.g.: http://www.gnu.org/manual/autoconf/index.html and http://www.airs.com/ian/configure/. Some are also documented in the INSTALL file that comes with the source distribution.]

The --prefix=PREFIX configure option isn't mentioned here. It apparently defaults to /usr/local, and sets the position of the php includes and libs. (in PREFIX/include/php and PREFIX/lib/php)


核心配置选项列表

下面是 PHP 的 configure 脚本使用的部分选项的列表，用于类 Unix 环境的编译。大部分配置选项在扩展模块参考页面适当的位置列出，而不是在这里。要查看所有可用配置选项的列表，在运行 autoconf 命令后在 PHP 的源代码目录运行 ./configure --help（参见安装与配置一章）。也可以阅读 » GNU configure 文档以获得有关 configure 命令的更详细信息，例如 --prefix=PREFIX。

Note:

这些选项只用在编译的时候。如果想要修改 PHP 的运行时配置，请阅读运行时配置。

  • 杂项
  • PHP 行为
  • 服务器

PHP 配置选项

杂项选项

--enable-debug

编译时加入调试符号。

--with-layout=TYPE

设置被安装文件的布局。TYPE 是 PHP（默认）或 GNU。

--with-pear=DIR

在 DIR（默认为 PREFIX/lib/php）中安装 PEAR。

--without-pear

不安装 PEAR。

--enable-sigchild

使用 PHP 自带的 SIGCHLD 处理器。

--disable-rpath

禁用在搜索路径中传递其他运行库。

--enable-libgcc

启用 libgcc 的精确链接。

--enable-php-streams

包含试验性的 PHP 流。不要使用此选项，除非是要测试代码！

--with-zlib-dir[=DIR]

定义 zlib 的安装目录。

--with-tsrm-pthreads

使用 POSIX 线程（默认）。

--enable-shared[=PKGS]

编译共享库 [default=yes]。

--enable-static[=PKGS]

编译静态库 [default=yes]。

--enable-fast-install[=PKGS]

为快速安装优化 [default=yes]。

--with-gnu-ld

假设 C 编译器使用 GNU ld [default=no]。

--disable-libtool-lock

避免锁死（可能破坏并联的编译）。

--with-pic

尝试仅使用 PIC/非 PIC 对象 [default=use both]。

--enable-memory-limit

编译内存限制支持功能。(自PHP 5.2.1开始不可用，默认enable)

--disable-url-fopen-wrapper

禁用 URL 形式的 fopen 封装协议。该协议允许通过 HTTP 或者 FTP 访问文件。 （自PHP5.2.5开始不可用）

--enable-versioning

仅导出必须的符号。查看 INSTALL 文件以获得更多信息。

PHP 选项

--enable-maintainer-mode

对偶然安装一下的情形启用此选项，使得不检查编译规则和依赖关系。

--with-config-file-path=PATH

设置 php.ini 的搜索路径。默认为 PREFIX/lib。

--enable-safe-mode

默认启用安全模式。

Warning

本特性已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除。

--with-exec-dir[=DIR]

在安全模式时仅允许在 DIR 目录中执行。默认目录为 /usr/local/php/bin。

Warning

本特性已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除。

--enable-magic-quotes

默认启用 magic quotes。

Warning

本特性已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除。

--disable-short-tags

默认禁用短形式的开始标签 <? 。

--enable-zend-multibyte

在词法与语法分析时允许多字节编码被执行。如果在编译 PHP 时使用了这个选项，就能够在 declare 结构中使用 encoding 指令。

Warning

本特性已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除。

--with-libdir

指定Uxin系统库文件目录用于构建 PHP。 对于64位系统, 需要指定 lib64 目录,比如 --with-libdir=lib64。

SAPI 选项

下面的列表包含 PHP 可用的 SAPI（服务器应用编程接口）。

--with-apxs[=FILE]

编译共享的 Apache 模块。FILE 是可选的 Apache apxs 工具的路径，默认指向 apxs。请确认指定的 apxs 已经安装在服务器中，并且它不是 Apache 源码包中的那个 apxs。

--with-apache[=DIR]

编译静态 Apache 模块。DIR 是 Apache 编译目录的顶层，默认为 /usr/local/apache。

--with-mod_charset

启用 mod_charset 的转换表（俄文的 Apache 使用）。

--with-apxs2[=FILE]

编译共享的 Apache 2.0 模块。FILE 是可选的 Apache apxs 工具的路径，默认指向 apxs。

--disable-cli

禁止编译 PHP 的 CLI 版本（使用它将同时强制使用 --without-pear 选项）。更多信息请参阅 PHP 的命令行模式。

--enable-phpdbg

启用 phpdbg 调试 SAPI 模块支持，PHP 5.6.x 以后的版本有效。

--enable-embed[=TYPE]

启用编译嵌入的 SAPI 库。TYPE 或者为 shared 或者为 static，默认为 shared。

--with-servlet[=DIR]

包含 servlet 支持。DIR 是 JSDK 的安装目录。此 SAPI 要求 java 扩展必须作为共享模块编译到 PHP 中。

--disable-cgi

禁止编译 CGI 版本的 PHP。

PHP 5.3.0 起，这个选项会启用 FastCGI，而在以前，必须使用 --enable-fastcgi 启用 FastCGI。

--enable-force-cgi-redirect

启用内部服务器重定向的安全检测。如果在 Apache 下使用 CGI 版本的 PHP，请启用该选项。

PHP 5.3.0 起，默认有效并不再存在。要禁用此功能，需要在 INI 配置文件中将 cgi.force_redirect 设为 0。

--enable-discard-path

如果启用该选项，PHP CGI 目录可以安全的放在 web 目录树的外面，人们无法避开 .htaccess 的安全限制。

PHP 5.3.0 起，默认禁用并不在存在。要启用此功能，需要设置 cgi-redirect INI 指令为 1。

--enable-fastcgi

如果启用，CGI 模块将被编译为支持 FastCGI。

PHP 5.3.0 起，此参数不再存在，并使用 --enable-cgi 替代。

--disable-path-info-check

如果该选项被禁用，例如 /info.php/test?a=b 形式的路径将不能工作。更多信息请参考 » Apache 手册。

从 PHP 5.3.0 起，此选项默认开启并且不再使用。如果想禁用此特性，需要在 INI 配置中将 cgi.fix_pathinfo 设置成 0。

User Contributed Notes

atesin () gmail ! com 04-Feb-2021 08:55
i'll answer myself (FINALLY!)

current "configure options" can be viewed with "php-config" shell script, aside with other compile time options too =D!!! ...

in some distributions it comes with the "php-devel" package... but until in this online manual "php-config" is mentioned in pecl extensions documentation (i couldn't find on pecl site), idk if that "php-devel" has something to do with this

... however i noticed they are literal strings inside the script, i hope the script itself were built together with php compilation o_O

in the previous page "configure options" (link shown above ^), there is an editor note with additional info about it
atesin () gmail ! com 04-Feb-2021 02:38
please somebody tell me how to display configure options used in php actual binary

it was shown in phpinfo() some years before, it was very useful, specially with 'phpize' recompilation and to enable some pecl/pear module :/

please tell me also which ctriteria had php guys used to suddenly decided to hide (or obfuscate) this info :/

thanks in advance


php.ini 配置

Table of Contents

  • php.ini 配置选项列表
  • php.ini 配置段列表
  • php.ini 核心配置选项说明

User Contributed Notes

There are no user contributed notes for this page.


php.ini 配置选项列表

可以在 php.ini 中使用下列配置选项对 PHP 进行配置。

"可修改范围"列决定了该配置选项在什么情况下可以被设置。查看 配置可被设定范围 列表查看具体定义。

配置选项
名字 | 默认 | 可修改范围 | 更新日志
allow_url_fopen | "1" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | 从 PHP 7.4.0 开始被废弃。
arg_separator.input | "&" | PHP_INI_PERDIR |
arg_separator.output | "&" | PHP_INI_ALL |
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR |
auto_detect_line_endings | "0" | PHP_INI_ALL |
auto_globals_jit | "1" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
bcmath.scale | "0" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM |
cgi.discard_path | "0" | PHP_INI_SYSTEM |
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_ALL |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
child_terminate | "0" | PHP_INI_ALL |
cli.pager | "" | PHP_INI_ALL | 自 PHP 5.4.0 可用.
cli.prompt | "\\b \\> " | PHP_INI_ALL | 自 PHP 5.4.0 可用.
cli_server.color | "0" | PHP_INI_ALL | PHP 5.4.0. 起生效
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.dotnet_version | "" | PHP_INI_SYSTEM | As of PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
curl.cainfo | NULL | PHP_INI_SYSTEM | 自 PHP 5.3.7. 起有效
date.default_latitude | "31.7667" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.83" | PHP_INI_ALL |
date.sunset_zenith | "90.83" | PHP_INI_ALL |
date.timezone | "" | PHP_INI_ALL |
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | 默认值为 "UTF-8"
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
disable_classes | "" | php.ini only |
disable_functions | "" | php.ini only |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
docref_ext | "" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | 本过时特性将肯定会在未来被移除。
enable_post_data_reading | On | PHP_INI_PERDIR |
engine | "1" | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL |
exif.encode_jis | "" | PHP_INI_ALL |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL |
exit_on_timeout | "" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | PHP_INI_ALL |
expose_php | "1" | php.ini only |
extension | NULL | php.ini only |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM |
fbsql.autocommit | "1" | PHP_INI_SYSTEM |
fbsql.batchsize | "1000" | PHP_INI_ALL |
fbsql.default_database | "" | PHP_INI_SYSTEM |
fbsql.default_database_password | "" | PHP_INI_SYSTEM |
fbsql.default_host | NULL | PHP_INI_SYSTEM |
fbsql.default_password | "" | PHP_INI_SYSTEM |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM |
fbsql.max_connections | "128" | PHP_INI_SYSTEM |
fbsql.max_links | "128" | PHP_INI_SYSTEM |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM |
fbsql.max_results | "128" | PHP_INI_SYSTEM |
fbsql.show_timestamp_decimals | "0" | PHP_INI_SYSTEM |
file_uploads | "1" | PHP_INI_SYSTEM |
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL |
geoip.custom_directory | "" | PHP_INI_ALL |
hard_timeout | "2" | PHP_INI_SYSTEM | PHP 7.1.0 起可用
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL |
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.
iconv.input_encoding | "" | PHP_INI_ALL | 在 PHP 5.6.0 中废弃。
iconv.output_encoding | "" | PHP_INI_ALL | 在 PHP 5.6.0 中废弃。
iconv.internal_encoding | "" | PHP_INI_ALL | 在 PHP 5.6.0 中废弃。
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
ignore_user_abort | "0" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL |
include_path | ".:/path/to/php/pear" | PHP_INI_ALL |
intl.default_locale |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Available since PHP 5.5 and PECL 3.0.0a1
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.auto | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Available since ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
last_modified | "0" | PHP_INI_ALL |
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
mail.add_x_header | "0" | PHP_INI_PERDIR |
mail.force_extra_parameters | NULL | php.ini only |
mail.log | "" | PHP_INI_PERDIR |
max_execution_time | "30" | PHP_INI_ALL |
max_input_nesting_level | "64" | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
max_input_time | "-1" | PHP_INI_PERDIR |
mbstring.language | "neutral" | PHP_INI_ALL | PHP_INI_PERDIR 位于 PHP <= 5.2.6
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.http_input | "pass" | PHP_INI_ALL |
mbstring.http_output | "pass" | PHP_INI_ALL |
mbstring.internal_encoding | NULL | PHP_INI_ALL |
mbstring.script_encoding | NULL | PHP_INI_ALL | 在 PHP 5.4.0. 中移除， 使用 zend.script_encoding 代替。
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP <= 5.2.6 是 PHP_INI_PERDIR。 Deprecated as of PHP 7.2.0; removed as of PHP 8.0.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL | Available as of PHP 5.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | 自 PHP 5.1.2 起有效。
mcrypt.algorithms_dir | null | PHP_INI_ALL |
mcrypt.modes_dir | null | PHP_INI_ALL |
memcache.allow_failover | "1" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
session.save_handler | "files" | PHP_INI_ALL | Supported since memcache 2.1.2
session.save_path | "" | PHP_INI_ALL | Supported since memcache 2.1.2
memcache.protocol | ascii | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Supported since memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Supported since memcache 3.0.4
memory_limit | "128M" | PHP_INI_ALL |
mongo.allow_empty_keys | 0 | PHP_INI_ALL |
mongo.allow_persistent | 1 | PHP_INI_ALL | Removed in 1.2.0
mongo.chunk_size | 262144 | PHP_INI_ALL |
mongo.cmd | "$" | PHP_INI_ALL |
mongo.default_host | "localhost" | PHP_INI_ALL |
mongo.default_port | 27017 | PHP_INI_ALL |
mongo.is_master_interval | 15 | PHP_INI_ALL | Added in 1.2.10, before 1.3.0 the default value was 60.
mongo.long_as_object | 0 | PHP_INI_ALL |
mongo.native_long | 1 | PHP_INI_ALL | Before 1.5.0, the default value was 0.
mongo.ping_interval | 5 | PHP_INI_ALL | Added in 1.2.10
mongo.utf8 | 1 | PHP_INI_ALL |
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | 自 PHP 4.3.0 起可用
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | 自 PHP 4.0.1 起可用
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL | 自 PHP 4.3.0 起可用。在 PHP <= 4.3.2 时为 PHP_INI_SYSTEM
mysqli.allow_local_infile | "0" | PHP_INI_SYSTEM | 自PHP 5.2.4起可用。在 PHP 7.2.16 和 7.3.3 之前，默认值为 "1"
mysqli.local_infile_directory |  | PHP_INI_SYSTEM |
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | 自PHP 5.3.0起可用。
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | 自PHP 5.3.0起可用。
mysqli.max_links | "-1" | PHP_INI_SYSTEM |
mysqli.default_port | "3306" | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_host | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_INI_ALL | 自PHP 5.0.0起可用。
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.reconnect | "0" | PHP_INI_SYSTEM |
mysqli.rollback_on_cached_plink | TRUE | PHP_INI_SYSTEM | 自 PHP 5.6.0 起可用。
mysqlnd.collect_statistics | "1" | PHP_INI_SYSTEM |
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM |
mysqlnd.debug | "" | PHP_INI_SYSTEM |
mysqlnd.log_mask | 0 | PHP_INI_ALL |
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL |
mysqlnd.net_read_timeout | "86400" | PHP_INI_ALL | Before PHP 7.2.0 the default value was "31536000" and the changeability was PHP_INI_SYSTEM
mysqlnd.net_cmd_buffer_size | "4096" | PHP_INI_SYSTEM |
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM |
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR |
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM |
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL |
mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM | Available since 1.0.0
mysqlnd_ms.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.force_config_usage | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.ini_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.config_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.collect_statistics | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.multi_master | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.disable_rw_split | 0 | PHP_INI_SYSTEM |
mysqlnd_mux.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.enable_qc | 1 | PHP_INI_SYSTEM |
mysqlnd_qc.ttl | 30 | PHP_INI_ALL |
mysqlnd_qc.cache_by_default | 0 | PHP_INI_ALL |
mysqlnd_qc.cache_no_table | 0 | PHP_INI_ALL |
mysqlnd_qc.use_request_time | 0 | PHP_INI_ALL |
mysqlnd_qc.time_statistics | 1 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics | 0 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics_log_file | /tmp/mysqlnd_qc.stats | PHP_INI_SYSTEM |
mysqlnd_qc.collect_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.query_trace_bt_depth | 3 | PHP_INI_SYSTEM |
mysqlnd_qc.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.ignore_sql_comments | 1 | PHP_INI_ALL |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | PHP_INI_SYSTEM |
mysqlnd_qc.std_data_copy | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.apc_prefix | qc_ | PHP_INI_ALL |
mysqlnd_qc.memc_server | 127.0.0.1 | PHP_INI_ALL |
mysqlnd_qc.memc_port | 11211 | PHP_INI_ALL |
mysqlnd_qc.sqlite_data_file | :memory: | PHP_INI_ALL |
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |
oci8.connection_class | "" | PHP_INI_ALL | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch | "100" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.events | Off | PHP_INI_SYSTEM | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.privileged_connect | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL | Available as of PHP 5.3.0
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | 在 PHP 7.1.2 至 7.1.6 （含）的版本，默认值是"1"
opcache.memory_consumption | "128" | PHP_INI_SYSTEM | 在 PHP 7.0.0 之前，默认值是 "64"
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM | 在 PHP 7.0.0 之前，默认值是 "4"
opcache.max_accelerated_files | "10000" | PHP_INI_SYSTEM | 在 PHP 7.0.0 之前，默认值是 "2000"
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.load_comments | "1" | PHP_INI_ALL | 从 PHP 7.0.0 开始被移除
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM | 从 PHP 7.2.0 开始被移除
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFFBFFF" | PHP_INI_SYSTEM | 从 PHP 5.6.18 开始，默认值从 0xFFFFFFFF 修改为 0x7FFFBFFF
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | 自 PHP 7.3.0 被移除
opcache.dups_fix | "0" | PHP_INI_ALL |
opcache.blacklist_filename | "" | PHP_INI_SYSTEM |
opcache.max_file_size | "0" | PHP_INI_SYSTEM |
opcache.consistency_checks | "0" | PHP_INI_ALL |
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | null | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_update_protection | "2" | PHP_INI_ALL |
opcache.huge_code_pages | "0" | PHP_INI_SYSTEM |
opcache.lockfile_path | "/tmp" | PHP_INI_SYSTEM |
opcache.opt_debug_level | "0" | PHP_INI_SYSTEM |
opcache.file_cache | NULL | PHP_INI_SYSTEM | 从 PHP 7.0.0 开始支持
opcache.file_cache_only | "0" | PHP_INI_SYSTEM | 从 PHP 7.0.0 开始支持
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM | 从 PHP 7.0.0 开始支持
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | 从 PHP 7.0.0 开始支持，仅适用于 Windows 平台
opcache.validate_permission | "0" | PHP_INI_SYSTEM | 从 PHP 7.0.14 开始支持
opcache.validate_root | "0" | PHP_INI_SYSTEM | 从 PHP 7.0.14 开始支持
opcache.preload | "" | PHP_INI_SYSTEM | 从 PHP 7.4.0 开始支持
opcache.preload_user | "" | PHP_INI_SYSTEM | 从 PHP 7.4.0 开始支持
open_basedir | NULL | PHP_INI_ALL | 在 PHP < 5.2.3 时是 PHP_INI_SYSTEM。
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
pcre.backtrack_limit | "100000" | PHP_INI_ALL | php 5.2.0 起可用。
pcre.recursion_limit | "100000" | PHP_INI_ALL | php 5.2.0 起可用。
pcre.jit | "1" | PHP_INI_ALL | PHP 7.0.0 起可用
pdo.dsn.* |  | 仅 php.ini |
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Available since PHP 5.1.1. 本过时特性将肯定会在未来被移除。
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | 从 PHP 4.2.0 起开始存在
pgsql.ignore_notice | "0" | PHP_INI_ALL | 从 PHP 4.3.0 起开始存在
pgsql.log_notice | "0" | PHP_INI_ALL | 从 PHP 4.3.0 起开始存在
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
phar.cache_list | "" | PHP_INI_SYSTEM |
post_max_size | "8M" | PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM |
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |
register_argc_argv | "1" | PHP_INI_PERDIR |
report_memleaks | "1" | PHP_INI_ALL |
report_zend_debug | "1" | PHP_INI_ALL |
request_order | "" | PHP_INI_PERDIR |
runkit.superglobal | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
serialize_precision | "-1" | PHP_INI_ALL | PHP 7.1.0 之前，默认值为 17。
session.save_path | "" | PHP_INI_ALL |
session.name | "PHPSESSID" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.auto_start | "0" | PHP_INI_PERDIR |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL |
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL |
session.cookie_httponly | "" | PHP_INI_ALL | 自 PHP 5.2.0 起有效
session.cookie_samesite | "" | PHP_INI_ALL | 自 PHP 7.3.0 起有效
session.use_strict_mode | "0" | PHP_INI_ALL | 自 PHP 5.5.2 起有效
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cache_expire | "180" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL |
session.trans_sid_tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.sid_length | "32" | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.sid_bits_per_character | "4" | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.upload_progress.enabled | "1" | PHP_INI_PERDIR |
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR |
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR |
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR |
session.upload_progress.freq | "1%" | PHP_INI_PERDIR |
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR |
session.lazy_write | "1" | PHP_INI_ALL |
session.hash_function | "0" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
session.hash_bits_per_character | "4" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
session.entropy_file | "" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
session.entropy_length | "0" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
short_open_tag | "1" | PHP_INI_PERDIR |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite3.extension_dir | "" | PHP_INI_SYSTEM | PHP 5.3.11 起可用
sqlite3.defensive | 1 | PHP_INI_SYSTEM | PHP 7.2.17 和 7.3.4 起可用，libsqlite ≥ 3.26.0。
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | 从 PHP 7.3.0 起可用。
syslog.filter | "no-ctrl" | PHP_INI_ALL | 从 PHP 7.3.0 起可用。
syslog.ident | "php" | PHP_INI_SYSTEM | 从 PHP 7.3.0 起可用。
sys_temp_dir | "" | PHP_INI_SYSTEM |
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |
tidy.default_config | "" | PHP_INI_SYSTEM |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR prior to PHP 5.4.0
track_errors | "0" | PHP_INI_ALL | 自 PHP 7.2.0 起废弃。
unserialize_callback_func | NULL | PHP_INI_ALL |
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL |
user_agent | NULL | PHP_INI_ALL |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM |
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM |
uopz.disable | "0" | PHP_INI_SYSTEM | Available as of uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Available as of uopz 6.0.1
uopz.overloads | "1" | PHP_INI_SYSTEM | Available as of uopz 2.0.2. Removed as of uopz 5.0.0.
variables_order | "EGPCS" | PHP_INI_PERDIR |
vld.active | "0" | PHP_INI_SYSTEM |
vld.execute | "1" | PHP_INI_SYSTEM | 从 vld 0.8.0 起可用。
vld.skip_append | "0" | PHP_INI_SYSTEM | 从 vld 0.8.0 起可用。
vld.skip_prepend | "0" | PHP_INI_SYSTEM | 从 vld 0.8.0 起可用。
windows.show_crt_warning | "0" | PHP_INI_ALL |
xbithack | "0" | PHP_INI_ALL |
xmlrpc_errors | "0" | PHP_INI_SYSTEM |
xmlrpc_error_number | "0" | PHP_INI_ALL |
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_mask | NULL | PHP_INI_ALL | 从 yaz 1.0.3 起可用。
zend.assertions | "1" | PHP_INI_ALL |
zend.detect_unicode | "1" | PHP_INI_ALL |
zend.enable_gc | "1" | PHP_INI_ALL |
zend.multibyte | "0" | PHP_INI_PERDIR |
zend.script_encoding | NULL | PHP_INI_ALL |
zend.signal_check | "0" | PHP_INI_SYSTEM |
zend_extension | NULL | php.ini only |
zlib.output_compression | "0" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |

User Contributed Notes

There are no user contributed notes for this page.


php.ini 配置段列表

This list includes the php.ini sections you can set to configure your PHP setup on a per Host or Path basis. These sections are optional.

These sections don't directly affect PHP. They are used to group other php.ini directives together and to get them to act upon a particular host or on a particular path.

These sections are used only in CGI/FastCGI mode and they can not set extension and zend_extension directives.

配置段
名字 | 可修改范围 | 更新日志
[HOST=] | PHP_INI_SYSTEM | 在 PHP 5.3.0 时增加。
[PATH=] | PHP_INI_SYSTEM | 在 PHP 5.3.0 时增加。

这是配置指令的简短说明。

[HOST=<host>]

This section allows you to define a set of php.ini directives that will take effect on the named host.

Example #1 Activate full on-screen error reporting for dev. domain

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

This section allows you to define a set of php.ini directives that will take effect when a script runs from the named path.

Example #2 Add security script for protected areas

[PATH=/home/site/public/secure]
auto_prepend_file=security.php

User Contributed Notes

dasloch at absatzen dot de 12-Feb-2020 12:47
Note that you cannot usefully set syslog.* in [PATH=] (and probably [HOST=]) sections, since the syslogger is initialized only once per php-fpm worker process, and not per request.
robinhook at mail dot com 22-Apr-2018 07:14
Sorry for the note. I've read some bad tutorials.
The correct syntax is : directive = 'value'
not a thing like : php_value[directive] = "somevalue"
robinhook at mail dot com 22-Apr-2018 06:59
this HOST and PATH sections doesn't seems to work in php.ini under apache 2.4 with php-fpm 7.1.16 for directive php_value or php_admin_value open_basedir or include_path.
phpinfo() says "none" in master and local values.
z dot himdi at bita dot nl 04-Aug-2011 07:53
On Windows IIS 7 server I noticed that [PATH=] was not listened to. [HOST=] however worked.
leo 06-May-2011 03:21
Just developed the probably first php.ini hack to add commands which will only be parsed before PHP 5.3 when using mod_php.

<?php

# Disable eAccelerator by default
eaccelerator.enable = 0

# Now, to prevent incompatibilities with Zend Optimizer+, we
# want to enable eAccelerator only in PHP 5.2 or lower.
[HOST=*]
eaccelerator.enable = 1

?>

What is happening here? In PHP 5.3, php.ini sections to set up PHP on a per host basis have been introduced:

http://www.php.net/manual/en/ini.sections.php

These sections only work in CGI/FastCGI mode, however there still seems to be a difference in how the php.ini file is parsed in PHP 5.2 and PHP 5.3 when using mod_php: PHP 5.3 ignores everything below the line [HOST=*], whereas PHP 5.2 does not.

In the above example, PHP 5.3 only reads "eaccelerator.enable = 0" and then stops at the invalid command [HOST=*]. However, PHP 5.2 seems to ignore the invalid command and parses the whole configuration file, ending up with "eaccelerator.enable = 1".
crash at lubyte dot de 06-Sep-2010 05:45
If you have a system which uses separated PHP inis for loading extensions (Debian, Fedora and most other distributions do so), [PATH=] or [HOST=] will prevent loading extensions defined in those ini files (extension= and zend_extension=).

I had some headache, when I added a hosts.ini to /etc/php5/cgi/conf.d (Debians default), where I wanted to define some defaults for a host name. The manual says extension= and zend_extension= aren't allowed in [HOST=] and [PATH=] (see above). I figured out that you can easily fix that with adding [PHP] after your definitions.

For example hosts.ini:
[HOST=dev.example.com]
display_errors = on

[PHP]

this will change the section back to [PHP] where extension= and zend_extension= is allowed.
robert dot johnson at icap dot com 12-Apr-2010 10:26
Adding PATH= applies only to the named path and does not include sub-directories, you have to add a PATH= value for each sub-directory.

Also some settings have no effect even though phpinfo recognises and displays the per-folder value as the 'local' value, and the default as the 'master' value.

'fastcgi.impersonate' always uses the master setting.
public at grik dot net 24-Sep-2009 03:00
In [HOST=...] one should use only the 1st server name from the list of server names.

I.E. if you have
server_name example.com, example2.com;
and will use www.example.com in a browser,
use [HOST=example.com] in php.ini for both addresses.

PHP looks not at the HOST request header (as I expected), but at the SERVER_NAME parameter (which by default is the 1st from the list of names, no matter what the HOST is).


php.ini 核心配置选项说明

该列表只包含核心的 php.ini 配置选项。扩展的配置选项在各个扩展的文档页面分别被描述。比如，有关 session 的选项可以在 sessions 页面找到。

Note:

以下列出了未设置 php.ini 时的默认值；开发环境和生产环境的 php.ini 值可能会有所不同。

语言选项

语言和杂类配置选项
名字 | 默认 | 可修改范围 | 更新日志
short_open_tag | "1" | PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
serialize_precision | "-1" | PHP_INI_ALL | 在 PHP 7.1.0 以前，默认值为 17。
disable_functions | "" | 仅仅为 PHP_INI_SYSTEM |
disable_classes | "" | 仅仅为 php.ini |
exit_on_timeout | "" | PHP_INI_ALL |
expose_php | "1" | php.ini only |
hard_timeout | "2" | PHP_INI_SYSTEM | 从 PHP 7.1.0 起可用
zend.exception_ignore_args | "0" | PHP_INI_ALL | 从 PHP 7.4.0 起可用
zend.multibyte | "0" | PHP_INI_ALL |
zend.script_encoding | NULL | PHP_INI_ALL |
zend.detect-unicode | NULL | PHP_INI_ALL | 从 PHP 5.4.0 起可用
zend.signal_check | "0" | PHP_INI_SYSTEM |
zend.assertions | "1" | PHP_INI_ALL |

这是配置指令的简短说明。

short_open_tag bool

决定是否允许使用 PHP 代码开始标志的缩写形式（<? ?>）。如果要和 XML 结合使用 PHP，可以禁用此选项以便于嵌入使用 <?xml ?>。否则还可以通过 PHP 来输出，例如：<?php echo '<?xml version="1.0"'; ?>。如果禁用了，必须使用 PHP 代码开始标志的完整形式（<?php ?>）。

Note:

本指令不会影响到缩写形式 <?=，因为它总是可用的。

precision int
浮点数中显示有效数字的位数。-1 means that an enhanced algorithm for rounding such numbers will be used.
serialize_precision int
The number of significant digits stored while serializing floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.
expose_php bool

决定是否暴露 PHP 被安装在服务器上（例如在 Web 服务器的信息头中加上其签名：X-Powered-By: PHP/5.3.7)。

disable_functions string

本指令可用于禁止某些函数。接受逗号分隔的函数名列表作为参数。

此指令仅能禁用 内置函数。 不能影响用户自定义函数。

本指令只能设置在 php.ini 中。例如，无法在 httpd.conf 中设置。

disable_classes string
本指令可以使你禁用某些类。用逗号分隔类名。 本指令只能设置在 php.ini 中。例如不能将其设置在 httpd.conf。
zend.assertions int
When set to 1, assertion code will be generated and executed (development mode). When set to 0, assertion code will be generated but it will be skipped (not executed) at runtime. When set to -1, assertion code will not be generated, making the assetions zero-cost (production mode).

Note:

If a process is started in production mode, zend.assertions cannot be changed at runtime, since the code for assertions was not generated.

If a process is started in development mode, zend.assertions cannot be set to -1 at runtime.

hard_timeout int

zend.exception_ignore_args bool

从异常产生的堆栈中排除参数。

zend.multibyte bool

启用多字节编码的源文件解析功能。启用 zend.multibyte 是使用 SJIS、BIG5 等在多字节字符串数据中包含特殊字符的字符编码所必需的。ISO-8859-1 兼容的编码，如 UTF-8、EUC 等，则不需要这个选项。

启用 zend.multibyte 需要 mbstring 扩展可用。

zend.script_encoding string

This value will be used unless a declare(encoding=...) directive appears at the top of the script. When ISO-8859-1 incompatible encoding is used, both zend.multibyte and zend.script_encoding must be used.

Literal strings will be transliterated from zend.script_enconding to mbstring.internal_encoding, as if mb_convert_encoding() would have been called.

zend.detect_unicode bool

Check for BOM (Byte Order Mark) and see if the file contains valid multibyte characters. This detection is performed before processing of __halt_compiler(). Available only in Zend Multibyte mode.

zend.signal_check bool

To check for replaced signal handlers on shutdown.

exit_on_timeout bool

这是一个用于 Apache 1 的 mod_php-only 指令，如果 PHP 执行超时，会强制 Apache 子程序退出.这样的超时会导致 Apache 1 内部的 longjmp() 调用，从而使一些扩展处于不一致的状态。通过终止进程，任何未完成的锁或内存将被清理。

资源限制

资源限制
名字 | 默认 | 可修改范围 | 更新日志
memory_limit | "128M" | PHP_INI_ALL |

这是配置指令的简短说明。

memory_limit int

设置了一个脚本允许分配的最大内存量，以字节（bytes）为单位。这有助于防止写得不好的脚本吃掉服务器上所有可用的内存。请注意，如果不需要内存限制，请将此指令设置为 -1。

当使用 int 时, 其值以字节来衡量。还可以使用在FAQ中描述的速记符。

请参阅：max_execution_time。

性能调整

性能调整
名字 | 默认 | 可修改范围 | 更新日志
realpath_cache_size | "4M" | PHP_INI_SYSTEM | PPHP 7.0.16 和 7.1.2 之前，默认值为 "16K"
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |

Note:

启用 open_basedir 将会 禁用 realpath cache。

这是配置指令的简短说明。

realpath_cache_size int

设定 PHP 使用的 realpath 缓存的大小。在 PHP 打开很多文件的系统中，这个值应该增加，以优化文件操作的数量。

这里的大小表示存储的路径字符串的总字节数，加上与缓存条目相关的数据大小。这意味着，为了在缓存中存储更长的路径，缓存大小必须更大。这个值不直接控制可以缓存的不同路径的数量。

缓存输入数据所需的大小取决于操作系统。

realpath_cache_ttl integer

缓存给定文件或目录的真实路径信息的持续时间（以秒为单位）。对于很少改变文件的系统，可以考虑增加该值。

数据处理

数据处理配置选项
名字 | 默认 | 可修改范围 | 更新日志
arg_separator.output | "&" | PHP_INI_ALL |
arg_separator.input | "&" | PHP_INI_PERDIR |
variables_order | "EGPCS" | PHP_INI_PERDIR |
request_order | "" | PHP_INI_PERDIR |
auto_globals_jit | "1" | PHP_INI_PERDIR |
register_argc_argv | "1" | PHP_INI_PERDIR |
enable_post_data_reading | "1" | PHP_INI_PERDIR | 从 PHP 5.4.0 起可用。
post_max_size | "8M" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
auto_append_file | NULL | PHP_INI_PERDIR |
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL |
input_encoding | "" | PHP_INI_ALL |
output_encoding | "" | PHP_INI_ALL |
internal_encoding | "" | PHP_INI_ALL |

这是配置指令的简短说明。

arg_separator.output string

在 PHP 生成的 URL 中用来分隔参数的分隔符。

arg_separator.input string

PHP 用于将输入的 URL 解析为变量的分隔符列表。

Note:

本指令中的每一个字符都被视为分隔符！

variables_order string

Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable parsing. For example, if variables_order is set to "SP" then PHP will create the superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting to "" means no superglobals will be set.

Warning

In both the CGI and FastCGI SAPIs, $_SERVER is also populated by values from the environment; S is always equivalent to ES regardless of the placement of E elsewhere in this directive.

Note:

The content and order of $_REQUEST is also affected by this directive.

request_order string

This directive describes the order in which PHP registers GET, POST and Cookie variables into the _REQUEST array. Registration is done from left to right, newer values override older values.

If this directive is not set, variables_order is used for $_REQUEST contents.

Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns.

auto_globals_jit bool

When enabled, the SERVER, REQUEST, and ENV variables are created when they're first used (Just In Time) instead of when the script starts. If these variables are not used within a script, having this directive on will result in a performance gain.

Warning

Usage of SERVER, REQUEST, and ENV variables is checked during the compile time so using them through e.g. variable variables will not cause their initialization.

register_argc_argv bool
Tells PHP whether to declare the argv & argc variables (that would contain the GET information). See also command line.
enable_post_data_reading bool
Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. This can be useful to proxy requests or to process the POST data in a memory efficient fashion.
post_max_size int
Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size. 当使用 int 时, 其值以字节来衡量。还可以使用在FAQ中描述的速记符。 If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. <form action="edit.php?processed=1">, and then checking if $_GET['processed'] is set.

Note:

PHP allows shortcuts for byte values, including K (kilo), M (mega) and G (giga). PHP will do the conversions automatically if you use any of these. Be careful not to exceed the 32 bit signed integer limit (if you're using 32bit versions) as it will cause your script to fail.

Changelog for post_max_size
版本 | 说明
5.3.4 | post_max_size = 0 will not disable the limit when the content type is application/x-www-form-urlencoded or is not registered with PHP.
5.3.2 , 5.2.12 | Allow unlimited post size by setting post_max_size to 0.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-prepending.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-appending.

Note: If the script is terminated with exit(), auto-append will not occur.

default_mimetype string

By default, PHP will output a media type using the Content-Type header. To disable this, simply set it to be empty.

PHP's built-in default media type is set to text/html.

default_charset string

"UTF-8" is the default value and its value is used as the default character encoding for htmlentities(), html_entity_decode() and htmlspecialchars() if the encoding parameter is omitted. The value of default_charset will also be used to set the default character set for iconv functions if the iconv.input_encoding, iconv.output_encoding and iconv.internal_encoding configuration options are unset, and for mbstring functions if the mbstring.http_input mbstring.http_output mbstring.internal_encoding configuration option is unset.

All versions of PHP will use this value as the charset within the default Content-Type header sent by PHP if the header isn't overridden by a call to header().

Setting default_charset to an empty value is not recommended.

input_encoding string

This setting is used for multibyte modules such as mbstring and iconv. Default is empty.

output_encoding string

This setting is used for multibyte modules such as mbstring and iconv. Default is empty.

internal_encoding string

This setting is used for multibyte modules such as mbstring and iconv. Default is empty. If empty, default_charset is used.

See also: magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase.

Paths and Directories

Paths and Directories Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM |
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
extension | NULL | php.ini only |
zend_extension | NULL | php.ini only |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM |
cgi.discard_path | "0" | PHP_INI_SYSTEM |
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_SYSTEM |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |

这是配置指令的简短说明。

include_path string

Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn't find it, check the next path, until it either locates the included file or returns with an E_WARNING or an E_ERROR. You may modify or set your include path at runtime using set_include_path().

Example #1 Unix include_path

include_path=".:/php/includes"

Example #2 Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory. However, it is more efficient to explicitly use include './file' than having PHP always check the current directory for every include.

Note:

ENV variables are also accessible in .ini files. As such it is possible to reference the home directory using ${LOGIN} and ${USER}.

Environment variables may vary between Server APIs as those environments may be different.

Example #3 Unix include_path using ${USER} env variable

include_path = ".:${USER}/pear/php"

open_basedir string

Limit the files that can be accessed by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

When a script tries to access the filesystem, for example using include, or fopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to access it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink. If the file doesn't exist then the symlink couldn't be resolved and the filename is compared to (a resolved) open_basedir.

open_basedir can affect more than just filesystem functions; for example if MySQL is configured to use mysqlnd drivers, LOAD DATA INFILE will be affected by open_basedir. Much of the extended functionality of PHP uses open_basedir in this way.

The special value . indicates that the working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().

In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

The restriction specified with open_basedir is a directory name, not a prefix.

The default is to allow all files to be opened.

Note:

open_basedir can be tightened at run-time. This means that if open_basedir is set to /www/ in php.ini a script can tighten the configuration to /www/tmp/ at run-time with ini_set(). When listing several directories, you can use the PATH_SEPARATOR constant as a separator regardless of the operating system.

Note:

Using open_basedir will set realpath_cache_size to 0 and thus disable the realpath cache.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below.

user_ini.cache_ttl int

user_ini.filename string

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example public_html .

extension_dir string

In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

zend_extension string

Name of dynamically loadable Zend extension (for example XDebug) to load when PHP starts up.

cgi.check_shebang_line bool

Controls whether CGI PHP checks for line starting with #! (shebang) at the top of the running script. This line might be needed if the script support running both as stand-alone script and via PHP CGI. PHP in CGI mode skips this line and ignores its content if this directive is turned on.

cgi.discard_path bool

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

cgi.fix_pathinfo bool

Provides real PATH_INFO/ PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the CGI specs. Setting this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting of zero causes PHP to behave as before. It is turned on by default. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect bool

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.

Note:

Windows Users: When using IIS this option must be turned off. For OmniHTTPD or Xitami the same applies.

cgi.nph bool

If cgi.nph is enabled it will force cgi to always sent Status: 200 with every request.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.

Note:

Setting this variable may cause security issues, know what you are doing first.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it's set to 0, PHP sends a » RFC 3875 "Status:" header that is supported by Apache and other web servers. When this option is set to 1, PHP will send » RFC 2616 compliant headers.

If this option is enabled, and you are running PHP in a CGI environment (e.g. PHP-FPM) you should not use standard RFC 2616 style HTTP status response headers, you should instead use their RFC 3875 equivalent e.g. instead of header("HTTP/1.0 404 Not found"); you should use header("Status: 404 Not Found");

Leave it set to 0 unless you know what you're doing.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

fastcgi.logging bool

Turns on SAPI logging when using FastCGI. Default is to enable logging.

File Uploads

File Uploads Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
file_uploads | "1" | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM |

这是配置指令的简短说明。

file_uploads bool

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

If the directory specified here is not writable, PHP falls back to the system default temporary directory. If open_basedir is on, then the system default directory must be allowed for an upload to succeed.

upload_max_filesize int

The maximum size of an uploaded file.

当使用 int 时, 其值以字节来衡量。还可以使用在FAQ中描述的速记符。
max_file_uploads int

The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

General SQL

General SQL Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
sql.safe_mode | "0" | PHP_INI_SYSTEM | Removed as of PHP 7.2.0

这是配置指令的简短说明。

sql.safe_mode bool

If turned on, database connection functions that specify default values will use those values in place of any user-supplied arguments. For details on the default values, see the documentation for the relevant connection functions.

Warning

This feature has been REMOVED as of PHP 7.2.0.

Windows Specific

Windows Specific Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
windows.show_crt_warning | "0" | PHP_INI_ALL |

这是配置指令的简短说明。

windows.show_crt_warning bool

This directive shows the Windows CRT warnings when enabled.

User Contributed Notes

Simone Pellegatta 19-Jan-2021 12:08
Be careful while using auto_prepend_file.

When the custom exception handler, set by set_exception_handler(), handles an uncaught exception, it interrupts the execution of every script.

If the script with the unhandled exception has been automatically prepended or included by an automatically prepended script, however, the main script will continue running anyway.

This could cause several issues: when we think that throwing an exception would automatically interrupt the current application, a whole chunk of code is going to run anyway.
Anton Bannikov 22-Apr-2020 02:40
I had a problem with 'open_basedir =' string in php.ini. This string was writtren in VirtualHost Directory directive of Apache2 and successfully rewrote the same php.ini setting! It happened with VestaCP, but I think, it's a common way. Goog luck!
luisdev 03-Mar-2020 02:59
https://haydenjames.io/understanding-php-memory_limit/ explains the memory_limit setting nicely.
diamondeagle at webmail dot co dot za 15-Aug-2019 11:14
Note regarding the upload_tmp_dir setting and UNC Paths:

When using PHP on Windows OS and IIS FastCGI, if you need to use a UNC path to a folder on a network drive for the upload_tmp_dir setting then you must use three \ characters at the front of the UNC path.

Windows and PHP use the first slash as an escape character, so if you only use two slashes then it passes a UNC path with just one backslash. That is not valid for UNC paths and you many experience problems when uploading files, such as errors saying that "PHP is missing a temporary folder".

Correct:
upload_tmp_dir = "\\\path\to\your\folder"

Incorrect:
upload_tmp_dir = "\\path\to\your\folder"
alaa morad 09-Jan-2019 08:16
add enctype="multipart/form-data" to your <form> tag or it will not upload any file even if file_uploads=on
ex:
<form method="POST" action="upload. php" enctype="multipart/form-data">
// form contents
</form>
abc500x500 at gmail dot com 26-Aug-2017 08:10
Please illuminate this:
memory_limit=128mb meaning which?

1-per script only then if in a moment 1000 user request php script maximum only 128mb of server ram use6 by script.
2-per script + per user if in a moment 1000 user request a php script about 1000*128mb=128gb ram use by script.
Thanks
Adam 27-Jan-2017 02:51
Remember that `open_basedir` restriction does not affect exec functions. As long as you do not disable exec functions (see `disable_functions`, users will be able to use `exec("/bin/cat [...]")` to access sensitive world readable files.
fernandobasso dot br at gmail dot com 17-Oct-2016 08:06
This might help in case someone happens to maintain old applications with a charset other than utf-8.

According to the docs, you can override the default charset if you use `header()`.

Suppose php.ini sets the default_charset to "UTF-8", but you need a legacy charset, like ISO-8859-1.

Still,

<?php header('Content-Type: text/html; Charset=ISO-8859-1'); ?>

would not override the charset, just add it as well and the result
was a response header like (note the two charsets):

    Content-Type:"text/html; Charset=ISO-8859-1;CHARSET=gb2312"

I found it strange the default one as `charset` with a lowercase `c`
as opposed to my custom charset with an uppercase `C`.

What solved was to _override_ the charset using all lowercase letters
as well for the word "charset":

<?php header('content-type: text/html; charset=ISO-8859-1'); ?>

Then, the double charset from the response headers disappeared, and only the single, custom charset remained.
dougal at gunters dot org 03-Mar-2016 05:11
It appears that if you use both the 'include_path' directives and 'open_basedir', that file searches will hit the include path *first*, before local files. But if 'open_basedir' is not in use, then local files are found first. For example, suppose you have code in '/var/www/myfile.php' which does:

<?php
  require_once('config.php');
?>

Further, assume that there is a local file '/var/www/config.php', and there is also a file '/var/local/php/config.php'.

Next, if your php.ini has:

  include_path = /var/local/php/

Normally, this would look for '/var/www/config.php' first, and if not found, then it would try '/var/local/php/config.php'.

But if you also have this in php.ini:

  open_basedir = /var/www/:/var/local/php/

Then the require would reverse the order of the search, and load '/var/local/php/config.php', even when the local 'config.php' file exists.

Furthermore, if include_path contains directories not in open_basedir, you can end up with a fatal error. For example, change the directive to:

  open_basedir = /var/www/:/var/local/includes/php/

Now the require will first find '/var/local/php/config.php' from the include_path, try to include it, but be unable to because of the open_basedir restrictions.
txyoji at yahoo dot com 21-Nov-2013 08:24
If you enable "open_basedir" option, it will disable the realpath_cache. This can be a significant performance hit.

https://bugs.php.net/bug.php?id=53263
michael dot buergi at gmx dot net 08-May-2013 06:18
the ini-setting "detect_unicode" is indeed "zend.detect_unicode" (according to the phpinfo of my 5.4.4)
iko at vision dot sk 01-May-2012 08:49
auto_globals_jit setting is also affecting $_REQUEST superglobal in 5.3 It is not explicitly stated in documentation.
kghbln 17-Nov-2011 03:09
Adding multiple directories to open_basedir:

open_basedir = "/var/www/htdocs/:/var/www/tmp/" adds both paths /var/www/htdocs/ and /var/www/tmp/. Do not forget the trailing slash, otherwise the last directory will be considered as a prefix (< 5.3.4).

On Windows you use ; as the seperator.
AntonioK 10-Mar-2011 05:29
Note that there is no way to disable eval() work by using disable_functions directive, because eval() is a language construct and not a function.

Many people advise to disable such potentially-insecure functions like system(), exec(), passthru(), eval() and so on in php.ini when not running in safe mode, but eval() would still work even it listed in disable_functions.
rlammers at linuxmail dot org 09-Jan-2011 04:23
This is a possible solution for a problem which seems to be a php-ini-problem but is not.

If a $_POST is used with large fields e.g. textarea's with more than 120kb characters php returns a blank screen, even if the max_post_size is 8M.

This problem may be caused by an apache-module SecFilter.

Adding the following lines to the .htaccess solves the problem.
SecFilterEngine Off
SecFilterScanPOST Off

I know this is not a php-issue, but i'm still posting it here since it looks like it is a php-problem and I did not find any sites or forums offering this solution.
amolitor at molitor-design dot com 10-Feb-2010 03:23
Amusingly, the include_path logically includes the current directory of the running file as the last entry all the time anyways, so part of the business about shoving "." into the include_path is spurious -- it's "there" on the end all the time, at least in the 5.2.12 source (see main/fopen_wrappers.c around line 503).

This one had me goin' for a while.
mrok at mrok dot com 22-Mar-2009 08:29
Note that on some Unix systems (i.e. PHP 5.1.6 on Centos 5.2) include_path in php.ini should NOT be quoted.

For example, instead of

 include_path='.:/usr/share/php'

use

 include_path=.:/usr/share/php

Using quotes does not cause any error message, but all of your require_once() directives will fail (indicating that file could not be opened) - unless full path to target file is provided.
leo at korfu dot cz 29-May-2006 03:45
"If the size of post data is greater than post_max_size..."

It seems that a more elegant way is comparison between post_max_size and $_SERVER['CONTENT_LENGTH']. Please note that the latter includes not only size of uploaded file plus post data but also multipart sequences. Leo
csg at DEL_THISdiatom dot de 02-Sep-2005 02:55
Starting with PHP 4.4.0 (at least PHP version 4.3.10 did have old, documented behaviour) interpretation of value of "session.save_path" did change in conjunction with "save_mode" and "open_basedir" enabled.

Documented ( http://de.php.net/manual/en/ref.session.php#ini.session.save-path ):
  Values of "session.save_path" should or may be  **without**  ending slash.
  For instance:
<?php
  // Valid only  *before* PHP 4.4.0:
  ini_set( "session.save_path", "/var/httpd/kunde/phptmp" );
?> will mean:
  The directory "/var/httpd/kunde/phptmp/" will be used to write data and therefore must be writable by the web server.

Starting with PHP 4.4.0 the server complains that "/var/httpd/kunde/" is not writable.
Solution: Add an ending slash in call of ini_set (or probably whereever you set "session.save_path"), e.g.:
<?php
  // Note the slash on ".....phptmp/":
  ini_set( "session.save_path", "/var/httpd/kunde/phptmp/" );
?>

Hope, that does help someone.


扩展库列表／归类

Table of Contents

  • 按字母顺序
  • 按归属分
  • 按状态分

本附录将 PHP 手册中的 150 多个扩展库以不同标准分类。

User Contributed Notes

There are no user contributed notes for this page.


按字母顺序

  • Apache
  • APCu
  • 数组
  • BC Math
  • Bzip2
  • Calendar
  • Classkit
  • 类/对象
  • COM
  • CSPRNG
  • Ctype
  • CUBRID
  • cURL
  • 日期/时间
  • DBA
  • dBase
  • DB++
  • Direct IO
  • 目录
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • 错误处理
  • Ev
  • Event
  • 程序执行
  • Exif
  • Expect
  • FANN
  • FANN
  • FrontBase
  • FDF
  • Fileinfo
  • filePro
  • 文件系统
  • Filter
  • FastCGI 进程管理器
  • FTP
  • 函数处理
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Hash
  • HRTime
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • GD
  • ImageMagick
  • IMAP
  • PHP 选项/信息
  • Ingres
  • Inotify
  • intl
  • JSON
  • LDAP
  • libxml
  • Lua
  • LZF
  • Mail
  • Mailparse
  • Math
  • 多字节字符串
  • Mcrypt
  • Memcache
  • Memcached
  • Memtrack
  • Mhash
  • Misc.
  • Mongo
  • MongoDB\BSON
  • MongoDB\Driver
  • mqseries
  • Mysql（原始）
  • Mysqli
  • Mysqlnd
  • mysqlnd_memcache
  • mysqlnd_ms
  • mysqlnd_mux
  • mysqlnd_qc
  • mysqlnd_uh
  • Ncurses
  • 网络
  • OAuth
  • OCI8
  • OPcache
  • OpenAL
  • OpenSSL
  • 输出控制
  • Paradox
  • Parle
  • 密码散列算法
  • PCNTL
  • PCRE
  • PDO
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • POSIX
  • Proctitle
  • PS
  • Pspell
  • pthreads
  • Quickhash
  • Radius
  • Rar
  • Readline
  • Recode
  • 反射
  • POSIX Regex
  • RRD
  • ScoutAPM
  • SeasLog
  • Semaphore
  • Sessions
  • Shared Memory
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Sodium
  • Solr
  • Sphinx
  • SPL
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Streams
  • 字符串
  • SVM
  • SVN
  • Swoole
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • tokyo_tyrant
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Variable handling
  • Varnish
  • WDDX
  • Weakref
  • win32service
  • WinCache
  • wkhtmltox
  • xattr
  • xdiff
  • Xhprof
  • XML 解析器
  • XMLDiff
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yaconf
  • Yaf
  • Yaml
  • Yar
  • YAZ
  • Zip
  • Zlib
  • 0MQ消息系统
  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


按归属分

核心扩展库

以下并非真正的扩展库，它们属于 PHP 内核的一部分，不能通过编译选项将其排除。

  • 数组

  • 类/对象

  • CSPRNG

  • 日期/时间

  • 目录

  • 错误处理

  • 程序执行

  • 文件系统

  • Filter

  • 函数处理

  • Hash

  • PHP 选项/信息

  • Mail

  • Math

  • Misc.

  • 网络

  • 输出控制

  • 密码散列算法

  • Phar

  • 反射

  • POSIX Regex

  • Sessions

  • SPL

  • Streams

  • 字符串

  • Tokenizer

  • URLs

  • Variable handling

绑定的扩展库

以下扩展库绑定在 PHP 发行包中。

  • Apache

  • BC Math

  • Calendar

  • COM

  • Ctype

  • DBA

  • Exif

  • Fileinfo

  • FTP

  • iconv

  • GD

  • intl

  • JSON

  • 多字节字符串

  • OPcache

  • PCNTL

  • PCRE

  • PDO

  • POSIX

  • Semaphore

  • Shared Memory

  • Sockets

  • SQLite3

  • XML-RPC

  • Zlib

外部扩展库

这些扩展库已经包含在PHP中但是需要编译它们才能使用，并且可能需要额外的扩展库。

  • Bzip2

  • cURL

  • dBase

  • DOM

  • Enchant

  • FrontBase

  • Gettext

  • GMP

  • Firebird/InterBase

  • IMAP

  • LDAP

  • libxml

  • Mcrypt

  • Mhash

  • Mysql（原始）

  • Mysqli

  • Mysqlnd

  • OCI8

  • OpenSSL

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • PostgreSQL

  • Pspell

  • Readline

  • Recode

  • SimpleXML

  • SNMP

  • SOAP

  • Sodium

  • Tidy

  • ODBC

  • WDDX

  • XML 解析器

  • XMLReader

  • XMLWriter

  • XSL

  • Zip

PECL 扩展库

以下扩展来自 » PECL，它们可能需要额外的库。还有更多的 PECL 扩展存在，但是在 PHP 手册中尚未有文档。

  • Classkit

  • CUBRID

  • DB++

  • Direct IO

  • Eio

  • Ev

  • Event

  • Expect

  • FDF

  • filePro

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • IBM DB2

  • ImageMagick

  • Ingres

  • Inotify

  • Lua

  • LuaSandbox

  • LZF

  • Mailparse

  • Memcache

  • Memcached

  • Memtrack

  • Mongo

  • mqseries

  • mysqlnd_memcache

  • mysqlnd_ms

  • mysqlnd_mux

  • mysqlnd_qc

  • mysqlnd_uh

  • Ncurses

  • OAuth

  • OpenAL

  • Paradox

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • Proctitle

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • RRD

  • runkit7

  • ScoutAPM

  • SeasLog

  • Solr

  • Sphinx

  • SQLSRV

  • ssdeep

  • SSH2

  • Statistics

  • Stomp

  • Swoole

  • SVM

  • SVN

  • Taint

  • TCP

  • tokyo_tyrant

  • Trader

  • V8js

  • Varnish

  • Weakref

  • win32service

  • WinCache

  • xattr

  • xdiff

  • Xhprof

  • Yaf

  • Yaml

  • YAZ

  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


按状态分

此部分所列出的扩展项不适用于生产环境――它们要么太老（已废弃），要么太新（试验中）。

已废弃的扩展库

以下扩展库已被废弃，通常有其他的扩展库替代。

  • Memtrack

试验中的扩展库

以下扩展库的行为――包括其函数的名称和所记载的有关此扩展库的其它任何东西――可能没有任何通知就在 PHP 的未来版本中进行变更。使用这些扩展时风险自担。

  • DB++

  • Hash

  • ImageMagick

  • Ncurses

  • Paradox

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • Oracle (PDO)

  • PS

  • XML-RPC

User Contributed Notes

There are no user contributed notes for this page.


函数别名列表

这里是函数别名列表，所有的别名列表如下。通常使用别名并不是一个好主意，这是因为它可能会废弃不用或者重新定义。这会导致不可移植脚本的出现。本列表是为了帮助想要升级他们旧有脚本到新版本语法的开发人员。很多 PHP 函数都有一个别名，可以用别名调用它。在某些情况下，两个名称都非常合适，无从取舍，is_int() 和 is_integer() 就是一个很好的例子。而有些情况则是，由于内部 API 的清理或其它一些原因，函数名被修改，但是老的名称保留了下来，以确保向后兼容性。使用这种别名通常不是个好主意，因为这种别名可能会被完全废弃或更名，导致脚本难以移植到新版本的 PHP 上。我们提供了本列表，来帮助那些要升级旧程序到更新语法的人。

别名列表
别名 | 主函数 | 使用的扩展模块
_ | gettext() | Gettext
chop | rtrim() | 基本语法
close | closedir() | 基本语法
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | 杂类函数
diskfreespace | disk_free_space() | 文件系统函数
doubleval | floatval() | 基本语法
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | 基本语法
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | 多字节字符串函数
i18n_discover_encoding | mb_detect_encoding() | 多字节字符串函数
i18n_http_input | mb_http_input() | 多字节字符串函数
i18n_http_output | mb_http_output() | 多字节字符串函数
i18n_internal_encoding | mb_internal_encoding() | 多字节字符串函数
i18n_ja_jp_hantozen | mb_convert_kana() | 多字节字符串函数
i18n_mime_header_decode | mb_decode_mimeheader() | 多字节字符串函数
i18n_mime_header_encode | mb_encode_mimeheader() | 多字节字符串函数
imap_create | imap_createmailbox() | IMAP
imap_fetchtext | imap_body() | IMAP
imap_getmailboxes | imap_list_full() | IMAP
imap_getsubscribed | imap_lsub_full() | IMAP
imap_header | imap_headerinfo() | IMAP
imap_listmailbox | imap_list() | IMAP
imap_listsubscribed | imap_lsub() | IMAP
imap_rename | imap_renamemailbox() | IMAP
imap_scan | imap_listscan() | IMAP
imap_scanmailbox | imap_listscan() | IMAP
ini_alter | ini_set() | 基本语法
is_double | is_float() | 基本语法
is_integer | is_int() | 基本语法
is_long | is_int() | 基本语法
is_real | is_float() | 基本语法
is_writeable | is_writable() | 基本语法
join | implode() | 基本语法
key_exists | array_key_exists() | 基本语法
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | 基本语法
mbstrcut | mb_strcut() | 多字节字符串函数
mbstrlen | mb_strlen() | 多字节字符串函数
mbstrpos | mb_strpos() | 多字节字符串函数
mbstrrpos | mb_strrpos() | 多字节字符串函数
mbsubstr | mb_substr() | 多字节字符串函数
mysql | mysql_db_query() | MySQL
mysql_createdb | mysql_create_db() | MySQL
mysql_db_name | mysql_result() | MySQL
mysql_dbname | mysql_result() | MySQL
mysql_dropdb | mysql_drop_db() | MySQL
mysql_fieldflags | mysql_field_flags() | MySQL
mysql_fieldlen | mysql_field_len() | MySQL
mysql_fieldname | mysql_field_name() | MySQL
mysql_fieldtable | mysql_field_table() | MySQL
mysql_fieldtype | mysql_field_type() | MySQL
mysql_freeresult | mysql_free_result() | MySQL
mysql_listdbs | mysql_list_dbs() | MySQL
mysql_listfields | mysql_list_fields() | MySQL
mysql_listtables | mysql_list_tables() | MySQL
mysql_numfields | mysql_num_fields() | MySQL
mysql_numrows | mysql_num_rows() | MySQL
mysql_selectdb | mysql_select_db() | MySQL
mysql_tablename | mysql_result() | MySQL
ociassignelem | OCI-Collection::assignElem | OCI8
ocibindbyname | oci_bind_by_name() | OCI8
ocicancel | oci_cancel() | OCI8
ocicloselob | OCI-Lob::close | OCI8
ocicollappend | OCI-Collection::append | OCI8
ocicollassign | OCI-Collection::assign | OCI8
ocicollmax | OCI-Collection::max | OCI8
ocicollsize | OCI-Collection::size | OCI8
ocicolltrim | OCI-Collection::trim | OCI8
ocicolumnisnull | oci_field_is_null() | OCI8
ocicolumnname | oci_field_name() | OCI8
ocicolumnprecision | oci_field_precision() | OCI8
ocicolumnscale | oci_field_scale() | OCI8
ocicolumnsize | oci_field_size() | OCI8
ocicolumntype | oci_field_type() | OCI8
ocicolumntyperaw | oci_field_type_raw() | OCI8
ocicommit | oci_commit() | OCI8
ocidefinebyname | oci_define_by_name() | OCI8
ocierror | oci_error() | OCI8
ociexecute | oci_execute() | OCI8
ocifetch | oci_fetch() | OCI8
ocifetchinto | oci_fetch_array(), oci_fetch_row(), oci_fetch_assoc(), oci_fetch_object() | OCI8
ocifetchstatement | oci_fetch_all() | OCI8
ocifreecollection | OCI-Collection::free | OCI8
ocifreecursor | oci_free_statement() | OCI8
ocifreedesc | oci_free_descriptor() | OCI8
ocifreestatement | oci_free_statement() | OCI8
ocigetelem | OCI-Collection::getElem | OCI8
ociinternaldebug | oci_internal_debug() | OCI8
ociloadlob | OCI-Lob::load | OCI8
ocilogon | oci_connect() | OCI8
ocinewcollection | oci_new_collection() | OCI8
ocinewcursor | oci_new_cursor() | OCI8
ocinewdescriptor | oci_new_descriptor() | OCI8
ocinlogon | oci_new_connect() | OCI8
ocinumcols | oci_num_fields() | OCI8
ociparse | oci_parse() | OCI8
ocipasswordchange | oci_password_change() | OCI8
ociplogon | oci_pconnect() | OCI8
ociresult | oci_result() | OCI8
ocirollback | oci_rollback() | OCI8
ocisavelob | OCI-Lob::save | OCI8
ocisavelobfile | OCI-Lob::import | OCI8
ociserverversion | oci_server_version() | OCI8
ocisetprefetch | oci_set_prefetch() | OCI8
ocistatementtype | oci_statement_type() | OCI8
ociwritelobtofile | OCI-Lob::export | OCI8
ociwritetemporarylob | OCI-Lob::writeTemporary | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | 基本语法
recode | recode_string() | Recode
show_source | highlight_file() | 基本语法
sizeof | count() | 基本语法
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | 基本语法
xptr_new_context | xpath_new_context() |

User Contributed Notes

There are no user contributed notes for this page.


保留字列表

Table of Contents

  • 关键词列表
  • 预定义类
  • 预定义常量
  • 其他保留字列表

以下是 PHP 中预定义标识符的列表。没有列在下面的标识符可以在脚本中作为自定义标识符使用。这些列表包括关键字和预定义变量、常量和类名。这些列表可能有遗漏，它是不完整的。

User Contributed Notes

There are no user contributed notes for this page.


关键词列表

这些词语在 PHP 中有着特殊的意义。它们中有些像是函数，有些像是常量......但是它们不是的，它们只是语言结构的一部分。不能使用它们的任何一个作为常量、方法名或是类名。但是可以将它们作为变量名使用，不过这样会导致混淆。

从PHP7.0.0开始这些关键字允许被用作类的属性、常量以及类的方法名，或者接口名和traints名，除了class不能被用作常量名。

PHP 关键词
__halt_compiler() | abstract | and | array() | as
break | callable (as of PHP 5.4) | case | catch | class
clone | const | continue | declare | default
die() | do | echo | else | elseif
empty() | enddeclare | endfor | endforeach | endif
endswitch | endwhile | eval() | exit() | extends
final | finally (从PHP 5.5开始) | for | foreach | function
global | goto (从PHP 5.3开始) | if | implements | include
include_once | instanceof | insteadof (从PHP 5.4开始) | interface | isset()
list() | namespace (从PHP 5.3开始) | new | or | print
private | protected | public | require | require_once
return | static | switch | throw | trait (从PHP 5.4开始)
try | unset() | use | var | while
xor | yield (从PHP 5.5开始) |  |  |
编译时常量
__CLASS__ | __DIR__ (从PHP 5.3开始) | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ (从PHP 5.3开始) | __TRAIT__ (从PHP 5.4开始) |  |  |  |

User Contributed Notes

Johnny D. 22-May-2020 06:37
const FORBIDDEN_TYPES = [
    'null',

    'bool',
    'false',
    'true',

    'int',
    'float',

    'string',
];
bla at taxistop dot be 19-Jul-2018 09:50
This list doesn't include 'self' and 'parent', which I take are indeed keywords.
Thomas Hansen 15-Aug-2016 10:08
Please note that reserved words are still not allowed to be used as namespace or as part of it:

<?php
namespace MyNameSpace\List;

class Test
{
}
?>

This will fail with a Parse error:  syntax error, unexpected 'List' (T_LIST), expecting identifier (T_STRING)
martindilling at gmail dot com 15-Apr-2013 10:20
RegEx to find all the keywords:

\b(
(a(bstract|nd|rray|s))|
(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|
(d(e(clare|fault)|ie|o))|
(e(cho|lse(if)?|mpty|nd(declare|for(each)?|if|switch|while)|val|x(it|tends)))|
(f(inal|or(each)?|unction))|
(g(lobal|oto))|
(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|
(n(amespace|ew))|
(p(r(i(nt|vate)|otected)|ublic))|
(re(quire(_once)?|turn))|
(s(tatic|witch))|
(t(hrow|r(ait|y)))|
(u(nset|se))|
(__halt_compiler|break|list|(x)?or|var|while)
)\b
Chris 04-Oct-2012 04:33
Here they are as arrays:

<?php
$keywords = array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor');

$predefined_constants = array('__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', '__TRAIT__');
?>

Along with get_defined_functions() and get_defined_constants(), this can be useful for checking eval() statements.


预定义类

本节列出标准的预定义类。各种扩展库定义了其它类，其说明在各自的参考文档中。

标准类

这些类由一些内建在 PHP 中的标准函数定义。

Directory
由dir()创建.
stdClass
Created by typecasting to object.
__PHP_Incomplete_Class
Possibly created by unserialize().

自 PHP 5 起预定义的类

这些额外的预定义类是 PHP 5.0.0 引进的。

exception
ErrorException
Available since PHP 5.1.0.
php_user_filter

Closure

PHP5.3.0中引入了一个预定义的final类Closure，它可以用于实现 匿名函数

关于更多信息，可以查看匿名函数.

Generator

The predefined final class Generator was introduced in PHP 5.5.0. It is used for representing generators.

For more information, see its class page.

从PHP 7开始预定义的类和接口

这些预定义的类和接口是在PHP 7.0.0 中开始引入的。

ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

特殊的类

以下这些标识符由于它们有特殊的用处，因此不可作为类名

self
Current class.
static
Current class in runtime.
parent
Parent class.

User Contributed Notes

xzero at elite7hackers dot net 08-Sep-2017 08:37
There comes improved version of amazing snippet posted by (spark at limao dot com dot br)  which allows dynamic methods generations and works as versatile extension of StdClass:

This one is faster, optimised for closures, and will work only with closures. Compatible: >= PHP 5.6
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return $this->{$key}->__invoke(... $params);
    }
}

?>

Usage examples:

<?php
$dynamic                = new Dynamic();
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod()
);
?>

This will accept arrays, strings and Closures but is a bit slower due to call_user_func_array
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return call_user_func_array($this->{$key}, $params);
    }
}

?>

Usage examples:
<?php
$dynamic                = new Dynamic();
$dynamic->myMethod      = "thatFunction";
$dynamic->hisMethod     = array($dynamic, "randomInt");
$dynamic->newMethod     = array(SomeClass, "staticMethod");
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod(),
    $dynamic->hisMethod()
);

?>
xzero at elite7hackers dot net 08-Sep-2017 08:32
There comes improved version of amazing snippet posted by which allows dynamic methods generations and works as versatile extension of StdClass:

This one is faster, optimised for closures, and will work only with closures. Compatible: >= PHP 5.6
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return $this->{$key}->__invoke(... $params);
    }
}

?>

Usage examples:

<?php
$dynamic                = new Dynamic();
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod()
);
?>

This will accept arrays, strings and Closures but is a bit slower due to call_user_func_array
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return call_user_func_array($this->{$key}, $params);
    }
}

?>

Usage examples:
<?php
$dynamic                = new Dynamic();
$dynamic->myMethod      = "thatFunction";
$dynamic->hisMethod     = array($dynamic, "randomInt");
$dynamic->newMethod     = array(SomeClass, "staticMethod");
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod(),
    $dynamic->hisMethod()
);

?>
Ashley Dambra 19-Feb-2014 06:43
Here a simple class that allow to set anonymous function. It's an optimised class of stdClass.

<?php
class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                if ($argument instanceOf Closure) {
                    $this->{$property} = $argument;
                } else {
                    $this->{$property} = $argument;
                }
            }
        }
    }

    public function __call($method, $arguments) {
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

$person = new stdObject(array(
    "name" => "nick",
    "age" => 23,
    "friends" => array("frank", "sally", "aaron"),
    "sayHi" => function() {
        return "Hello there";
    }
));

$person->sayHi2 = function() {
    return "Hello there 2";
};

$person->test = function() {
    return "test";
};

var_dump($person->name, $person->test(), $person->sayHi2());
?>
wyattstorch42 at outlook dot com 24-Dec-2013 01:15
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

<?php
/**
 * An implementation of var_export() that is compatible with instances
 * of stdClass.
 * @param mixed $variable The variable you want to export
 * @param bool $return If used and set to true, improved_var_export()
 *     will return the variable representation instead of outputting it.
 * @return mixed|null Returns the variable representation when the
 *     return parameter is used and evaluates to TRUE. Otherwise, this
 *     function will return NULL.
 */
function improved_var_export ($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) '.improved_var_export(get_object_vars($variable), true);
    } else if (is_array($variable)) {
        $array = array ();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true).' => '.improved_var_export($value, true);
        }
        $result = 'array ('.implode(', ', $array).')';
    } else {
        $result = var_export($variable, true);
    }

    if (!$return) {
        print $result;
        return null;
    } else {
        return $result;
    }
}

// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);

improved_var_export((object) array (
    'prop1' => true,
    'prop2' => $obj,
    'assocArray' => array (
        'apple' => 'good',
        'orange' => 'great'
    )
));

/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
spark at limao dot com dot br 15-Aug-2011 02:21
if you want a Dynamic class you can extend from, add atributes AND methods on the fly you can use this:
<?php
    class Dynamic extends stdClass{
        public function __call($key,$params){
            if(!isset($this->{$key})) throw new Exception("Call to undefined method ".get_class($this)."::".$key."()");
            $subject = $this->{$key};
            call_user_func_array($subject,$params);
        }
    }
?>

this will accept both arrays, strings and Closures:
<?php
    $dynamic->myMethod = "thatFunction";
    $dynamic->hisMethod = array($instance,"aMethod");
    $dynamic->newMethod = array(SomeClass,"staticMethod");
    $dynamic->anotherMethod = function(){
        echo "Hey there";
    };
?>

then call them away =D
Typer85 at gmail dot com 17-Feb-2007 08:58
In response to the note below mine,

This list is not incomplete. Read the Manual folks, its listed there plain and simple:

"This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference."

Depending on what extensions you have, they might define their own classes. This list is just the standard classes as defined by PHP with no regards to extensions.
unknown 23-Jul-2002 10:29
It's handy to have a array of the reserved classes.....
var_dump (get_declared_classes ());


预定义常量

内核预定义常量

这些常量在 PHP 的内核中定义。它包含 PHP、Zend 引擎和 SAPI 模块。

PHP_VERSION (string)
The current PHP version as a string in "major.minor.release[extra]" notation.
PHP_MAJOR_VERSION (int)
The current PHP "major" version as an integer (e.g., int(5) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_MINOR_VERSION (int)
The current PHP "minor" version as an integer (e.g., int(2) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_RELEASE_VERSION (int)
The current PHP "release" version as an integer (e.g., int(7) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_VERSION_ID (int)
The current PHP version as an integer, useful for version comparisons (e.g., int(50207) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_EXTRA_VERSION (string)
The current PHP "extra" version as a string (e.g., '-extra' from version "5.2.7-extra"). Often used by distribution vendors to indicate a package version. Available since PHP 5.2.7.
PHP_ZTS (int)
Available since PHP 5.2.7.
PHP_DEBUG (int)
Available since PHP 5.2.7.
PHP_MAXPATHLEN (int)
The maximum length of filenames (including path) supported by this build of PHP. Available since PHP 5.3.0.
PHP_OS (string)
The operating system PHP was built for.
PHP_OS_FAMILY (string)
The operating system family PHP was built for. Either of 'Windows', 'BSD', 'Darwin', 'Solaris', 'Linux' or 'Unknown'. Available as of PHP 7.2.0.
PHP_SAPI (string)
The Server API for this build of PHP.参见 php_sapi_name()。
PHP_EOL (string)
当前平台中对于换行符的定义。自 PHP 5.0.2 起可用
PHP_INT_MAX (int)
当前 PHP 版本支持的最大整型数字。在 32 位系统中通常为 int(2147483647)，64 位系统中为 int(9223372036854775807)。自 PHP 5.0.5 起可用。
PHP_INT_MIN (int)
当前 PHP 版本支持的最大整型数字。在 32 位系统中通常为 int(-2147483648)，64 系统中为 int(-9223372036854775808)。自 PHP 7.0.0 起可用。通常情况下 PHP_INT_MIN === ~PHP_INT_MAX。
PHP_INT_SIZE (int)
The size of an integer in bytes in this build of PHP. 自 PHP 5.0.5 起可用
PHP_FLOAT_DIG (int)
Number of decimal digits that can be rounded into a float and back without precision loss. Available as of PHP 7.2.0.
PHP_FLOAT_EPSILON (float)
Smallest representable positive number x, so that x + 1.0 != 1.0. Available as of PHP 7.2.0.
PHP_FLOAT_MIN (float)
Smallest representable positive floating point number. If you need the smallest representable negative floating point number, use - PHP_FLOAT_MAX. Available as of PHP 7.2.0.
PHP_FLOAT_MAX (float)
Largest representable floating point number. Available as of PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
PHP_PREFIX (string)
The value "--prefix" was set to at configure.
PHP_BINDIR (string)
Specifies where the binaries were installed into.
PHP_BINARY (string)
Specifies the PHP binary path during script execution. Available since PHP 5.4.
PHP_MANDIR (string)
Specifies where the manpages were installed into. Available since PHP 5.3.7.
PHP_LIBDIR (string)
PHP_DATADIR (string)
PHP_SYSCONFDIR (string)
PHP_LOCALSTATEDIR (string)
PHP_CONFIG_FILE_PATH (string)
PHP_CONFIG_FILE_SCAN_DIR (string)
PHP_SHLIB_SUFFIX (string)
The build-platform's shared library suffix, such as "so" (most Unixes) or "dll" (Windows).
PHP_FD_SETSIZE (string)
The maximum number of file descriptors for select system calls. Available as of PHP 7.1.0.
E_ERROR (int)
Error reporting constant
E_WARNING (int)
Error reporting constant
E_PARSE (int)
Error reporting constant
E_NOTICE (int)
Error reporting constant
E_CORE_ERROR (int)
Error reporting constant
E_CORE_WARNING (int)
Error reporting constant
E_COMPILE_ERROR (int)
Error reporting constant
E_COMPILE_WARNING (int)
Error reporting constant
E_USER_ERROR (int)
Error reporting constant
E_USER_WARNING (int)
Error reporting constant
E_USER_NOTICE (int)
Error reporting constant
E_RECOVERABLE_ERROR (int)
Error reporting constant. Available since PHP 5.2.0
E_DEPRECATED (int)
Error reporting constant. Available since PHP 5.3.0
E_USER_DEPRECATED (int)
Error reporting constant. Available since PHP 5.3.0
E_ALL (int)
Error reporting constant
E_STRICT (int)
Error reporting constant
__COMPILER_HALT_OFFSET__ (int)
自 PHP 5.1.0 起有效
true (boolean)
See Booleans.
false (boolean)
See Booleans.
null (null)
See Null.
PHP_WINDOWS_EVENT_CTRL_C (int)
A Windows CTRL+C event. Available as of PHP 7.4.0 (Windows only).
PHP_WINDOWS_EVENT_CTRL_BREAK (int)
A Windows CTRL+BREAK event. Available as of PHP 7.4.0 (Windows only).

参见 魔术常量。

标准预定义常量

所有在核心扩展 的常量是 PHP 默认定义的。

User Contributed Notes

nabikaz at gmail dot com 10-Nov-2016 10:18
Don't use `PHP_EOL` for textarea of form to array, use it:

array_values(array_filter(explode("\n", str_replace("\r", '', $_POST['data']))))
Anonymous 27-Jan-2015 03:25
PHP_EOL can be used like that:

<?php

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

?>

Which is the same of \r\n or \n depending on the OS.
You can put those lines in a while for example, and create a log file.
rdcapasso 08-Sep-2013 09:16
Volker's getOS() function needs to have the order of cases changed in the switch statement since "darwin" contains "win", which means that both "windows" and "darwin" will return self::OS_WIN. I've moved the 'dar' case above the 'win' case:

<?php
class System {

    const OS_UNKNOWN = 1;
    const OS_WIN = 2;
    const OS_LINUX = 3;
    const OS_OSX = 4;

    /**
     * @return int
     */
    static public function getOS() {
        switch (true) {
            case stristr(PHP_OS, 'DAR'): return self::OS_OSX;
            case stristr(PHP_OS, 'WIN'): return self::OS_WIN;
            case stristr(PHP_OS, 'LINUX'): return self::OS_LINUX;
            default : return self::OS_UNKNOWN;
        }
    }

}
?>


其他保留字列表

以下关键字不可被用于类名、接口名和trait名，并且它们被禁止用于命名空间。

Reserved words
int (从PHP 7开始) | float (从PHP 7开始) | bool (从PHP 7开始) | string (从PHP 7开始)
true (从PHP 7开始) | false (从PHP 7开始) | null (从PHP 7开始)

以下关键词已经被建议保留。尽管你仍然可以将它们用于类名、接口名和trait名（以及命名空间），但是考虑到在将来的PHP版本中可能会使用，因此非常不推荐去使用它们。

Soft reserved words
resource (从PHP 7开始) object (从PHP 7开始) mixed (从PHP 7开始) numeric (从PHP 7开始)

User Contributed Notes

There are no user contributed notes for this page.


资源类型列表

以下是一个建立，使用和销毁资源的函数列表。可以用 is_resource()函数测定一个变量是否是资源，函数 get_resource_type()则返回该资源的类型。

资源类型
资源类型名称 | 建立者 | 使用者 | 销毁者 | 定义
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | None | Aspell dictionary
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | None | COM object reference
VARIANT
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | PDF document with CPDF lib
cpdf outline
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | Curl session
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection
dbx_result_object | dbx_query() | None | dbx result
domxml attribute
domxml document
domxml node
xpath context
xpath object
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() | fbsql_close() | Link to fbsql database
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File
ftp | ftp_connect(), ftp_ssl_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site(), ftp_alloc(), ftp_chmod(), ftp_exec(), ftp_get_option(), ftp_nb_continue(), ftp_nb_fget(), ftp_nb_fput(), ftp_nb_get(), ftp_nb_put(), ftp_raw(), ftp_set_option() | ftp_close() | FTP stream
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | GD Image
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD
gd PS encoding
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server
imap chain persistent
imap persistent
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction
java
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result
ldap result entry
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server
SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFGradient
SWFMorph
SWFMovie
SWFShape
SWFSprite
SWFText
SWFTextField
mnogosearch agent
mnogosearch result
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL
msql query | msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_flags(), msql_field_len(), msql_field_name(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsoft SQL Server database
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsoft SQL Server
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsoft SQL Server result
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result
oci8 collection
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database
oci8 descriptor
oci8 server
oci8 session
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result
birdstep link
birdstep result
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file
pdf object
pdf outline
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result
pgsql string
printer
printer brush
printer font
printer pen
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close()
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket
sockets i/o vector
stream | opendir() | readdir(), rewinddir() | closedir() | Dir handle
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library
sybase-db result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file

User Contributed Notes

csaba at alum dot mit dot edu 06-Nov-2009 10:25
On my PHP 5.2 under Windows Vista, the resource type listed as interbase link is actually Firebird/InterBase link


可用过滤器列表

Table of Contents

  • 字符串过滤器
  • string.strip_tags
  • 转换过滤器
  • 压缩过滤器
  • 加密过滤器

下面列出了用在 stream_filter_append()中的几个内置的流过滤器。用户的 PHP 版本中的过滤器也许比这里列出的更多（或更少）。

值得指出 stream_filter_append()与 stream_filter_prepend()之间有少许不平衡。每个 PHP 流都含有一个小的 读取缓冲区，它存储了来自文件系统或其它资源的几段数据以便更有效率地处理。数据一从资源进入流的内部缓冲区，立刻被附上的过滤器处理而不管 PHP 程序是否真的已经准备好接收数据。当过滤器是 appended时如果数据等待在读取缓冲区，数据将被立即通过过滤器处理，使其效果看上去是透明的。然而当过滤器是 prepended时如果数据等待在读取缓冲区，数据将 不会被该过滤器处理。该数据将会等到从资源取得下一段数据后才会被处理。

用 stream_get_filters()来列出 PHP 中已安装的过滤器。

User Contributed Notes

There are no user contributed notes for this page.


字符串过滤器

每个过滤器都正如其名字暗示的那样工作并与内置的 PHP 字符串函数的行为相对应。对于指定过滤器的更多信息，请参考该函数的手册页。

string.rot13（自 PHP 4.3.0 起）使用此过滤器等同于用 str_rot13()函数处理所有的流数据。

Example #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Outputs:  Guvf vf n grfg.   */
?>

string.toupper（自 PHP 5.0.0 起）使用此过滤器等同于用 strtoupper()函数处理所有的流数据。

Example #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Outputs:  THIS IS A TEST.   */
?>

string.tolower（自 PHP 5.0.0 起）使用此过滤器等同于用 strtolower()函数处理所有的流数据。

Example #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Outputs:  this is a test.   */
?>

User Contributed Notes

There are no user contributed notes for this page.


string.strip_tags

使用此过滤器等同于用 strip_tags()函数处理所有的流数据。可以用两种格式接收参数：一种是和 strip_tags()函数第二个参数相似的一个包含有标记列表的字符串，一种是一个包含有标记名的数组。

Warning

本特性已自 PHP 7.3.0 起废弃。强烈建议不要使用本特性。

Example #1 string.strip_tags

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */
?>

User Contributed Notes

There are no user contributed notes for this page.


转换过滤器

如同 string.* 过滤器，convert.* 过滤器的作用就和其名字一样。转换过滤器是 PHP 5.0.0 添加的。对于指定过滤器的更多信息，请参考该函数的手册页。

convert.base64-encode和 convert.base64-decode使用这两个过滤器等同于分别用 base64_encode()和 base64_decode()函数处理所有的流数据。 convert.base64-encode支持以一个关联数组给出的参数。如果给出了 line-length，base64 输出将被用 line-length个字符为 长度而截成块。如果给出了 line-break-chars，每块将被用给出的字符隔开。这些参数的效果和用 base64_encode()再加上 chunk_split()相同。

Example #1 convert.base64-encode & convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBpcyBhIHRlc3QuCg==  */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBp
          :  cyBhIHRl
          :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Outputs:  This is a test.  */
?>

convert.quoted-printable-encode和 convert.quoted-printable-decode使用此过滤器的 decode 版本等同于用 quoted_printable_decode()函数处理所有的流数据。没有和 convert.quoted-printable-encode相对应的函数。 convert.quoted-printable-encode支持以一个关联数组给出的参数。除了支持和 convert.base64-encode一样的附加参数外， convert.quoted-printable-encode还支持布尔参数 binary和 force-encode-first。 convert.base64-decode只支持 line-break-chars参数作为从编码载荷中剥离的类型提示。

Example #2 convert.quoted-printable-encode & convert.quoted-printable-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Outputs:  =This is a test.=0A  */
?>

User Contributed Notes

There are no user contributed notes for this page.


压缩过滤器

虽然 压缩封装协议提供了在本地文件系统中 创建 gzip 和 bz2 兼容文件的方法，但不代表可以在网络的流中提供通用压缩的意思，也不代表可以将一个非压缩的流转换成一个压缩流。对此，压缩过滤器可以在任何时候应用于任何流资源。

Note: 压缩过滤器 不产生命令行工具如 gzip的头和尾信息。只是压缩和解压数据流中的有效载荷部分。

zlib.deflate（压缩）和 zlib.inflate（解压）实现了定义与 » RFC 1951的压缩算法。 deflate过滤器可以接受以一个关联数组传递的最多三个参数。 level定义了压缩强度（1-9）。数字更高通常会产生更小的载荷，但要消耗更多的处理时间。存在两个特殊压缩等级：0（完全不压缩）和 -1（zlib 内部默认值，目前是 6）。 window是压缩回溯窗口大小，以二的次方表示。更高的值（大到 15 —— 32768 字节）产生更好的压缩效果但消耗更多内存，低的值（低到 9 —— 512 字节）产生产生较差的压缩效果但内存消耗低。目前默认的 window大小是 15。 memory用来指示要分配多少工作内存。合法的数值范围是从 1（最小分配）到 9（最大分配）。内存分配仅影响速度，不会影响生成的载荷的大小。

Note: 因为最常用的参数是压缩等级，也可以提供一个整数值作为此参数（而不用数组）。

zlib.* 压缩过滤器自 PHP 版本 5.1.0起可用，在激活 zlib的前提下。也可以通过安装来自 » PECL的 » zlib_filter包作为一个后门在 5.0.x版中使用。此过滤器在 PHP 4 中 不可用。

Example #1 zlib.deflate和 zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
echo "The original text was:\n";
/* Use readfile and zlib.inflate to decompress on the fly */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.
The original text was:
This is a test.
This is only a test.
This is not an important string.

 */
?>

Example #2 zlib.deflate简单参数用法

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
/* Here "6" indicates compression level 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.

 */
?>

bzip2.compress和 bzip2.decompress工作的方式与上面讲的 zlib 过滤器相同。 bzip2.compress过滤器接受以一个关联数组给出的最多两个参数： blocks是从 1 到 9 的整数值，指定分配多少个 100K 字节的内存块作为工作区。 work是 0 到 250 的整数值，指定在退回到一个慢一些，但更可靠的算法之前做多少次常规压缩算法的尝试。调整此参数仅影响到速度，压缩输出和内存使用都不受此设置的影响。将此参数设为 0 指示 bzip 库使用内部默认算法。 bzip2.decompress过滤器仅接受一个参数，可以用普通的布尔值传递，或者用一个关联数组中的 small单元传递。当 small设为 &true; 值时，指示 bzip 库用最小的内存占用来执行解压缩，代价是速度会慢一些。

bzip2.* 压缩过滤器自 PHP 版本 5.1.0起可用，在激活 bz2支持的前提下。也可以通过安装来自 » PECL的 » bz2_filter包作为一个后门在 5.0.x版中使用。此过滤器在 PHP 4 中 不可用。

Example #3 bzip2.compress和 bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "The original file is " . filesize('LICENSE') . " bytes long.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "The compressed file is " . filesize('LICENSE.compressed') . " bytes long.\n";

/* Generates output:

The original text is 3288 characters long.
The compressed file is 1488 bytes long.

 */
?>

User Contributed Notes

Anonymous 10-Feb-2021 06:37
To use the zlib.inflate filter with data originally written using gzcompress() or zlib.deflate, set the window option to 15 as outlined here: https://bugs.php.net/bug.php?id=68556

<?php
$fh = fopen(file_name, 'rb');
stream_filter_append($fh, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15]);
$contents = stream_get_contents($fh);
fclose($fh);
bohwaz 08-Jul-2018 01:39
Please note that there is currently a bug in this feature. ftell(), fseek() and fstat() functions cannot be used. Writing to a stream after using this function will not change the stream position as it should.

See bug: https://bugs.php.net/bug.php?id=49874

Also the zlib filters don't work with php://temp, php://memory and php://input streams, nothing is outputted to those streams.
Anonymous 21-Aug-2015 06:12
To read a gzip encoded stream from http
<?php
$opts = [
    "http" => [
        "method" => "GET",
        "header" => [ "Accept-Encoding: gzip" ],
    ]
];
$ctx = stream_context_create($opts);
$f = fopen("http://php.net", "r", false, $ctx);
// check  stream_get_meta_data($f)["wrapper_data"] has "Content-Encoding: gzip"
stream_filter_append($f, "zlib.inflate", STREAM_FILTER_READ, ["window" => 30]);
echo stream_get_contents($f); // any stream processing
fclose($f);


加密过滤器

mcrypt.*和 mdecrypt.*使用 libmcrypt 提供了对称的加密和解密。这两组过滤器都支持 mcrypt 扩展库中相同的算法，格式为 mcrypt.ciphername，其中 ciphername是密码的名字，将被传递给 mcrypt_module_open()。有以下五个过滤器参数可用：

mcrypt 过滤器参数
参数 | 是否必须 | 默认值 | 取值举例
mode | 可选 | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | 可选 | ini_get('mcrypt.algorithms_dir') | algorithms 模块的目录
modes_dir | 可选 | ini_get('mcrypt.modes_dir') | modes 模块的目录
iv | 必须 | N/A | 典型为 8，16 或 32 字节的二进制数据。根据密码而定
key | 必须 | N/A | 典型为 8，16 或 32 字节的二进制数据。根据密码而定

Example #1 用 3DES 将文件加密输出

<?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secert-file.enc', 'wb');
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'Secret secret secret data');
fclose($fp);
?>

Example #2 读取加密的文件

<?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secert-file.enc', 'rb');
stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_WRITE, $opts);
$data = rtrim(stream_get_contents($fp));
fclose($fp);

echo $data;
?>

User Contributed Notes

Maarten Bodewes 06-Aug-2017 12:21
The examples on this page should be destroyed with utmost urgency.

Strangely most people will fall over the use of generating the IV and 3DES key using MD5, a weak hash function, e.g. the previous note and CryptoFails blog.

http://www.cryptofails.com/post/70059608390/php-documentation-woes

A password based key derivation function should be used (bcrypt, PBKDF2).

However the use of MD-5 for key derivation however isn't that bad and if the password is strong enough (it usually isn't) then the generated DES ABC key is strong enough even now.

Using an identical IV for each password means that this function directly leaks information about the encrypted file. If the start of two encrypted files is identical then this function will directly leak information. For instance, if the routine encrypts multiple images then the JPEG header would be easily distinguished.

All in all these examples use deprecated routines (mcrypt), deprecated cryptographic functions (MD5 / DES) and then incorrectly perform the actual encryption. Enough reason to destroy them in the first place.
Uwe Ohse 22-Feb-2017 04:17
1) The mcrypt module has been deprecated with PHP 7.1.
What does that mean for the encryption filters?

2) deriving the IV from the secret passphrase seems wrong. This leaks information about the passphrase without need.

3) using md5() for this? Really? hash() has been available since PHP 5.1.2.

4) hashing the passphrase twice does not add any security.

5) using substr() on binary data (why, oh why, is true passed to md5()?) might lead to headaches if mbstring.func_overload is used.


所支持的套接字传输器（Socket Transports）列表

Table of Contents

  • Internet 领域：TCP，UDP，SSL 和 TLS
  • Unix 领域：Unix 和 UDG

以下是 PHP 内置用于基于流的套接字函数例如 fsockopen()和 stream_socket_client()的各种 URL 风格的套接字传输器。这些传输器 不适用于 Sockets 扩展库。

要得到自己的 PHP 版本中所安装的传输器列表，使用 stream_get_transports()。

User Contributed Notes

There are no user contributed notes for this page.


Internet 领域：TCP，UDP，SSL 和 TLS

PHP 3，PHP 4，PHP 5。 ssl://& tls://自 PHP 4.3 起可用。

sslv2://& sslv3://自 PHP 5.0.2 起可用。

Note: 如果没有指定传输器，则假定为 tcp://。

  • 127.0.0.1
  • fe80::1
  • www.example.com
  • tcp://127.0.0.1
  • tcp://fe80::1
  • tcp://www.example.com
  • udp://www.example.com
  • ssl://www.example.com
  • sslv2://www.example.com
  • sslv3://www.example.com
  • tls://www.example.com

Internet 领域套接字在目标地址中还期望有一个端口号。在 fsockopen()中在第二个参数中指定，这样就不会影响传输器的 URL。然而在 stream_socket_client()和相关的函数中是用传统的 URL，端口号在传输器 URL 后面以冒号分隔而指定。

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Note: 带端口号的 IPv6 数字地址
在上面的第二个例子中，IPv4 和主机名的例子只加了一个冒号和端口号，但 IPv6 的地址被放在方括号中： [fe80::1]。这是为了将 IPv6 地址中的冒号和用来分隔端口号的冒号区别开来。

ssl://和 tls://传输器（仅在 openssl 支持已编译入 PHP 后可用）是 tcp://传输器加入 SSL 加密后的扩展。在 PHP 4.3.0 中 OpenSSL 支持必须被静态编译入 PHP，在 PHP 5.0.0 中可以编译为模块或者静态的。

ssl://将根据远程服务器的兼容性和参数设置尝试与之建立 SSL V2 或 SSL V3 链接 sslv2://和 sslv3://将明确的选择 SSL V2 或 SSL V3 协议进行连接。

ssl://和 tls://传输器的上下文选项（自 PHP 4.3.2 起）
名称 | 用法 | 默认值
verify_peer | &true; 或 &false;。用于 SSL 证书请求验证。 | &false;
allow_self_signed | &true; 或 &false;。允许自签名的证书。 | &false;
cafile | 本地文件系统中证书授权机构文件的位置，应和 verify_peer上下文选项一起使用来认证远端的身份。 |
capath | 如果没有指定 cafile或者如果该处没找到证书，则在 capath指定的目录中搜索相配的证书。 capath必须是一个正确的被散列化的证书目录。 |
local_cert | 文件系统中本地证书文件的路径。必须是一个用 PEM 编码并包含你的证书和私人密钥的文件。可以选择包括发行者的证书链。 |
passphrase | 你的 local_cert文件编码的 passphrase。 |
CN_match | 所期待的 Common Name。PHP 能进行有限的通配符匹配。如果 Common Name 与此不匹配，连接尝试会失败。 |

Note: 因为 ssl://是 https:// 和 ftps:// 封装协议的底层传输器，适用于 ssl://的任何上下文选项也适用于 https://和 ftps://。

User Contributed Notes

christian at lantian dot eu 17-Sep-2013 12:46
@pablo dot livardo  :  I think that the problem you found is caused by the difference between the client/server encryption methods used.

The 465 port is used for SMTPS, and the server starts the encryption immediately it receives your connection. So, your code will work.

The 587 port is used for Submission (MSA or Mail Submission Agent) which works like the port 25. The server accepts your connection and doesn't activate the encryption. If you want an encrypted connection on the port 587, you must connect on it without encryption, you must start to dialog with the server (with EHLO) and after that you must ask the server to start the encrypted connection using the STARTTLS command. The server starts the encryption and now you can start as well the encryption on your client.

So, in few words, you can not use :

<?php $fp = fsockopen("tls://mail.example.com", 587, $errno, $errstr);  ?>

but you can use:

 <?php $fp = stream_socket_client("mail.example.com:587", $errno, $errstr); ?>

and after you send the STARTTLS command, you can enable the crypto:

<?php stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); ?>

P.S. My previous note on this page was totally wrong, so I ask the php.net admin to remove it.

:)
christian at lantian dot eu 16-Sep-2013 08:17
@pablo dot livardo  :  I think that the problem you found is caused by the difference between the client/server encryption methods used.

You tried to access the port 587 using TLS encryption, but the server uses the SSLv3 encryption on this port.

You can communicate with the Google server on port 465 because on this port the communication is encrypted using TLS and your client is configured to recognize the TLS.

So, if you want to connect on the Google server over the port 587, you simply must write:

<?php
$fp = fsockopen("ssl://mail.example.com", 587, $errno, $errstr);
?>

instead of:

<?php
$fp = fsockopen("tls://mail.example.com", 587, $errno, $errstr);
?>

:)
stefan at example dot com 20-Aug-2010 05:42
Actually, PHP is very able to start with an unencrypted connection and then switch to an encrypted one - refer to http://php.net/stream_socket_enable_crypto .
pablo dot livardo at gmail dot com 09-Dec-2009 09:56
I've been having a problem with a TLS connection.

<?php
$fp = fsockopen("tls://mail.example.com", 587, $errno, $errstr);
?>

Which gives me an error of:

SSL operation failed with code 1. OpenSSL Error messages: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

I believe this is caused by PHP not being able to start with an unencrypted connection and then switch to encryption even though the functionality is built into OpenSSL.

For Google Mail users you can avoid this by using port 465 instead of 587.


Unix 领域：Unix 和 UDG

unix://自 PHP 3 起可用， udg://自 PHP 5 起可用。

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix://提供了在 Unix 域中对套接字流连接的访问。 udg://提供了替代的传输器以用户数据报协议（UDP）来访问 Unix 域套接字。

Unix 域套接字（UNIX Domain Socket），和 Internet Domain Socket 不同，不期望端口号。在 fsockopen()中 portno参数应被设为 0。

User Contributed Notes

Matthew Fortune 16-Feb-2007 03:03
It appears that fsockopen prior to php5 did not need the unix:// qualifier when opening a unix domain socket:

php4: fsockopen("/tmp/mysocket"......);

php5: fsockopen("unix:///tmp/mysocket"......);

This caught me out when upgrading.


PHP 类型比较表

以下的表格显示了 PHP 类型 和 比较运算符 在松散和严格比较时的作用。该补充材料还和 类型戏法 的相关章节内容有关。同时，大量的用户注释和 » BlueShoes 的工作也给该材料提供了帮助。

在使用这些表格之前，需要明白变量类型及它们的意义。例如，"42" 是一个字符串而 42 是一个整数。false 是一个布尔值而 "false" 是一个字符串。

Note:

HTML 表单并不传递整数、浮点数或者布尔值，它们只传递字符串。要想检测一个字符串是不是数字，可以使用 is_numeric() 函数。

Note:

在没有定义变量 $x 的时候，诸如 if ($x) 的用法会导致一个 E_NOTICE 级别的错误。所以，可以考虑用 empty() 或者 isset() 函数来初始化变量。

Note:

某些数值操作会导致一个特殊值，可以用常量 NAN 表示。 无论是松散还是严格比较，这个值和其他任意值（包括它自身，但排除 true）比较时都会产生 false 的结果， 例如 NAN != NAN 和 NAN !== NAN。 导致 NAN 的操作例子包括 sqrt(-1)、asin(2)、 acosh(0)。

使用 PHP 函数对变量 $x 进行比较
表达式 | gettype() | empty() | is_null() | isset() | boolean : if($x)
$x = ""; | string | true | false | true | false
$x = null; | NULL | true | true | false | false
var $x; | NULL | true | true | false | false
$x is undefined | NULL | true | true | false | false
$x = array(); | array | true | false | true | false
$x = array('a', 'b'); | array | false | false | true | true
$x = false; | boolean | true | false | true | false
$x = true; | boolean | false | false | true | true
$x = 1; | integer | false | false | true | true
$x = 42; | integer | false | false | true | true
$x = 0; | integer | true | false | true | false
$x = -1; | integer | false | false | true | true
$x = "1"; | string | false | false | true | true
$x = "0"; | string | true | false | true | false
$x = "-1"; | string | false | false | true | true
$x = "php"; | string | false | false | true | true
$x = "true"; | string | false | false | true | true
$x = "false"; | string | false | false | true | true

松散比较 ==
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | array() | "php" | ""
true | true | false | true | false | true | true | false | true | false | false | true | false
false | false | true | false | true | false | false | true | false | true | true | false | true
1 | true | false | true | false | false | true | false | false | false | false | false | false
0 | false | true | false | true | false | false | true | false | true | false | true | true
-1 | true | false | false | false | true | false | false | true | false | false | false | false
"1" | true | false | true | false | false | true | false | false | false | false | false | false
"0" | false | true | false | true | false | false | true | false | false | false | false | false
"-1" | true | false | false | false | true | false | false | true | false | false | false | false
null | false | true | false | true | false | false | false | false | true | true | false | true
array() | false | true | false | false | false | false | false | false | true | true | false | false
"php" | true | false | false | true | false | false | false | false | false | false | true | false
"" | false | true | false | true | false | false | false | false | true | false | false | true

严格比较 ===
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | array() | "php" | ""
true | true | false | false | false | false | false | false | false | false | false | false | false
false | false | true | false | false | false | false | false | false | false | false | false | false
1 | false | false | true | false | false | false | false | false | false | false | false | false
0 | false | false | false | true | false | false | false | false | false | false | false | false
-1 | false | false | false | false | true | false | false | false | false | false | false | false
"1" | false | false | false | false | false | true | false | false | false | false | false | false
"0" | false | false | false | false | false | false | true | false | false | false | false | false
"-1" | false | false | false | false | false | false | false | true | false | false | false | false
null | false | false | false | false | false | false | false | false | true | false | false | false
array() | false | false | false | false | false | false | false | false | false | true | false | false
"php" | false | false | false | false | false | false | false | false | false | false | true | false
"" | false | false | false | false | false | false | false | false | false | false | false | true

User Contributed Notes

Anonymous 17-Nov-2020 02:24
I noticed that some "magic" also happens when comparing strings with leading zeros with only two equal signs:

<?php
var_dump('1' == '01');
var_dump('01' == '000001');
?>

Output:
bool(true)
bool(true)

If the string contains only numbers all leading zeroes seem to be ignored.
TrickyFoxy 02-Jan-2020 08:25
<?php
echo md5('240610708') == md5('QNKCDZO') ? "equal" : "not equal"; // prints equal!!!
php at ckls dot net 20-Aug-2018 02:50
regarding the editors note in php at richardneill dot org note:
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

While this is true, there is still the following behaviour:
<?php
$x = "1";
$y = "+1";
var_dump($x == $x);
?>
outputs "bool(true)".
So still be wary of string-comparison where both strings might be interpreted as numbers.
mark at theanti dot social 29-Mar-2018 08:59
There is also 0.0 which is not identical to 0.

  $x = 0.0;
  gettype($x); // double
  empty($x); // true
  is_null($x); //false
  isset($x); // true
  is_numeric($x); // true
  $x ? true : false; // false
  $x == 0; // true
  $x == "0"; // true
  $x == "0.0"; // true
  $x == false; // true
  $x == null; // true
  $x === 0; // false
  $x === false; // false
  $x === null; // false
  $x === "0"; // false
  $x === "0.0"; // false
alt dot jl-3gi8b7l at binich dot com 10-Mar-2018 03:41
Here's how PHP handles loose and strict comparisons of default parameters in functions:

Very unintuitive:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return $x; // returns 0 !!
    }

echo f(0);
?>

Here some further tests:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return 'A:'.$x;
    if ($x === 'surprise')
        return 'B:'.$x;
    return 'C:'.$x;
    }

echo "\n".f(0); // A:0 !!
echo "\n".f(0.0); // A:0 !!
echo "\n".f(NULL); // C: !!
echo "\n".f(FALSE); // C:
echo "\n".f(); // A:surprise
echo "\n".f(''); // C:
echo "\n".f((integer)0); // A:0
echo "\n".f((string)0); // C:0
echo "\n".f('0'); // C:0
echo "\n".f(0.1); // C:0.1
echo "\n".f(array()); // C:Array
echo "\n".f('surprise'); // A:surprise
?>
biziclop at vipmail dot hu 12-Aug-2017 08:57
Want to strictly compare integers that may or may not be converted to floats (via PHPExcel import/export, etc.)? You are out of luck:

var_dump(   (int)1 ===   (int)1 ); // bool(true)
var_dump( (float)1 === (float)1 ); // bool(true)
var_dump( (float)1 ===   (int)1 ); // bool(false)
var_dump(   (int)1 === (float)1 ); // bool(false)

This slightly complicated function might help you:

function equal_numbers( $a, $b ){
  if( $a === $b )  return true;
  if(   is_int( $a ) && is_float( $b ))  return (float)$a === $b && $a ===   (int)$b;
  if( is_float( $a ) &&   is_int( $b ))  return   (int)$a === $b && $a === (float)$b;
  return false;
}

Here are some tests:

test(100, 100.0 ); // int(100) float(100) bool(true)
test(  0,  -0   ); // int(0)   int(0)     bool(true)
test( -0,  -0.0 ); // int(0)   float(-0)  bool(true)
test(  0, 1/0   ); // int(0)   float(INF) bool(false)
test(  0, acos(2));// int(0)   float(NAN) bool(false)
test(       PHP_INT_MAX * 10, 0 );             //float(92233720368547758080) int(0) bool(false)
test((float)PHP_INT_MAX,     PHP_INT_MAX     );//float(9223372036854775808)  int(9223372036854775807) bool(false)
test((float)PHP_INT_MAX / 2, PHP_INT_MAX / 2 );//float(4611686018427387904)  float(4611686018427387904) bool(true)

function test( $a, $b ){
  var_dump( $a, $b, equal_numbers( $a, $b ));
}
engineer dot morozov at gmail dot com 07-Feb-2016 03:23
If you want to calculate how much more/less items by the criterion

Example:

in loop:
$counter += intval($item->isValid()) <=> 0.5;

if $counter >= 0 - valid items are more then invalid on $counter
if $counter  < 0 - valid items are less then invalid on $counter
trexx68 25-Apr-2015 05:11
If you want to view the truth tables colorized, just:

1. Save a local copy of this page as an .html file,
2. View the page source with any text editor.
3. Replace the opening <head> tag so it will include this:

<head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

4. Replace the closing </body> tag with this:

  <script>
    $( "td:contains('FALSE')" ).css("color", "red");
    $( "td:contains('TRUE')" ).css("color", "green");
  </script>
</body>

5. Save the file, and view it on your browser.  Enjoy.
aravind dot a dot padmanabhan at gmail dot com 22-Apr-2015 02:31
please note that

$x = 0.0 ;
print empty($x); // returns 1 (true)

$x = "0.0";
print empty($x); // returns blank (false);
Anonymous 16-Oct-2014 06:19
The loose comparison chart is missing a few things.

array(1)==true returns true.

also:

(int)array(1) === 1 returns true

This is symmetric:

array(1) === (array)1 returns true

but the loose comparison

array(1)==1 still returns false.
blue dot hirano at gmail dot com 07-Sep-2014 02:29
The truth tables really ought to be colorized; they're very hard to read as they are right now (just big arrays of TRUE and FALSE).

Also, something to consider: clustering the values which compare similarly (like is done on qntm.org/equality) would make the table easier to read as well. (This can be done simply by hand by rearranging the order of headings to bring related values closer together).
Anonymous 21-Nov-2013 01:43
I'm running PHP 5.5.3.

This is a correction to one of the previous posts.

<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //false
?>

Output is:

true, false, false
crazy888s at hotmail dot com 14-Dec-2012 06:14
PHP's loose comparisons can be a huge convenience when used properly! It's extremely helpful to just remember the following are always FALSE:

null, false, "", 0, "0", array()

If your application never depends on a particular "empty/false/null/0/not set" value type, you won't have to worry about 99% of the other weird cases listed here. You won't need empty() or isset(). And ALL variable types will always work as expected for statements like:

if(boolean && !string){...}
if(array){...}
if(!null || int){...}

Consider the same when working with your database values.
php at richardneill dot org 12-Apr-2012 07:45
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

Be wary of string-comparison where both strings might be interpreted as numbers.  Eg:

$x="123456789012345678901234567890"; $y="123456789012345678900000000000";
echo  ($x==$y)?"equal":"not_equal";   #Prints equal !!

Both strings are getting converted to floats, then losing precision, then becoming equal :-(

Using "===" or making either of the strings non-numeric will prevent this.
[This is on a 32-bit machine, on a 64-bit, you will have to make the strings longer to see the effect]
Jouriy LYSENKO 17-Jun-2011 02:18
If $var not declared.

In php 5.2 :
<?php if($var) ?> - work

in php 5.3 :
<?php if($var) ?> - dont work and generate error E_NOTICE
php at benizi dot com 15-Feb-2010 10:31
It's interesting to note that 'empty()' and 'boolean : if($x)'
are paired as logical opposites, as are 'is_null()' and 'isset()'.
edgar at goodforall dot eu 15-Dec-2009 06:55
Some function to write out your own comparisson table in tsv format. Can be easily modified to add more testcases and/or binary functions. It will test all comparables against each other with all functions.

<?php
$funcs = array(
        /* Testing equality */
        'eq' => '==',
        'ne' => '!=',
        'gt' => '>',
        'lt' => '<',
        'ne2' => '<>',
        'lte' => '<=',
        'gte' => '>=',
        /* Testing identity */
        'id' => '===',
        'nid' => '!=='
);
class Test {
        protected $a;
        public $b;
        public function __construct($a,$b){
                $this->a = $a;
                $this->b = $b;
        }
        public function getab(){
                return $this->a.",". $this->b;
        }

}
$tst1 = new Test(1,2);
$tst2 = new Test(1,2);
$tst3 = new Test(2,2);
$tst4 = new Test(1,1);

$arr1 = array(1,2,3);
$arr2 = array(2,3,4);
$arr3 = array('a','b','c','d');
$arr4 = array('a','b','c');
$arr5 = array();

$comp1 = array(
        'ints' => array(-1,0,1,2),
        'floats' => array(-1.1,0.0,1.1,2.0),
        'string' => array('str', 'str1', '', '1'),
        'bools' => array(true, false),
        'null' => array(null),
        'objects' => array($tst1,$tst2,$tst3,$tst4),
        'arrays' => array($arr1, $arr2, $arr3, $arr4, $arr5)
);
$fbody = array();

foreach($funcs as $name => $op){
        $fbody[$name] = create_function('$a,$b', 'return $a ' . $op . ' $b;');
}

$table = array(array('function', 'comp1', 'comp2', 'f comp1 comp2', 'type'));
/* Do comparisons */
$comp2  = array();
foreach($comp1 as $type => $val){
        $comp2[$type] = $val;
}

foreach($comp1 as $key1 => $val1){
        foreach($comp2 as $key2 => $val2){
                addTableEntry($key1, $key2, $val1, $val2);
        }
}
$out = '';
foreach($table as $row){
        $out .= sprintf("%-20s\t%-20s\t%-20s\t%-20s\t%-20s\n", $row[0], $row[1], $row[2], $row[3], $row[4]);
}

print $out;
exit;

function addTableEntry($n1, $n2, $comp1, $comp2){
        global $table, $fbody;
        foreach($fbody as $fname => $func){
                        foreach($comp1 as $val1){
  foreach($comp2 as $val2){
                                        $val = $func($val1,$val2);
                                                $table[] = array($fname, gettype($val1) . ' => ' . sprintval($val1), gettype($val2) .' => ' . sprintval($val2), gettype($val) . ' => ' . sprintval($val), gettype($val1) . "-" . gettype($val2) . '-' . $fname);
                                        }
                        }
        }
}

function sprintval($val){
        if(is_object($val)){
                return 'object-' . $val->getab();
        }
        if(is_array($val)){
                return implode(',', $val);
        }
        if(is_bool($val)){
                if($val){
                        return 'true';
                }
                return 'false';
        }
        return strval($val);
}

?>
info at shaelf dot ru 06-Jan-2008 01:51
Compare object
<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //true
?>
frank 14-Aug-2007 03:06
A comparison table for <=,<,=>,> would be nice...
Following are TRUE (tested PHP4&5):
NULL <= -1
NULL <= 0
NULL <= 1
!(NULL >= -1)
NULL >= 0
!(NULL >= 1)
That was a surprise for me (and it is not like SQL, I would like to have the option to have SQL semantics with NULL...).
Jan 29-Dec-2005 11:23
Note that php comparison is not transitive:

"php" == 0 => true
0 == null => true
null == "php" => false
jerryschwartz at comfortable dot com 26-Jul-2005 01:04
In some languages, a boolean is promoted to an integer (with a value of 1 or -1, typically) if used in an expression with an integer. I found that PHP has it both ways:

If you add a boolean with a value of true to an integer with a value of 3, the result will be 4 (because the boolean is cast as an integer).

On the other hand, if you test a boolean with a value of true for equality with an integer with a value of three, the result will be true (because the integer is cast as a boolean).

Surprisingly, at first glance, if you use either < or > as the comparison operator the result is always false (again, because the integer as cast as a boolean, and true is neither greater nor less than true).
tom 17-Jun-2005 02:27
<?php
if (strlen($_POST['var']) > 0) {
    // form value is ok
}
?>

When working with HTML forms this a good way to:

(A) let "0" post values through like select or radio values that correspond to array keys or checkbox booleans that would return FALSE with empty(), and;
(B) screen out $x = "" values, that would return TRUE with isset()!

Because HTML forms post values as strings, this is a good way to test variables!

[[Editor Note: This will create a PHP Error of level E_NOTICE if the checked variable (in this case $_POST['var']) is undefined. It may be used after (in conjuection with) isset() to prevent this.]]
aidan at php dot net 24-Jan-2005 07:00
The way PHP handles comparisons when multiple types are concerned is quite confusing.

For example:
"php" == 0

This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.


解析器代号列表

PHP 语言的不同部分在内部被表示为类似 T_SR 的类型。PHP 在解析错误时输出这样的标识符，例如 "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."。

应该知道 T_SR 的含义。对于所有不知道的人，下表列出了这些标识符，PHP 语法和在手册中适当位置的参考。

代号
代号 | 语法 | 参考
T_ABSTRACT | abstract | 抽象类（自 PHP 5.0.0 起可用）
T_AND_EQUAL | &= | 赋值运算符
T_ARRAY | array() | array()，数组语法
T_ARRAY_CAST | (array) | 类型转换
T_AS | as | foreach
T_BAD_CHARACTER |  | 在 ASCII 32 之前除了 \t (0x09), \n (0x0a) 和 \r (0x0d) 以外的任何字符
T_BOOLEAN_AND | && | 逻辑运算符
T_BOOLEAN_OR | || | 逻辑运算符
T_BOOL_CAST | (bool) 或 (boolean) | 类型转换
T_BREAK | break | break
T_CASE | case | switch
T_CATCH | catch | 异常（自 PHP 5.0.0 起可用）
T_CHARACTER |  |
T_CLASS | class | 类和对象
T_CLONE | clone | 类和对象。仅用于 PHP 5。
T_CLOSE_TAG | ?> 或 %> |
T_COMMENT | // 或 #，以及 PHP 5 下的 /* */ | 注释
T_CONCAT_EQUAL | .= | 赋值运算符
T_CONST | const |
T_CONSTANT_ENCAPSED_STRING | "foo" 或 'bar' | 字符串语法
T_CONTINUE | continue |
T_CURLY_OPEN |  |
T_DEC | -- | 递增/递减运算符
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIV_EQUAL | /= | 赋值运算符
T_DNUMBER | 0.12，等等 | 浮点数
T_DOC_COMMENT | /** */ | PHPDoc 风格的注释（仅用于 PHP 5）
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | 复杂变量解析语法
T_DOUBLE_ARROW | => | 数组语法
T_DOUBLE_CAST | (real), (double) 或 (float) | 类型转换
T_DOUBLE_COLON | :: | 见下面的 T_PAAMAYIM_NEKUDOTAYIM
T_ECHO | echo | echo
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE |  |
T_ENDDECLARE | enddeclare | declare，替代语法
T_ENDFOR | endfor | for，替代语法
T_ENDFOREACH | endforeach | foreach，替代语法
T_ENDIF | endif | if，替代语法
T_ENDSWITCH | endswitch | switch，替代语法
T_ENDWHILE | endwhile | while，替代语法
T_END_HEREDOC |  | heredoc 语法
T_EVAL | eval() | eval()
T_EXIT | exit 或 die | exit(), die()
T_EXTENDS | extends | extends，类和对象
T_FILE | __FILE__ | 常量
T_FINAL | final | Final 关键字（自 PHP 5.0.0 起可用）
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function 或 cfunction | 函数
T_GLOBAL | global | 变量范围
T_HALT_COMPILER | __halt_compiler() | __halt_compiler（自 PHP 5.1.0 起可用）
T_IF | if | if
T_IMPLEMENTS | implements | 对象接口（自 PHP 5.0.0 起可用）
T_INC | ++ | 递增／递减运算符
T_INCLUDE | include() | include
T_INCLUDE_ONCE | include_once() | include_once
T_INLINE_HTML |  |
T_INSTANCEOF | instanceof | type operators（仅 PHP5）
T_INT_CAST | (int) 或 (integer) | 类型转换
T_INTERFACE | interface | 对象接口（自 PHP 5.0.0 起可用）
T_ISSET | isset() | isset()
T_IS_EQUAL | == | 比较运算符
T_IS_GREATER_OR_EQUAL | >= | 比较运算符
T_IS_IDENTICAL | === | 比较运算符
T_IS_NOT_EQUAL | != or <> | 比较运算符
T_IS_NOT_IDENTICAL | !== | 比较运算符
T_IS_SMALLER_OR_EQUAL | <= | 比较运算符
T_LINE | __LINE__ | 常量
T_LIST | list() | list()
T_LNUMBER | 123，012，0x1ac，等等 | 整型
T_LOGICAL_AND | and | 逻辑运算符
T_LOGICAL_OR | or | 逻辑运算符
T_LOGICAL_XOR | xor | 逻辑运算符
T_MINUS_EQUAL | -= | 赋值运算符
T_ML_COMMENT | /* 和 */ | 注释（仅用于 PHP 4）
T_MOD_EQUAL | %= | 赋值运算符
T_MUL_EQUAL | *= | 赋值运算符
T_NEW | new | 类和对象
T_NUM_STRING |  |
T_OBJECT_CAST | (object) | 类型转换
T_OBJECT_OPERATOR | -> | 类和对象
T_OPEN_TAG | <?php, <? 或 <% | 从 HTML 转义
T_OPEN_TAG_WITH_ECHO | <?= or <%= | 从 HTML 转义
T_OR_EQUAL | |= | 赋值运算符
T_PAAMAYIM_NEKUDOTAYIM | :: | ::。也定义为 T_DOUBLE_COLON。
T_PLUS_EQUAL | += | 赋值运算符
T_PRINT | print() | print
T_PRIVATE | private | 类和对象。仅用于 PHP 5。
T_PUBLIC | public | 类和对象。仅用于 PHP 5。
T_PROTECTED | protected | 类和对象。仅用于 PHP 5。
T_REQUIRE | require() | require
T_REQUIRE_ONCE | require_once() | require_once
T_RETURN | return | 返回值
T_SL | << | 位运算符
T_SL_EQUAL | <<= | 赋值运算符
T_SR | >> | 位运算符
T_SR_EQUAL | >>= | 赋值运算符
T_START_HEREDOC | <<< | heredoc 语法
T_STATIC | static | 变量范围
T_STRING |  |
T_STRING_CAST | (string) | 类型转换
T_STRING_VARNAME |  |
T_SWITCH | switch | switch
T_THROW | throw | 异常（自 PHP 5.0.0 起可用）
T_TRY | try | 异常（自 PHP 5.0.0 起可用）
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | （无文档; 类型为 null）
T_USE | use | （未实现）
T_VAR | var | 类和对象
T_VARIABLE | $foo | 变量
T_WHILE | while | while，do..while
T_WHITESPACE |  |
T_XOR_EQUAL | ^= | 赋值运算符
T_FUNC_C | __FUNCTION__ | 常量，自 PHP 4.3.0 起可用
T_CLASS_C | __CLASS__ | 常量，自 PHP 4.3.0 起可用

参见 token_name()。

User Contributed Notes

fgm at osinet dot fr 22-Sep-2008 01:08
T_ENCAPSED_AND_WHITESPACED is returned when parsing strings with evaluated content, like "some $value" or this example from the Strings reference page:

<?php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

This last example is tokenized as:
T_ECHO
  echo
T_WHITESPACE
  %20 (a space character)
T_START_HEREDOC
  <<
T_ENCAPSED_AND_WHITESPACE
  My name is "
T_VARIABLE
  $name
T_ENCAPSED_AND_WHITESPACE
  ". I am printing some
T_VARIABLE
  $foo
T_OBJECT_OPERATOR
  ->
T_STRING
  foo
T_ENCAPSED_AND_WHITESPACE
  . Now, I am printing some
T_CURLY_OPEN
  {
T_VARIABLE
  $foo
T_OBJECT_OPERATOR
  ->
T_STRING
  bar
(terminal)
  [
T_LNUMBER
  1
(terminal)
  ]
(terminal)
  }
T_ENCAPSED_AND_WHITESPACE
  . This should print a capital 'A': \x41
T_END_HEREDOC
  EOT
(terminal)
  ;
nathan at unfinitydesign dot com 22-Sep-2008 05:52
T_ENCAPSED_AND_WHITESPACE is whitespace which intersects a group of tokens. For example, an "unexpected T_ENCAPSED_AND_WHITESPACE" error is produced by the following code:

<?php
$main_output_world = 'snakes!';
echo('There are' 10 $main_output_world);
?>

Note the missing concatenation operator between the two strings leads to the whitespace error that is so named above. The concatenation operator instructs PHP to ignore the whitespace between the two code tokens (the so named "encapsed" data"), rather than parse it as a token itself.

The correct code would be:

<?php
$main_output_world = 'snakes!';
echo('There are' . 10 . $main_output_world);
?>

Note the addition of the concatenation operator between each token.


用户空间命名指南

Table of Contents

  • 全局命名空间
  • 规则
  • 提示

以下是在用户空间 PHP 代码中怎样最佳选择标识符名称的指南。当在全局命名空间中选择创建的符号名称时，要考虑到以下指导方针以免未来的 PHP 版本破坏掉用户使用的符号名称。

User Contributed Notes

There are no user contributed notes for this page.


全局命名空间

以下代码结构会进入全局命名空间：

  • functions（函数）

  • classes（类）

  • interfaces（接口）

  • constants（常量，并非类常量）

  • 在函数／方法之外定义的变量

User Contributed Notes

There are no user contributed notes for this page.


规则

以下列表指出了 PHP 工程在选择新的内部标识符时保留给自己的权利。最终指南是官方的» 编码标准：

  • PHP 拥有最顶层命名空间，但是会尝试找到合体的描述命名以避免任何明显的冲突。

  • 函数名在两个词中间使用下划线，类名则同时使用 camelCase 和 PascalCase 规则。

  • PHP 在任何扩展库的全局符号前附加上扩展库的名称（此规则在过去则有无数例外）。例如：

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos()（以前的一个失误例子）

    • new SplFileObject()

  • Iterators 和 Exceptions 则只是简单加上 "Iterator" 和 "Exception" 后缀。例如：

    • ArrayIterator

    • LogicException

  • PHP 保留所有以 __ 开头的符号作为魔术符号。建议用户不要在 PHP 中创建以 __ 打头的符号，除非是要使用有文档记载的魔术函数功能。例如：

    • __get()

    • __autoload()

User Contributed Notes

There are no user contributed notes for this page.


提示

要写出能经受住时间考验的代码，建议在全局的命名空间中，尽量不要用变量、函数或类名，以避免与其它用户空间代码出现命名空间冲突。

防止函数和类的命名冲突的一个常见方法是使用自己专属名字的 namespace。

<?php

namespace MyProject;

function my_function() {
    return true;
}

\MyProject\my_function();

这仍然需要你跟踪已经使用过的命名空间，但一旦你用了在决定了要使用的命名空间后，你可以添加所有的函数和类到它，不用再考虑冲突。

最好的做法是，尽量控制一下添加到全局范围内的变量，以防止与第三方代码的命名产生命名空间冲突。

Note: Variable scoping

Because of PHP's scoping rules variables defined inside functions and methods are not in the global scope and as such cannot conflict with other variables defined in the global scope.

User Contributed Notes

There are no user contributed notes for this page.


关于本手册

Table of Contents

  • 手册的格式
  • 关于用户注释
  • 如何阅读函数的定义（函数原型）
  • 本手册中所涉及的 PHP 版本
  • 如何得到关于 PHP 更多的信息
  • 如何帮助改进本文档
  • 如何生成手册的各种格式
  • 手册译文

User Contributed Notes

There are no user contributed notes for this page.


手册的格式

《PHP 参考手册》提供了多种不同格式的版本，它们可以分为两组：在线阅读版本和可下载打包版本。

Note:

有些出版商可能已经出版了本手册的一些印刷版本。不推荐印刷版，因为 PHP 参考手册更新得非常快，这些印刷版本的内容很快将过时。

可以访问 » PHP.net 网站及其众多的镜像站点来在线阅读《PHP 参考手册》。为了保证最佳的访问速度，应该选择地理位置最接近的镜像站点。PHP 手册的在线版本目前有两种 CSS 样式表：便于浏览和便于打印。

和绝大多数离线格式的手册相比，在线阅读版本有两个显著的优点，即它集成了用户注释，并且可以使用其中的 » URL 快捷方式快速进入手册中想阅读的部分；但是，它的明显的缺点是必须要联网才能阅读。

目前，《PHP 参考手册》提供多种离线阅读格式，最适合于自己的格式取决于所使用的操作系统和个人的阅读习惯。关于《PHP 参考手册》如何被制作成如此多的版本，请查阅本附录中如何生成手册的各种格式一节。

跨平台性最好的格式是 HTML 格式格式。HTML 格式提供了两种方式：一种只有一个很大的 HTML 文件；另一种方式是每一节分成一个独立文件（它们形成一个包含有几千个文件的文件包）。我们提供的是这两种版本的压缩包，需要使用解压缩工具解压出压缩包中的文件。

对于 Windows 平台，我们利用了 Windows HTML 帮助应用程序结合本手册的 HTML 格式，形成了本手册的 Windows HTML 帮助版本。该版本提供手册的全文搜索、完整的索引以及书签功能。很多 Windows 平台下流行的 PHP 集成开发环境也集成了该版本的手册，以给开发者提供最方便快捷的参考。CHM 阅读器也有 Linux 版本，可以到 » xCHM 或 » GnoCHM 网站了解更多信息。

同时，PHP 手册也有» 扩展 CHM 版本提供下载。它更新的速度比较慢，但是提供了附加的功能。由于制作帮助页面时采用的技术的特殊性，它只可在 Microsoft Windows 下工作。

User Contributed Notes

There are no user contributed notes for this page.


关于用户注释

用户注释在本手册的开发过程中搬演了相当重要的角色。通过允许手册的读者利用它们的浏览器提供范例、解释和进一步的阐述，我们便能够把这些反馈信息包含到手册的正文中。而且，当这些注释被包含后，读者就可以在线通过它们被提交的格式来阅读它们，也可以通过某些离线格式来阅读。

Note:

用户注释在网上出现之前并不成熟，因此这些文字和代码的质量，甚至它们的真实性无从得到保证（这并不是说本手册本身的质量和准确性没有任何的保证）。

Note:

由于用户注释被认为是 PHP 手册的一部分，因此它使用本文档的许可协议（目前为创作共用许可协议）。请查阅手册版权页以了解更多详细信息。

User Contributed Notes

There are no user contributed notes for this page.


如何阅读函数的定义（函数原型）

文档中的每个函数都只是快速参考，学会如何阅读和理解文档将使得 PHP 的使用更加简单。和依赖赖于复制／粘贴范例比起来，用户一定更希望知道如何阅读函数的定义（函数原型）：

Note: 先决条件，对变量类型的基本理解

尽管 PHP 是一种松散类型语言，但变量类型有重要的意义，需要理解它的基本知识。

函数定义告诉我们函数返回什么类型的值，让我们用函数 strlen() 的定义作为第一个范例：

strlen

(PHP 4, PHP 5, PHP 7)
strlen -- Get string length

说明
strlen ( string $string ) : int

返回给定的字符串 string 的长度。

对函数定义的解释
组成部分 | 说明
strlen | 函数名称。
(PHP 4, PHP 5, PHP 7) | strlen() 在 PHP 4, PHP 5 和 PHP 7 的所有版本中都存在。
( string $string ) | 第一个（本例中是唯一的）参数，在该函数中名为 string，且类型为 string。
int | 该函数返回的值的类型，这里为整型 int（即以数字来衡量的字符串的长度）。

可以将以上函数的定义写成一般形式：

          函数名          ( 参数类型           参数名 )        返回类型
      function name    ( parameter type   parameter name ) : returned type

很多函数都有多个变量，例如 in_array()。其函数原型如下：

      in_array ( mixed $needle, array $haystack , bool $strict = false ) : bool

这是什么意思？in_array() 返回一个"布尔"值，成功（如果在参数 haystack 中能找到参数 needle）则返回 true, 或者在失败时返回 false（如果在参数 haystack 中找不到参数 needle）。第一个参数被命名为 needle 且其类型不定，因此我们将其称为"混和"类型。该混和类型的 needle 参数（我们要找的对象）可以是一个标量的值（字符串、整数、或者浮点数），或者一个数组。haystack（我们寻找的范围）是第二个参数。第三个可选参数被命名为 strict。所有的可选参数都用 [ 方括号 ] 括起来。手册表明 strict 参数默认值为布尔值 false。需要了解函数工作的细节，请参阅手册中和该函数相关的页面。

函数参数前的 & 符号使参数以 引用 方式传递，如下所见：

       preg_match ( string $pattern , string $subject [, array &$matches
      [, int $flags = 0 [, int $offset = 0 ]]] ) : int

在这个例子中，我们可以看到，第三个可选参数 &$matches 会意引用方式传递。

有的函数包含更复杂的 PHP 版本信息。我们拿 html_entity_decode() 举例：

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

它意味着该函数只可在 PHP 4.3.0 及以后发布的版本中使用。

User Contributed Notes

There are no user contributed notes for this page.


本手册中所涉及的 PHP 版本

本手册包含有 PHP 过去，现在和未来版本的信息。如果（不同版本）有功能变化则作为注释、更新日志以及插入文本方式在手册页中注明。 文档内最早的版本是 PHP 7.0.0。

当对应于最新（尚未发布）开发版的 PHP 有文档存在时，将会被标记为"可在 Git 获取"或者"开发版本"。应该计划好相关变更，虽不多见但确有可能会有变动。

所有开发都放置于 Git 中，应按照» 匿名 Git 访问页面中的方法来取出。

要澄清一点，手册会指明 PHP 的主版本号，次版本号和发布编号。以 PHP 7.3.1 为例，5 是主版本号，3 是次版本号，1 是发布编号。通常 PHP 只会在主、次版本更新时增加新特性，在发布编号更新时修正错误。不过也不完全是这样。

还要注意 PHP 手册是以现在时态书写的，而不是将来时态，即使某特性当前还尚未可用。原因是这样一来手册就可以经受住时间的考验，而不用在每次 PHP 更新时都去修改无聊的语法。

PHP 手册会多次列出 PHP 配置选项的"默认值"。默认值是没有 php.ini 配置文件时的值，所以与 php.ini-development 和 php.ini-production 存在很大差异。同时这些值也是基于最新版本的 PHP。请参考 PHP 配置选项列表以了解更多信息。

User Contributed Notes

There are no user contributed notes for this page.


如何得到关于 PHP 更多的信息

本手册并不打算提供基本的编程开发指导。刚学编程的或者新手程序员会发现仅仅用本手册来学习如何用 PHP 编程是一件很困难的事情。应该寻找一本更适合初学者的书。

目前，PHP 官方提供了许多邮件列表来讨论 PHP 编程相关的各个方面的问题。如果卡在了某个问题上，可以到该邮件列表寻求帮助。有关支持以及邮件列表请访问 » PHP.net 支持页面。

User Contributed Notes

There are no user contributed notes for this page.


如何帮助改进本文档

可以通过以下三种途径来帮助改善本文档。

如果发现本手册任何一个格式的版本中有错误，请通过设在 » https://bugs.php.net/ 的纠错系统向我们报告，并将提交的错误分类为"文档问题 (Documentation Problem)"。所有文档相关的问题，包括手册格式，都应作为错误提交。

Note:

请勿滥用纠错系统来寻求帮助。如需帮助请访问» 支持页面。

通过提交注释，用户可以向其它读者提供更多的范例、解释和阐述。但请勿在注释系统提交错误报告。更多细节见关于用户注释一节。

PHP 手册被翻译成很多种语言。如果懂英语和另一种语言，可以加入翻译团队来帮助改善文档。关于开始一个新语种的翻译，或者加入某一个语言版本的翻译工作，请下载并阅读 » http://doc.php.net/tutorial/。

PHP 文档项目也有一个 IRC 频道，许多手册作者都常去。可以访问 irc.efnet.org 服务器上的 #php.doc 与他们讨论改善 PHP 文档的方法。

User Contributed Notes

There are no user contributed notes for this page.


如何生成手册的各种格式

本手册使用 XML 语言编写，同时运用了 » DocBook XML DTD。还用了 » PhD（基于 [PH]P 的 [D]ocBook 渲染器）来维护和格式化。

将 XML 语言作为源文件格式，使得我们只需维护该源文件文档，就可以可以利用它生成许多其它的输出格式。生在在线手册格式的工具是 » PhD。我们使用 » Microsoft HTML Help Workshop 来生成本手册的 Windows HTML 帮助 格式。当然，PHP 本身也完成了其它一些转换和格式化工作。

PHP 手册被生成多种不同语言和格式，详情见 » https://www.php.net/docs.php。XML 格式的源代码可以通过 SVN 下载，并通过 » https://svn.php.net/viewvc/ 在线浏览。文档存放于 phpdoc 模块中。

User Contributed Notes

There are no user contributed notes for this page.


手册译文

《PHP 参考手册》不但有各种不同的格式，而且还有各种语言的版本。手册的正文最初是用英语撰写的，后来有来自全世界各地的工作组致力于本手册各种语言版本的翻译工作。如果某个函数或者章节的内容尚未被翻译，则该语言版本手册的发布将落后于英语版本。

翻译工作者首先从本手册的 XML 源代码（可于 » https://github.com/php/doc-en" 获取）入手，将这些源代码翻译成他们的母语。不要从生成后的版本开始翻译（比如 HTML 或纯文本版）。因为编译系统会负责将 XML 源代码转换成可阅读版本。

Note:

要帮忙翻译手册，请发一封空的电子邮件到 » phpdoc-subscribe@lists.php.net 加入 phpdoc 邮件列表以便与文档翻译小组取得联系。邮件列表的地址为 phpdoc@lists.php.net。请在电子邮件中声明对文档翻译工作感兴趣，有人会回复并帮助加入到已经存在的翻译小组，或者开始新语种的翻译工作。

目前，本手册已经（或部分）有超过 10 种语言可用。

可以访问 » https://www.php.net/docs.php 来下载各种版本。

User Contributed Notes

There are no user contributed notes for this page.


Creative Commons Attribution 3.0

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  1. "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.
  2. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License.
  3. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership.
  4. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
  5. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work.
  6. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  7. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
  8. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.

2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.

3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  1. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
  2. to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified.";
  3. to Distribute and Publicly Perform the Work including as incorporated in Collections; and,
  4. to Distribute and Publicly Perform Adaptations.

  5. For the avoidance of doubt:

    1. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;
    2. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and,
    3. Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License.

The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved.

4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  1. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(b), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(b), as requested.
  2. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Section 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4 (b) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
  3. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination.

  1. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  2. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  1. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  2. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  3. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  4. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent
  5. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
  6. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law.

User Contributed Notes

There are no user contributed notes for this page.


索引

Table of Contents

  • 函数和方法列表
  • 示例列表

User Contributed Notes

There are no user contributed notes for this page.


函数和方法列表

手册中所有函数和方法的列表

a b c d e f g h i j k l m n o p q r s t u v w x y z _ ?

  • a
    • abs - 绝对值
    • acos - 反余弦
    • acosh - 反双曲余弦
    • addcslashes - 以 C 语言风格使用反斜线转义字符串中的字符
    • addslashes - 使用反斜线引用字符串
    • apache_child_terminate - 在本次请求结束后终止 apache 子进程
    • apache_getenv - 获取 Apache subprocess_env 变量
    • apache_get_modules - 获得已加载的Apache模块列表
    • apache_get_version - 获得Apache版本信息
    • apache_lookup_uri - 对指定的 URI 执行部分请求并返回所有有关信息
    • apache_note - 取得或设置 apache 请求记录
    • apache_request_headers - 获取全部 HTTP 请求头信息
    • apache_response_headers - 获得全部 HTTP 响应头信息
    • apache_setenv - 设置 Apache 子进程环境变量
    • APCUIterator::current - Get current item
    • APCUIterator::getTotalCount - Get total count
    • APCUIterator::getTotalHits - Get total cache hits
    • APCUIterator::getTotalSize - Get total cache size
    • APCUIterator::key - Get iterator key
    • APCUIterator::next - Move pointer to next item
    • APCUIterator::rewind - Rewinds iterator
    • APCUIterator::valid - Checks if current position is valid
    • APCUIterator::__construct - Constructs an APCUIterator iterator object
    • apcu_add - Cache a new variable in the data store
    • apcu_cache_info - Retrieves cached information from APCu's data store
    • apcu_cas - Updates an old value with a new value
    • apcu_clear_cache - Clears the APCu cache
    • apcu_dec - Decrease a stored number
    • apcu_delete - Removes a stored variable from the cache
    • apcu_enabled - Whether APCu is usable in the current environment
    • apcu_entry - Atomically fetch or generate a cache entry
    • apcu_exists - Checks if entry exists
    • apcu_fetch - Fetch a stored variable from the cache
    • apcu_inc - Increase a stored number
    • apcu_key_info - Get detailed information about the cache key
    • apcu_sma_info - Retrieves APCu Shared Memory Allocation information
    • apcu_store - Cache a variable in the data store
    • AppendIterator::append - Appends an iterator
    • AppendIterator::current - Gets the current value
    • AppendIterator::getArrayIterator - Gets the ArrayIterator
    • AppendIterator::getInnerIterator - Gets the inner iterator
    • AppendIterator::getIteratorIndex - Gets an index of iterators
    • AppendIterator::key - Gets the current key
    • AppendIterator::next - Moves to the next element
    • AppendIterator::rewind - Rewinds the Iterator
    • AppendIterator::valid - Checks validity of the current element
    • AppendIterator::__construct - Constructs an AppendIterator
    • array - 新建一个数组
    • ArrayAccess::offsetExists - 检查一个偏移位置是否存在
    • ArrayAccess::offsetGet - 获取一个偏移位置的值
    • ArrayAccess::offsetSet - 设置一个偏移位置的值
    • ArrayAccess::offsetUnset - 复位一个偏移位置的值
    • ArrayIterator::append - Append an element
    • ArrayIterator::asort - Sort array by values
    • ArrayIterator::count - Count elements
    • ArrayIterator::current - Return current array entry
    • ArrayIterator::getArrayCopy - Get array copy
    • ArrayIterator::getFlags - Get behavior flags
    • ArrayIterator::key - Return current array key
    • ArrayIterator::ksort - Sort array by keys
    • ArrayIterator::natcasesort - Sort an array naturally, case insensitive
    • ArrayIterator::natsort - Sort an array naturally
    • ArrayIterator::next - Move to next entry
    • ArrayIterator::offsetExists - Check if offset exists
    • ArrayIterator::offsetGet - Get value for an offset
    • ArrayIterator::offsetSet - Set value for an offset
    • ArrayIterator::offsetUnset - Unset value for an offset
    • ArrayIterator::rewind - Rewind array back to the start
    • ArrayIterator::seek - Seek to position
    • ArrayIterator::serialize - Serialize
    • ArrayIterator::setFlags - Set behaviour flags
    • ArrayIterator::uasort - Sort with a user-defined comparison function and maintain index association
    • ArrayIterator::uksort - Sort by keys using a user-defined comparison function
    • ArrayIterator::unserialize - Unserialize
    • ArrayIterator::valid - Check whether array contains more entries
    • ArrayIterator::__construct - Construct an ArrayIterator
    • ArrayObject::append - 追加新的值作为最后一个元素。
    • ArrayObject::asort - Sort the entries by value
    • ArrayObject::count - 统计 ArrayObject 内 public 属性的数量
    • ArrayObject::exchangeArray - Exchange the array for another one
    • ArrayObject::getArrayCopy - Creates a copy of the ArrayObject
    • ArrayObject::getFlags - Gets the behavior flags
    • ArrayObject::getIterator - Create a new iterator from an ArrayObject instance
    • ArrayObject::getIteratorClass - Gets the iterator classname for the ArrayObject
    • ArrayObject::ksort - Sort the entries by key
    • ArrayObject::natcasesort - Sort an array using a case insensitive "natural order" algorithm
    • ArrayObject::natsort - Sort entries using a "natural order" algorithm
    • ArrayObject::offsetExists - Returns whether the requested index exists
    • ArrayObject::offsetGet - Returns the value at the specified index
    • ArrayObject::offsetSet - 为指定索引设定新的值
    • ArrayObject::offsetUnset - Unsets the value at the specified index
    • ArrayObject::serialize - Serialize an ArrayObject
    • ArrayObject::setFlags - Sets the behavior flags
    • ArrayObject::setIteratorClass - Sets the iterator classname for the ArrayObject
    • ArrayObject::uasort - Sort the entries with a user-defined comparison function and maintain key association
    • ArrayObject::uksort - Sort the entries by keys using a user-defined comparison function
    • ArrayObject::unserialize - Unserialize an ArrayObject
    • ArrayObject::__construct - Construct a new array object
    • array_change_key_case - 将数组中的所有键名修改为全大写或小写
    • array_chunk - 将一个数组分割成多个
    • array_column - 返回数组中指定的一列
    • array_combine - 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值
    • array_count_values - 统计数组中所有的值
    • array_diff - 计算数组的差集
    • array_diff_assoc - 带索引检查计算数组的差集
    • array_diff_key - 使用键名比较计算数组的差集
    • array_diff_uassoc - 用用户提供的回调函数做索引检查来计算数组的差集
    • array_diff_ukey - 用回调函数对键名比较计算数组的差集
    • array_fill - 用给定的值填充数组
    • array_fill_keys - 使用指定的键和值填充数组
    • array_filter - 使用回调函数过滤数组的元素
    • array_flip - 交换数组中的键和值
    • array_intersect - 计算数组的交集
    • array_intersect_assoc - 带索引检查计算数组的交集
    • array_intersect_key - 使用键名比较计算数组的交集
    • array_intersect_uassoc - 带索引检查计算数组的交集，用回调函数比较索引
    • array_intersect_ukey - 用回调函数比较键名来计算数组的交集
    • array_keys - 返回数组中部分的或所有的键名
    • array_key_exists - 检查数组里是否有指定的键名或索引
    • array_key_first - 获取指定数组的第一个键值
    • array_key_last - 获取一个数组的最后一个键值
    • array_map - 为数组的每个元素应用回调函数
    • array_merge - 合并一个或多个数组
    • array_merge_recursive - 递归地合并一个或多个数组
    • array_multisort - 对多个数组或多维数组进行排序
    • array_pad - 以指定长度将一个值填充进数组
    • array_pop - 弹出数组最后一个单元（出栈）
    • array_product - 计算数组中所有值的乘积
    • array_push - 将一个或多个单元压入数组的末尾（入栈）
    • array_rand - 从数组中随机取出一个或多个随机键
    • array_reduce - 用回调函数迭代地将数组简化为单一的值
    • array_replace - 使用传递的数组替换第一个数组的元素
    • array_replace_recursive - 使用传递的数组递归替换第一个数组的元素
    • array_reverse - 返回单元顺序相反的数组
    • array_search - 在数组中搜索给定的值，如果成功则返回首个相应的键名
    • array_shift - 将数组开头的单元移出数组
    • array_slice - 从数组中取出一段
    • array_splice - 去掉数组中的某一部分并用其它值取代
    • array_sum - 对数组中所有值求和
    • array_udiff - 用回调函数比较数据来计算数组的差集
    • array_udiff_assoc - 带索引检查计算数组的差集，用回调函数比较数据
    • array_udiff_uassoc - 带索引检查计算数组的差集，用回调函数比较数据和索引
    • array_uintersect - 计算数组的交集，用回调函数比较数据
    • array_uintersect_assoc - 带索引检查计算数组的交集，用回调函数比较数据
    • array_uintersect_uassoc - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引
    • array_unique - 移除数组中重复的值
    • array_unshift - 在数组开头插入一个或多个单元
    • array_values - 返回数组中所有的值
    • array_walk - 使用用户自定义函数对数组中的每个元素做回调处理
    • array_walk_recursive - 对数组中的每个成员递归地应用用户函数
    • arsort - 对数组进行逆向排序并保持索引关系
    • asin - 反正弦
    • asinh - 反双曲正弦
    • asort - 对数组进行排序并保持索引关系
    • assert - 检查一个断言是否为 false
    • assert_options - 设置/获取断言的各种标志
    • atan - 反正切
    • atan2 - 两个参数的反正切
    • atanh - 反双曲正切
  • b
    • base64_decode - 对使用 MIME base64 编码的数据进行解码
    • base64_encode - 使用 MIME base64 对数据进行编码
    • basename - 返回路径中的文件名部分
    • BaseResult::getWarnings - Fetch warnings from last operation
    • BaseResult::getWarningsCount - Fetch warning count from last operation
    • base_convert - 在任意进制之间转换数字
    • bcadd - 2个任意精度数字的加法计算
    • bccomp - 比较两个任意精度的数字
    • bcdiv - 2个任意精度的数字除法计算
    • bcmod - 对一个任意精度数字取模
    • bcmul - 2个任意精度数字乘法计算
    • bcpow - 任意精度数字的乘方
    • bcpowmod - Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale - 设置所有bc数学函数的默认小数点保留位数
    • bcsqrt - 任意精度数字的二次方根
    • bcsub - 2个任意精度数字的减法
    • bin2hex - 函数把包含数据的二进制字符串转换为十六进制值
    • bindec - 二进制转换为十进制
    • bindtextdomain - Sets or gets the path for a domain
    • bind_textdomain_codeset - Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned
    • boolval - 获取变量的布尔值
    • bson_decode - 反序列化一个 BSON 对象为 PHP 数组
    • bson_encode - 序列化一个 PHP 变量为 BSON 字符串
    • bzclose - 关闭一个 bzip2 文件
    • bzcompress - 把一个字符串压缩成 bzip2 编码数据
    • bzdecompress - 解压经 bzip2 编码过的数据
    • bzerrno - 返回一个 bzip2 错误码
    • bzerror - 返回包含 bzip2 错误号和错误字符串的一个 array
    • bzerrstr - 返回一个 bzip2 的错误字符串
    • bzflush - 强制写入所有写缓冲区的数据
    • bzopen - 打开 bzip2 压缩文件
    • bzread - bzip2 文件二进制安全地读取
    • bzwrite - 二进制安全地写入 bzip2 文件
  • c
    • CachingIterator::count - The number of elements in the iterator
    • CachingIterator::current - Return the current element
    • CachingIterator::getCache - Retrieve the contents of the cache
    • CachingIterator::getFlags - Get flags used
    • CachingIterator::getInnerIterator - Returns the inner iterator
    • CachingIterator::hasNext - Check whether the inner iterator has a valid next element
    • CachingIterator::key - Return the key for the current element
    • CachingIterator::next - Move the iterator forward
    • CachingIterator::offsetExists - The offsetExists purpose
    • CachingIterator::offsetGet - The offsetGet purpose
    • CachingIterator::offsetSet - The offsetSet purpose
    • CachingIterator::offsetUnset - The offsetUnset purpose
    • CachingIterator::rewind - Rewind the iterator
    • CachingIterator::setFlags - The setFlags purpose
    • CachingIterator::valid - Check whether the current element is valid
    • CachingIterator::__construct - Construct a new CachingIterator object for the iterator
    • CachingIterator::__toString - Return the string representation of the current element
    • CallbackFilterIterator::accept - Calls the callback with the current value, the current key and the inner iterator as arguments
    • CallbackFilterIterator::__construct - Create a filtered iterator from another iterator
    • call_user_func - 把第一个参数作为回调函数调用
    • call_user_func_array - 调用回调函数，并把一个数组参数作为回调函数的参数
    • cal_days_in_month - 返回某个历法中某年中某月的天数
    • cal_from_jd - 转换Julian Day计数到一个支持的历法。
    • cal_info - 返回选定历法的信息
    • cal_to_jd - 从一个支持的历法转变为Julian Day计数。
    • ceil - 进一法取整
    • chdir - 改变目录
    • checkdate - 验证一个格里高里日期
    • checkdnsrr - 给指定的主机（域名）或者IP地址做DNS通信检查
    • chgrp - 改变文件所属的组
    • chmod - 改变文件模式
    • chop - rtrim 的别名
    • chown - 改变文件的所有者
    • chr - 返回指定的字符
    • chroot - 改变根目录
    • chunk_split - 将字符串分割成小块
    • classkit_import - Import new class method definitions from a file
    • classkit_method_add - Dynamically adds a new method to a given class
    • classkit_method_copy - Copies a method from class to another
    • classkit_method_redefine - Dynamically changes the code of the given method
    • classkit_method_remove - Dynamically removes the given method
    • classkit_method_rename - Dynamically changes the name of the given method
    • class_alias - 为一个类创建别名
    • class_exists - 检查类是否已定义
    • class_implements - 返回指定的类实现的所有接口。
    • class_parents - 返回指定类的父类。
    • class_uses - Return the traits used by the given class
    • clearstatcache - 清除文件状态缓存
    • Client::getClient - Get client session
    • Client::__construct - Client constructor
    • cli_get_process_title - Returns the current process title
    • cli_set_process_title - Sets the process title
    • closedir - 关闭目录句柄
    • closelog - 关闭系统日志链接
    • Closure::bind - 复制一个闭包，绑定指定的$this对象和类作用域。
    • Closure::bindTo - 复制当前闭包对象，绑定指定的$this对象和类作用域。
    • Closure::__construct - 用于禁止实例化的构造函数
    • Collator::asort - Sort array maintaining index association
    • Collator::compare - Compare two Unicode strings
    • Collator::create - Create a collator
    • Collator::getAttribute - Get collation attribute value
    • Collator::getErrorCode - Get collator's last error code
    • Collator::getErrorMessage - Get text for collator's last error code
    • Collator::getLocale - Get the locale name of the collator
    • Collator::getSortKey - Get sorting key for a string
    • Collator::getStrength - Get current collation strength
    • Collator::setAttribute - Set collation attribute
    • Collator::setStrength - Set collation strength
    • Collator::sort - Sort array using specified collator
    • Collator::sortWithSortKeys - Sort array using specified collator and sort keys
    • Collator::__construct - Create a collator
    • Collectable::isGarbage - Determine whether an object has been marked as garbage
    • Collectable::setGarbage - Mark an object as garbage
    • Collection::add - Add collection document
    • Collection::addOrReplaceOne - Add or replace collection document
    • Collection::count - Get document count
    • Collection::createIndex - Create collection index
    • Collection::dropIndex - Drop collection index
    • Collection::existsInDatabase - Check if collection exists in database
    • Collection::find - Search for document
    • Collection::getName - Get collection name
    • Collection::getOne - Get one document
    • Collection::getSchema - Get schema object
    • Collection::getSession - Get session object
    • Collection::modify - Modify collection documents
    • Collection::remove - Remove collection documents
    • Collection::removeOne - Remove one collection document
    • Collection::replaceOne - Replace one collection document
    • Collection::__construct - Collection constructor
    • CollectionAdd::execute - Execute the statement
    • CollectionAdd::__construct - CollectionAdd constructor
    • CollectionFind::bind - Bind value to query placeholder
    • CollectionFind::execute - Execute the statement
    • CollectionFind::fields - Set document field filter
    • CollectionFind::groupBy - Set grouping criteria
    • CollectionFind::having - Set condition for aggregate functions
    • CollectionFind::limit - Limit number of returned documents
    • CollectionFind::lockExclusive - Execute operation with EXCLUSIVE LOCK
    • CollectionFind::lockShared - Execute operation with SHARED LOCK
    • CollectionFind::offset - Skip given number of elements to be returned
    • CollectionFind::sort - Set the sorting criteria
    • CollectionFind::__construct - CollectionFind constructor
    • CollectionModify::arrayAppend - Append element to an array field
    • CollectionModify::arrayInsert - Insert element into an array field
    • CollectionModify::bind - Bind value to query placeholder
    • CollectionModify::execute - Execute modify operation
    • CollectionModify::limit - Limit number of modified documents
    • CollectionModify::patch - Patch document
    • CollectionModify::replace - Replace document field
    • CollectionModify::set - Set document attribute
    • CollectionModify::skip - Skip elements
    • CollectionModify::sort - Set the sorting criteria
    • CollectionModify::unset - Unset the value of document fields
    • CollectionModify::__construct - CollectionModify constructor
    • CollectionRemove::bind - Bind value to placeholder
    • CollectionRemove::execute - Execute remove operation
    • CollectionRemove::limit - Limit number of documents to remove
    • CollectionRemove::sort - Set the sorting criteria
    • CollectionRemove::__construct - CollectionRemove constructor
    • ColumnResult::getCharacterSetName - Get character set
    • ColumnResult::getCollationName - Get collation name
    • ColumnResult::getColumnLabel - Get column label
    • ColumnResult::getColumnName - Get column name
    • ColumnResult::getFractionalDigits - Get fractional digit length
    • ColumnResult::getLength - Get column field length
    • ColumnResult::getSchemaName - Get schema name
    • ColumnResult::getTableLabel - Get table label
    • ColumnResult::getTableName - Get table name
    • ColumnResult::getType - Get column type
    • ColumnResult::isNumberSigned - Check if signed type
    • ColumnResult::isPadded - Check if padded
    • ColumnResult::__construct - ColumnResult constructor
    • com::__construct - com class constructor
    • CommonMark\CQL::__construct - CQL Construction
    • CommonMark\CQL::__invoke - CQL Execution
    • CommonMark\Interfaces\IVisitable::accept - Visitation
    • CommonMark\Interfaces\IVisitor::enter - Visitation
    • CommonMark\Interfaces\IVisitor::leave - Visitation
    • CommonMark\Node::accept - Visitation
    • CommonMark\Node::appendChild - AST Manipulation
    • CommonMark\Node::insertAfter - AST Manipulation
    • CommonMark\Node::insertBefore - AST Manipulation
    • CommonMark\Node::prependChild - AST Manipulation
    • CommonMark\Node::replace - AST Manipulation
    • CommonMark\Node::unlink - AST Manipulation
    • CommonMark\Node\BulletList::__construct - BulletList Construction
    • CommonMark\Node\CodeBlock::__construct - CodeBlock Construction
    • CommonMark\Node\Heading::__construct - Heading Construction
    • CommonMark\Node\Image::__construct - Image Construction
    • CommonMark\Node\Link::__construct - Link Construction
    • CommonMark\Node\OrderedList::__construct - OrderedList Construction
    • CommonMark\Node\Text::__construct - Text Construction
    • CommonMark\Parse - Parsing
    • CommonMark\Parser::finish - Parsing
    • CommonMark\Parser::parse - Parsing
    • CommonMark\Parser::__construct - Parsing
    • CommonMark\Render - Rendering
    • CommonMark\Render\HTML - Rendering
    • CommonMark\Render\Latex - Rendering
    • CommonMark\Render\Man - Rendering
    • CommonMark\Render\XML - Rendering
    • compact - 建立一个数组，包括变量名和它们的值
    • COMPersistHelper::GetCurFileName - Get current filename
    • COMPersistHelper::GetMaxStreamSize - Get maximum stream size
    • COMPersistHelper::InitNew - Initialize object to default state
    • COMPersistHelper::LoadFromFile - Load object from file
    • COMPersistHelper::LoadFromStream - Load object from stream
    • COMPersistHelper::SaveToFile - Save object to file
    • COMPersistHelper::SaveToStream - Save object to stream
    • COMPersistHelper::__construct - Construct a COMPersistHelper object
    • Componere\Abstract\Definition::addInterface - Add Interface
    • Componere\Abstract\Definition::addMethod - Add Method
    • Componere\Abstract\Definition::addTrait - Add Trait
    • Componere\Abstract\Definition::getReflector - Reflection
    • Componere\cast - Casting
    • Componere\cast_by_ref - Casting
    • Componere\Definition::addConstant - Add Constant
    • Componere\Definition::addProperty - Add Property
    • Componere\Definition::getClosure - Get Closure
    • Componere\Definition::getClosures - Get Closures
    • Componere\Definition::isRegistered - State Detection
    • Componere\Definition::register - Registration
    • Componere\Definition::__construct - Definition Construction
    • Componere\Method::getReflector - Reflection
    • Componere\Method::setPrivate - Accessibility Modification
    • Componere\Method::setProtected - Accessibility Modification
    • Componere\Method::setStatic - Accessibility Modification
    • Componere\Method::__construct - Method Construction
    • Componere\Patch::apply - Application
    • Componere\Patch::derive - Patch Derivation
    • Componere\Patch::getClosure - Get Closure
    • Componere\Patch::getClosures - Get Closures
    • Componere\Patch::isApplied - State Detection
    • Componere\Patch::revert - Reversal
    • Componere\Patch::__construct - Patch Construction
    • Componere\Value::hasDefault - Value Interaction
    • Componere\Value::isPrivate - Accessibility Detection
    • Componere\Value::isProtected - Accessibility Detection
    • Componere\Value::isStatic - Accessibility Detection
    • Componere\Value::setPrivate - Accessibility Modification
    • Componere\Value::setProtected - Accessibility Modification
    • Componere\Value::setStatic - Accessibility Modification
    • Componere\Value::__construct - Value Construction
    • com_create_guid - Generate a globally unique identifier (GUID)
    • com_event_sink - Connect events from a COM object to a PHP object
    • com_get_active_object - Returns a handle to an already running instance of a COM object
    • com_load_typelib - 装载一个 Typelib
    • com_message_pump - Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo - Print out a PHP class definition for a dispatchable interface
    • Cond::broadcast - 广播条件变量
    • Cond::create - 创建一个条件变量
    • Cond::destroy - 销毁条件变量
    • Cond::signal - 发送唤醒信号
    • Cond::wait - 等待
    • connection_aborted - 检查客户端是否已经断开
    • connection_status - 返回连接的状态位
    • constant - 返回一个常量的值
    • Context 参数 - Context 参数列表
    • convert_cyr_string - 将字符由一种 Cyrillic 字符转换成另一种
    • convert_uudecode - 解码一个 uuencode 编码的字符串
    • convert_uuencode - 使用 uuencode 编码一个字符串
    • copy - 拷贝文件
    • cos - 余弦
    • cosh - 双曲余弦
    • count - 计算数组中的单元数目，或对象中的属性个数
    • Countable::count - 统计一个对象的元素个数
    • count_chars - 返回字符串所用字符的信息
    • crc32 - 计算一个字符串的 crc32 多项式
    • create_function - Create an anonymous (lambda-style) function
    • CrudOperationBindable::bind - Bind value to placeholder
    • CrudOperationLimitable::limit - Set result limit
    • CrudOperationSkippable::skip - Number of operations to skip
    • CrudOperationSortable::sort - Sort results
    • crypt - 单向字符串散列
    • ctype_alnum - 做字母和数字字符检测
    • ctype_alpha - 做纯字符检测
    • ctype_cntrl - 做控制字符检测
    • ctype_digit - 做纯数字检测
    • ctype_graph - 做可打印字符串检测，空格除外
    • ctype_lower - 做小写字符检测
    • ctype_print - 做可打印字符检测
    • ctype_punct - 检测可打印的字符是不是不包含空白、数字和字母
    • ctype_space - 做空白字符检测
    • ctype_upper - 做大写字母检测
    • ctype_xdigit - 检测字符串是否只包含十六进制字符
    • cubrid_affected_rows - Return the number of rows affected by the last SQL statement
    • cubrid_bind - Bind variables to a prepared statement as parameters
    • cubrid_client_encoding - Return the current CUBRID connection charset
    • cubrid_close - Close CUBRID connection
    • cubrid_close_prepare - Close the request handle
    • cubrid_close_request - Close the request handle
    • cubrid_column_names - Get the column names in result
    • cubrid_column_types - Get column types in result
    • cubrid_col_get - Get contents of collection type column using OID
    • cubrid_col_size - Get the number of elements in collection type column using OID
    • cubrid_commit - Commit a transaction
    • cubrid_connect - Open a connection to a CUBRID Server
    • cubrid_connect_with_url - Establish the environment for connecting to CUBRID server
    • cubrid_current_oid - Get OID of the current cursor location
    • cubrid_data_seek - Move the internal row pointer of the CUBRID result
    • cubrid_db_name - Get db name from results of cubrid_list_dbs
    • cubrid_disconnect - Close a database connection
    • cubrid_drop - Delete an instance using OID
    • cubrid_errno - Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error - Get the error message
    • cubrid_error_code - Get error code for the most recent function call
    • cubrid_error_code_facility - Get the facility code of error
    • cubrid_error_msg - Get last error message for the most recent function call
    • cubrid_execute - Execute a prepared SQL statement
    • cubrid_fetch - Fetch the next row from a result set
    • cubrid_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • cubrid_fetch_assoc - Return the associative array that corresponds to the fetched row
    • cubrid_fetch_field - Get column information from a result and return as an object
    • cubrid_fetch_lengths - Return an array with the lengths of the values of each field from the current row
    • cubrid_fetch_object - Fetch the next row and return it as an object
    • cubrid_fetch_row - Return a numerical array with the values of the current row
    • cubrid_field_flags - Return a string with the flags of the given field offset
    • cubrid_field_len - Get the maximum length of the specified field
    • cubrid_field_name - Return the name of the specified field index
    • cubrid_field_seek - Move the result set cursor to the specified field offset
    • cubrid_field_table - Return the name of the table of the specified field
    • cubrid_field_type - Return the type of the column corresponding to the given field offset
    • cubrid_free_result - Free the memory occupied by the result data
    • cubrid_get - Get a column using OID
    • cubrid_get_autocommit - Get auto-commit mode of the connection
    • cubrid_get_charset - Return the current CUBRID connection charset
    • cubrid_get_class_name - Get the class name using OID
    • cubrid_get_client_info - Return the client library version
    • cubrid_get_db_parameter - Returns the CUBRID database parameters
    • cubrid_get_query_timeout - Get the query timeout value of the request
    • cubrid_get_server_info - Return the CUBRID server version
    • cubrid_insert_id - Return the ID generated for the last updated AUTO_INCREMENT column
    • cubrid_is_instance - Check whether the instance pointed by OID exists
    • cubrid_list_dbs - Return an array with the list of all existing CUBRID databases
    • cubrid_load_from_glo - Read data from a GLO instance and save it in a file
    • cubrid_lob2_bind - Bind a lob object or a string as a lob object to a prepared statement as parameters
    • cubrid_lob2_close - Close LOB object
    • cubrid_lob2_export - Export the lob object to a file
    • cubrid_lob2_import - Import BLOB/CLOB data from a file
    • cubrid_lob2_new - Create a lob object
    • cubrid_lob2_read - Read from BLOB/CLOB data
    • cubrid_lob2_seek - Move the cursor of a lob object
    • cubrid_lob2_seek64 - Move the cursor of a lob object
    • cubrid_lob2_size - Get a lob object's size
    • cubrid_lob2_size64 - Get a lob object's size
    • cubrid_lob2_tell - Tell the cursor position of the LOB object
    • cubrid_lob2_tell64 - Tell the cursor position of the LOB object
    • cubrid_lob2_write - Write to a lob object
    • cubrid_lob_close - Close BLOB/CLOB data
    • cubrid_lob_export - Export BLOB/CLOB data to file
    • cubrid_lob_get - Get BLOB/CLOB data
    • cubrid_lob_send - Read BLOB/CLOB data and send straight to browser
    • cubrid_lob_size - Get BLOB/CLOB data size
    • cubrid_lock_read - Set a read lock on the given OID
    • cubrid_lock_write - Set a write lock on the given OID
    • cubrid_move_cursor - Move the cursor in the result
    • cubrid_new_glo - Create a glo instance
    • cubrid_next_result - Get result of next query when executing multiple SQL statements
    • cubrid_num_cols - Return the number of columns in the result set
    • cubrid_num_fields - Return the number of columns in the result set
    • cubrid_num_rows - Get the number of rows in the result set
    • cubrid_pconnect - Open a persistent connection to a CUBRID server
    • cubrid_pconnect_with_url - Open a persistent connection to CUBRID server
    • cubrid_ping - Ping a server connection or reconnect if there is no connection
    • cubrid_prepare - Prepare a SQL statement for execution
    • cubrid_put - Update a column using OID
    • cubrid_query - Send a CUBRID query
    • cubrid_real_escape_string - Escape special characters in a string for use in an SQL statement
    • cubrid_result - Return the value of a specific field in a specific row
    • cubrid_rollback - Roll back a transaction
    • cubrid_save_to_glo - Save requested file in a GLO instance
    • cubrid_schema - Get the requested schema information
    • cubrid_send_glo - Read data from glo and send it to std output
    • cubrid_seq_drop - Delete an element from sequence type column using OID
    • cubrid_seq_insert - Insert an element to a sequence type column using OID
    • cubrid_seq_put - Update the element value of sequence type column using OID
    • cubrid_set_add - Insert a single element to set type column using OID
    • cubrid_set_autocommit - Set autocommit mode of the connection
    • cubrid_set_db_parameter - Sets the CUBRID database parameters
    • cubrid_set_drop - Delete an element from set type column using OID
    • cubrid_set_query_timeout - Set the timeout time of query execution
    • cubrid_unbuffered_query - Perform a query without fetching the results into memory
    • cubrid_version - Get the CUBRID PHP module's version
    • CURL context options - CURL 上下文选项列表
    • CURLFile::getFilename - 获取被上传文件的 文件名
    • CURLFile::getMimeType - 获取被上传文件的 MIME 类型
    • CURLFile::getPostFilename - 获取 POST 请求时使用的 文件名
    • CURLFile::setMimeType - 设置被上传文件的 MIME 类型
    • CURLFile::setPostFilename - 设置 POST 请求时使用的文件名
    • CURLFile::__construct - 创建 CURLFile 对象
    • curl_close - 关闭 cURL 会话
    • curl_copy_handle - 复制一个cURL句柄和它的所有选项
    • curl_errno - 返回最后一次的错误代码
    • curl_error - 返回当前会话最后一次错误的字符串
    • curl_escape - 使用 URL 编码给定的字符串
    • curl_exec - 执行 cURL 会话
    • curl_getinfo - 获取一个cURL连接资源句柄的信息
    • curl_init - 初始化 cURL 会话
    • curl_multi_add_handle - 向curl批处理会话中添加单独的curl句柄
    • curl_multi_close - 关闭一组cURL句柄
    • curl_multi_errno - 返回上一次 curl 批处理的错误码
    • curl_multi_exec - 运行当前 cURL 句柄的子连接
    • curl_multi_getcontent - 如果设置了CURLOPT_RETURNTRANSFER，则返回获取的输出的文本流
    • curl_multi_info_read - 获取当前解析的cURL的相关传输信息
    • curl_multi_init - 返回一个新cURL批处理句柄
    • curl_multi_remove_handle - 移除cURL批处理句柄资源中的某个句柄资源
    • curl_multi_select - 等待所有cURL批处理中的活动连接
    • curl_multi_setopt - 为 cURL 并行处理设置一个选项
    • curl_multi_strerror - 返回字符串描述的错误代码
    • curl_pause - 暂停和取消暂停一个连接。
    • curl_reset - 重置一个 libcurl 会话句柄的所有的选项
    • curl_setopt - 设置 cURL 传输选项
    • curl_setopt_array - 为 cURL 传输会话批量设置选项
    • curl_share_close - 关闭 cURL 共享句柄
    • curl_share_errno - 返回共享 curl 句柄的最后一次错误号
    • curl_share_init - 初始化一个 cURL 共享句柄。
    • curl_share_setopt - 为 cURL 共享句柄设置选项。
    • curl_share_strerror - 返回错误号对应的错误消息
    • curl_strerror - 返回错误代码的字符串描述
    • curl_unescape - 解码给定的 URL 编码的字符串
    • curl_version - 获取 cURL 版本信息
    • current - 返回数组中的当前值
  • d
    • data:// - 数据（RFC 2397）
    • DatabaseObject::existsInDatabase - Check if object exists in database
    • DatabaseObject::getName - Get object name
    • DatabaseObject::getSession - Get session name
    • date - 格式化一个本地时间／日期
    • DateInterval::createFromDateString - Sets up a DateInterval from the relative parts of the string
    • DateInterval::format - Formats the interval
    • DateInterval::__construct - Creates a new DateInterval object
    • DatePeriod::getDateInterval - Gets the interval
    • DatePeriod::getEndDate - Gets the end date
    • DatePeriod::getRecurrences - Gets the number of recurrences
    • DatePeriod::getStartDate - Gets the start date
    • DatePeriod::__construct - Creates a new DatePeriod object
    • DateTime::add - 给一个 DateTime 对象增加一定量的天，月，年，小时，分钟 以及秒。
    • DateTime::createFromFormat - 根据给定的格式解析日期时间字符串
    • DateTime::createFromImmutable - Returns new DateTime object encapsulating the given DateTimeImmutable object
    • DateTime::createFromInterface - Returns new DateTime object encapsulating the given DateTimeInterface object
    • DateTime::diff - Returns the difference between two DateTime objects
    • DateTime::format - Returns date formatted according to given format
    • DateTime::getLastErrors - 获取警告和错误信息
    • DateTime::getOffset - Returns the timezone offset
    • DateTime::getTimestamp - Gets the Unix timestamp
    • DateTime::getTimezone - Return time zone relative to given DateTime
    • DateTime::modify - 修改日期时间对象的值
    • DateTime::setDate - 设置 DateTime 对象的日期
    • DateTime::setISODate - 设置 ISO 日期
    • DateTime::setTime - 设置 DateTime 对象的时间
    • DateTime::setTimestamp - 以 Unix 时间戳的方式设置 DateTime 对象
    • DateTime::setTimezone - 设置 DateTime 对象的时区
    • DateTime::sub - 对一个 DateTime 对象减去一定量的 日、月、年、小时、分钟和秒。
    • DateTime::__construct - 返回一个新的 DateTime 对象
    • DateTime::__set_state - __set_state 魔术方法处理函数
    • DateTime::__wakeup - The __wakeup handler
    • DateTimeImmutable::add - Adds an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::createFromFormat - Parses a time string according to a specified format
    • DateTimeImmutable::createFromInterface - Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
    • DateTimeImmutable::createFromMutable - Returns new DateTimeImmutable object encapsulating the given DateTime object
    • DateTimeImmutable::getLastErrors - Returns the warnings and errors
    • DateTimeImmutable::modify - Creates a new object with modified timestamp
    • DateTimeImmutable::setDate - Sets the date
    • DateTimeImmutable::setISODate - Sets the ISO date
    • DateTimeImmutable::setTime - Sets the time
    • DateTimeImmutable::setTimestamp - Sets the date and time based on a Unix timestamp
    • DateTimeImmutable::setTimezone - Sets the time zone
    • DateTimeImmutable::sub - Subtracts an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::__construct - Returns new DateTimeImmutable object
    • DateTimeImmutable::__set_state - The __set_state handler
    • DateTimeZone::getLocation - 返回与时区相关的定位信息。
    • DateTimeZone::getName - 返回时区名称。
    • DateTimeZone::getOffset - 返回相对于 GMT 的时差。
    • DateTimeZone::getTransitions - Returns all transitions for the timezone
    • DateTimeZone::listAbbreviations - 返回一个包含 dst (夏令时)，时差和时区信息的关联数组。
    • DateTimeZone::listIdentifiers - 返回一个包含了所有时区标示符的索引数组。
    • DateTimeZone::__construct - 创建新的DateTimeZone对象
    • date_add - 别名 DateTime::add
    • date_create - 别名 DateTime::__construct
    • date_create_from_format - 别名 DateTime::createFromFormat
    • date_create_immutable - 别名 DateTimeImmutable::__construct
    • date_create_immutable_from_format - 别名 DateTimeImmutable::createFromFormat
    • date_date_set - 别名 DateTime::setDate
    • date_default_timezone_get - 取得一个脚本中所有日期时间函数所使用的默认时区
    • date_default_timezone_set - 设定用于一个脚本中所有日期时间函数的默认时区
    • date_diff - 别名 DateTime::diff
    • date_format - 别名 DateTime::format
    • date_get_last_errors - 别名 DateTime::getLastErrors
    • date_interval_create_from_date_string - 别名 DateInterval::createFromDateString
    • date_interval_format - 别名 DateInterval::format
    • date_isodate_set - 别名 DateTime::setISODate
    • date_modify - 别名 DateTime::modify
    • date_offset_get - 别名 DateTime::getOffset
    • date_parse - 返回指定日期/时间的详细信息的关联数组
    • date_parse_from_format - Get info about given date formatted according to the specified format
    • date_sub - 别名 DateTime::sub
    • date_sunrise - 返回给定的日期与地点的日出时间
    • date_sunset - 返回给定的日期与地点的日落时间
    • date_sun_info - Returns an array with information about sunset/sunrise and twilight begin/end
    • date_timestamp_get - 别名 DateTime::getTimestamp
    • date_timestamp_set - 别名 DateTime::setTimestamp
    • date_timezone_get - 别名 DateTime::getTimezone
    • date_timezone_set - 别名 DateTime::setTimezone
    • date_time_set - 别名 DateTime::setTime
    • db2_autocommit - Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param - Binds a PHP variable to an SQL statement parameter
    • db2_client_info - Returns an object with properties that describe the DB2 database client
    • db2_close - Closes a database connection
    • db2_columns - Returns a result set listing the columns and associated metadata for a table
    • db2_column_privileges - Returns a result set listing the columns and associated privileges for a table
    • db2_commit - Commits a transaction
    • db2_connect - Returns a connection to a database
    • db2_conn_error - Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg - Returns the last connection error message and SQLCODE value
    • db2_cursor_type - Returns the cursor type used by a statement resource
    • db2_escape_string - Used to escape certain characters
    • db2_exec - Executes an SQL statement directly
    • db2_execute - Executes a prepared SQL statement
    • db2_fetch_array - Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc - Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both - Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object - Returns an object with properties representing columns in the fetched row
    • db2_fetch_row - Sets the result set pointer to the next row or requested row
    • db2_field_display_size - Returns the maximum number of bytes required to display a column
    • db2_field_name - Returns the name of the column in the result set
    • db2_field_num - Returns the position of the named column in a result set
    • db2_field_precision - Returns the precision of the indicated column in a result set
    • db2_field_scale - Returns the scale of the indicated column in a result set
    • db2_field_type - Returns the data type of the indicated column in a result set
    • db2_field_width - Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys - Returns a result set listing the foreign keys for a table
    • db2_free_result - Frees resources associated with a result set
    • db2_free_stmt - Frees resources associated with the indicated statement resource
    • db2_get_option - Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id - Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read - Gets a user defined size of LOB files with each invocation
    • db2_next_result - Requests the next result set from a stored procedure
    • db2_num_fields - Returns the number of fields contained in a result set
    • db2_num_rows - Returns the number of rows affected by an SQL statement
    • db2_pclose - Closes a persistent database connection
    • db2_pconnect - Returns a persistent connection to a database
    • db2_prepare - Prepares an SQL statement to be executed
    • db2_primary_keys - Returns a result set listing primary keys for a table
    • db2_procedures - Returns a result set listing the stored procedures registered in a database
    • db2_procedure_columns - Returns a result set listing stored procedure parameters
    • db2_result - Returns a single column from a row in the result set
    • db2_rollback - Rolls back a transaction
    • db2_server_info - Returns an object with properties that describe the DB2 database server
    • db2_set_option - Set options for connection or statement resources
    • db2_special_columns - Returns a result set listing the unique row identifier columns for a table
    • db2_statistics - Returns a result set listing the index and statistics for a table
    • db2_stmt_error - Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg - Returns a string containing the last SQL statement error message
    • db2_tables - Returns a result set listing the tables and associated metadata in a database
    • db2_table_privileges - Returns a result set listing the tables and associated privileges in a database
    • dbase_add_record - Adds a record to a database
    • dbase_close - Closes a database
    • dbase_create - Creates a database
    • dbase_delete_record - Deletes a record from a database
    • dbase_get_header_info - Gets the header info of a database
    • dbase_get_record - Gets a record from a database as an indexed array
    • dbase_get_record_with_names - Gets a record from a database as an associative array
    • dbase_numfields - Gets the number of fields of a database
    • dbase_numrecords - Gets the number of records in a database
    • dbase_open - Opens a database
    • dbase_pack - Packs a database
    • dbase_replace_record - Replaces a record in a database
    • dba_close - Close a DBA database
    • dba_delete - Delete DBA entry specified by key
    • dba_exists - Check whether key exists
    • dba_fetch - Fetch data specified by key
    • dba_firstkey - Fetch first key
    • dba_handlers - List all the handlers available
    • dba_insert - Insert entry
    • dba_key_split - Splits a key in string representation into array representation
    • dba_list - List all open database files
    • dba_nextkey - Fetch next key
    • dba_open - Open database
    • dba_optimize - Optimize database
    • dba_popen - Open database persistently
    • dba_replace - Replace or insert entry
    • dba_sync - Synchronize database
    • dbplus_add - Add a tuple to a relation
    • dbplus_aql - Perform AQL query
    • dbplus_chdir - Get/Set database virtual current directory
    • dbplus_close - Close a relation
    • dbplus_curr - Get current tuple from relation
    • dbplus_errcode - Get error string for given errorcode or last error
    • dbplus_errno - Get error code for last operation
    • dbplus_find - Set a constraint on a relation
    • dbplus_first - Get first tuple from relation
    • dbplus_flush - Flush all changes made on a relation
    • dbplus_freealllocks - Free all locks held by this client
    • dbplus_freelock - Release write lock on tuple
    • dbplus_freerlocks - Free all tuple locks on given relation
    • dbplus_getlock - Get a write lock on a tuple
    • dbplus_getunique - Get an id number unique to a relation
    • dbplus_info - Get information about a relation
    • dbplus_last - Get last tuple from relation
    • dbplus_lockrel - Request write lock on relation
    • dbplus_next - Get next tuple from relation
    • dbplus_open - Open relation file
    • dbplus_prev - Get previous tuple from relation
    • dbplus_rchperm - Change relation permissions
    • dbplus_rcreate - Creates a new DB++ relation
    • dbplus_rcrtexact - Creates an exact but empty copy of a relation including indices
    • dbplus_rcrtlike - Creates an empty copy of a relation with default indices
    • dbplus_resolve - Resolve host information for relation
    • dbplus_restorepos - Restore position
    • dbplus_rkeys - Specify new primary key for a relation
    • dbplus_ropen - Open relation file local
    • dbplus_rquery - Perform local (raw) AQL query
    • dbplus_rrename - Rename a relation
    • dbplus_rsecindex - Create a new secondary index for a relation
    • dbplus_runlink - Remove relation from filesystem
    • dbplus_rzap - Remove all tuples from relation
    • dbplus_savepos - Save position
    • dbplus_setindex - Set index
    • dbplus_setindexbynumber - Set index by number
    • dbplus_sql - Perform SQL query
    • dbplus_tcl - Execute TCL code on server side
    • dbplus_tremove - Remove tuple and return new current tuple
    • dbplus_undo - Undo
    • dbplus_undoprepare - Prepare undo
    • dbplus_unlockrel - Give up write lock on relation
    • dbplus_unselect - Remove a constraint from relation
    • dbplus_update - Update specified tuple in relation
    • dbplus_xlockrel - Request exclusive lock on relation
    • dbplus_xunlockrel - Free exclusive lock on relation
    • dcgettext - Overrides the domain for a single lookup
    • dcngettext - Plural version of dcgettext
    • debug_backtrace - 产生一条回溯跟踪(backtrace)
    • debug_print_backtrace - 打印一条回溯。
    • debug_zval_dump - Dumps a string representation of an internal zend value to output
    • decbin - 十进制转换为二进制
    • dechex - 十进制转换为十六进制
    • decoct - 十进制转换为八进制
    • define - 定义一个常量
    • defined - 检查某个名称的常量是否存在
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - 将角度转换为弧度
    • delete - 参见 unlink 或 unset
    • dgettext - Override the current domain
    • die - 等同于 exit
    • dio_close - Closes the file descriptor given by fd
    • dio_fcntl - Performs a c library fcntl on fd
    • dio_open - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow
    • dio_read - Reads bytes from a file descriptor
    • dio_seek - Seeks to pos on fd from whence
    • dio_stat - Gets stat information about the file descriptor fd
    • dio_tcsetattr - Sets terminal attributes and baud rate for a serial port
    • dio_truncate - Truncates file descriptor fd to offset bytes
    • dio_write - Writes data to fd with optional truncation at length
    • dir - 返回一个 Directory 类实例
    • Directory::close - 释放目录句柄
    • Directory::read - 从目录句柄中读取条目
    • Directory::rewind - 倒回目录句柄
    • DirectoryIterator::current - Return the current DirectoryIterator item
    • DirectoryIterator::getATime - Get last access time of the current DirectoryIterator item
    • DirectoryIterator::getBasename - Get base name of current DirectoryIterator item
    • DirectoryIterator::getCTime - Get inode change time of the current DirectoryIterator item
    • DirectoryIterator::getExtension - Gets the file extension
    • DirectoryIterator::getFilename - Return file name of current DirectoryIterator item
    • DirectoryIterator::getGroup - Get group for the current DirectoryIterator item
    • DirectoryIterator::getInode - Get inode for the current DirectoryIterator item
    • DirectoryIterator::getMTime - Get last modification time of current DirectoryIterator item
    • DirectoryIterator::getOwner - Get owner of current DirectoryIterator item
    • DirectoryIterator::getPath - Get path of current Iterator item without filename
    • DirectoryIterator::getPathname - Return path and file name of current DirectoryIterator item
    • DirectoryIterator::getPerms - Get the permissions of current DirectoryIterator item
    • DirectoryIterator::getSize - Get size of current DirectoryIterator item
    • DirectoryIterator::getType - Determine the type of the current DirectoryIterator item
    • DirectoryIterator::isDir - Determine if current DirectoryIterator item is a directory
    • DirectoryIterator::isDot - Determine if current DirectoryIterator item is '.' or '..'
    • DirectoryIterator::isExecutable - Determine if current DirectoryIterator item is executable
    • DirectoryIterator::isFile - Determine if current DirectoryIterator item is a regular file
    • DirectoryIterator::isLink - Determine if current DirectoryIterator item is a symbolic link
    • DirectoryIterator::isReadable - Determine if current DirectoryIterator item can be read
    • DirectoryIterator::isWritable - Determine if current DirectoryIterator item can be written to
    • DirectoryIterator::key - Return the key for the current DirectoryIterator item
    • DirectoryIterator::next - Move forward to next DirectoryIterator item
    • DirectoryIterator::rewind - Rewind the DirectoryIterator back to the start
    • DirectoryIterator::seek - Seek to a DirectoryIterator item
    • DirectoryIterator::valid - Check whether current DirectoryIterator position is a valid file
    • DirectoryIterator::__construct - Constructs a new directory iterator from a path
    • DirectoryIterator::__toString - Get file name as a string
    • dirname - 返回路径中的目录部分
    • diskfreespace - disk_free_space 的别名
    • disk_free_space - 返回目录中的可用空间
    • disk_total_space - 返回一个目录的磁盘总大小
    • dl - 运行时载入一个 PHP 扩展
    • dngettext - Plural version of dgettext
    • dns_check_record - 别名 checkdnsrr
    • dns_get_mx - 别名 getmxrr
    • dns_get_record - 获取指定主机的DNS记录
    • DocResult::fetchAll - Get all rows
    • DocResult::fetchOne - Get one row
    • DocResult::getWarnings - Get warnings from last operation
    • DocResult::getWarningsCount - Get warning count from last operation
    • DocResult::__construct - DocResult constructor
    • DOMAttr::isId - Checks if attribute is a defined ID
    • DOMAttr::__construct - Creates a new DOMAttr object
    • DOMCdataSection::__construct - Constructs a new DOMCdataSection object
    • DOMCharacterData::appendData - Append the string to the end of the character data of the node
    • DOMCharacterData::deleteData - Remove a range of characters from the node
    • DOMCharacterData::insertData - Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::replaceData - Replace a substring within the DOMCharacterData node
    • DOMCharacterData::substringData - Extracts a range of data from the node
    • DOMComment::__construct - Creates a new DOMComment object
    • DOMDocument::createAttribute - Create new attribute
    • DOMDocument::createAttributeNS - Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection - Create new cdata node
    • DOMDocument::createComment - Create new comment node
    • DOMDocument::createDocumentFragment - Create new document fragment
    • DOMDocument::createElement - Create new element node
    • DOMDocument::createElementNS - Create new element node with an associated namespace
    • DOMDocument::createEntityReference - Create new entity reference node
    • DOMDocument::createProcessingInstruction - Creates new PI node
    • DOMDocument::createTextNode - Create new text node
    • DOMDocument::getElementById - Searches for an element with a certain id
    • DOMDocument::getElementsByTagName - Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS - Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode - Import node into current document
    • DOMDocument::load - Load XML from a file
    • DOMDocument::loadHTML - Load HTML from a string
    • DOMDocument::loadHTMLFile - Load HTML from a file
    • DOMDocument::loadXML - Load XML from a string
    • DOMDocument::normalizeDocument - Normalizes the document
    • DOMDocument::registerNodeClass - Register extended class used to create base node type
    • DOMDocument::relaxNGValidate - Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource - Performs relaxNG validation on the document
    • DOMDocument::save - Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML - Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile - Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML - Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate - Validates a document based on a schema. Only XML Schema 1.0 is supported.
    • DOMDocument::schemaValidateSource - Validates a document based on a schema
    • DOMDocument::validate - Validates the document based on its DTD
    • DOMDocument::xinclude - Substitutes XIncludes in a DOMDocument Object
    • DOMDocument::__construct - Creates a new DOMDocument object
    • DOMDocumentFragment::appendXML - Append raw XML data
    • DOMElement::getAttribute - Returns value of attribute
    • DOMElement::getAttributeNode - Returns attribute node
    • DOMElement::getAttributeNodeNS - Returns attribute node
    • DOMElement::getAttributeNS - Returns value of attribute
    • DOMElement::getElementsByTagName - Gets elements by tagname
    • DOMElement::getElementsByTagNameNS - Get elements by namespaceURI and localName
    • DOMElement::hasAttribute - Checks to see if attribute exists
    • DOMElement::hasAttributeNS - Checks to see if attribute exists
    • DOMElement::removeAttribute - Removes attribute
    • DOMElement::removeAttributeNode - Removes attribute
    • DOMElement::removeAttributeNS - Removes attribute
    • DOMElement::setAttribute - Adds new attribute
    • DOMElement::setAttributeNode - Adds new attribute node to element
    • DOMElement::setAttributeNodeNS - Adds new attribute node to element
    • DOMElement::setAttributeNS - Adds new attribute
    • DOMElement::setIdAttribute - Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode - Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS - Declares the attribute specified by local name and namespace URI to be of type ID
    • DOMElement::__construct - Creates a new DOMElement object
    • DOMEntityReference::__construct - Creates a new DOMEntityReference object
    • DOMImplementation::createDocument - Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType - Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature - Test if the DOM implementation implements a specific feature
    • DOMImplementation::__construct - Creates a new DOMImplementation object
    • DOMNamedNodeMap::count - Get number of nodes in the map
    • DOMNamedNodeMap::getNamedItem - Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS - Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item - Retrieves a node specified by index
    • DOMNode::appendChild - Adds new child at the end of the children
    • DOMNode::C14N - Canonicalize nodes to a string
    • DOMNode::C14NFile - Canonicalize nodes to a file
    • DOMNode::cloneNode - Clones a node
    • DOMNode::getLineNo - Get line number for a node
    • DOMNode::getNodePath - Get an XPath for a node
    • DOMNode::hasAttributes - Checks if node has attributes
    • DOMNode::hasChildNodes - Checks if node has children
    • DOMNode::insertBefore - Adds a new child before a reference node
    • DOMNode::isDefaultNamespace - Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isSameNode - Indicates if two nodes are the same node
    • DOMNode::isSupported - Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceUri - Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix - Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize - Normalizes the node
    • DOMNode::removeChild - Removes child from list of children
    • DOMNode::replaceChild - Replaces a child
    • DOMNodeList::count - Get number of nodes in the list
    • DOMNodeList::item - Retrieves a node specified by index
    • DOMProcessingInstruction::__construct - Creates a new DOMProcessingInstruction object
    • DOMText::isElementContentWhitespace - Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent - Indicates whether this text node contains whitespace
    • DOMText::splitText - Breaks this node into two nodes at the specified offset
    • DOMText::__construct - Creates a new DOMText object
    • DOMXPath::evaluate - Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query - Evaluates the given XPath expression
    • DOMXPath::registerNamespace - Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions - Register PHP functions as XPath functions
    • DOMXPath::__construct - Creates a new DOMXPath object
    • dom_import_simplexml - Gets a DOMElement object from a SimpleXMLElement object
    • dotnet::__construct - dotnet class constructor
    • doubleval - floatval 的别名
    • Ds\Collection::clear - Removes all values
    • Ds\Collection::copy - Returns a shallow copy of the collection
    • Ds\Collection::isEmpty - Returns whether the collection is empty
    • Ds\Collection::toArray - Converts the collection to an array
    • Ds\Deque::allocate - Allocates enough memory for a required capacity
    • Ds\Deque::apply - Updates all values by applying a callback function to each value
    • Ds\Deque::capacity - Returns the current capacity
    • Ds\Deque::clear - Removes all values from the deque
    • Ds\Deque::contains - Determines if the deque contains given values
    • Ds\Deque::copy - Returns a shallow copy of the deque
    • Ds\Deque::count - Returns the number of values in the collection
    • Ds\Deque::filter - Creates a new deque using a callable to determine which values to include
    • Ds\Deque::find - Attempts to find a value's index
    • Ds\Deque::first - Returns the first value in the deque
    • Ds\Deque::get - Returns the value at a given index
    • Ds\Deque::insert - Inserts values at a given index
    • Ds\Deque::isEmpty - Returns whether the deque is empty
    • Ds\Deque::join - Joins all values together as a string
    • Ds\Deque::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Deque::last - Returns the last value
    • Ds\Deque::map - Returns the result of applying a callback to each value
    • Ds\Deque::merge - Returns the result of adding all given values to the deque
    • Ds\Deque::pop - Removes and returns the last value
    • Ds\Deque::push - Adds values to the end of the deque
    • Ds\Deque::reduce - Reduces the deque to a single value using a callback function
    • Ds\Deque::remove - Removes and returns a value by index
    • Ds\Deque::reverse - Reverses the deque in-place
    • Ds\Deque::reversed - Returns a reversed copy
    • Ds\Deque::rotate - Rotates the deque by a given number of rotations
    • Ds\Deque::set - Updates a value at a given index
    • Ds\Deque::shift - Removes and returns the first value
    • Ds\Deque::slice - Returns a sub-deque of a given range
    • Ds\Deque::sort - Sorts the deque in-place
    • Ds\Deque::sorted - Returns a sorted copy
    • Ds\Deque::sum - Returns the sum of all values in the deque
    • Ds\Deque::toArray - Converts the deque to an array
    • Ds\Deque::unshift - Adds values to the front of the deque
    • Ds\Deque::__construct - Creates a new instance
    • Ds\Hashable::equals - Determines whether an object is equal to the current instance
    • Ds\Hashable::hash - Returns a scalar value to be used as a hash value
    • Ds\Map::allocate - Allocates enough memory for a required capacity
    • Ds\Map::apply - Updates all values by applying a callback function to each value
    • Ds\Map::capacity - Returns the current capacity
    • Ds\Map::clear - Removes all values
    • Ds\Map::copy - Returns a shallow copy of the map
    • Ds\Map::count - Returns the number of values in the map
    • Ds\Map::diff - Creates a new map using keys that aren't in another map
    • Ds\Map::filter - Creates a new map using a callable to determine which pairs to include
    • Ds\Map::first - Returns the first pair in the map
    • Ds\Map::get - Returns the value for a given key
    • Ds\Map::hasKey - Determines whether the map contains a given key
    • Ds\Map::hasValue - Determines whether the map contains a given value
    • Ds\Map::intersect - Creates a new map by intersecting keys with another map
    • Ds\Map::isEmpty - Returns whether the map is empty
    • Ds\Map::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Map::keys - Returns a set of the map's keys
    • Ds\Map::ksort - Sorts the map in-place by key
    • Ds\Map::ksorted - Returns a copy, sorted by key
    • Ds\Map::last - Returns the last pair of the map
    • Ds\Map::map - Returns the result of applying a callback to each value
    • Ds\Map::merge - Returns the result of adding all given associations
    • Ds\Map::pairs - Returns a sequence containing all the pairs of the map
    • Ds\Map::put - Associates a key with a value
    • Ds\Map::putAll - Associates all key-value pairs of a traversable object or array
    • Ds\Map::reduce - Reduces the map to a single value using a callback function
    • Ds\Map::remove - Removes and returns a value by key
    • Ds\Map::reverse - Reverses the map in-place
    • Ds\Map::reversed - Returns a reversed copy
    • Ds\Map::skip - Returns the pair at a given positional index
    • Ds\Map::slice - Returns a subset of the map defined by a starting index and length
    • Ds\Map::sort - Sorts the map in-place by value
    • Ds\Map::sorted - Returns a copy, sorted by value
    • Ds\Map::sum - Returns the sum of all values in the map
    • Ds\Map::toArray - Converts the map to an array
    • Ds\Map::union - Creates a new map using values from the current instance and another map
    • Ds\Map::values - Returns a sequence of the map's values
    • Ds\Map::xor - Creates a new map using keys of either the current instance or of another map, but not of both
    • Ds\Map::__construct - Creates a new instance
    • Ds\Pair::clear - Removes all values
    • Ds\Pair::copy - Returns a shallow copy of the pair
    • Ds\Pair::isEmpty - Returns whether the pair is empty
    • Ds\Pair::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Pair::toArray - Converts the pair to an array
    • Ds\Pair::__construct - Creates a new instance
    • Ds\PriorityQueue::allocate - Allocates enough memory for a required capacity
    • Ds\PriorityQueue::capacity - Returns the current capacity
    • Ds\PriorityQueue::clear - Removes all values
    • Ds\PriorityQueue::copy - Returns a shallow copy of the queue
    • Ds\PriorityQueue::count - Returns the number of values in the queue
    • Ds\PriorityQueue::isEmpty - Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\PriorityQueue::peek - Returns the value at the front of the queue
    • Ds\PriorityQueue::pop - Removes and returns the value with the highest priority
    • Ds\PriorityQueue::push - Pushes values into the queue
    • Ds\PriorityQueue::toArray - Converts the queue to an array
    • Ds\PriorityQueue::__construct - Creates a new instance
    • Ds\Queue::allocate - Allocates enough memory for a required capacity
    • Ds\Queue::capacity - Returns the current capacity
    • Ds\Queue::clear - Removes all values
    • Ds\Queue::copy - Returns a shallow copy of the queue
    • Ds\Queue::count - Returns the number of values in the queue
    • Ds\Queue::isEmpty - Returns whether the queue is empty
    • Ds\Queue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Queue::peek - Returns the value at the front of the queue
    • Ds\Queue::pop - Removes and returns the value at the front of the queue
    • Ds\Queue::push - Pushes values into the queue
    • Ds\Queue::toArray - Converts the queue to an array
    • Ds\Queue::__construct - Creates a new instance
    • Ds\Sequence::allocate - Allocates enough memory for a required capacity
    • Ds\Sequence::apply - Updates all values by applying a callback function to each value
    • Ds\Sequence::capacity - Returns the current capacity
    • Ds\Sequence::contains - Determines if the sequence contains given values
    • Ds\Sequence::filter - Creates a new sequence using a callable to determine which values to include
    • Ds\Sequence::find - Attempts to find a value's index
    • Ds\Sequence::first - Returns the first value in the sequence
    • Ds\Sequence::get - Returns the value at a given index
    • Ds\Sequence::insert - Inserts values at a given index
    • Ds\Sequence::join - Joins all values together as a string
    • Ds\Sequence::last - Returns the last value
    • Ds\Sequence::map - Returns the result of applying a callback to each value
    • Ds\Sequence::merge - Returns the result of adding all given values to the sequence
    • Ds\Sequence::pop - Removes and returns the last value
    • Ds\Sequence::push - Adds values to the end of the sequence
    • Ds\Sequence::reduce - Reduces the sequence to a single value using a callback function
    • Ds\Sequence::remove - Removes and returns a value by index
    • Ds\Sequence::reverse - Reverses the sequence in-place
    • Ds\Sequence::reversed - Returns a reversed copy
    • Ds\Sequence::rotate - Rotates the sequence by a given number of rotations
    • Ds\Sequence::set - Updates a value at a given index
    • Ds\Sequence::shift - Removes and returns the first value
    • Ds\Sequence::slice - Returns a sub-sequence of a given range
    • Ds\Sequence::sort - Sorts the sequence in-place
    • Ds\Sequence::sorted - Returns a sorted copy
    • Ds\Sequence::sum - Returns the sum of all values in the sequence
    • Ds\Sequence::unshift - Adds values to the front of the sequence
    • Ds\Set::add - Adds values to the set
    • Ds\Set::allocate - Allocates enough memory for a required capacity
    • Ds\Set::capacity - Returns the current capacity
    • Ds\Set::clear - Removes all values
    • Ds\Set::contains - Determines if the set contains all values
    • Ds\Set::copy - Returns a shallow copy of the set
    • Ds\Set::count - Returns the number of values in the set
    • Ds\Set::diff - Creates a new set using values that aren't in another set
    • Ds\Set::filter - Creates a new set using a callable to determine which values to include
    • Ds\Set::first - Returns the first value in the set
    • Ds\Set::get - Returns the value at a given index
    • Ds\Set::intersect - Creates a new set by intersecting values with another set
    • Ds\Set::isEmpty - Returns whether the set is empty
    • Ds\Set::join - Joins all values together as a string
    • Ds\Set::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Set::last - Returns the last value in the set
    • Ds\Set::merge - Returns the result of adding all given values to the set
    • Ds\Set::reduce - Reduces the set to a single value using a callback function
    • Ds\Set::remove - Removes all given values from the set
    • Ds\Set::reverse - Reverses the set in-place
    • Ds\Set::reversed - Returns a reversed copy
    • Ds\Set::slice - Returns a sub-set of a given range
    • Ds\Set::sort - Sorts the set in-place
    • Ds\Set::sorted - Returns a sorted copy
    • Ds\Set::sum - Returns the sum of all values in the set
    • Ds\Set::toArray - Converts the set to an array
    • Ds\Set::union - Creates a new set using values from the current instance and another set
    • Ds\Set::xor - Creates a new set using values in either the current instance or in another set, but not in both
    • Ds\Set::__construct - Creates a new instance
    • Ds\Stack::allocate - Allocates enough memory for a required capacity
    • Ds\Stack::capacity - Returns the current capacity
    • Ds\Stack::clear - Removes all values
    • Ds\Stack::copy - Returns a shallow copy of the stack
    • Ds\Stack::count - Returns the number of values in the stack
    • Ds\Stack::isEmpty - Returns whether the stack is empty
    • Ds\Stack::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Stack::peek - Returns the value at the top of the stack
    • Ds\Stack::pop - Removes and returns the value at the top of the stack
    • Ds\Stack::push - Pushes values onto the stack
    • Ds\Stack::toArray - Converts the stack to an array
    • Ds\Stack::__construct - Creates a new instance
    • Ds\Vector::allocate - Allocates enough memory for a required capacity
    • Ds\Vector::apply - Updates all values by applying a callback function to each value
    • Ds\Vector::capacity - Returns the current capacity
    • Ds\Vector::clear - Removes all values
    • Ds\Vector::contains - Determines if the vector contains given values
    • Ds\Vector::copy - Returns a shallow copy of the vector
    • Ds\Vector::count - Returns the number of values in the collection
    • Ds\Vector::filter - Creates a new vector using a callable to determine which values to include
    • Ds\Vector::find - Attempts to find a value's index
    • Ds\Vector::first - Returns the first value in the vector
    • Ds\Vector::get - Returns the value at a given index
    • Ds\Vector::insert - Inserts values at a given index
    • Ds\Vector::isEmpty - Returns whether the vector is empty
    • Ds\Vector::join - Joins all values together as a string
    • Ds\Vector::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Vector::last - Returns the last value
    • Ds\Vector::map - Returns the result of applying a callback to each value
    • Ds\Vector::merge - Returns the result of adding all given values to the vector
    • Ds\Vector::pop - Removes and returns the last value
    • Ds\Vector::push - Adds values to the end of the vector
    • Ds\Vector::reduce - Reduces the vector to a single value using a callback function
    • Ds\Vector::remove - Removes and returns a value by index
    • Ds\Vector::reverse - Reverses the vector in-place
    • Ds\Vector::reversed - Returns a reversed copy
    • Ds\Vector::rotate - Rotates the vector by a given number of rotations
    • Ds\Vector::set - Updates a value at a given index
    • Ds\Vector::shift - Removes and returns the first value
    • Ds\Vector::slice - Returns a sub-vector of a given range
    • Ds\Vector::sort - Sorts the vector in-place
    • Ds\Vector::sorted - Returns a sorted copy
    • Ds\Vector::sum - Returns the sum of all values in the vector
    • Ds\Vector::toArray - Converts the vector to an array
    • Ds\Vector::unshift - Adds values to the front of the vector
    • Ds\Vector::__construct - Creates a new instance
  • e
    • each - 返回数组中当前的键／值对并将数组指针向前移动一步
    • easter_date - 得到指定年份的复活节午夜时的Unix时间戳。
    • easter_days - 得到指定年份的3月21日到复活节之间的天数
    • echo - 输出一个或多个字符串
    • eio_busy - Artificially increase load. Could be useful in tests, benchmarking
    • eio_cancel - Cancels a request
    • eio_chmod - Change file/directory permissions
    • eio_chown - Change file/directory permissions
    • eio_close - Close file
    • eio_custom - Execute custom request like any other eio_* call
    • eio_dup2 - Duplicate a file descriptor
    • eio_event_loop - Polls libeio until all requests proceeded
    • eio_fallocate - Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod - Change file permissions
    • eio_fchown - Change file ownership
    • eio_fdatasync - Synchronize a file's in-core state with storage device
    • eio_fstat - Get file status
    • eio_fstatvfs - Get file system statistics
    • eio_fsync - Synchronize a file's in-core state with storage device
    • eio_ftruncate - Truncate a file
    • eio_futime - Change file last access and modification times
    • eio_get_event_stream - Get stream representing a variable used in internal communications with libeio
    • eio_get_last_error - Returns string describing the last error associated with a request resource
    • eio_grp - Creates a request group
    • eio_grp_add - Adds a request to the request group
    • eio_grp_cancel - Cancels a request group
    • eio_grp_limit - Set group limit
    • eio_init - (Re-)initialize Eio
    • eio_link - Create a hardlink for file
    • eio_lstat - Get file status
    • eio_mkdir - Create directory
    • eio_mknod - Create a special or ordinary file
    • eio_nop - Does nothing, except go through the whole request cycle
    • eio_npending - Returns number of finished, but unhandled requests
    • eio_nready - Returns number of not-yet handled requests
    • eio_nreqs - Returns number of requests to be processed
    • eio_nthreads - Returns number of threads currently in use
    • eio_open - Opens a file
    • eio_poll - Can be to be called whenever there are pending requests that need finishing
    • eio_read - Read from a file descriptor at given offset
    • eio_readahead - Perform file readahead into page cache
    • eio_readdir - Reads through a whole directory
    • eio_readlink - Read value of a symbolic link
    • eio_realpath - Get the canonicalized absolute pathname
    • eio_rename - Change the name or location of a file
    • eio_rmdir - Remove a directory
    • eio_seek - Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • eio_sendfile - Transfer data between file descriptors
    • eio_set_max_idle - Set maximum number of idle threads
    • eio_set_max_parallel - Set maximum parallel threads
    • eio_set_max_poll_reqs - Set maximum number of requests processed in a poll
    • eio_set_max_poll_time - Set maximum poll time
    • eio_set_min_parallel - Set minimum parallel thread number
    • eio_stat - Get file status
    • eio_statvfs - Get file system statistics
    • eio_symlink - Create a symbolic link
    • eio_sync - Commit buffer cache to disk
    • eio_syncfs - Calls Linux' syncfs syscall, if available
    • eio_sync_file_range - Sync a file segment with disk
    • eio_truncate - Truncate a file
    • eio_unlink - Delete a name and possibly the file it refers to
    • eio_utime - Change file last access and modification times
    • eio_write - Write to file
    • empty - 检查一个变量是否为空
    • EmptyIterator::current - The current() method
    • EmptyIterator::key - The key() method
    • EmptyIterator::next - The next() method
    • EmptyIterator::rewind - The rewind() method
    • EmptyIterator::valid - The valid() method
    • enchant_broker_describe - Enumerates the Enchant providers
    • enchant_broker_dict_exists - Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free - Free the broker resource and its dictionaries
    • enchant_broker_free_dict - Free a dictionary resource
    • enchant_broker_get_dict_path - Get the directory path for a given backend
    • enchant_broker_get_error - Returns the last error of the broker
    • enchant_broker_init - Create a new broker object capable of requesting
    • enchant_broker_list_dicts - Returns a list of available dictionaries
    • enchant_broker_request_dict - Create a new dictionary using a tag
    • enchant_broker_request_pwl_dict - Creates a dictionary using a PWL file
    • enchant_broker_set_dict_path - Set the directory path for a given backend
    • enchant_broker_set_ordering - Declares a preference of dictionaries to use for the language
    • enchant_dict_add - Add a word to personal word list
    • enchant_dict_add_to_personal - 别名 enchant_dict_add
    • enchant_dict_add_to_session - Add 'word' to this spell-checking session
    • enchant_dict_check - Check whether a word is correctly spelled or not
    • enchant_dict_describe - Describes an individual dictionary
    • enchant_dict_get_error - Returns the last error of the current spelling-session
    • enchant_dict_is_added - Whether or not 'word' exists in this spelling-session
    • enchant_dict_is_in_session - 别名 enchant_dict_is_added
    • enchant_dict_quick_check - Check the word is correctly spelled and provide suggestions
    • enchant_dict_store_replacement - Add a correction for a word
    • enchant_dict_suggest - Will return a list of values if any of those pre-conditions are not met
    • end - 将数组的内部指针指向最后一个单元
    • ereg - 正则表达式匹配
    • eregi - 不区分大小写的正则表达式匹配
    • eregi_replace - 不区分大小写的正则表达式替换
    • ereg_replace - 正则表达式替换
    • Error::getCode - 获取错误代码
    • Error::getFile - 获取错误发生时的文件
    • Error::getLine - 获取错误发生时的行号
    • Error::getMessage - 获取错误信息
    • Error::getPrevious - 返回先前的 Throwable
    • Error::getTrace - 获取调用栈（stack trace）
    • Error::getTraceAsString - 获取字符串形式的调用栈（stack trace）
    • Error::__clone - 克隆 error
    • Error::__construct - 初始化 error 对象
    • Error::__toString - error 的字符串表达
    • ErrorException::getSeverity - 获取异常的严重程度
    • ErrorException::__construct - 构造一个异常（Exception）
    • error_clear_last - 清除最近一次错误
    • error_get_last - 获取最后发生的错误
    • error_log - 发送错误信息到某个地方
    • error_reporting - 设置应该报告何种 PHP 错误
    • escapeshellarg - 把字符串转码为可以在 shell 命令里使用的参数
    • escapeshellcmd - shell 元字符转义
    • Ev::backend - Returns an integer describing the backend used by libev
    • Ev::depth - Returns recursion depth
    • Ev::embeddableBackends - Returns the set of backends that are embeddable in other event loops
    • Ev::feedSignal - Feed a signal event info Ev
    • Ev::feedSignalEvent - Feed signal event into the default loop
    • Ev::iteration - Return the number of times the default event loop has polled for new events
    • Ev::now - Returns the time when the last iteration of the default event loop has started
    • Ev::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress
    • Ev::recommendedBackends - Returns a bit mask of recommended backends for current platform
    • Ev::resume - Resume previously suspended default event loop
    • Ev::run - Begin checking for events and calling callbacks for the default loop
    • Ev::sleep - Block the process for the given number of seconds
    • Ev::stop - Stops the default event loop
    • Ev::supportedBackends - Returns the set of backends supported by current libev configuration
    • Ev::suspend - Suspend the default event loop
    • Ev::time - Returns the current time in fractional seconds since the epoch
    • Ev::verify - Performs internal consistency checks(for debugging)
    • eval - 把字符串作为PHP代码执行
    • EvCheck::createStopped - Create instance of a stopped EvCheck watcher
    • EvCheck::__construct - Constructs the EvCheck watcher object
    • EvChild::createStopped - Create instance of a stopped EvCheck watcher
    • EvChild::set - Configures the watcher
    • EvChild::__construct - Constructs the EvChild watcher object
    • EvEmbed::createStopped - Create stopped EvEmbed watcher object
    • EvEmbed::set - Configures the watcher
    • EvEmbed::sweep - Make a single, non-blocking sweep over the embedded loop
    • EvEmbed::__construct - Constructs the EvEmbed object
    • Event::add - Makes event pending
    • Event::addSignal - Makes signal event pending
    • Event::addTimer - Makes timer event pending
    • Event::del - Makes event non-pending
    • Event::delSignal - Makes signal event non-pending
    • Event::delTimer - Makes timer event non-pending
    • Event::free - Make event non-pending and free resources allocated for this event
    • Event::getSupportedMethods - Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending - Detects whether event is pending or scheduled
    • Event::set - Re-configures event
    • Event::setPriority - Set event priority
    • Event::setTimer - Re-configures timer event
    • Event::signal - Constructs signal event object
    • Event::timer - Constructs timer event object
    • Event::__construct - Constructs Event object
    • EventBase::dispatch - Dispatch pending events
    • EventBase::exit - Stop dispatching events
    • EventBase::free - Free resources allocated for this event base
    • EventBase::getFeatures - Returns bitmask of features supported
    • EventBase::getMethod - Returns event method in use
    • EventBase::getTimeOfDayCached - Returns the current event base time
    • EventBase::gotExit - Checks if the event loop was told to exit
    • EventBase::gotStop - Checks if the event loop was told to exit
    • EventBase::loop - Dispatch pending events
    • EventBase::priorityInit - Sets number of priorities per event base
    • EventBase::reInit - Re-initialize event base(after a fork)
    • EventBase::stop - Tells event_base to stop dispatching events
    • EventBase::__construct - Constructs EventBase object
    • EventBuffer::add - Append data to the end of an event buffer
    • EventBuffer::addBuffer - Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom - Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::copyout - Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain - Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking - 说明
    • EventBuffer::expand - Reserves space in buffer
    • EventBuffer::freeze - Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock - Acquires a lock on buffer
    • EventBuffer::prepend - Prepend data to the front of the buffer
    • EventBuffer::prependBuffer - Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup - Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read - Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom - Read data from a file onto the end of the buffer
    • EventBuffer::readLine - Extracts a line from the front of the buffer
    • EventBuffer::search - Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol - Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr - Substracts a portion of the buffer data
    • EventBuffer::unfreeze - Re-enable calls that modify an event buffer
    • EventBuffer::unlock - Releases lock acquired by EventBuffer::lock
    • EventBuffer::write - Write contents of the buffer to a file or socket
    • EventBuffer::__construct - Constructs EventBuffer object
    • EventBufferEvent::close - Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect - Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost - Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::createPair - Creates two buffer events connected to each other
    • EventBufferEvent::disable - Disable events read, write, or both on a buffer event
    • EventBufferEvent::enable - Enable events read, write, or both on a buffer event
    • EventBufferEvent::free - Free a buffer event
    • EventBufferEvent::getDnsErrorString - Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled - Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput - Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput - Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read - Read buffer's data
    • EventBufferEvent::readBuffer - Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks - Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority - Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts - Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark - Adjusts read and/or write watermarks
    • EventBufferEvent::sslError - Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter - Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo - Returns a textual description of the cipher
    • EventBufferEvent::sslGetCipherName - Returns the current cipher name of the SSL connection
    • EventBufferEvent::sslGetCipherVersion - Returns version of cipher used by current SSL connection
    • EventBufferEvent::sslGetProtocol - Returns the name of the protocol used for current SSL connection
    • EventBufferEvent::sslRenegotiate - Tells a bufferevent to begin SSL renegotiation
    • EventBufferEvent::sslSocket - Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write - Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer - Adds contents of the entire buffer to a buffer event's output buffer
    • EventBufferEvent::__construct - Constructs EventBufferEvent object
    • EventConfig::avoidMethod - Tells libevent to avoid specific event method
    • EventConfig::requireFeatures - Enters a required event method feature that the application demands
    • EventConfig::setMaxDispatchInterval - Prevents priority inversion
    • EventConfig::__construct - Constructs EventConfig object
    • EventDnsBase::addNameserverIp - Adds a nameserver to the DNS base
    • EventDnsBase::addSearch - Adds a domain to the list of search domains
    • EventDnsBase::clearSearch - Removes all current search suffixes
    • EventDnsBase::countNameservers - Gets the number of configured nameservers
    • EventDnsBase::loadHosts - Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf - Scans the resolv.conf-formatted file
    • EventDnsBase::setOption - Set the value of a configuration option
    • EventDnsBase::setSearchNdots - Set the 'ndots' parameter for searches
    • EventDnsBase::__construct - Constructs EventDnsBase object
    • EventHttp::accept - Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias - Adds a server alias to the HTTP server object
    • EventHttp::bind - Binds an HTTP server on the specified address and port
    • EventHttp::removeServerAlias - Removes server alias
    • EventHttp::setAllowedMethods - Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback - Sets a callback for specified URI
    • EventHttp::setDefaultCallback - Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize - Sets maximum request body size
    • EventHttp::setMaxHeadersSize - Sets maximum HTTP header size
    • EventHttp::setTimeout - Sets the timeout for an HTTP request
    • EventHttp::__construct - Constructs EventHttp object(the HTTP server)
    • EventHttpConnection::getBase - Returns event base associated with the connection
    • EventHttpConnection::getPeer - Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest - Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback - Set callback for connection close
    • EventHttpConnection::setLocalAddress - Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort - Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize - Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize - Sets maximum header size
    • EventHttpConnection::setRetries - Sets the retry limit for the connection
    • EventHttpConnection::setTimeout - Sets the timeout for the connection
    • EventHttpConnection::__construct - Constructs EventHttpConnection object
    • EventHttpRequest::addHeader - Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel - Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders - Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection - Closes associated HTTP connection
    • EventHttpRequest::findHeader - Finds the value belonging a header
    • EventHttpRequest::free - Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent - Returns EventBufferEvent object
    • EventHttpRequest::getCommand - Returns the request command(method)
    • EventHttpRequest::getConnection - Returns EventHttpConnection object
    • EventHttpRequest::getHost - Returns the request host
    • EventHttpRequest::getInputBuffer - Returns the input buffer
    • EventHttpRequest::getInputHeaders - Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer - Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders - Returns associative array of the output headers
    • EventHttpRequest::getResponseCode - Returns the response code
    • EventHttpRequest::getUri - Returns the request URI
    • EventHttpRequest::removeHeader - Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError - Send an HTML error message to the client
    • EventHttpRequest::sendReply - Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk - Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd - Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart - Initiate a chunked reply
    • EventHttpRequest::__construct - Constructs EventHttpRequest object
    • EventListener::disable - Disables an event connect listener object
    • EventListener::enable - Enables an event connect listener object
    • EventListener::getBase - Returns event base associated with the event listener
    • EventListener::getSocketName - Retreives the current address to which the listener's socket is bound
    • EventListener::setCallback - The setCallback purpose
    • EventListener::setErrorCallback - Set event listener's error callback
    • EventListener::__construct - Creates new connection listener associated with an event base
    • EventSslContext::__construct - Constructs an OpenSSL context for use with Event classes
    • EventUtil::getLastSocketErrno - Returns the most recent socket error number
    • EventUtil::getLastSocketError - Returns the most recent socket error
    • EventUtil::getSocketFd - Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName - Retreives the current address to which the socket is bound
    • EventUtil::setSocketOption - Sets socket options
    • EventUtil::sslRandPoll - Generates entropy by means of OpenSSL's RAND_poll()
    • EventUtil::__construct - The abstract constructor
    • EvFork::createStopped - Creates a stopped instance of EvFork watcher class
    • EvFork::__construct - Constructs the EvFork watcher object
    • EvIdle::createStopped - Creates instance of a stopped EvIdle watcher object
    • EvIdle::__construct - Constructs the EvIdle watcher object
    • EvIo::createStopped - Create stopped EvIo watcher object
    • EvIo::set - Configures the watcher
    • EvIo::__construct - Constructs EvIo watcher object
    • EvLoop::backend - Returns an integer describing the backend used by libev
    • EvLoop::check - Creates EvCheck object associated with the current event loop instance
    • EvLoop::child - Creates EvChild object associated with the current event loop
    • EvLoop::defaultLoop - Returns or creates the default event loop
    • EvLoop::embed - Creates an instance of EvEmbed watcher associated with the current EvLoop object
    • EvLoop::fork - Creates EvFork watcher object associated with the current event loop instance
    • EvLoop::idle - Creates EvIdle watcher object associated with the current event loop instance
    • EvLoop::invokePending - Invoke all pending watchers while resetting their pending state
    • EvLoop::io - Create EvIo watcher object associated with the current event loop instance
    • EvLoop::loopFork - Must be called after a fork
    • EvLoop::now - Returns the current "event loop time"
    • EvLoop::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress
    • EvLoop::periodic - Creates EvPeriodic watcher object associated with the current event loop instance
    • EvLoop::prepare - Creates EvPrepare watcher object associated with the current event loop instance
    • EvLoop::resume - Resume previously suspended default event loop
    • EvLoop::run - Begin checking for events and calling callbacks for the loop
    • EvLoop::signal - Creates EvSignal watcher object associated with the current event loop instance
    • EvLoop::stat - Creates EvStat watcher object associated with the current event loop instance
    • EvLoop::stop - Stops the event loop
    • EvLoop::suspend - Suspend the loop
    • EvLoop::timer - Creates EvTimer watcher object associated with the current event loop instance
    • EvLoop::verify - Performs internal consistency checks(for debugging)
    • EvLoop::__construct - Constructs the event loop object
    • EvPeriodic::again - Simply stops and restarts the periodic watcher again
    • EvPeriodic::at - Returns the absolute time that this watcher is supposed to trigger next
    • EvPeriodic::createStopped - Create a stopped EvPeriodic watcher
    • EvPeriodic::set - Configures the watcher
    • EvPeriodic::__construct - Constructs EvPeriodic watcher object
    • EvPrepare::createStopped - Creates a stopped instance of EvPrepare watcher
    • EvPrepare::__construct - Constructs EvPrepare watcher object
    • EvSignal::createStopped - Create stopped EvSignal watcher object
    • EvSignal::set - Configures the watcher
    • EvSignal::__construct - Constructs EvSignal watcher object
    • EvStat::attr - Returns the values most recently detected by Ev
    • EvStat::createStopped - Create a stopped EvStat watcher object
    • EvStat::prev - Returns the previous set of values returned by EvStat::attr
    • EvStat::set - Configures the watcher
    • EvStat::stat - Initiates the stat call
    • EvStat::__construct - Constructs EvStat watcher object
    • EvTimer::again - Restarts the timer watcher
    • EvTimer::createStopped - Creates EvTimer stopped watcher object
    • EvTimer::set - Configures the watcher
    • EvTimer::__construct - Constructs an EvTimer watcher object
    • EvWatcher::clear - Clear watcher pending status
    • EvWatcher::feed - Feeds the given revents set into the event loop
    • EvWatcher::getLoop - Returns the loop responsible for the watcher
    • EvWatcher::invoke - Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive - Configures whether to keep the loop from returning
    • EvWatcher::setCallback - Sets new callback for the watcher
    • EvWatcher::start - Starts the watcher
    • EvWatcher::stop - Stops the watcher
    • EvWatcher::__construct - Abstract constructor of a watcher object
    • Exception::getCode - 获取异常代码
    • Exception::getFile - 创建异常时的程序文件名称
    • Exception::getLine - 获取创建的异常所在文件中的行号
    • Exception::getMessage - 获取异常消息内容
    • Exception::getPrevious - 返回异常链中的前一个异常
    • Exception::getTrace - 获取异常追踪信息
    • Exception::getTraceAsString - 获取字符串类型的异常追踪信息
    • Exception::__clone - 异常克隆
    • Exception::__construct - 异常构造函数
    • Exception::__toString - 将异常对象转换为字符串
    • exec - 执行一个外部程序
    • Executable::execute - Execute statement
    • ExecutionStatus::__construct - ExecutionStatus constructor
    • exif_imagetype - 判断一个图像的类型
    • exif_read_data - 从 JPEG 或 TIFF 文件中读取 EXIF 头信息
    • exif_tagname - 获取指定索引的头名称
    • exif_thumbnail - 取得嵌入在 TIFF 或 JPEG 图像中的缩略图
    • exit - 输出一个消息并且退出当前脚本
    • exp - 计算 e 的指数
    • expect:// - 处理交互式的流
    • expect_expectl - Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen - Execute command via Bourne shell, and open the PTY stream to the process
    • explode - 使用一个字符串分割另一个字符串
    • expm1 - 返回 exp(number) - 1，甚至当 number 的值接近零也能计算出准确结果
    • expression - Bind prepared statement variables as parameters
    • Expression::__construct - Expression constructor
    • extension_loaded - 检查一个扩展是否已经加载
    • extract - 从数组中将变量导入到当前的符号表
    • ezmlm_hash - 计算 EZMLM 所需的散列值
  • f
    • FANNConnection::getFromNeuron - 返回开始连接的神经元。
    • FANNConnection::getToNeuron - 返回终止神经元的位置。
    • FANNConnection::getWeight - 返回连接权重。
    • FANNConnection::setWeight - 设置连接权重。
    • FANNConnection::__construct - 连接构造器
    • fann_cascadetrain_on_data - 在整个数据集上训练，使用一段时间的 Cascade2 训练算法。
    • fann_cascadetrain_on_file - 读取文件并在整个数据集上训练，使用 Cascade2 训练算法训练一段时间。
    • fann_clear_scaling_params - 清除缩放参数
    • fann_copy - 创建一个 fann 结构体的副本。
    • fann_create_from_file - 从配置文件中构建一个反向传播神经网络。
    • fann_create_shortcut - 创建一个含快捷连接而非全连接的标准反向传播神经网络。
    • fann_create_shortcut_array - 创建一个含快捷连接而非全连接的标准反向传播神经网络。
    • fann_create_sparse - 创建一个标准的反向传播神经网络，该网络不是全连接。
    • fann_create_sparse_array - 创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。
    • fann_create_standard - 创建标准的全连接反向传播神经网络。
    • fann_create_standard_array - 创建一个全连接的反向传播神经网络，该网络使用一个表示每层大小的数组来构造。
    • fann_create_train - 创建一个空的训练数据结构。
    • fann_create_train_from_callback - 从用户提供的函数创建训练数据结构。
    • fann_descale_input - 在获取基于先前计算的参数之后，在输入向量中缩小数据
    • fann_descale_output - 在获取基于先前计算的参数之后，在输出向量中缩小数据
    • fann_descale_train - 基于先前计算的参数来缩小输入和输出数据
    • fann_destroy - 销毁整个网络并且适当地释放所有的关联内存。
    • fann_destroy_train - 销毁训练数据。
    • fann_duplicate_train_data - 返回 fann 训练数据精确的副本。
    • fann_get_activation_function - 返回激励函数
    • fann_get_activation_steepness - 为提供的神经和网络层数返回激活陡度
    • fann_get_bias_array - 获取网络中每一层的偏差数
    • fann_get_bit_fail - 失败位的数量
    • fann_get_bit_fail_limit - 返回训练期间使用的误差限制
    • fann_get_cascade_activation_functions - 返回级联激活函数
    • fann_get_cascade_activation_functions_count - 返回级联激活函数的数量
    • fann_get_cascade_activation_steepnesses - 返回级联激活陡度
    • fann_get_cascade_activation_steepnesses_count - 激活陡度的数量
    • fann_get_cascade_candidate_change_fraction - 返回级联候选变化分数
    • fann_get_cascade_candidate_limit - 返回候选限度
    • fann_get_cascade_candidate_stagnation_epochs - 返回层叠候选停滞周期的数量
    • fann_get_cascade_max_cand_epochs - 返回候选周期的最大值
    • fann_get_cascade_max_out_epochs - 返回输出周期的最大值
    • fann_get_cascade_min_cand_epochs - 返回最小的候选周期
    • fann_get_cascade_min_out_epochs - 返回最小输出周期
    • fann_get_cascade_num_candidates - 返回训练期间使用的候选数量
    • fann_get_cascade_num_candidate_groups - 返回候选组的数量
    • fann_get_cascade_output_change_fraction - 返回级联输出变化分数
    • fann_get_cascade_output_stagnation_epochs - 返回级联输出停滞周期的数量
    • fann_get_cascade_weight_multiplier - 返回权重因子
    • fann_get_connection_array - 获取网络中的连接。
    • fann_get_connection_rate - 获取当网络创建时连接的使用率。
    • fann_get_errno - 返回最后一个错误数字。
    • fann_get_errstr - 返回最后的错误字符串。
    • fann_get_layer_array - 获取网络中每层的神经元数量。
    • fann_get_learning_momentum - 返回学习动量
    • fann_get_learning_rate - 返回学习速率
    • fann_get_MSE - 从网络中读取均方误差。
    • fann_get_network_type - 获取所创建的神经网络类型。
    • fann_get_num_input - 获取输入神经元的数量。
    • fann_get_num_layers - 获取神经网络的层数。
    • fann_get_num_output - 获取输出神经元的数量。
    • fann_get_quickprop_decay - 返回衰退值，用于在 quickprop 训练迭代时衰减权重
    • fann_get_quickprop_mu - 返回放大系数
    • fann_get_rprop_decrease_factor - 返回 RPROP 训练期间的衰减系数
    • fann_get_rprop_delta_max - 返回最大步长
    • fann_get_rprop_delta_min - 返回最小步长
    • fann_get_rprop_delta_zero - 返回初始步长
    • fann_get_rprop_increase_factor - 返回 RPROP 训练的递增系数
    • fann_get_sarprop_step_error_shift - 返回 sarprop 步值的误差偏移
    • fann_get_sarprop_step_error_threshold_factor - 返回 sarprop 算法步值的误差阈值系数
    • fann_get_sarprop_temperature - 返回 sarprop 算法温度
    • fann_get_sarprop_weight_decay_shift - 返回 sarprop 算法权重衰减变化值
    • fann_get_total_connections - 获取整个网络中所有的连接数。
    • fann_get_total_neurons - 获取整个网络中神经元的数量。
    • fann_get_training_algorithm - 返回训练算法。
    • fann_get_train_error_function - 返回训练中使用的错误函数。
    • fann_get_train_stop_function - 返回训练中使用的停止函数。
    • fann_init_weights - 使用 Widrow 和 Nguyen 算法初始化权重。
    • fann_length_train_data - 返回训练数据中训练模式的数量。
    • fann_merge_train_data - 合并训练数据。
    • fann_num_input_train_data - 返回训练数据中每个训练模式输入的数量。
    • fann_num_output_train_data - 返回训练数据中每个训练模式输出的数量。
    • fann_print_error - 打印错误字符串。
    • fann_randomize_weights - 给每个连接赋一个介于 min_weight 和 max_weight 之间的随机权重。
    • fann_read_train_from_file - 读取存储训练数据的文件。
    • fann_reset_errno - 重置最后的错误代码。
    • fann_reset_errstr - 重置最后的错误字符串。
    • fann_reset_MSE - 重置网络中的均方误差。
    • fann_run - 将通过神经网络运行输入。
    • fann_save - 将整个网络保存至配置文件。
    • fann_save_train - 将训练结构体保存至文件。
    • fann_scale_input - 在以前计算参数的基础上，在训练之前放大输入向量中的数据
    • fann_scale_input_train_data - 在训练数据中缩放输入至指定范围
    • fann_scale_output - 在以前计算参数的基础上，在训练之前放大输出向量中的数据
    • fann_scale_output_train_data - 在训练数据中缩放输出至指定范围
    • fann_scale_train - 在以前计算参数的基础上，缩放输入和输出数据
    • fann_scale_train_data - 在训练数据中缩放输入和输出到指定的范围
    • fann_set_activation_function - 为已应用的神经元和层设置激活函数
    • fann_set_activation_function_hidden - 为所有隐藏层设置激活函数
    • fann_set_activation_function_layer - 为已应用的层中所有的神经元设置激活函数。
    • fann_set_activation_function_output - 为输出层设置激活函数
    • fann_set_activation_steepness - 为提供的神经元和层设置激活陡度
    • fann_set_activation_steepness_hidden - 为所有隐藏层中所有的神经元设置激活函数陡度
    • fann_set_activation_steepness_layer - 为提供的层中所有的神经元设置激活陡度
    • fann_set_activation_steepness_output - 在输出层中设置激活陡度
    • fann_set_bit_fail_limit - 设置训练期间使用的误差
    • fann_set_callback - 设置训练期间使用的回调函数。
    • fann_set_cascade_activation_functions - 设置级联候选激活函数的数组
    • fann_set_cascade_activation_steepnesses - 设置级联候选激活陡度的数组。
    • fann_set_cascade_candidate_change_fraction - 设置级联候选更改分数
    • fann_set_cascade_candidate_limit - 设置候选限度
    • fann_set_cascade_candidate_stagnation_epochs - 设置级联候选停止周期数
    • fann_set_cascade_max_cand_epochs - 设置最大候选周期数
    • fann_set_cascade_max_out_epochs - 设置最大输出周期
    • fann_set_cascade_min_cand_epochs - 设置最小候选周期
    • fann_set_cascade_min_out_epochs - 设置最小输出周期
    • fann_set_cascade_num_candidate_groups - 设置候选组数量
    • fann_set_cascade_output_change_fraction - 设置级联输出改变分数
    • fann_set_cascade_output_stagnation_epochs - 设置级联输出停滞周期的值
    • fann_set_cascade_weight_multiplier - 设置权重因子
    • fann_set_error_log - 设置错误记录保存的位置。
    • fann_set_input_scaling_params - 根据训练数据计算将来使用的输入比例参数
    • fann_set_learning_momentum - 设置学习动量。
    • fann_set_learning_rate - 设置学习速率。
    • fann_set_output_scaling_params - 根据训练数据计算将来使用的输出缩放参数
    • fann_set_quickprop_decay - 设置quickprop算法衰减因子
    • fann_set_quickprop_mu - 设置 quickprop 算法放大因子
    • fann_set_rprop_decrease_factor - 使用 RPROP 算法训练时，设置下降因子
    • fann_set_rprop_delta_max - 设置最大步长
    • fann_set_rprop_delta_min - 设置最小步长
    • fann_set_rprop_delta_zero - 设置初始步长
    • fann_set_rprop_increase_factor - 使用 RPROP 算法训练时，设置增长因子
    • fann_set_sarprop_step_error_shift - 设置 sarprop 算法的步误差偏移量
    • fann_set_sarprop_step_error_threshold_factor - 设置 sarprop 算法的步误差阈值因子
    • fann_set_sarprop_temperature - 设置 sarprop 算法的温度
    • fann_set_sarprop_weight_decay_shift - 设置 sarprop 算法的权重衰减偏移值
    • fann_set_scaling_params - 根据训练数据计算输入和输出缩放参数以供将来使用
    • fann_set_training_algorithm - 设置训练算法。
    • fann_set_train_error_function - 设置训练期间使用的错误函数。
    • fann_set_train_stop_function - 设置训练期间使用的停止函数。
    • fann_set_weight - 在网络中设置一个连接。
    • fann_set_weight_array - 在网络中设置一个连接。
    • fann_shuffle_train_data - 打算训练数据，使顺序随机。
    • fann_subset_train_data - 返回一个训练数据子集的副本。
    • fann_test - 使用一组输入和一组期望的输出来测试。
    • fann_test_data - 使用训练数据来测试并且计算出 MSE
    • fann_train - 使用一个输入集和一个期望的输出集来迭代训练一次。
    • fann_train_epoch - 使用一组训练数据训练一个周期。
    • fann_train_on_data - 在整个数据集上训练一段时间。
    • fann_train_on_file - 在从某个文件读取的整个数据集上训练一段时间。
    • fastcgi_finish_request - 冲刷(flush)所有响应的数据给客户端
    • fbird_add_user - 别名 ibase_add_user
    • fbird_affected_rows - 别名 ibase_affected_rows
    • fbird_backup - 别名 ibase_backup
    • fbird_blob_add - 别名 ibase_blob_add
    • fbird_blob_cancel - Cancel creating blob
    • fbird_blob_close - 别名 ibase_blob_close
    • fbird_blob_create - 别名 ibase_blob_create
    • fbird_blob_echo - 别名 ibase_blob_echo
    • fbird_blob_get - 别名 ibase_blob_get
    • fbird_blob_import - 别名 ibase_blob_import
    • fbird_blob_info - 别名 ibase_blob_info
    • fbird_blob_open - 别名 ibase_blob_open
    • fbird_close - 别名 ibase_close
    • fbird_commit - 别名 ibase_commit
    • fbird_commit_ret - 别名 ibase_commit_ret
    • fbird_connect - 别名 ibase_connect
    • fbird_db_info - 别名 ibase_db_info
    • fbird_delete_user - 别名 ibase_delete_user
    • fbird_drop_db - 别名 ibase_drop_db
    • fbird_errcode - 别名 ibase_errcode
    • fbird_errmsg - 别名 ibase_errmsg
    • fbird_execute - 别名 ibase_execute
    • fbird_fetch_assoc - 别名 ibase_fetch_assoc
    • fbird_fetch_object - 别名 ibase_fetch_object
    • fbird_fetch_row - 别名 ibase_fetch_row
    • fbird_field_info - 别名 ibase_field_info
    • fbird_free_event_handler - 别名 ibase_free_event_handler
    • fbird_free_query - 别名 ibase_free_query
    • fbird_free_result - 别名 ibase_free_result
    • fbird_gen_id - 别名 ibase_gen_id
    • fbird_maintain_db - 别名 ibase_maintain_db
    • fbird_modify_user - 别名 ibase_modify_user
    • fbird_name_result - 别名 ibase_name_result
    • fbird_num_fields - 别名 ibase_num_fields
    • fbird_num_params - 别名 ibase_num_params
    • fbird_param_info - 别名 ibase_param_info
    • fbird_pconnect - 别名 ibase_pconnect
    • fbird_prepare - 别名 ibase_prepare
    • fbird_query - 别名 ibase_query
    • fbird_restore - 别名 ibase_restore
    • fbird_rollback - 别名 ibase_rollback
    • fbird_rollback_ret - 别名 ibase_rollback_ret
    • fbird_server_info - 别名 ibase_server_info
    • fbird_service_attach - 别名 ibase_service_attach
    • fbird_service_detach - 别名 ibase_service_detach
    • fbird_set_event_handler - 别名 ibase_set_event_handler
    • fbird_trans - 别名 ibase_trans
    • fbird_wait_event - 别名 ibase_wait_event
    • fbsql_affected_rows - Get number of affected rows in previous FrontBase operation
    • fbsql_autocommit - Enable or disable autocommit
    • fbsql_blob_size - Get the size of a BLOB
    • fbsql_change_user - Change logged in user of the active connection
    • fbsql_clob_size - Get the size of a CLOB
    • fbsql_close - Close FrontBase connection
    • fbsql_commit - Commits a transaction to the database
    • fbsql_connect - Open a connection to a FrontBase Server
    • fbsql_create_blob - Create a BLOB
    • fbsql_create_clob - Create a CLOB
    • fbsql_create_db - Create a FrontBase database
    • fbsql_database - Get or set the database name used with a connection
    • fbsql_database_password - Sets or retrieves the password for a FrontBase database
    • fbsql_data_seek - Move internal result pointer
    • fbsql_db_query - Send a FrontBase query
    • fbsql_db_status - Get the status for a given database
    • fbsql_drop_db - Drop (delete) a FrontBase database
    • fbsql_errno - Returns the error number from previous operation
    • fbsql_error - Returns the error message from previous operation
    • fbsql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • fbsql_fetch_assoc - Fetch a result row as an associative array
    • fbsql_fetch_field - Get column information from a result and return as an object
    • fbsql_fetch_lengths - Get the length of each output in a result
    • fbsql_fetch_object - Fetch a result row as an object
    • fbsql_fetch_row - Get a result row as an enumerated array
    • fbsql_field_flags - Get the flags associated with the specified field in a result
    • fbsql_field_len - Returns the length of the specified field
    • fbsql_field_name - Get the name of the specified field in a result
    • fbsql_field_seek - Set result pointer to a specified field offset
    • fbsql_field_table - Get name of the table the specified field is in
    • fbsql_field_type - Get the type of the specified field in a result
    • fbsql_free_result - Free result memory
    • fbsql_get_autostart_info - 说明
    • fbsql_hostname - Get or set the host name used with a connection
    • fbsql_insert_id - Get the id generated from the previous INSERT operation
    • fbsql_list_dbs - List databases available on a FrontBase server
    • fbsql_list_fields - List FrontBase result fields
    • fbsql_list_tables - List tables in a FrontBase database
    • fbsql_next_result - Move the internal result pointer to the next result
    • fbsql_num_fields - Get number of fields in result
    • fbsql_num_rows - Get number of rows in result
    • fbsql_password - Get or set the user password used with a connection
    • fbsql_pconnect - Open a persistent connection to a FrontBase Server
    • fbsql_query - Send a FrontBase query
    • fbsql_read_blob - Read a BLOB from the database
    • fbsql_read_clob - Read a CLOB from the database
    • fbsql_result - Get result data
    • fbsql_rollback - Rollback a transaction to the database
    • fbsql_rows_fetched - Get the number of rows affected by the last statement
    • fbsql_select_db - Select a FrontBase database
    • fbsql_set_characterset - Change input/output character set
    • fbsql_set_lob_mode - Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password - Change the password for a given user
    • fbsql_set_transaction - Set the transaction locking and isolation
    • fbsql_start_db - Start a database on local or remote server
    • fbsql_stop_db - Stop a database on local or remote server
    • fbsql_tablename - 别名 fbsql_table_name
    • fbsql_table_name - Get table name of field
    • fbsql_username - Get or set the username for the connection
    • fbsql_warnings - Enable or disable FrontBase warnings
    • fclose - 关闭一个已打开的文件指针
    • fdf_add_doc_javascript - Adds javascript code to the FDF document
    • fdf_add_template - Adds a template into the FDF document
    • fdf_close - Close an FDF document
    • fdf_create - Create a new FDF document
    • fdf_enum_values - Call a user defined function for each document value
    • fdf_errno - Return error code for last fdf operation
    • fdf_error - Return error description for FDF error code
    • fdf_get_ap - Get the appearance of a field
    • fdf_get_attachment - Extracts uploaded file embedded in the FDF
    • fdf_get_encoding - Get the value of the /Encoding key
    • fdf_get_file - Get the value of the /F key
    • fdf_get_flags - Gets the flags of a field
    • fdf_get_opt - Gets a value from the opt array of a field
    • fdf_get_status - Get the value of the /STATUS key
    • fdf_get_value - Get the value of a field
    • fdf_get_version - Gets version number for FDF API or file
    • fdf_header - Sets FDF-specific output headers
    • fdf_next_field_name - Get the next field name
    • fdf_open - Open a FDF document
    • fdf_open_string - Read a FDF document from a string
    • fdf_remove_item - Sets target frame for form
    • fdf_save - Save a FDF document
    • fdf_save_string - Returns the FDF document as a string
    • fdf_set_ap - Set the appearance of a field
    • fdf_set_encoding - Sets FDF character encoding
    • fdf_set_file - Set PDF document to display FDF data in
    • fdf_set_flags - Sets a flag of a field
    • fdf_set_javascript_action - Sets an javascript action of a field
    • fdf_set_on_import_javascript - Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt - Sets an option of a field
    • fdf_set_status - Set the value of the /STATUS key
    • fdf_set_submit_form_action - Sets a submit form action of a field
    • fdf_set_target_frame - Set target frame for form display
    • fdf_set_value - Set the value of a field
    • fdf_set_version - Sets version number for a FDF file
    • fdiv - Divides two numbers, according to IEEE 754
    • feof - 测试文件指针是否到了文件结束的位置
    • FFI::addr - Creates an unmanaged pointer to C data
    • FFI::alignof - Gets the alignment
    • FFI::arrayType - Dynamically constructs a new C array type
    • FFI::cast - Performs a C type cast
    • FFI::cdef - Creates a new FFI object
    • FFI::free - Releases an unmanaged data structure
    • FFI::isNull - Checks whether a FFI\CData is a null pointer
    • FFI::load - Loads C declarations from a C header file
    • FFI::memcmp - Compares memory areas
    • FFI::memcpy - Copies one memory area to another
    • FFI::memset - Fills a memory area
    • FFI::new - Creates a C data structure
    • FFI::scope - Instantiates an FFI object with C declarations parsed during preloading
    • FFI::sizeof - Gets the size of C data or types
    • FFI::string - Creates a PHP string from a memory area
    • FFI::type - Creates an FFI\CType object from a C declaration
    • FFI::typeof - Gets the FFI\CType of FFI\CData
    • fflush - 将缓冲内容输出到文件
    • fgetc - 从文件指针中读取字符
    • fgetcsv - 从文件指针中读入一行并解析 CSV 字段
    • fgets - 从文件指针中读取一行
    • fgetss - 从文件指针中读取一行并过滤掉 HTML 标记
    • file - 把整个文件读入一个数组中
    • file:// - 访问本地文件系统
    • fileatime - 取得文件的上次访问时间
    • filectime - 取得文件的 inode 修改时间
    • filegroup - 取得文件的组
    • fileinode - 取得文件的 inode
    • filemtime - 取得文件修改时间
    • fileowner - 取得文件的所有者
    • fileperms - 取得文件的权限
    • filepro - Read and verify the map file
    • filepro_fieldcount - Find out how many fields are in a filePro database
    • filepro_fieldname - Gets the name of a field
    • filepro_fieldtype - Gets the type of a field
    • filepro_fieldwidth - Gets the width of a field
    • filepro_retrieve - Retrieves data from a filePro database
    • filepro_rowcount - Find out how many rows are in a filePro database
    • filesize - 取得文件大小
    • FilesystemIterator::current - The current file
    • FilesystemIterator::getFlags - Get the handling flags
    • FilesystemIterator::key - Retrieve the key for the current file
    • FilesystemIterator::next - Move to the next file
    • FilesystemIterator::rewind - Rewinds back to the beginning
    • FilesystemIterator::setFlags - Sets handling flags
    • FilesystemIterator::__construct - Constructs a new filesystem iterator
    • filetype - 取得文件类型
    • file_exists - 检查文件或目录是否存在
    • file_get_contents - 将整个文件读入一个字符串
    • file_put_contents - 将一个字符串写入文件
    • FilterIterator::accept - Check whether the current element of the iterator is acceptable
    • FilterIterator::current - Get the current element value
    • FilterIterator::getInnerIterator - Get the inner iterator
    • FilterIterator::key - Get the current key
    • FilterIterator::next - Move the iterator forward
    • FilterIterator::rewind - Rewind the iterator
    • FilterIterator::valid - Check whether the current element is valid
    • FilterIterator::__construct - Construct a filterIterator
    • filter_has_var - 检测是否存在指定类型的变量
    • filter_id - 返回与某个特定名称的过滤器相关联的id
    • filter_input - 通过名称获取特定的外部变量，并且可以通过过滤器处理它
    • filter_input_array - 获取一系列外部变量，并且可以通过过滤器处理它们
    • filter_list - 返回所支持的过滤器列表
    • filter_var - 使用特定的过滤器过滤一个变量
    • filter_var_array - 获取多个变量并且过滤它们
    • finfo::buffer - 别名 finfo_buffer()
    • finfo::file - 别名 finfo_file()
    • finfo::set_flags - 别名 finfo_set_flags()
    • finfo::__construct - 别名 finfo_open
    • finfo_close - 关闭 fileinfo 资源
    • finfo_open - 创建一个 fileinfo 资源
    • floatval - 获取变量的浮点值
    • flock - 轻便的咨询文件锁定
    • floor - 舍去法取整
    • flush - 刷新输出缓冲
    • fmod - 返回除法的浮点数余数
    • fnmatch - 用模式匹配文件名
    • fopen - 打开文件或者 URL
    • forward_static_call - Call a static method
    • forward_static_call_array - Call a static method and pass the arguments as array
    • fpassthru - 输出文件指针处的所有剩余数据
    • fprintf - 将格式化后的字符串写入到流
    • fputcsv - 将行格式化为 CSV 并写入文件指针
    • fputs - fwrite 的别名
    • fread - 读取文件（可安全用于二进制文件）
    • FrenchToJD - 从一个French Republican历法的日期得到Julian Day计数。
    • fscanf - 从文件中格式化输入
    • fseek - 在文件指针中定位
    • fsockopen - 打开一个网络连接或者一个Unix套接字连接
    • fstat - 通过已打开的文件指针取得文件信息
    • ftell - 返回文件指针读/写的位置
    • ftok - Convert a pathname and a project identifier to a System V IPC key
    • ftp:// - 访问 FTP(s) URLs
    • FTP context options - FTP context option listing
    • ftp_alloc - 为要上传的文件分配空间
    • ftp_append - 将文件内容追加到 FTP 服务器上的指定文件
    • ftp_cdup - 切换到当前目录的父目录
    • ftp_chdir - 在 FTP 服务器上改变当前目录
    • ftp_chmod - 设置 FTP 服务器上的文件权限
    • ftp_close - 关闭一个 FTP 连接
    • ftp_connect - 建立一个新的 FTP 连接
    • ftp_delete - 删除 FTP 服务器上的一个文件
    • ftp_exec - 在 FTP 服务器运行指定的命令
    • ftp_fget - 从 FTP 服务器上下载一个文件并保存到本地一个已经打开的文件中
    • ftp_fput - 上传一个已经打开的文件到 FTP 服务器
    • ftp_get - 从 FTP 服务器上下载一个文件
    • ftp_get_option - 返回当前 FTP 连接的各种不同的选项设置
    • ftp_login - 登录 FTP 服务器
    • ftp_mdtm - 返回指定文件的最后修改时间
    • ftp_mkdir - 建立新目录
    • ftp_mlsd - 返回指定目录中的文件列表
    • ftp_nb_continue - 连续获取／发送文件（以不分块的方式 non-blocking）
    • ftp_nb_fget - 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）
    • ftp_nb_fput - 将文件存储到 FTP 服务器 （非阻塞）
    • ftp_nb_get - 从 FTP 服务器上获取文件并写入本地文件（non-blocking）
    • ftp_nb_put - 存储一个文件至 FTP 服务器（non-blocking）
    • ftp_nlist - 返回给定目录的文件列表
    • ftp_pasv - 返回当前 FTP 被动模式是否打开
    • ftp_put - 上传文件到 FTP 服务器
    • ftp_pwd - 返回当前目录名
    • ftp_quit - ftp_close 的 别名
    • ftp_raw - 向 FTP 服务器发送命令
    • ftp_rawlist - 返回指定目录下文件的详细列表
    • ftp_rename - 更改 FTP 服务器上的文件或目录名
    • ftp_rmdir - 删除目录
    • ftp_set_option - 设置各种 FTP 运行时选项
    • ftp_site - 向服务器发送 SITE 命令
    • ftp_size - 返回指定文件的大小
    • ftp_ssl_connect - 打开 SSL-FTP 连接
    • ftp_systype - 返回远程 FTP 服务器的操作系统类型
    • ftruncate - 将文件截断到给定的长度
    • function_exists - 如果给定的函数已经被定义就返回 true
    • func_get_arg - 返回参数列表的某一项
    • func_get_args - 返回一个包含函数参数列表的数组
    • func_num_args - Returns the number of arguments passed to the function
    • fwrite - 写入文件（可安全用于二进制文件）
  • g
    • gc_collect_cycles - 强制收集所有现存的垃圾循环周期
    • gc_disable - 停用循环引用收集器
    • gc_enable - 激活循环引用收集器
    • gc_enabled - 返回循环引用计数器的状态
    • gc_mem_caches - Reclaims memory used by the Zend Engine memory manager
    • gc_status - Gets information about the garbage collector
    • gd_info - 取得当前安装的 GD 库的信息
    • GearmanClient::addOptions - Add client options
    • GearmanClient::addServer - Add a job server to the client
    • GearmanClient::addServers - Add a list of job servers to the client
    • GearmanClient::addTask - Add a task to be run in parallel
    • GearmanClient::addTaskBackground - Add a background task to be run in parallel
    • GearmanClient::addTaskHigh - Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground - Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow - Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground - Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus - Add a task to get status
    • GearmanClient::clearCallbacks - Clear all task callback functions
    • GearmanClient::clone - Create a copy of a GearmanClient object
    • GearmanClient::context - Get the application context
    • GearmanClient::data - Get the application data (deprecated)
    • GearmanClient::do - Run a single task and return a result [deprecated]
    • GearmanClient::doBackground - Run a task in the background
    • GearmanClient::doHigh - Run a single high priority task
    • GearmanClient::doHighBackground - Run a high priority task in the background
    • GearmanClient::doJobHandle - Get the job handle for the running task
    • GearmanClient::doLow - Run a single low priority task
    • GearmanClient::doLowBackground - Run a low priority task in the background
    • GearmanClient::doNormal - Run a single task and return a result
    • GearmanClient::doStatus - Get the status for the running task
    • GearmanClient::echo - Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error - Returns an error string for the last error encountered
    • GearmanClient::getErrno - Get an errno value
    • GearmanClient::jobStatus - Get the status of a background job
    • GearmanClient::ping - Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions - Remove client options
    • GearmanClient::returnCode - Get the last Gearman return code
    • GearmanClient::runTasks - Run a list of tasks in parallel
    • GearmanClient::setClientCallback - Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback - Set a function to be called on task completion
    • GearmanClient::setContext - Set application context
    • GearmanClient::setCreatedCallback - Set a callback for when a task is queued
    • GearmanClient::setData - Set application data (deprecated)
    • GearmanClient::setDataCallback - Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback - Set a callback for worker exceptions
    • GearmanClient::setFailCallback - Set callback for job failure
    • GearmanClient::setOptions - Set client options
    • GearmanClient::setStatusCallback - Set a callback for collecting task status
    • GearmanClient::setTimeout - Set socket I/O activity timeout
    • GearmanClient::setWarningCallback - Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback - Set a callback for accepting incremental data updates
    • GearmanClient::timeout - Get current socket I/O activity timeout value
    • GearmanClient::wait - Wait for I/O activity on all connections in a client
    • GearmanClient::__construct - Create a GearmanClient instance
    • GearmanJob::complete - Send the result and complete status (deprecated)
    • GearmanJob::data - Send data for a running job (deprecated)
    • GearmanJob::exception - Send exception for running job (deprecated)
    • GearmanJob::fail - Send fail status (deprecated)
    • GearmanJob::functionName - Get function name
    • GearmanJob::handle - Get the job handle
    • GearmanJob::returnCode - Get last return code
    • GearmanJob::sendComplete - Send the result and complete status
    • GearmanJob::sendData - Send data for a running job
    • GearmanJob::sendException - Send exception for running job (exception)
    • GearmanJob::sendFail - Send fail status
    • GearmanJob::sendStatus - Send status
    • GearmanJob::sendWarning - Send a warning
    • GearmanJob::setReturn - Set a return value
    • GearmanJob::status - Send status (deprecated)
    • GearmanJob::unique - Get the unique identifier
    • GearmanJob::warning - Send a warning (deprecated)
    • GearmanJob::workload - Get workload
    • GearmanJob::workloadSize - Get size of work load
    • GearmanJob::__construct - Create a GearmanJob instance
    • GearmanTask::create - Create a task (deprecated)
    • GearmanTask::data - Get data returned for a task
    • GearmanTask::dataSize - Get the size of returned data
    • GearmanTask::function - Get associated function name (deprecated)
    • GearmanTask::functionName - Get associated function name
    • GearmanTask::isKnown - Determine if task is known
    • GearmanTask::isRunning - Test whether the task is currently running
    • GearmanTask::jobHandle - Get the job handle
    • GearmanTask::recvData - Read work or result data into a buffer for a task
    • GearmanTask::returnCode - Get the last return code
    • GearmanTask::sendData - Send data for a task (deprecated)
    • GearmanTask::sendWorkload - Send data for a task
    • GearmanTask::taskDenominator - Get completion percentage denominator
    • GearmanTask::taskNumerator - Get completion percentage numerator
    • GearmanTask::unique - Get the unique identifier for a task
    • GearmanTask::uuid - Get the unique identifier for a task (deprecated)
    • GearmanTask::__construct - Create a GearmanTask instance
    • GearmanWorker::addFunction - Register and add callback function
    • GearmanWorker::addOptions - Add worker options
    • GearmanWorker::addServer - Add a job server
    • GearmanWorker::addServers - Add job servers
    • GearmanWorker::clone - Create a copy of the worker
    • GearmanWorker::echo - Test job server response
    • GearmanWorker::error - Get the last error encountered
    • GearmanWorker::getErrno - Get errno
    • GearmanWorker::options - Get worker options
    • GearmanWorker::register - Register a function with the job server
    • GearmanWorker::removeOptions - Remove worker options
    • GearmanWorker::returnCode - Get last Gearman return code
    • GearmanWorker::setId - Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers
    • GearmanWorker::setOptions - Set worker options
    • GearmanWorker::setTimeout - Set socket I/O activity timeout
    • GearmanWorker::timeout - Get socket I/O activity timeout
    • GearmanWorker::unregister - Unregister a function name with the job servers
    • GearmanWorker::unregisterAll - Unregister all function names with the job servers
    • GearmanWorker::wait - Wait for activity from one of the job servers
    • GearmanWorker::work - Wait for and perform jobs
    • GearmanWorker::__construct - Create a GearmanWorker instance
    • Gender\Gender::connect - Connect to an external name dictionary
    • Gender\Gender::country - Get textual country representation
    • Gender\Gender::get - Get gender of a name
    • Gender\Gender::isNick - Check if the name0 is an alias of the name1
    • Gender\Gender::similarNames - Get similar names
    • Gender\Gender::__construct - Construct the Gender object
    • Generator::current - 返回当前产生的值
    • Generator::key - 返回当前产生的键
    • Generator::next - 生成器继续执行
    • Generator::rewind - 重置迭代器
    • Generator::send - 向生成器中传入一个值
    • Generator::throw - 向生成器中抛入一个异常
    • Generator::valid - 检查迭代器是否被关闭
    • Generator::__wakeup - 序列化回调
    • geoip_asnum_by_name - 获取自治系统号(ASN)
    • geoip_continent_code_by_name - 获取七大洲的大写字母简称
    • geoip_country_code3_by_name - 获取三个字母组成的国家简称
    • geoip_country_code_by_name - 获取国家代码
    • geoip_country_name_by_name - 获取国家的全称
    • geoip_database_info - 获取 GeoIP 数据库的信息
    • geoip_db_avail - GeoIP 数据库是否可用
    • geoip_db_filename - 返回 GeoIP 数据库相对应的文件名
    • geoip_db_get_all_info - 返回所有 GeoIP 数据库类型的详细信息
    • geoip_domain_by_name - 获取二级域名
    • geoip_id_by_name - 获取网络连接类型
    • geoip_isp_by_name - 获取 ISP (网络服务提供商)的名称
    • geoip_netspeedcell_by_name - 获取网络连接速度
    • geoip_org_by_name - 获取机构的名称
    • geoip_record_by_name - 返回 GeoIP 数据库中详细的城市信息
    • geoip_region_by_name - 获取国家和地区代码
    • geoip_region_name_by_code - 返回给定的国家和地区代码组合所对应的地区名称
    • geoip_setup_custom_directory - 自定义 GeoIP 数据库的目录
    • geoip_time_zone_by_country_and_region - 返回国家和地区的时区
    • getallheaders - 获取全部 HTTP 请求头信息
    • getcwd - 取得当前工作目录
    • getdate - 取得日期／时间信息
    • getenv - 获取一个环境变量的值
    • gethostbyaddr - 获取指定的IP地址对应的主机名
    • gethostbyname - 返回主机名对应的 IPv4地址。
    • gethostbynamel - 获取互联网主机名对应的 IPv4 地址列表
    • gethostname - 获取主机名
    • getimagesize - 取得图像大小
    • getimagesizefromstring - 从字符串中获取图像尺寸信息
    • getlastmod - 获取页面最后修改的时间
    • getmxrr - 获取互联网主机名对应的 MX 记录
    • getmygid - 获取当前 PHP 脚本拥有者的 GID
    • getmyinode - 获取当前脚本的索引节点（inode）
    • getmypid - 获取 PHP 进程的 ID
    • getmyuid - 获取 PHP 脚本所有者的 UID
    • getopt - 从命令行参数列表中获取选项
    • getprotobyname - Get protocol number associated with protocol name
    • getprotobynumber - Get protocol name associated with protocol number
    • getrandmax - 显示随机数最大的可能值
    • getrusage - 获取当前资源使用状况
    • getservbyname - 获取互联网服务协议对应的端口
    • getservbyport - Get Internet service which corresponds to port and protocol
    • getSession - Connect to a MySQL server
    • gettext - Lookup a message in the current domain
    • gettimeofday - 取得当前时间
    • gettype - 获取变量的类型
    • get_browser - 获取浏览器具有的功能
    • get_called_class - 后期静态绑定（"Late Static Binding"）类的名称
    • get_cfg_var - 获取 PHP 配置选项的值
    • get_class - 返回对象的类名
    • get_class_methods - 返回由类的方法名组成的数组
    • get_class_vars - 返回由类的默认属性组成的数组
    • get_current_user - 获取当前 PHP 脚本所有者名称
    • get_declared_classes - 返回由已定义类的名字所组成的数组
    • get_declared_interfaces - 返回一个数组包含所有已声明的接口
    • get_declared_traits - 返回所有已定义的 traits 的数组
    • get_defined_constants - 返回所有常量的关联数组，键是常量名，值是常量值
    • get_defined_functions - 返回所有已定义函数的数组
    • get_defined_vars - 返回由所有已定义变量所组成的数组
    • get_extension_funcs - 返回模块函数名称的数组
    • get_headers - 取得服务器响应一个 HTTP 请求所发送的所有标头
    • get_html_translation_table - 返回使用 htmlspecialchars 和 htmlentities 后的转换表
    • get_included_files - 返回被 include 和 require 文件名的 array
    • get_include_path - 获取当前的 include_path 配置选项
    • get_loaded_extensions - 返回所有编译并加载模块名的 array
    • get_magic_quotes_gpc - 获取当前 magic_quotes_gpc 的配置选项设置
    • get_magic_quotes_runtime - 获取当前 magic_quotes_runtime 配置选项的激活状态
    • get_meta_tags - 从一个文件中提取所有的 meta 标签 content 属性，返回一个数组
    • get_object_vars - 返回由对象属性组成的关联数组
    • get_parent_class - 返回对象或类的父类名
    • get_required_files - 别名 get_included_files
    • get_resources - Returns active resources
    • get_resource_id - Returns an integer identifier for the given resource
    • get_resource_type - 返回资源（resource）类型
    • glob - 寻找与模式匹配的文件路径
    • glob:// - 查找匹配的文件路径模式
    • GlobIterator::count - Get the number of directories and files
    • GlobIterator::__construct - Construct a directory using glob
    • Gmagick::addimage - Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage - Adds random noise to the image
    • Gmagick::annotateimage - Annotates an image with text
    • Gmagick::blurimage - Adds blur filter to image
    • Gmagick::borderimage - Surrounds the image with a border
    • Gmagick::charcoalimage - Simulates a charcoal drawing
    • Gmagick::chopimage - Removes a region of an image and trims
    • Gmagick::clear - Clears all resources associated to Gmagick object
    • Gmagick::commentimage - Adds a comment to your image
    • Gmagick::compositeimage - Composite one image onto another
    • Gmagick::cropimage - Extracts a region of the image
    • Gmagick::cropthumbnailimage - Creates a crop thumbnail
    • Gmagick::current - The current purpose
    • Gmagick::cyclecolormapimage - Displaces an image's colormap
    • Gmagick::deconstructimages - Returns certain pixel differences between images
    • Gmagick::despeckleimage - The despeckleimage purpose
    • Gmagick::destroy - The destroy purpose
    • Gmagick::drawimage - Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage - Enhance edges within the image
    • Gmagick::embossimage - Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage - Improves the quality of a noisy image
    • Gmagick::equalizeimage - Equalizes the image histogram
    • Gmagick::flipimage - Creates a vertical mirror image
    • Gmagick::flopimage - The flopimage purpose
    • Gmagick::frameimage - Adds a simulated three-dimensional border
    • Gmagick::gammaimage - Gamma-corrects an image
    • Gmagick::getcopyright - Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename - The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor - Returns the image background color
    • Gmagick::getimageblueprimary - Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor - Returns the image border color
    • Gmagick::getimagechanneldepth - Gets the depth for a particular image channel
    • Gmagick::getimagecolors - Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace - Gets the image colorspace
    • Gmagick::getimagecompose - Returns the composite operator associated with the image
    • Gmagick::getimagedelay - Gets the image delay
    • Gmagick::getimagedepth - Gets the depth of the image
    • Gmagick::getimagedispose - Gets the image disposal method
    • Gmagick::getimageextrema - Gets the extrema for the image
    • Gmagick::getimagefilename - Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat - Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma - Gets the image gamma
    • Gmagick::getimagegreenprimary - Returns the chromaticy green primary point
    • Gmagick::getimageheight - Returns the image height
    • Gmagick::getimagehistogram - Gets the image histogram
    • Gmagick::getimageindex - Gets the index of the current active image
    • Gmagick::getimageinterlacescheme - Gets the image interlace scheme
    • Gmagick::getimageiterations - Gets the image iterations
    • Gmagick::getimagematte - Check if the image has a matte channel
    • Gmagick::getimagemattecolor - Returns the image matte color
    • Gmagick::getimageprofile - Returns the named image profile
    • Gmagick::getimageredprimary - Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent - Gets the image rendering intent
    • Gmagick::getimageresolution - Gets the image X and Y resolution
    • Gmagick::getimagescene - Gets the image scene
    • Gmagick::getimagesignature - Generates an SHA-256 message digest
    • Gmagick::getimagetype - Gets the potential image type
    • Gmagick::getimageunits - Gets the image units of resolution
    • Gmagick::getimagewhitepoint - Returns the chromaticity white point
    • Gmagick::getimagewidth - Returns the width of the image
    • Gmagick::getpackagename - Returns the GraphicsMagick package name
    • Gmagick::getquantumdepth - Returns the Gmagick quantum depth as a string
    • Gmagick::getreleasedate - Returns the GraphicsMagick release date as a string
    • Gmagick::getsamplingfactors - Gets the horizontal and vertical sampling factor
    • Gmagick::getsize - Returns the size associated with the Gmagick object
    • Gmagick::getversion - Returns the GraphicsMagick API version
    • Gmagick::hasnextimage - Checks if the object has more images
    • Gmagick::haspreviousimage - Checks if the object has a previous image
    • Gmagick::implodeimage - Creates a new image as a copy
    • Gmagick::labelimage - Adds a label to an image
    • Gmagick::levelimage - Adjusts the levels of an image
    • Gmagick::magnifyimage - Scales an image proportionally 2x
    • Gmagick::mapimage - Replaces the colors of an image with the closest color from a reference image
    • Gmagick::medianfilterimage - Applies a digital filter
    • Gmagick::minifyimage - Scales an image proportionally to half its size
    • Gmagick::modulateimage - Control the brightness, saturation, and hue
    • Gmagick::motionblurimage - Simulates motion blur
    • Gmagick::newimage - Creates a new image
    • Gmagick::nextimage - Moves to the next image
    • Gmagick::normalizeimage - Enhances the contrast of a color image
    • Gmagick::oilpaintimage - Simulates an oil painting
    • Gmagick::previousimage - Move to the previous image in the object
    • Gmagick::profileimage - Adds or removes a profile from an image
    • Gmagick::quantizeimage - Analyzes the colors within a reference image
    • Gmagick::quantizeimages - The quantizeimages purpose
    • Gmagick::queryfontmetrics - Returns an array representing the font metrics
    • Gmagick::queryfonts - Returns the configured fonts
    • Gmagick::queryformats - Returns formats supported by Gmagick
    • Gmagick::radialblurimage - Radial blurs an image
    • Gmagick::raiseimage - Creates a simulated 3d button-like effect
    • Gmagick::read - Reads image from filename
    • Gmagick::readimage - Reads image from filename
    • Gmagick::readimageblob - Reads image from a binary string
    • Gmagick::readimagefile - The readimagefile purpose
    • Gmagick::reducenoiseimage - Smooths the contours of an image
    • Gmagick::removeimage - Removes an image from the image list
    • Gmagick::removeimageprofile - Removes the named image profile and returns it
    • Gmagick::resampleimage - Resample image to desired resolution
    • Gmagick::resizeimage - Scales an image
    • Gmagick::rollimage - Offsets an image
    • Gmagick::rotateimage - Rotates an image
    • Gmagick::scaleimage - Scales the size of an image
    • Gmagick::separateimagechannel - Separates a channel from the image
    • Gmagick::setCompressionQuality - Sets the object's default compression quality
    • Gmagick::setfilename - Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor - Sets the image background color
    • Gmagick::setimageblueprimary - Sets the image chromaticity blue primary point
    • Gmagick::setimagebordercolor - Sets the image border color
    • Gmagick::setimagechanneldepth - Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace - Sets the image colorspace
    • Gmagick::setimagecompose - Sets the image composite operator
    • Gmagick::setimagedelay - Sets the image delay
    • Gmagick::setimagedepth - Sets the image depth
    • Gmagick::setimagedispose - Sets the image disposal method
    • Gmagick::setimagefilename - Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat - Sets the format of a particular image
    • Gmagick::setimagegamma - Sets the image gamma
    • Gmagick::setimagegreenprimary - Sets the image chromaticity green primary point
    • Gmagick::setimageindex - Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme - Sets the interlace scheme of the image
    • Gmagick::setimageiterations - Sets the image iterations
    • Gmagick::setimageprofile - Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary - Sets the image chromaticity red primary point
    • Gmagick::setimagerenderingintent - Sets the image rendering intent
    • Gmagick::setimageresolution - Sets the image resolution
    • Gmagick::setimagescene - Sets the image scene
    • Gmagick::setimagetype - Sets the image type
    • Gmagick::setimageunits - Sets the image units of resolution
    • Gmagick::setimagewhitepoint - Sets the image chromaticity white point
    • Gmagick::setsamplingfactors - Sets the image sampling factors
    • Gmagick::setsize - Sets the size of the Gmagick object
    • Gmagick::shearimage - Creating a parallelogram
    • Gmagick::solarizeimage - Applies a solarizing effect to the image
    • Gmagick::spreadimage - Randomly displaces each pixel in a block
    • Gmagick::stripimage - Strips an image of all profiles and comments
    • Gmagick::swirlimage - Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage - Changes the size of an image
    • Gmagick::trimimage - Remove edges from the image
    • Gmagick::write - 别名 Gmagick::writeimage
    • Gmagick::writeimage - Writes an image to the specified filename
    • Gmagick::__construct - The Gmagick constructor
    • GmagickDraw::annotate - Draws text on the image
    • GmagickDraw::arc - Draws an arc
    • GmagickDraw::bezier - Draws a bezier curve
    • GmagickDraw::ellipse - Draws an ellipse on the image
    • GmagickDraw::getfillcolor - Returns the fill color
    • GmagickDraw::getfillopacity - Returns the opacity used when drawing
    • GmagickDraw::getfont - Returns the font
    • GmagickDraw::getfontsize - Returns the font pointsize
    • GmagickDraw::getfontstyle - Returns the font style
    • GmagickDraw::getfontweight - Returns the font weight
    • GmagickDraw::getstrokecolor - Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity - Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth - Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration - Returns the text decoration
    • GmagickDraw::gettextencoding - Returns the code set used for text annotations
    • GmagickDraw::line - The line purpose
    • GmagickDraw::point - Draws a point
    • GmagickDraw::polygon - Draws a polygon
    • GmagickDraw::polyline - Draws a polyline
    • GmagickDraw::rectangle - Draws a rectangle
    • GmagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle - Draws a rounded rectangle
    • GmagickDraw::scale - Adjusts the scaling factor
    • GmagickDraw::setfillcolor - Sets the fill color to be used for drawing filled objects
    • GmagickDraw::setfillopacity - The setfillopacity purpose
    • GmagickDraw::setfont - Sets the fully-specified font to use when annotating with text
    • GmagickDraw::setfontsize - Sets the font pointsize to use when annotating with text
    • GmagickDraw::setfontstyle - Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight - Sets the font weight
    • GmagickDraw::setstrokecolor - Sets the color used for stroking object outlines
    • GmagickDraw::setstrokeopacity - Specifies the opacity of stroked object outlines
    • GmagickDraw::setstrokewidth - Sets the width of the stroke used to draw object outlines
    • GmagickDraw::settextdecoration - Specifies a decoration
    • GmagickDraw::settextencoding - Specifies the text code set
    • GmagickPixel::getcolor - Returns the color
    • GmagickPixel::getcolorcount - Returns the color count associated with this color
    • GmagickPixel::getcolorvalue - Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor - Sets the color
    • GmagickPixel::setcolorvalue - Sets the normalized value of one of the channels
    • GmagickPixel::__construct - The GmagickPixel constructor
    • gmdate - 格式化一个 GMT/UTC 日期／时间
    • gmmktime - 取得 GMT 日期的 UNIX 时间戳
    • gmp_abs - Absolute value
    • gmp_add - Add numbers
    • gmp_and - Bitwise AND
    • gmp_binomial - Calculates binomial coefficient
    • gmp_clrbit - Clear bit
    • gmp_cmp - Compare numbers
    • gmp_com - Calculates one's complement
    • gmp_div - 别名 gmp_div_q
    • gmp_divexact - Exact division of numbers
    • gmp_div_q - Divide numbers
    • gmp_div_qr - Divide numbers and get quotient and remainder
    • gmp_div_r - Remainder of the division of numbers
    • gmp_export - Export to a binary string
    • gmp_fact - Factorial
    • gmp_gcd - Calculate GCD
    • gmp_gcdext - Calculate GCD and multipliers
    • gmp_hamdist - Hamming distance
    • gmp_import - Import from a binary string
    • gmp_init - Create GMP number
    • gmp_intval - Convert GMP number to integer
    • gmp_invert - Inverse by modulo
    • gmp_jacobi - Jacobi symbol
    • gmp_kronecker - Kronecker symbol
    • gmp_lcm - Calculate LCM
    • gmp_legendre - Legendre symbol
    • gmp_mod - Modulo operation
    • gmp_mul - Multiply numbers
    • gmp_neg - Negate number
    • gmp_nextprime - Find next prime number
    • gmp_or - Bitwise OR
    • gmp_perfect_power - Perfect power check
    • gmp_perfect_square - Perfect square check
    • gmp_popcount - Population count
    • gmp_pow - Raise number into power
    • gmp_powm - Raise number into power with modulo
    • gmp_prob_prime - Check if number is "probably prime"
    • gmp_random - Random number
    • gmp_random_bits - Random number
    • gmp_random_range - Random number
    • gmp_random_seed - Sets the RNG seed
    • gmp_root - Take the integer part of nth root
    • gmp_rootrem - Take the integer part and remainder of nth root
    • gmp_scan0 - Scan for 0
    • gmp_scan1 - Scan for 1
    • gmp_setbit - Set bit
    • gmp_sign - Sign of number
    • gmp_sqrt - Calculate square root
    • gmp_sqrtrem - Square root with remainder
    • gmp_strval - Convert GMP number to string
    • gmp_sub - Subtract numbers
    • gmp_testbit - Tests if a bit is set
    • gmp_xor - Bitwise XOR
    • gmstrftime - 根据区域设置格式化 GMT/UTC 时间／日期
    • gnupg_adddecryptkey - Add a key for decryption
    • gnupg_addencryptkey - Add a key for encryption
    • gnupg_addsignkey - Add a key for signing
    • gnupg_cleardecryptkeys - Removes all keys which were set for decryption before
    • gnupg_clearencryptkeys - Removes all keys which were set for encryption before
    • gnupg_clearsignkeys - Removes all keys which were set for signing before
    • gnupg_decrypt - Decrypts a given text
    • gnupg_decryptverify - Decrypts and verifies a given text
    • gnupg_encrypt - Encrypts a given text
    • gnupg_encryptsign - Encrypts and signs a given text
    • gnupg_export - Exports a key
    • gnupg_geterror - Returns the errortext, if a function fails
    • gnupg_getprotocol - Returns the currently active protocol for all operations
    • gnupg_import - Imports a key
    • gnupg_init - Initialize a connection
    • gnupg_keyinfo - Returns an array with information about all keys that matches the given pattern
    • gnupg_setarmor - Toggle armored output
    • gnupg_seterrormode - Sets the mode for error_reporting
    • gnupg_setsignmode - Sets the mode for signing
    • gnupg_sign - Signs a given text
    • gnupg_verify - Verifies a signed text
    • grapheme_extract - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
    • grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
    • grapheme_strlen - Get string length in grapheme units
    • grapheme_strpos - Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack
    • grapheme_substr - Return part of a string
    • GregorianToJD - 转变一个Gregorian历法日期到Julian Day计数
    • gzclose - Close an open gz-file pointer
    • gzcompress - Compress a string
    • gzdecode - Decodes a gzip compressed string
    • gzdeflate - Deflate a string
    • gzencode - Create a gzip compressed string
    • gzeof - Test for EOF on a gz-file pointer
    • gzfile - Read entire gz-file into an array
    • gzgetc - Get character from gz-file pointer
    • gzgets - Get line from file pointer
    • gzgetss - Get line from gz-file pointer and strip HTML tags
    • gzinflate - Inflate a deflated string
    • gzopen - Open gz-file
    • gzpassthru - Output all remaining data on a gz-file pointer
    • gzputs - 别名 gzwrite
    • gzread - Binary-safe gz-file read
    • gzrewind - Rewind the position of a gz-file pointer
    • gzseek - Seek on a gz-file pointer
    • gztell - Tell gz-file pointer read/write position
    • gzuncompress - Uncompress a compressed string
    • gzwrite - Binary-safe gz-file write
  • h
    • hash - 生成哈希值 （消息摘要）
    • hash_algos - 返回已注册的哈希算法列表
    • hash_copy - 拷贝哈希运算上下文
    • hash_equals - 可防止时序攻击的字符串比较
    • hash_file - 给指定文件的内容生成哈希值
    • hash_final - 结束增量哈希，并且返回摘要结果
    • hash_hkdf - Generate a HKDF key derivation of a supplied key input
    • hash_hmac - 使用 HMAC 方法生成带有密钥的哈希值
    • hash_hmac_algos - Return a list of registered hashing algorithms suitable for hash_hmac
    • hash_hmac_file - 使用 HMAC 方法和给定文件的内容生成带密钥的哈希值
    • hash_init - 初始化增量哈希运算上下文
    • hash_pbkdf2 - 生成所提供密码的 PBKDF2 密钥导出
    • hash_update - 向活跃的哈希运算上下文中填充数据
    • hash_update_file - 从文件向活跃的哈希运算上下文中填充数据
    • hash_update_stream - 从打开的流向活跃的哈希运算上下文中填充数据
    • header - 发送原生 HTTP 头
    • headers_list - 返回已发送的 HTTP 响应头（或准备发送的）
    • headers_sent - 检测 HTTP 头是否已经发送
    • header_register_callback - 调用一个 header 函数
    • header_remove - 删除之前设置的 HTTP 头
    • hebrev - 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）
    • hebrevc - 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew），并且转换换行符
    • hex2bin - 转换十六进制字符串为二进制字符串
    • hexdec - 十六进制转换为十进制
    • highlight_file - 语法高亮一个文件
    • highlight_string - 字符串的语法高亮
    • hrtime - 获取系统的高精度时间
    • HRTime\PerformanceCounter::getFrequency - Timer frequency in ticks per second
    • HRTime\PerformanceCounter::getTicks - Current ticks from the system
    • HRTime\PerformanceCounter::getTicksSince - Ticks elapsed since the given value
    • HRTime\StopWatch::getElapsedTicks - Get elapsed ticks for all intervals
    • HRTime\StopWatch::getElapsedTime - Get elapsed time for all intervals
    • HRTime\StopWatch::getLastElapsedTicks - Get elapsed ticks for the last interval
    • HRTime\StopWatch::getLastElapsedTime - Get elapsed time for the last interval
    • HRTime\StopWatch::isRunning - Whether the measurement is running
    • HRTime\StopWatch::start - Start time measurement
    • HRTime\StopWatch::stop - Stop time measurement
    • htmlentities - 将字符转换为 HTML 转义字符
    • htmlspecialchars - 将特殊字符转换为 HTML 实体
    • htmlspecialchars_decode - 将特殊的 HTML 实体转换回普通字符
    • html_entity_decode - Convert HTML entities to their corresponding characters
    • http:// - 访问 HTTP(s) 网址
    • HTTP context 选项 - HTTP context 的选项列表
    • http_build_query - 生成 URL-encode 之后的请求字符串
    • http_response_code - 获取/设置响应的 HTTP 状态码
    • hypot - 计算一直角三角形的斜边长度
  • i
    • ibase_add_user - Add a user to a security database
    • ibase_affected_rows - Return the number of rows that were affected by the previous query
    • ibase_backup - Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add - Add data into a newly created blob
    • ibase_blob_cancel - Cancel creating blob
    • ibase_blob_close - Close blob
    • ibase_blob_create - Create a new blob for adding data
    • ibase_blob_echo - Output blob contents to browser
    • ibase_blob_get - Get len bytes data from open blob
    • ibase_blob_import - Create blob, copy file in it, and close it
    • ibase_blob_info - Return blob length and other useful info
    • ibase_blob_open - Open blob for retrieving data parts
    • ibase_close - Close a connection to an InterBase database
    • ibase_commit - Commit a transaction
    • ibase_commit_ret - Commit a transaction without closing it
    • ibase_connect - Open a connection to a database
    • ibase_db_info - Request statistics about a database
    • ibase_delete_user - Delete a user from a security database
    • ibase_drop_db - Drops a database
    • ibase_errcode - Return an error code
    • ibase_errmsg - Return error messages
    • ibase_execute - Execute a previously prepared query
    • ibase_fetch_assoc - Fetch a result row from a query as an associative array
    • ibase_fetch_object - Get an object from a InterBase database
    • ibase_fetch_row - Fetch a row from an InterBase database
    • ibase_field_info - Get information about a field
    • ibase_free_event_handler - Cancels a registered event handler
    • ibase_free_query - Free memory allocated by a prepared query
    • ibase_free_result - Free a result set
    • ibase_gen_id - Increments the named generator and returns its new value
    • ibase_maintain_db - Execute a maintenance command on the database server
    • ibase_modify_user - Modify a user to a security database
    • ibase_name_result - Assigns a name to a result set
    • ibase_num_fields - Get the number of fields in a result set
    • ibase_num_params - Return the number of parameters in a prepared query
    • ibase_param_info - Return information about a parameter in a prepared query
    • ibase_pconnect - Open a persistent connection to an InterBase database
    • ibase_prepare - Prepare a query for later binding of parameter placeholders and execution
    • ibase_query - Execute a query on an InterBase database
    • ibase_restore - Initiates a restore task in the service manager and returns immediately
    • ibase_rollback - Roll back a transaction
    • ibase_rollback_ret - Roll back a transaction without closing it
    • ibase_server_info - Request information about a database server
    • ibase_service_attach - Connect to the service manager
    • ibase_service_detach - Disconnect from the service manager
    • ibase_set_event_handler - Register a callback function to be called when events are posted
    • ibase_trans - Begin a transaction
    • ibase_wait_event - Wait for an event to be posted by the database
    • iconv - 字符串按要求的字符编码来转换
    • iconv_get_encoding - 获取 iconv 扩展的内部配置变量
    • iconv_mime_decode - 解码一个MIME头字段
    • iconv_mime_decode_headers - 一次性解码多个 MIME 头字段
    • iconv_mime_encode - Composes a MIME header field
    • iconv_set_encoding - 为字符编码转换设定当前设置
    • iconv_strlen - 返回字符串的字符数统计
    • iconv_strpos - Finds position of first occurrence of a needle within a haystack
    • iconv_strrpos - Finds the last occurrence of a needle within a haystack
    • iconv_substr - 截取字符串的部分
    • idate - 将本地时间日期格式化为整数
    • idn_to_ascii - 将域名转换为 IDNA ASCII 格式
    • idn_to_utf8 - 将域名从 IDNA ASCII 转换为 Unicode
    • ignore_user_abort - 设置客户端断开连接时是否中断脚本的执行
    • image2wbmp - 以 WBMP 格式将图像输出到浏览器或文件
    • imageaffine - 返回经过仿射变换后的图像，剪切区域可选
    • imageaffinematrixconcat - Concatenate two affine transformation matrices
    • imageaffinematrixget - Get an affine transformation matrix
    • imagealphablending - 设定图像的混色模式
    • imageantialias - 是否使用抗锯齿（antialias）功能
    • imagearc - 画椭圆弧
    • imagebmp - Output a BMP image to browser or file
    • imagechar - 水平地画一个字符
    • imagecharup - 垂直地画一个字符
    • imagecolorallocate - 为一幅图像分配颜色
    • imagecolorallocatealpha - 为一幅图像分配颜色 + alpha
    • imagecolorat - 取得某像素的颜色索引值
    • imagecolorclosest - 取得与指定的颜色最接近的颜色的索引值
    • imagecolorclosestalpha - 取得与指定的颜色加透明度最接近的颜色
    • imagecolorclosesthwb - 取得与给定颜色最接近的色度的黑白色的索引
    • imagecolordeallocate - 取消图像颜色的分配
    • imagecolorexact - 取得指定颜色的索引值
    • imagecolorexactalpha - 取得指定的颜色加透明度的索引值
    • imagecolormatch - 使一个图像中调色板版本的颜色与真彩色版本更能匹配
    • imagecolorresolve - 取得指定颜色的索引值或有可能得到的最接近的替代值
    • imagecolorresolvealpha - 取得指定颜色 + alpha 的索引值或有可能得到的最接近的替代值
    • imagecolorset - 给指定调色板索引设定颜色
    • imagecolorsforindex - 取得某索引的颜色
    • imagecolorstotal - 取得一幅图像的调色板中颜色的数目
    • imagecolortransparent - 将某个颜色定义为透明色
    • imageconvolution - 用系数 div 和 offset 申请一个 3x3 的卷积矩阵
    • imagecopy - 拷贝图像的一部分
    • imagecopymerge - 拷贝并合并图像的一部分
    • imagecopymergegray - 用灰度拷贝并合并图像的一部分
    • imagecopyresampled - 重采样拷贝部分图像并调整大小
    • imagecopyresized - 拷贝部分图像并调整大小
    • imagecreate - 新建一个基于调色板的图像
    • imagecreatefrombmp - 由文件或 URL 创建一个新图象。
    • imagecreatefromgd - 从 GD 文件或 URL 新建一图像
    • imagecreatefromgd2 - 从 GD2 文件或 URL 新建一图像
    • imagecreatefromgd2part - 从给定的 GD2 文件或 URL 中的部分新建一图像
    • imagecreatefromgif - 由文件或 URL 创建一个新图象。
    • imagecreatefromjpeg - 由文件或 URL 创建一个新图象。
    • imagecreatefrompng - 由文件或 URL 创建一个新图象。
    • imagecreatefromstring - 从字符串中的图像流新建一图像
    • imagecreatefromwbmp - 由文件或 URL 创建一个新图象。
    • imagecreatefromwebp - 由文件或 URL 创建一个新图象。
    • imagecreatefromxbm - 由文件或 URL 创建一个新图象。
    • imagecreatefromxpm - 由文件或 URL 创建一个新图象。
    • imagecreatetruecolor - 新建一个真彩色图像
    • imagecrop - Crop an image to the given rectangle
    • imagecropauto - Crop an image automatically using one of the available modes
    • imagedashedline - 画一虚线
    • imagedestroy - 销毁一图像
    • imageellipse - 画一个椭圆
    • imagefill - 区域填充
    • imagefilledarc - 画一椭圆弧且填充
    • imagefilledellipse - 画一椭圆并填充
    • imagefilledpolygon - 画一多边形并填充
    • imagefilledrectangle - 画一矩形并填充
    • imagefilltoborder - 区域填充到指定颜色的边界为止
    • imagefilter - 对图像使用过滤器
    • imageflip - Flips an image using a given mode
    • imagefontheight - 取得字体高度
    • imagefontwidth - 取得字体宽度
    • imageftbbox - 给出一个使用 FreeType 2 字体的文本框
    • imagefttext - 使用 FreeType 2 字体将文本写入图像
    • imagegammacorrect - 对 GD 图像应用 gamma 修正
    • imagegd - 将 GD 图像输出到浏览器或文件
    • imagegd2 - 将 GD2 图像输出到浏览器或文件
    • imagegetclip - Get the clipping rectangle
    • imagegetinterpolation - Get the interpolation method
    • imagegif - 输出图象到浏览器或文件。
    • imagegrabscreen - Captures the whole screen
    • imagegrabwindow - Captures a window
    • imageinterlace - 启用或禁用隔行扫描
    • imageistruecolor - 检查图像是否为真彩色图像
    • imagejpeg - 输出图象到浏览器或文件。
    • imagelayereffect - 设定 alpha 混色标志以使用绑定的 libgd 分层效果
    • imageline - 画一条线段
    • imageloadfont - 载入一新字体
    • imageopenpolygon - Draws an open polygon
    • imagepalettecopy - 将调色板从一幅图像拷贝到另一幅
    • imagepalettetotruecolor - Converts a palette based image to true color
    • imagepng - 以 PNG 格式将图像输出到浏览器或文件
    • imagepolygon - 画一个多边形
    • imagerectangle - 画一个矩形
    • imageresolution - Get or set the resolution of the image
    • imagerotate - 用给定角度旋转图像
    • imagesavealpha - 设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息（与单一透明色相反）
    • imagescale - Scale an image using the given new width and height
    • imagesetbrush - 设定画线用的画笔图像
    • imagesetclip - Set the clipping rectangle
    • imagesetinterpolation - Set the interpolation method
    • imagesetpixel - 画一个单一像素
    • imagesetstyle - 设定画线的风格
    • imagesetthickness - 设定画线的宽度
    • imagesettile - 设定用于填充的贴图
    • imagestring - 水平地画一行字符串
    • imagestringup - 垂直地画一行字符串
    • imagesx - 取得图像宽度
    • imagesy - 取得图像高度
    • imagetruecolortopalette - 将真彩色图像转换为调色板图像
    • imagettfbbox - 取得使用 TrueType 字体的文本的范围
    • imagettftext - 用 TrueType 字体向图像写入文本
    • imagetypes - 返回当前 PHP 版本所支持的图像类型
    • imagewbmp - 以 WBMP 格式将图像输出到浏览器或文件
    • imagewebp - 将 WebP 格式的图像输出到浏览器或文件
    • imagexbm - 将 XBM 图像输出到浏览器或文件
    • image_type_to_extension - 取得图像类型的文件后缀
    • image_type_to_mime_type - 取得 getimagesize，exif_read_data，exif_thumbnail，exif_imagetype 所返回的图像类型的 MIME 类型
    • Imagick::adaptiveBlurImage - Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage - Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage - Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage - Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage - Adds new image to Imagick object image list
    • Imagick::addNoiseImage - Adds random noise to the image
    • Imagick::affineTransformImage - Transforms an image
    • Imagick::animateImages - Animates an image or images
    • Imagick::annotateImage - Annotates an image with text
    • Imagick::appendImages - Append a set of images
    • Imagick::autoLevelImage - Description
    • Imagick::averageImages - Average a set of images
    • Imagick::blackThresholdImage - Forces all pixels below the threshold into black
    • Imagick::blueShiftImage - Description
    • Imagick::blurImage - Adds blur filter to image
    • Imagick::borderImage - Surrounds the image with a border
    • Imagick::brightnessContrastImage - Description
    • Imagick::charcoalImage - Simulates a charcoal drawing
    • Imagick::chopImage - Removes a region of an image and trims
    • Imagick::clampImage - Description
    • Imagick::clear - Clears all resources associated to Imagick object
    • Imagick::clipImage - Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath - Description
    • Imagick::clipPathImage - Clips along the named paths from the 8BIM profile
    • Imagick::clone - Makes an exact copy of the Imagick object
    • Imagick::clutImage - Replaces colors in the image
    • Imagick::coalesceImages - Composites a set of images
    • Imagick::colorFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::colorizeImage - Blends the fill color with the image
    • Imagick::colorMatrixImage - Description
    • Imagick::combineImages - Combines one or more images into a single image
    • Imagick::commentImage - Adds a comment to your image
    • Imagick::compareImageChannels - Returns the difference in one or more images
    • Imagick::compareImageLayers - Returns the maximum bounding region between images
    • Imagick::compareImages - Compares an image to a reconstructed image
    • Imagick::compositeImage - 把一张图合并到一张图
    • Imagick::contrastImage - Change the contrast of the image
    • Imagick::contrastStretchImage - Enhances the contrast of a color image
    • Imagick::convolveImage - Applies a custom convolution kernel to the image
    • Imagick::count - Get the number of images
    • Imagick::cropImage - 截图图片的一块区域
    • Imagick::cropThumbnailImage - 创建缩略图
    • Imagick::current - Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage - Displaces an image's colormap
    • Imagick::decipherImage - Deciphers an image
    • Imagick::deconstructImages - Returns certain pixel differences between images
    • Imagick::deleteImageArtifact - Delete image artifact
    • Imagick::deleteImageProperty - Description
    • Imagick::deskewImage - Removes skew from the image
    • Imagick::despeckleImage - Reduces the speckle noise in an image
    • Imagick::destroy - Destroys the Imagick object
    • Imagick::displayImage - Displays an image
    • Imagick::displayImages - Displays an image or image sequence
    • Imagick::distortImage - Distorts an image using various distortion methods
    • Imagick::drawImage - 把 ImagickDraw 对象渲染到当前图片上
    • Imagick::edgeImage - Enhance edges within the image
    • Imagick::embossImage - Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage - Enciphers an image
    • Imagick::enhanceImage - Improves the quality of a noisy image
    • Imagick::equalizeImage - Equalizes the image histogram
    • Imagick::evaluateImage - Applies an expression to an image
    • Imagick::exportImagePixels - Exports raw image pixels
    • Imagick::extentImage - Set image size
    • Imagick::filter - Description
    • Imagick::flattenImages - Merges a sequence of images
    • Imagick::flipImage - Creates a vertical mirror image
    • Imagick::floodFillPaintImage - Changes the color value of any pixel that matches target
    • Imagick::flopImage - Creates a vertical mirror image
    • Imagick::forwardFourierTransformImage - Description
    • Imagick::frameImage - Adds a simulated three-dimensional border
    • Imagick::functionImage - Applies a function on the image
    • Imagick::fxImage - Evaluate expression for each pixel in the image
    • Imagick::gammaImage - Gamma-corrects an image
    • Imagick::gaussianBlurImage - Blurs an image
    • Imagick::getColorspace - Gets the colorspace
    • Imagick::getCompression - Gets the object compression type
    • Imagick::getCompressionQuality - Gets the object compression quality
    • Imagick::getCopyright - Returns the ImageMagick API copyright as a string
    • Imagick::getFilename - The filename associated with an image sequence
    • Imagick::getFont - Gets font
    • Imagick::getFormat - Returns the format of the Imagick object
    • Imagick::getGravity - Gets the gravity
    • Imagick::getHomeURL - Returns the ImageMagick home URL
    • Imagick::getImage - Returns a new Imagick object
    • Imagick::getImageAlphaChannel - 获取图像的 alpha 通道
    • Imagick::getImageArtifact - Get image artifact
    • Imagick::getImageAttribute - Description
    • Imagick::getImageBackgroundColor - Returns the image background color
    • Imagick::getImageBlob - Returns the image sequence as a blob
    • Imagick::getImageBluePrimary - Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor - Returns the image border color
    • Imagick::getImageChannelDepth - Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion - Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions - Gets channel distortions
    • Imagick::getImageChannelExtrema - Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis - The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean - Gets the mean and standard deviation
    • Imagick::getImageChannelRange - Gets channel range
    • Imagick::getImageChannelStatistics - Returns statistics for each channel in the image
    • Imagick::getImageClipMask - Gets image clip mask
    • Imagick::getImageColormapColor - Returns the color of the specified colormap index
    • Imagick::getImageColors - Gets the number of unique colors in the image
    • Imagick::getImageColorspace - Gets the image colorspace
    • Imagick::getImageCompose - Returns the composite operator associated with the image
    • Imagick::getImageCompression - Gets the current image's compression type
    • Imagick::getImageCompressionQuality - Gets the current image's compression quality
    • Imagick::getImageDelay - Gets the image delay
    • Imagick::getImageDepth - Gets the image depth
    • Imagick::getImageDispose - Gets the image disposal method
    • Imagick::getImageDistortion - Compares an image to a reconstructed image
    • Imagick::getImageExtrema - Gets the extrema for the image
    • Imagick::getImageFilename - Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat - Returns the format of a particular image in a sequence
    • Imagick::getImageGamma - Gets the image gamma
    • Imagick::getImageGeometry - Gets the width and height as an associative array
    • Imagick::getImageGravity - Gets the image gravity
    • Imagick::getImageGreenPrimary - Returns the chromaticy green primary point
    • Imagick::getImageHeight - Returns the image height
    • Imagick::getImageHistogram - Gets the image histogram
    • Imagick::getImageIndex - Gets the index of the current active image
    • Imagick::getImageInterlaceScheme - Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod - Returns the interpolation method
    • Imagick::getImageIterations - Gets the image iterations
    • Imagick::getImageLength - Returns the image length in bytes
    • Imagick::getImageMatte - Return if the image has a matte channel
    • Imagick::getImageMatteColor - Returns the image matte color
    • Imagick::getImageMimeType - Description
    • Imagick::getImageOrientation - Gets the image orientation
    • Imagick::getImagePage - Returns the page geometry
    • Imagick::getImagePixelColor - Returns the color of the specified pixel
    • Imagick::getImageProfile - Returns the named image profile
    • Imagick::getImageProfiles - Returns the image profiles
    • Imagick::getImageProperties - Returns the image properties
    • Imagick::getImageProperty - Returns the named image property
    • Imagick::getImageRedPrimary - Returns the chromaticity red primary point
    • Imagick::getImageRegion - Extracts a region of the image
    • Imagick::getImageRenderingIntent - Gets the image rendering intent
    • Imagick::getImageResolution - 获取图像的x,y轴分辨率
    • Imagick::getImagesBlob - Returns all image sequences as a blob
    • Imagick::getImageScene - Gets the image scene
    • Imagick::getImageSignature - Generates an SHA-256 message digest
    • Imagick::getImageSize - Returns the image length in bytes
    • Imagick::getImageTicksPerSecond - Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity - Gets the image total ink density
    • Imagick::getImageType - Gets the potential image type
    • Imagick::getImageUnits - 获取图像的分辨率单位
    • Imagick::getImageVirtualPixelMethod - Returns the virtual pixel method
    • Imagick::getImageWhitePoint - Returns the chromaticity white point
    • Imagick::getImageWidth - Returns the image width
    • Imagick::getInterlaceScheme - Gets the object interlace scheme
    • Imagick::getIteratorIndex - Gets the index of the current active image
    • Imagick::getNumberImages - Returns the number of images in the object
    • Imagick::getOption - Returns a value associated with the specified key
    • Imagick::getPackageName - Returns the ImageMagick package name
    • Imagick::getPage - Returns the page geometry
    • Imagick::getPixelIterator - Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator - Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize - Gets point size
    • Imagick::getQuantum - Description
    • Imagick::getQuantumDepth - Gets the quantum depth
    • Imagick::getQuantumRange - Returns the Imagick quantum range
    • Imagick::getRegistry - Description
    • Imagick::getReleaseDate - Returns the ImageMagick release date
    • Imagick::getResource - Returns the specified resource's memory usage
    • Imagick::getResourceLimit - Returns the specified resource limit
    • Imagick::getSamplingFactors - Gets the horizontal and vertical sampling factor
    • Imagick::getSize - Returns the size associated with the Imagick object
    • Imagick::getSizeOffset - Returns the size offset
    • Imagick::getVersion - Returns the ImageMagick API version
    • Imagick::haldClutImage - Replaces colors in the image
    • Imagick::hasNextImage - Checks if the object has more images
    • Imagick::hasPreviousImage - Checks if the object has a previous image
    • Imagick::identifyFormat - Description
    • Imagick::identifyImage - Identifies an image and fetches attributes
    • Imagick::implodeImage - Creates a new image as a copy
    • Imagick::importImagePixels - Imports image pixels
    • Imagick::inverseFourierTransformImage - Description
    • Imagick::labelImage - Adds a label to an image
    • Imagick::levelImage - Adjusts the levels of an image
    • Imagick::linearStretchImage - Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage - Animates an image or images
    • Imagick::listRegistry - Description
    • Imagick::magnifyImage - Scales an image proportionally 2x
    • Imagick::mapImage - Replaces the colors of an image with the closest color from a reference image
    • Imagick::matteFloodfillImage - Changes the transparency value of a color
    • Imagick::medianFilterImage - Applies a digital filter
    • Imagick::mergeImageLayers - Merges image layers
    • Imagick::minifyImage - Scales an image proportionally to half its size
    • Imagick::modulateImage - Control the brightness, saturation, and hue
    • Imagick::montageImage - Creates a composite image
    • Imagick::morphImages - Method morphs a set of images
    • Imagick::morphology - Description
    • Imagick::mosaicImages - Forms a mosaic from images
    • Imagick::motionBlurImage - Simulates motion blur
    • Imagick::negateImage - Negates the colors in the reference image
    • Imagick::newImage - 创建一张图片
    • Imagick::newPseudoImage - Creates a new image
    • Imagick::nextImage - Moves to the next image
    • Imagick::normalizeImage - Enhances the contrast of a color image
    • Imagick::oilPaintImage - Simulates an oil painting
    • Imagick::opaquePaintImage - Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers - Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage - Performs an ordered dither
    • Imagick::paintFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage - Change any pixel that matches color
    • Imagick::paintTransparentImage - Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage - Fetch basic attributes about the image
    • Imagick::pingImageBlob - Quickly fetch attributes
    • Imagick::pingImageFile - Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage - Simulates a Polaroid picture
    • Imagick::posterizeImage - Reduces the image to a limited number of color level
    • Imagick::previewImages - Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage - Move to the previous image in the object
    • Imagick::profileImage - Adds or removes a profile from an image
    • Imagick::quantizeImage - Analyzes the colors within a reference image
    • Imagick::quantizeImages - Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics - Returns an array representing the font metrics
    • Imagick::queryFonts - Returns the configured fonts
    • Imagick::queryFormats - Returns formats supported by Imagick
    • Imagick::radialBlurImage - Radial blurs an image
    • Imagick::raiseImage - Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage - Creates a high-contrast, two-color image
    • Imagick::readImage - Reads image from filename
    • Imagick::readImageBlob - 从二进制字符串里读取图片
    • Imagick::readImageFile - Reads image from open filehandle
    • Imagick::readimages - Description
    • Imagick::recolorImage - Recolors image
    • Imagick::reduceNoiseImage - Smooths the contours of an image
    • Imagick::remapImage - Remaps image colors
    • Imagick::removeImage - Removes an image from the image list
    • Imagick::removeImageProfile - Removes the named image profile and returns it
    • Imagick::render - Renders all preceding drawing commands
    • Imagick::resampleImage - Resample image to desired resolution
    • Imagick::resetImagePage - Reset image page
    • Imagick::resizeImage - Scales an image
    • Imagick::rollImage - Offsets an image
    • Imagick::rotateImage - Rotates an image
    • Imagick::rotationalBlurImage - Description
    • Imagick::roundCorners - Rounds image corners
    • Imagick::sampleImage - Scales an image with pixel sampling
    • Imagick::scaleImage - Scales the size of an image
    • Imagick::segmentImage - Segments an image
    • Imagick::selectiveBlurImage - Description
    • Imagick::separateImageChannel - Separates a channel from the image
    • Imagick::sepiaToneImage - Sepia tones an image
    • Imagick::setBackgroundColor - Sets the object's default background color
    • Imagick::setColorspace - Set colorspace
    • Imagick::setCompression - Sets the object's default compression type
    • Imagick::setCompressionQuality - Sets the object's default compression quality
    • Imagick::setFilename - Sets the filename before you read or write the image
    • Imagick::setFirstIterator - Sets the Imagick iterator to the first image
    • Imagick::setFont - Sets font
    • Imagick::setFormat - Sets the format of the Imagick object
    • Imagick::setGravity - Sets the gravity
    • Imagick::setImage - Replaces image in the object
    • Imagick::setImageAlphaChannel - Sets image alpha channel
    • Imagick::setImageArtifact - Set image artifact
    • Imagick::setImageAttribute - Description
    • Imagick::setImageBackgroundColor - Sets the image background color
    • Imagick::setImageBias - Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum - Description
    • Imagick::setImageBluePrimary - Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor - Sets the image border color
    • Imagick::setImageChannelDepth - Sets the depth of a particular image channel
    • Imagick::setImageClipMask - Sets image clip mask
    • Imagick::setImageColormapColor - Sets the color of the specified colormap index
    • Imagick::setImageColorspace - Sets the image colorspace
    • Imagick::setImageCompose - Sets the image composite operator
    • Imagick::setImageCompression - 设置图片压缩的类型
    • Imagick::setImageCompressionQuality - 设置图片压缩的质量
    • Imagick::setImageDelay - Sets the image delay
    • Imagick::setImageDepth - Sets the image depth
    • Imagick::setImageDispose - Sets the image disposal method
    • Imagick::setImageExtent - Sets the image size
    • Imagick::setImageFilename - Sets the filename of a particular image
    • Imagick::setImageFormat - 为图片设置指定的格式
    • Imagick::setImageGamma - Sets the image gamma
    • Imagick::setImageGravity - Sets the image gravity
    • Imagick::setImageGreenPrimary - Sets the image chromaticity green primary point
    • Imagick::setImageIndex - Set the iterator position
    • Imagick::setImageInterlaceScheme - Sets the image compression
    • Imagick::setImageInterpolateMethod - Sets the image interpolate pixel method
    • Imagick::setImageIterations - Sets the image iterations
    • Imagick::setImageMatte - Sets the image matte channel
    • Imagick::setImageMatteColor - Sets the image matte color
    • Imagick::setImageOpacity - Sets the image opacity level
    • Imagick::setImageOrientation - Sets the image orientation
    • Imagick::setImagePage - Sets the page geometry of the image
    • Imagick::setImageProfile - Adds a named profile to the Imagick object
    • Imagick::setImageProperty - Sets an image property
    • Imagick::setImageRedPrimary - Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent - Sets the image rendering intent
    • Imagick::setImageResolution - Sets the image resolution
    • Imagick::setImageScene - Sets the image scene
    • Imagick::setImageTicksPerSecond - Sets the image ticks-per-second
    • Imagick::setImageType - Sets the image type
    • Imagick::setImageUnits - Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod - Sets the image virtual pixel method
    • Imagick::setImageWhitePoint - Sets the image chromaticity white point
    • Imagick::setInterlaceScheme - Sets the image compression
    • Imagick::setIteratorIndex - Set the iterator position
    • Imagick::setLastIterator - Sets the Imagick iterator to the last image
    • Imagick::setOption - Set an option
    • Imagick::setPage - Sets the page geometry of the Imagick object
    • Imagick::setPointSize - Sets point size
    • Imagick::setProgressMonitor - Description
    • Imagick::setRegistry - Description
    • Imagick::setResolution - Sets the image resolution
    • Imagick::setResourceLimit - Sets the limit for a particular resource
    • Imagick::setSamplingFactors - Sets the image sampling factors
    • Imagick::setSize - Sets the size of the Imagick object
    • Imagick::setSizeOffset - Sets the size and offset of the Imagick object
    • Imagick::setType - Sets the image type attribute
    • Imagick::shadeImage - Creates a 3D effect
    • Imagick::shadowImage - Simulates an image shadow
    • Imagick::sharpenImage - Sharpens an image
    • Imagick::shaveImage - Shaves pixels from the image edges
    • Imagick::shearImage - Creating a parallelogram
    • Imagick::sigmoidalContrastImage - Adjusts the contrast of an image
    • Imagick::sketchImage - Simulates a pencil sketch
    • Imagick::smushImages - Description
    • Imagick::solarizeImage - Applies a solarizing effect to the image
    • Imagick::sparseColorImage - Interpolates colors
    • Imagick::spliceImage - Splices a solid color into the image
    • Imagick::spreadImage - Randomly displaces each pixel in a block
    • Imagick::statisticImage - Description
    • Imagick::steganoImage - Hides a digital watermark within the image
    • Imagick::stereoImage - Composites two images
    • Imagick::stripImage - 去掉图片的所有配置和设置
    • Imagick::subImageMatch - Description
    • Imagick::swirlImage - Swirls the pixels about the center of the image
    • Imagick::textureImage - Repeatedly tiles the texture image
    • Imagick::thresholdImage - Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage - Changes the size of an image
    • Imagick::tintImage - Applies a color vector to each pixel in the image
    • Imagick::transformImage - Convenience method for setting crop size and the image geometry
    • Imagick::transformImageColorspace - Transforms an image to a new colorspace
    • Imagick::transparentPaintImage - Paints pixels transparent
    • Imagick::transposeImage - Creates a vertical mirror image
    • Imagick::transverseImage - Creates a horizontal mirror image
    • Imagick::trimImage - Remove edges from the image
    • Imagick::uniqueImageColors - Discards all but one of any pixel color
    • Imagick::unsharpMaskImage - Sharpens an image
    • Imagick::valid - Checks if the current item is valid
    • Imagick::vignetteImage - Adds vignette filter to the image
    • Imagick::waveImage - Applies wave filter to the image
    • Imagick::whiteThresholdImage - Force all pixels above the threshold into white
    • Imagick::writeImage - 把图片写入指定的文件
    • Imagick::writeImageFile - Writes an image to a filehandle
    • Imagick::writeImages - Writes an image or image sequence
    • Imagick::writeImagesFile - Writes frames to a filehandle
    • Imagick::__construct - The Imagick constructor
    • Imagick::__toString - Returns the image as a string
    • ImagickDraw::affine - Adjusts the current affine transformation matrix
    • ImagickDraw::annotation - Draws text on the image
    • ImagickDraw::arc - Draws an arc
    • ImagickDraw::bezier - Draws a bezier curve
    • ImagickDraw::circle - Draws a circle
    • ImagickDraw::clear - Clears the ImagickDraw
    • ImagickDraw::clone - Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color - Draws color on image
    • ImagickDraw::comment - Adds a comment
    • ImagickDraw::composite - Composites an image onto the current image
    • ImagickDraw::destroy - Frees all associated resources
    • ImagickDraw::ellipse - Draws an ellipse on the image
    • ImagickDraw::getClipPath - Obtains the current clipping path ID
    • ImagickDraw::getClipRule - Returns the current polygon fill rule
    • ImagickDraw::getClipUnits - Returns the interpretation of clip path units
    • ImagickDraw::getFillColor - Returns the fill color
    • ImagickDraw::getFillOpacity - Returns the opacity used when drawing
    • ImagickDraw::getFillRule - Returns the fill rule
    • ImagickDraw::getFont - Returns the font
    • ImagickDraw::getFontFamily - Returns the font family
    • ImagickDraw::getFontSize - Returns the font pointsize
    • ImagickDraw::getFontStretch - Description
    • ImagickDraw::getFontStyle - Returns the font style
    • ImagickDraw::getFontWeight - Returns the font weight
    • ImagickDraw::getGravity - Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias - Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor - Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray - Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset - Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap - Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin - Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit - Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity - Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth - Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment - Returns the text alignment
    • ImagickDraw::getTextAntialias - Returns the current text antialias setting
    • ImagickDraw::getTextDecoration - Returns the text decoration
    • ImagickDraw::getTextEncoding - Returns the code set used for text annotations
    • ImagickDraw::getTextInterlineSpacing - Description
    • ImagickDraw::getTextInterwordSpacing - Description
    • ImagickDraw::getTextKerning - Description
    • ImagickDraw::getTextUnderColor - Returns the text under color
    • ImagickDraw::getVectorGraphics - Returns a string containing vector graphics
    • ImagickDraw::line - Draws a line
    • ImagickDraw::matte - Paints on the image's opacity channel
    • ImagickDraw::pathClose - Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute - Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative - Draws an elliptical arc
    • ImagickDraw::pathFinish - Terminates the current path
    • ImagickDraw::pathLineToAbsolute - Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute - Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative - Draws a horizontal line
    • ImagickDraw::pathLineToRelative - Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute - Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative - Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute - Starts a new sub-path
    • ImagickDraw::pathMoveToRelative - Starts a new sub-path
    • ImagickDraw::pathStart - Declares the start of a path drawing list
    • ImagickDraw::point - Draws a point
    • ImagickDraw::polygon - Draws a polygon
    • ImagickDraw::polyline - Draws a polyline
    • ImagickDraw::pop - Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath - Terminates a clip path definition
    • ImagickDraw::popDefs - Terminates a definition list
    • ImagickDraw::popPattern - Terminates a pattern definition
    • ImagickDraw::push - Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath - Starts a clip path definition
    • ImagickDraw::pushDefs - Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern - Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle - Draws a rectangle
    • ImagickDraw::render - Renders all preceding drawing commands onto the image
    • ImagickDraw::resetVectorGraphics - Description
    • ImagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle - Draws a rounded rectangle
    • ImagickDraw::scale - Adjusts the scaling factor
    • ImagickDraw::setClipPath - Associates a named clipping path with the image
    • ImagickDraw::setClipRule - Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits - Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor - Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL - Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule - Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont - Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily - Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize - Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch - Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle - Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight - Sets the font weight
    • ImagickDraw::setGravity - Sets the text placement gravity
    • ImagickDraw::setResolution - Description
    • ImagickDraw::setStrokeAlpha - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias - Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor - Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray - Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset - Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap - Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin - Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit - Specifies the miter limit
    • ImagickDraw::setStrokeOpacity - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL - Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth - Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment - Specifies a text alignment
    • ImagickDraw::setTextAntialias - Controls whether text is antialiased
    • ImagickDraw::setTextDecoration - Specifies a decoration
    • ImagickDraw::setTextEncoding - Specifies the text code set
    • ImagickDraw::setTextInterlineSpacing - Description
    • ImagickDraw::setTextInterwordSpacing - Description
    • ImagickDraw::setTextKerning - Description
    • ImagickDraw::setTextUnderColor - Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics - Sets the vector graphics
    • ImagickDraw::setViewbox - Sets the overall canvas size
    • ImagickDraw::skewX - Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY - Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate - Applies a translation to the current coordinate system
    • ImagickDraw::__construct - The ImagickDraw constructor
    • ImagickPixel::clear - Clears resources associated with this object
    • ImagickPixel::destroy - Deallocates resources associated with this object
    • ImagickPixel::getColor - Returns the color
    • ImagickPixel::getColorAsString - Returns the color as a string
    • ImagickPixel::getColorCount - Returns the color count associated with this color
    • ImagickPixel::getColorQuantum - Description
    • ImagickPixel::getColorValue - Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum - Description
    • ImagickPixel::getHSL - Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex - Description
    • ImagickPixel::isPixelSimilar - Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum - Description
    • ImagickPixel::isSimilar - Check the distance between this color and another
    • ImagickPixel::setColor - Sets the color
    • ImagickPixel::setColorCount - Description
    • ImagickPixel::setColorValue - Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum - Description
    • ImagickPixel::setHSL - Sets the normalized HSL color
    • ImagickPixel::setIndex - Description
    • ImagickPixel::__construct - The ImagickPixel constructor
    • ImagickPixelIterator::clear - Clear resources associated with a PixelIterator
    • ImagickPixelIterator::destroy - Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow - Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow - Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow - Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow - Returns the previous row
    • ImagickPixelIterator::newPixelIterator - Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator - Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator - Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow - Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow - Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow - Set the pixel iterator row
    • ImagickPixelIterator::syncIterator - Syncs the pixel iterator
    • ImagickPixelIterator::__construct - The ImagickPixelIterator constructor
    • imap_8bit - Convert an 8bit string to a quoted-printable string
    • imap_alerts - Returns all IMAP alert messages that have occurred
    • imap_append - Append a string message to a specified mailbox
    • imap_base64 - Decode BASE64 encoded text
    • imap_binary - Convert an 8bit string to a base64 string
    • imap_body - Read the message body
    • imap_bodystruct - Read the structure of a specified body section of a specific message
    • imap_check - Check current mailbox
    • imap_clearflag_full - Clears flags on messages
    • imap_close - Close an IMAP stream
    • imap_create - 别名 imap_createmailbox
    • imap_createmailbox - Create a new mailbox
    • imap_delete - Mark a message for deletion from current mailbox
    • imap_deletemailbox - Delete a mailbox
    • imap_errors - Returns all of the IMAP errors that have occurred
    • imap_expunge - Delete all messages marked for deletion
    • imap_fetchbody - Fetch a particular section of the body of the message
    • imap_fetchheader - Returns header for a message
    • imap_fetchmime - Fetch MIME headers for a particular section of the message
    • imap_fetchstructure - Read the structure of a particular message
    • imap_fetchtext - 别名 imap_body
    • imap_fetch_overview - Read an overview of the information in the headers of the given message
    • imap_gc - Clears IMAP cache
    • imap_getacl - Gets the ACL for a given mailbox
    • imap_getmailboxes - Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed - List all the subscribed mailboxes
    • imap_get_quota - Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot - Retrieve the quota settings per user
    • imap_header - 别名 imap_headerinfo
    • imap_headerinfo - Read the header of the message
    • imap_headers - Returns headers for all messages in a mailbox
    • imap_last_error - Gets the last IMAP error that occurred during this page request
    • imap_list - Read the list of mailboxes
    • imap_listmailbox - 别名 imap_list
    • imap_listscan - Returns the list of mailboxes that matches the given text
    • imap_listsubscribed - 别名 imap_lsub
    • imap_lsub - List all the subscribed mailboxes
    • imap_mail - Send an email message
    • imap_mailboxmsginfo - Get information about the current mailbox
    • imap_mail_compose - Create a MIME message based on given envelope and body sections
    • imap_mail_copy - Copy specified messages to a mailbox
    • imap_mail_move - Move specified messages to a mailbox
    • imap_mime_header_decode - Decode MIME header elements
    • imap_msgno - Gets the message sequence number for the given UID
    • imap_mutf7_to_utf8 - Decode a modified UTF-7 string to UTF-8
    • imap_num_msg - Gets the number of messages in the current mailbox
    • imap_num_recent - Gets the number of recent messages in current mailbox
    • imap_open - Open an IMAP stream to a mailbox
    • imap_ping - Check if the IMAP stream is still active
    • imap_qprint - Convert a quoted-printable string to an 8 bit string
    • imap_rename - 别名 imap_renamemailbox
    • imap_renamemailbox - Rename an old mailbox to new mailbox
    • imap_reopen - Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist - Parses an address string
    • imap_rfc822_parse_headers - Parse mail headers from a string
    • imap_rfc822_write_address - Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody - Save a specific body section to a file
    • imap_scan - 别名 imap_listscan
    • imap_scanmailbox - 别名 imap_listscan
    • imap_search - This function returns an array of messages matching the given search criteria
    • imap_setacl - Sets the ACL for a given mailbox
    • imap_setflag_full - Sets flags on messages
    • imap_set_quota - Sets a quota for a given mailbox
    • imap_sort - Gets and sort messages
    • imap_status - Returns status information on a mailbox
    • imap_subscribe - Subscribe to a mailbox
    • imap_thread - Returns a tree of threaded message
    • imap_timeout - Set or fetch imap timeout
    • imap_uid - This function returns the UID for the given message sequence number
    • imap_undelete - Unmark the message which is marked deleted
    • imap_unsubscribe - Unsubscribe from a mailbox
    • imap_utf7_decode - Decodes a modified UTF-7 encoded string
    • imap_utf7_encode - Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 - Converts MIME-encoded text to UTF-8
    • imap_utf8_to_mutf7 - Encode a UTF-8 string to modified UTF-7
    • implode - 将一个一维数组的值转化为字符串
    • inet_ntop - Converts a packed internet address to a human readable representation
    • inet_pton - Converts a human readable IP address to its packed in_addr representation
    • InfiniteIterator::next - Moves the inner Iterator forward or rewinds it
    • InfiniteIterator::__construct - Constructs an InfiniteIterator
    • inflate_add - Incrementally inflate encoded data
    • inflate_get_read_len - Get number of bytes read so far
    • inflate_get_status - Get decompression status
    • inflate_init - Initialize an incremental inflate context
    • ingres_autocommit - Switch autocommit on or off
    • ingres_autocommit_state - Test if the connection is using autocommit
    • ingres_charset - Returns the installation character set
    • ingres_close - Close an Ingres database connection
    • ingres_commit - Commit a transaction
    • ingres_connect - Open a connection to an Ingres database
    • ingres_cursor - Get a cursor name for a given result resource
    • ingres_errno - Get the last Ingres error number generated
    • ingres_error - Get a meaningful error message for the last error generated
    • ingres_errsqlstate - Get the last SQLSTATE error code generated
    • ingres_escape_string - Escape special characters for use in a query
    • ingres_execute - Execute a prepared query
    • ingres_fetch_array - Fetch a row of result into an array
    • ingres_fetch_assoc - Fetch a row of result into an associative array
    • ingres_fetch_object - Fetch a row of result into an object
    • ingres_fetch_proc_return - Get the return value from a procedure call
    • ingres_fetch_row - Fetch a row of result into an enumerated array
    • ingres_field_length - Get the length of a field
    • ingres_field_name - Get the name of a field in a query result
    • ingres_field_nullable - Test if a field is nullable
    • ingres_field_precision - Get the precision of a field
    • ingres_field_scale - Get the scale of a field
    • ingres_field_type - Get the type of a field in a query result
    • ingres_free_result - Free the resources associated with a result identifier
    • ingres_next_error - Get the next Ingres error
    • ingres_num_fields - Get the number of fields returned by the last query
    • ingres_num_rows - Get the number of rows affected or returned by a query
    • ingres_pconnect - Open a persistent connection to an Ingres database
    • ingres_prepare - Prepare a query for later execution
    • ingres_query - Send an SQL query to Ingres
    • ingres_result_seek - Set the row position before fetching data
    • ingres_rollback - Roll back a transaction
    • ingres_set_environment - Set environment features controlling output options
    • ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
    • ini_alter - 别名 ini_set
    • ini_get - 获取一个配置选项的值
    • ini_get_all - 获取所有配置选项
    • ini_restore - 恢复配置选项的值
    • ini_set - 为一个配置选项设置值
    • inotify_add_watch - Add a watch to an initialized inotify instance
    • inotify_init - Initialize an inotify instance
    • inotify_queue_len - Return a number upper than zero if there are pending events
    • inotify_read - Read events from an inotify instance
    • inotify_rm_watch - Remove an existing watch from an inotify instance
    • intdiv - 对除法结果取整
    • interface_exists - 检查接口是否已被定义
    • IntlBreakIterator::createCharacterInstance - Create break iterator for boundaries of combining character sequences
    • IntlBreakIterator::createCodePointInstance - Create break iterator for boundaries of code points
    • IntlBreakIterator::createLineInstance - Create break iterator for logically possible line breaks
    • IntlBreakIterator::createSentenceInstance - Create break iterator for sentence breaks
    • IntlBreakIterator::createTitleInstance - Create break iterator for title-casing breaks
    • IntlBreakIterator::createWordInstance - Create break iterator for word breaks
    • IntlBreakIterator::current - Get index of current position
    • IntlBreakIterator::first - Set position to the first character in the text
    • IntlBreakIterator::following - Advance the iterator to the first boundary following specified offset
    • IntlBreakIterator::getErrorCode - Get last error code on the object
    • IntlBreakIterator::getErrorMessage - Get last error message on the object
    • IntlBreakIterator::getLocale - Get the locale associated with the object
    • IntlBreakIterator::getPartsIterator - Create iterator for navigating fragments between boundaries
    • IntlBreakIterator::getText - Get the text being scanned
    • IntlBreakIterator::isBoundary - Tell whether an offset is a boundary?s offset
    • IntlBreakIterator::last - Set the iterator position to index beyond the last character
    • IntlBreakIterator::next - Advance the iterator the next boundary
    • IntlBreakIterator::preceding - Set the iterator position to the first boundary before an offset
    • IntlBreakIterator::previous - Set the iterator position to the boundary immediately before the current
    • IntlBreakIterator::setText - Set the text being scanned
    • IntlBreakIterator::__construct - Private constructor for disallowing instantiation
    • IntlCalendar::add - Add a (signed) amount of time to a field
    • IntlCalendar::after - Whether this object?s time is after that of the passed object
    • IntlCalendar::before - Whether this object?s time is before that of the passed object
    • IntlCalendar::clear - Clear a field or all fields
    • IntlCalendar::createInstance - Create a new IntlCalendar
    • IntlCalendar::equals - Compare time of two IntlCalendar objects for equality
    • IntlCalendar::fieldDifference - Calculate difference between given time and this object?s time
    • IntlCalendar::fromDateTime - Create an IntlCalendar from a DateTime object or string
    • IntlCalendar::get - Get the value for a field
    • IntlCalendar::getActualMaximum - The maximum value for a field, considering the object?s current time
    • IntlCalendar::getActualMinimum - The minimum value for a field, considering the object?s current time
    • IntlCalendar::getAvailableLocales - Get array of locales for which there is data
    • IntlCalendar::getDayOfWeekType - Tell whether a day is a weekday, weekend or a day that has a transition between the two
    • IntlCalendar::getErrorCode - Get last error code on the object
    • IntlCalendar::getErrorMessage - Get last error message on the object
    • IntlCalendar::getFirstDayOfWeek - Get the first day of the week for the calendar?s locale
    • IntlCalendar::getGreatestMinimum - Get the largest local minimum value for a field
    • IntlCalendar::getKeywordValuesForLocale - Get set of locale keyword values
    • IntlCalendar::getLeastMaximum - Get the smallest local maximum for a field
    • IntlCalendar::getLocale - Get the locale associated with the object
    • IntlCalendar::getMaximum - Get the global maximum value for a field
    • IntlCalendar::getMinimalDaysInFirstWeek - Get minimal number of days the first week in a year or month can have
    • IntlCalendar::getMinimum - Get the global minimum value for a field
    • IntlCalendar::getNow - Get number representing the current time
    • IntlCalendar::getRepeatedWallTimeOption - Get behavior for handling repeating wall time
    • IntlCalendar::getSkippedWallTimeOption - Get behavior for handling skipped wall time
    • IntlCalendar::getTime - Get time currently represented by the object
    • IntlCalendar::getTimeZone - Get the object?s timezone
    • IntlCalendar::getType - Get the calendar type
    • IntlCalendar::getWeekendTransition - Get time of the day at which weekend begins or ends
    • IntlCalendar::inDaylightTime - Whether the object?s time is in Daylight Savings Time
    • IntlCalendar::isEquivalentTo - Whether another calendar is equal but for a different time
    • IntlCalendar::isLenient - Whether date/time interpretation is in lenient mode
    • IntlCalendar::isSet - Whether a field is set
    • IntlCalendar::isWeekend - Whether a certain date/time is in the weekend
    • IntlCalendar::roll - Add value to field without carrying into more significant fields
    • IntlCalendar::set - Set a time field or several common fields at once
    • IntlCalendar::setFirstDayOfWeek - Set the day on which the week is deemed to start
    • IntlCalendar::setLenient - Set whether date/time interpretation is to be lenient
    • IntlCalendar::setMinimalDaysInFirstWeek - Set minimal number of days the first week in a year or month can have
    • IntlCalendar::setRepeatedWallTimeOption - Set behavior for handling repeating wall times at negative timezone offset transitions
    • IntlCalendar::setSkippedWallTimeOption - Set behavior for handling skipped wall times at positive timezone offset transitions
    • IntlCalendar::setTime - Set the calendar time in milliseconds since the epoch
    • IntlCalendar::setTimeZone - Set the timezone used by this calendar
    • IntlCalendar::toDateTime - Convert an IntlCalendar into a DateTime object
    • IntlCalendar::__construct - Private constructor for disallowing instantiation
    • IntlChar::charAge - Get the "age" of the code point
    • IntlChar::charDigitValue - Get the decimal digit value of a decimal digit character
    • IntlChar::charDirection - Get bidirectional category value for a code point
    • IntlChar::charFromName - Find Unicode character by name and return its code point value
    • IntlChar::charMirror - Get the "mirror-image" character for a code point
    • IntlChar::charName - Retrieve the name of a Unicode character
    • IntlChar::charType - Get the general category value for a code point
    • IntlChar::chr - Return Unicode character by code point value
    • IntlChar::digit - Get the decimal digit value of a code point for a given radix
    • IntlChar::enumCharNames - Enumerate all assigned Unicode characters within a range
    • IntlChar::enumCharTypes - Enumerate all code points with their Unicode general categories
    • IntlChar::foldCase - Perform case folding on a code point
    • IntlChar::forDigit - Get character representation for a given digit and radix
    • IntlChar::getBidiPairedBracket - Get the paired bracket character for a code point
    • IntlChar::getBlockCode - Get the Unicode allocation block containing a code point
    • IntlChar::getCombiningClass - Get the combining class of a code point
    • IntlChar::getFC_NFKC_Closure - Get the FC_NFKC_Closure property for a code point
    • IntlChar::getIntPropertyMaxValue - Get the max value for a Unicode property
    • IntlChar::getIntPropertyMinValue - Get the min value for a Unicode property
    • IntlChar::getIntPropertyValue - Get the value for a Unicode property for a code point
    • IntlChar::getNumericValue - Get the numeric value for a Unicode code point
    • IntlChar::getPropertyEnum - Get the property constant value for a given property name
    • IntlChar::getPropertyName - Get the Unicode name for a property
    • IntlChar::getPropertyValueEnum - Get the property value for a given value name
    • IntlChar::getPropertyValueName - Get the Unicode name for a property value
    • IntlChar::getUnicodeVersion - Get the Unicode version
    • IntlChar::hasBinaryProperty - Check a binary Unicode property for a code point
    • IntlChar::isalnum - Check if code point is an alphanumeric character
    • IntlChar::isalpha - Check if code point is a letter character
    • IntlChar::isbase - Check if code point is a base character
    • IntlChar::isblank - Check if code point is a "blank" or "horizontal space" character
    • IntlChar::iscntrl - Check if code point is a control character
    • IntlChar::isdefined - Check whether the code point is defined
    • IntlChar::isdigit - Check if code point is a digit character
    • IntlChar::isgraph - Check if code point is a graphic character
    • IntlChar::isIDIgnorable - Check if code point is an ignorable character
    • IntlChar::isIDPart - Check if code point is permissible in an identifier
    • IntlChar::isIDStart - Check if code point is permissible as the first character in an identifier
    • IntlChar::isISOControl - Check if code point is an ISO control code
    • IntlChar::isJavaIDPart - Check if code point is permissible in a Java identifier
    • IntlChar::isJavaIDStart - Check if code point is permissible as the first character in a Java identifier
    • IntlChar::isJavaSpaceChar - Check if code point is a space character according to Java
    • IntlChar::islower - Check if code point is a lowercase letter
    • IntlChar::isMirrored - Check if code point has the Bidi_Mirrored property
    • IntlChar::isprint - Check if code point is a printable character
    • IntlChar::ispunct - Check if code point is punctuation character
    • IntlChar::isspace - Check if code point is a space character
    • IntlChar::istitle - Check if code point is a titlecase letter
    • IntlChar::isUAlphabetic - Check if code point has the Alphabetic Unicode property
    • IntlChar::isULowercase - Check if code point has the Lowercase Unicode property
    • IntlChar::isupper - Check if code point has the general category "Lu" (uppercase letter)
    • IntlChar::isUUppercase - Check if code point has the Uppercase Unicode property
    • IntlChar::isUWhiteSpace - Check if code point has the White_Space Unicode property
    • IntlChar::isWhitespace - Check if code point is a whitespace character according to ICU
    • IntlChar::isxdigit - Check if code point is a hexadecimal digit
    • IntlChar::ord - Return Unicode code point value of character
    • IntlChar::tolower - Make Unicode character lowercase
    • IntlChar::totitle - Make Unicode character titlecase
    • IntlChar::toupper - Make Unicode character uppercase
    • IntlCodePointBreakIterator::getLastCodePoint - Get last code point passed over after advancing or receding the iterator
    • IntlDateFormatter::create - Create a date formatter
    • IntlDateFormatter::format - Format the date/time value as a string
    • IntlDateFormatter::formatObject - Formats an object
    • IntlDateFormatter::getCalendar - Get the calendar type used for the IntlDateFormatter
    • IntlDateFormatter::getCalendarObject - Get copy of formatter?s calendar object
    • IntlDateFormatter::getDateType - Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode - Get the error code from last operation
    • IntlDateFormatter::getErrorMessage - Get the error text from the last operation
    • IntlDateFormatter::getLocale - Get the locale used by formatter
    • IntlDateFormatter::getPattern - Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType - Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZone - Get formatter?s timezone
    • IntlDateFormatter::getTimeZoneId - Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::isLenient - Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime - Parse string to a field-based time value
    • IntlDateFormatter::parse - Parse string to a timestamp value
    • IntlDateFormatter::setCalendar - Sets the calendar type used by the formatter
    • IntlDateFormatter::setLenient - Set the leniency of the parser
    • IntlDateFormatter::setPattern - Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZone - Sets formatter?s timezone
    • IntlGregorianCalendar::getGregorianChange - Get the Gregorian Calendar change date
    • IntlGregorianCalendar::isLeapYear - Determine if the given year is a leap year
    • IntlGregorianCalendar::setGregorianChange - Set the Gregorian Calendar the change date
    • IntlGregorianCalendar::__construct - Create the Gregorian Calendar class
    • IntlIterator::current - Get the current element
    • IntlIterator::key - Get the current key
    • IntlIterator::next - Move forward to the next element
    • IntlIterator::rewind - Rewind the iterator to the first element
    • IntlIterator::valid - Check if current position is valid
    • IntlPartsIterator::getBreakIterator - Get IntlBreakIterator backing this parts iterator
    • IntlRuleBasedBreakIterator::getBinaryRules - Get the binary form of compiled rules
    • IntlRuleBasedBreakIterator::getRules - Get the rule set used to create this object
    • IntlRuleBasedBreakIterator::getRuleStatus - Get the largest status value from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::getRuleStatusVec - Get the status values from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::__construct - Create iterator from ruleset
    • IntlTimeZone::countEquivalentIDs - Get the number of IDs in the equivalency group that includes the given ID
    • IntlTimeZone::createDefault - Create a new copy of the default timezone for this host
    • IntlTimeZone::createEnumeration - Get an enumeration over time zone IDs associated with the given country or offset
    • IntlTimeZone::createTimeZone - Create a timezone object for the given ID
    • IntlTimeZone::createTimeZoneIDEnumeration - Get an enumeration over system time zone IDs with the given filter conditions
    • IntlTimeZone::fromDateTimeZone - Create a timezone object from DateTimeZone
    • IntlTimeZone::getCanonicalID - Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
    • IntlTimeZone::getDisplayName - Get a name of this time zone suitable for presentation to the user
    • IntlTimeZone::getDSTSavings - Get the amount of time to be added to local standard time to get local wall clock time
    • IntlTimeZone::getEquivalentID - Get an ID in the equivalency group that includes the given ID
    • IntlTimeZone::getErrorCode - Get last error code on the object
    • IntlTimeZone::getErrorMessage - Get last error message on the object
    • IntlTimeZone::getGMT - Create GMT (UTC) timezone
    • IntlTimeZone::getID - Get timezone ID
    • IntlTimeZone::getIDForWindowsID - Translate a Windows timezone into a system timezone
    • IntlTimeZone::getOffset - Get the time zone raw and GMT offset for the given moment in time
    • IntlTimeZone::getRawOffset - Get the raw GMT offset (before taking daylight savings time into account
    • IntlTimeZone::getRegion - Get the region code associated with the given system time zone ID
    • IntlTimeZone::getTZDataVersion - Get the timezone data version currently used by ICU
    • IntlTimeZone::getUnknown - Get the "unknown" time zone
    • IntlTimeZone::getWindowsID - Translate a system timezone into a Windows timezone
    • IntlTimeZone::hasSameRules - Check if this zone has the same rules and offset as another zone
    • IntlTimeZone::toDateTimeZone - Convert to DateTimeZone object
    • IntlTimeZone::useDaylightTime - Check if this time zone uses daylight savings time
    • intl_error_name - Get symbolic name for a given error code
    • intl_get_error_code - Get the last error code
    • intl_get_error_message - Get description of the last error
    • intl_is_failure - Check whether the given error code indicates failure
    • intval - 获取变量的整数值
    • in_array - 检查数组中是否存在某个值
    • ip2long - 将 IPV4 的字符串互联网协议转换成长整型数字
    • iptcembed - 将二进制 IPTC 数据嵌入到一幅 JPEG 图像中
    • iptcparse - 将二进制 IPTC 块解析为单个标记
    • isset - 检测变量是否已设置并且非 null
    • is_a - 如果对象属于该类或该类是此对象的父类则返回 true
    • is_array - 检测变量是否是数组
    • is_bool - 检测变量是否是布尔值
    • is_callable - 检测参数是否为合法的可调用结构
    • is_countable - Verify that the contents of a variable is a countable value
    • is_dir - 判断给定文件名是否是一个目录
    • is_double - is_float 的别名
    • is_executable - 判断给定文件名是否可执行
    • is_file - 判断给定文件名是否为一个正常的文件
    • is_finite - 判断是否为有限值
    • is_float - 检测变量是否是浮点型
    • is_infinite - 判断是否为无限值
    • is_int - 检测变量是否是整数
    • is_integer - is_int 的别名
    • is_iterable - Verify that the contents of a variable is an iterable value
    • is_link - 判断给定文件名是否为一个符号连接
    • is_long - is_int 的别名
    • is_nan - 判断是否为合法数值
    • is_null - 检测变量是否为 null
    • is_numeric - 检测变量是否为数字或数字字符串
    • is_object - 检测变量是否是一个对象
    • is_readable - 判断给定文件名是否可读
    • is_real - is_float 的别名
    • is_resource - 检测变量是否为资源类型
    • is_scalar - 检测变量是否是一个标量
    • is_soap_fault - Checks if a SOAP call has failed
    • is_string - 检测变量是否是字符串
    • is_subclass_of - 如果此对象是该类的子类，则返回 true
    • is_tainted - Checks whether a string is tainted
    • is_uploaded_file - 判断文件是否是通过 HTTP POST 上传的
    • is_writable - 判断给定的文件名是否可写
    • is_writeable - is_writable 的别名
    • Iterator::current - 返回当前元素
    • Iterator::key - 返回当前元素的键
    • Iterator::next - 向前移动到下一个元素
    • Iterator::rewind - 返回到迭代器的第一个元素
    • Iterator::valid - 检查当前位置是否有效
    • IteratorAggregate::getIterator - 获取一个外部迭代器
    • IteratorIterator::current - Get the current value
    • IteratorIterator::getInnerIterator - Get the inner iterator
    • IteratorIterator::key - Get the key of the current element
    • IteratorIterator::next - Forward to the next element
    • IteratorIterator::rewind - Rewind to the first element
    • IteratorIterator::valid - Checks if the iterator is valid
    • IteratorIterator::__construct - Create an iterator from anything that is traversable
    • iterator_apply - 为迭代器中每个元素调用一个用户自定义函数
    • iterator_count - 计算迭代器中元素的个数
    • iterator_to_array - 将迭代器中的元素拷贝到数组
  • j
    • JDDayOfWeek - 返回星期的日期
    • JDMonthName - 返回月份的名称
    • JDToFrench - 转变一个Julian Day计数到French Republican历法的日期
    • JDToGregorian - 转变一个Julian Day计数为Gregorian历法日期
    • jdtojewish - 转换一个julian天数为Jewish历法的日期
    • JDToJulian - 转变一个Julian Day计数到Julian历法的日期
    • jdtounix - 转变Julian Day计数为一个Unix时间戳
    • JewishToJD - 转变一个Jewish历法的日期为一个Julian Day计数
    • join - 别名 implode
    • jpeg2wbmp - 将 JPEG 图像文件转换为 WBMP 图像文件
    • JsonSerializable::jsonSerialize - 指定需要被序列化成 JSON 的数据
    • json_decode - 对 JSON 格式的字符串进行解码
    • json_encode - 对变量进行 JSON 编码
    • json_last_error - 返回最后发生的错误
    • json_last_error_msg - Returns the error string of the last json_encode() or json_decode() call
    • JulianToJD - 转变一个Julian历法的日期为Julian Day计数
  • k
    • key - 从关联数组中取得键名
    • key_exists - 别名 array_key_exists
    • krsort - 对数组按照键名逆向排序
    • ksort - 对数组按照键名排序
  • l
    • lcfirst - 使一个字符串的第一个字符小写
    • lcg_value - 组合线性同余发生器
    • lchgrp - 修改符号链接的所有组
    • lchown - 修改符号链接的所有者
    • ldap_8859_to_t61 - Translate 8859 characters to t61 characters
    • ldap_add - Add entries to LDAP directory
    • ldap_add_ext - Add entries to LDAP directory
    • ldap_bind - 绑定 LDAP 目录
    • ldap_bind_ext - Bind to LDAP directory
    • ldap_close - 别名 ldap_unbind
    • ldap_compare - Compare value of attribute found in entry specified with DN
    • ldap_connect - Connect to an LDAP server
    • ldap_control_paged_result - Send LDAP pagination control
    • ldap_control_paged_result_response - Retrieve the LDAP pagination cookie
    • ldap_count_entries - Count the number of entries in a search
    • ldap_delete - Delete an entry from a directory
    • ldap_delete_ext - Delete an entry from a directory
    • ldap_dn2ufn - Convert DN to User Friendly Naming format
    • ldap_err2str - Convert LDAP error number into string error message
    • ldap_errno - Return the LDAP error number of the last LDAP command
    • ldap_error - Return the LDAP error message of the last LDAP command
    • ldap_escape - Escape a string for use in an LDAP filter or DN
    • ldap_exop - Performs an extended operation
    • ldap_exop_passwd - PASSWD extended operation helper
    • ldap_exop_refresh - Refresh extended operation helper
    • ldap_exop_whoami - WHOAMI extended operation helper
    • ldap_explode_dn - Splits DN into its component parts
    • ldap_first_attribute - Return first attribute
    • ldap_first_entry - Return first result id
    • ldap_first_reference - Return first reference
    • ldap_free_result - Free result memory
    • ldap_get_attributes - Get attributes from a search result entry
    • ldap_get_dn - Get the DN of a result entry
    • ldap_get_entries - Get all result entries
    • ldap_get_option - Get the current value for given option
    • ldap_get_values - Get all values from a result entry
    • ldap_get_values_len - Get all binary values from a result entry
    • ldap_list - Single-level search
    • ldap_modify - 别名 ldap_mod_replace
    • ldap_modify_batch - Batch and execute modifications on an LDAP entry
    • ldap_mod_add - Add attribute values to current attributes
    • ldap_mod_add_ext - Add attribute values to current attributes
    • ldap_mod_del - Delete attribute values from current attributes
    • ldap_mod_del_ext - Delete attribute values from current attributes
    • ldap_mod_replace - Replace attribute values with new ones
    • ldap_mod_replace_ext - Replace attribute values with new ones
    • ldap_next_attribute - Get the next attribute in result
    • ldap_next_entry - Get next result entry
    • ldap_next_reference - Get next reference
    • ldap_parse_exop - Parse result object from an LDAP extended operation
    • ldap_parse_reference - Extract information from reference entry
    • ldap_parse_result - Extract information from result
    • ldap_read - Read an entry
    • ldap_rename - Modify the name of an entry
    • ldap_rename_ext - Modify the name of an entry
    • ldap_sasl_bind - Bind to LDAP directory using SASL
    • ldap_search - Search LDAP tree
    • ldap_set_option - Set the value of the given option
    • ldap_set_rebind_proc - Set a callback function to do re-binds on referral chasing
    • ldap_sort - Sort LDAP result entries on the client side
    • ldap_start_tls - Start TLS
    • ldap_t61_to_8859 - Translate t61 characters to 8859 characters
    • ldap_unbind - Unbind from LDAP directory
    • levenshtein - 计算两个字符串之间的编辑距离
    • libxml_clear_errors - Clear libxml error buffer
    • libxml_disable_entity_loader - Disable the ability to load external entities
    • libxml_get_errors - Retrieve array of errors
    • libxml_get_last_error - Retrieve last error from libxml
    • libxml_set_external_entity_loader - Changes the default external entity loader
    • libxml_set_streams_context - Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors - Disable libxml errors and allow user to fetch error information as needed
    • LimitIterator::current - Get current element
    • LimitIterator::getInnerIterator - Get inner iterator
    • LimitIterator::getPosition - Return the current position
    • LimitIterator::key - Get current key
    • LimitIterator::next - Move the iterator forward
    • LimitIterator::rewind - Rewind the iterator to the specified starting offset
    • LimitIterator::seek - Seek to the given position
    • LimitIterator::valid - Check whether the current element is valid
    • LimitIterator::__construct - Construct a LimitIterator
    • link - 建立一个硬连接
    • linkinfo - 获取一个连接的信息
    • list - 把数组中的值赋给一组变量
    • Locale::acceptFromHttp - Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::canonicalize - Canonicalize the locale string
    • Locale::composeLocale - Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches - Checks if a language tag filter matches with locale
    • Locale::getAllVariants - Gets the variants for the input locale
    • Locale::getDefault - Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage - Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName - Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion - Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript - Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant - Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords - Gets the keywords for the input locale
    • Locale::getPrimaryLanguage - Gets the primary language for the input locale
    • Locale::getRegion - Gets the region for the input locale
    • Locale::getScript - Gets the script for the input locale
    • Locale::lookup - Searches the language tag list for the best match to the language
    • Locale::parseLocale - Returns a key-value array of locale ID subtag elements
    • Locale::setDefault - Sets the default runtime locale
    • localeconv - Get numeric formatting information
    • localtime - 取得本地时间
    • log - 自然对数
    • log1p - 返回 log(1 + number)，甚至当 number 的值接近零也能计算出准确结果
    • log10 - 以 10 为底的对数
    • log_cmd_delete - Callback When Deleting Documents
    • log_cmd_insert - Callback When Inserting Documents
    • log_cmd_update - Callback When Updating Documents
    • log_getmore - Callback When Retrieving Next Cursor Batch
    • log_killcursor - Callback When Executing KILLCURSOR operations
    • log_reply - Callback When Reading the MongoDB reply
    • log_write_batch - Callback When Writing Batches
    • long2ip - 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）
    • lstat - 给出一个文件或符号连接的信息
    • ltrim - 删除字符串开头的空白字符（或其他字符）
    • Lua::assign - 将一个php变量赋值给Lua
    • Lua::call - 调用Lua函数
    • Lua::eval - 将字符串当做Lua代码执行
    • Lua::getVersion - 获取Lua版本
    • Lua::include - 解析Lua脚本文件
    • Lua::registerCallback - 向Lua中注册php函数
    • Lua::__construct - Lua 构造方法
    • LuaClosure::__invoke - 调用luaclosure
    • LuaSandbox::callFunction - Call a function in a Lua global variable
    • LuaSandbox::disableProfiler - Disable the profiler
    • LuaSandbox::enableProfiler - Enable the profiler.
    • LuaSandbox::getCPUUsage - Fetch the current CPU time usage of the Lua environment
    • LuaSandbox::getMemoryUsage - Fetch the current memory usage of the Lua environment
    • LuaSandbox::getPeakMemoryUsage - Fetch the peak memory usage of the Lua environment
    • LuaSandbox::getProfilerFunctionReport - Fetch profiler data
    • LuaSandbox::getVersionInfo - Return the versions of LuaSandbox and Lua
    • LuaSandbox::loadBinary - Load a precompiled binary chunk into the Lua environment
    • LuaSandbox::loadString - Load Lua code into the Lua environment
    • LuaSandbox::pauseUsageTimer - Pause the CPU usage timer
    • LuaSandbox::registerLibrary - Register a set of PHP functions as a Lua library
    • LuaSandbox::setCPULimit - Set the CPU time limit for the Lua environment
    • LuaSandbox::setMemoryLimit - Set the memory limit for the Lua environment
    • LuaSandbox::unpauseUsageTimer - Unpause the timer paused by LuaSandbox::pauseUsageTimer
    • LuaSandbox::wrapPhpFunction - Wrap a PHP callable in a LuaSandboxFunction
    • LuaSandboxFunction::call - Call a Lua function
    • LuaSandboxFunction::dump - Dump the function as a binary blob
    • LuaSandboxFunction::__construct - Unused
    • lzf_compress - LZF compression
    • lzf_decompress - LZF decompression
    • lzf_optimized_for - Determines what LZF extension was optimized for
  • m
    • mail - 发送邮件
    • mailparse_determine_best_xfer_encoding - Gets the best way of encoding
    • mailparse_msg_create - Create a mime mail resource
    • mailparse_msg_extract_part - Extracts/decodes a message section
    • mailparse_msg_extract_part_file - Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file - Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free - Frees a MIME resource
    • mailparse_msg_get_part - Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_part_data - Returns an associative array of info about the message
    • mailparse_msg_get_structure - Returns an array of mime section names in the supplied message
    • mailparse_msg_parse - Incrementally parse data into buffer
    • mailparse_msg_parse_file - Parses a file
    • mailparse_rfc822_parse_addresses - Parse RFC 822 compliant addresses
    • mailparse_stream_encode - Streams data from source file pointer, apply encoding and write to destfp
    • mailparse_uudecode_all - Scans the data from fp and extract each embedded uuencoded file
    • main - 虚拟的main
    • max - 找出最大值
    • mb_check_encoding - 检查字符串在指定的编码里是否有效
    • mb_chr - Get a specific character
    • mb_convert_case - 对字符串进行大小写转换
    • mb_convert_encoding - 转换字符的编码
    • mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
    • mb_convert_variables - 转换一个或多个变量的字符编码
    • mb_decode_mimeheader - 解码 MIME 头字段中的字符串
    • mb_decode_numericentity - 根据 HTML 数字字符串解码成字符
    • mb_detect_encoding - 检测字符的编码
    • mb_detect_order - 设置/获取 字符编码的检测顺序
    • mb_encode_mimeheader - 为 MIME 头编码字符串
    • mb_encode_numericentity - Encode character to HTML numeric string reference
    • mb_encoding_aliases - Get aliases of a known encoding type
    • mb_ereg - Regular expression match with multibyte support
    • mb_eregi - Regular expression match ignoring case with multibyte support
    • mb_eregi_replace - Replace regular expression with multibyte support ignoring case
    • mb_ereg_match - Regular expression match for multibyte string
    • mb_ereg_replace - Replace regular expression with multibyte support
    • mb_ereg_replace_callback - Perform a regular expression search and replace with multibyte support using a callback
    • mb_ereg_search - Multibyte regular expression match for predefined multibyte string
    • mb_ereg_search_getpos - Returns start point for next regular expression match
    • mb_ereg_search_getregs - Retrieve the result from the last multibyte regular expression match
    • mb_ereg_search_init - Setup string and regular expression for a multibyte regular expression match
    • mb_ereg_search_pos - Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
    • mb_ereg_search_regs - Returns the matched part of a multibyte regular expression
    • mb_ereg_search_setpos - Set start point of next regular expression match
    • mb_get_info - 获取 mbstring 的内部设置
    • mb_http_input - 检测 HTTP 输入字符编码
    • mb_http_output - 设置/获取 HTTP 输出字符编码
    • mb_internal_encoding - 设置/获取内部字符编码
    • mb_language - 设置/获取当前的语言
    • mb_list_encodings - 返回所有支持编码的数组
    • mb_ord - Get code point of character
    • mb_output_handler - 在输出缓冲中转换字符编码的回调函数
    • mb_parse_str - 解析 GET/POST/COOKIE 数据并设置全局变量
    • mb_preferred_mime_name - 获取 MIME 字符串
    • mb_regex_encoding - Set/Get character encoding for multibyte regex
    • mb_regex_set_options - Set/Get the default options for mbregex functions
    • mb_scrub - Description
    • mb_send_mail - 发送编码过的邮件
    • mb_split - 使用正则表达式分割多字节字符串
    • mb_strcut - 获取字符的一部分
    • mb_strimwidth - 获取按指定宽度截断的字符串
    • mb_stripos - 大小写不敏感地查找字符串在另一个字符串中首次出现的位置
    • mb_stristr - 大小写不敏感地查找字符串在另一个字符串里的首次出现
    • mb_strlen - 获取字符串的长度
    • mb_strpos - 查找字符串在另一个字符串中首次出现的位置
    • mb_strrchr - 查找指定字符在另一个字符串中最后一次的出现
    • mb_strrichr - 大小写不敏感地查找指定字符在另一个字符串中最后一次的出现
    • mb_strripos - 大小写不敏感地在字符串中查找一个字符串最后出现的位置
    • mb_strrpos - 查找字符串在一个字符串中最后出现的位置
    • mb_strstr - 查找字符串在另一个字符串里的首次出现
    • mb_strtolower - 使字符串小写
    • mb_strtoupper - 使字符串大写
    • mb_strwidth - 返回字符串的宽度
    • mb_str_split - Given a multibyte string, return an array of its characters
    • mb_substitute_character - 设置/获取替代字符
    • mb_substr - 获取部分字符串
    • mb_substr_count - 统计字符串出现的次数
    • mcrypt_cbc - 以 CBC 模式加解密数据
    • mcrypt_cfb - 以 CFB 模式加解密数据
    • mcrypt_create_iv - 从随机源创建初始向量
    • mcrypt_decrypt - 使用给定参数解密密文
    • mcrypt_ecb - 已废弃：使用 ECB 模式加解密数据
    • mcrypt_encrypt - 使用给定参数加密明文
    • mcrypt_enc_get_algorithms_name - 返回打开的算法名称
    • mcrypt_enc_get_block_size - 返回打开的算法的分组大小
    • mcrypt_enc_get_iv_size - 返回打开的算法的初始向量大小
    • mcrypt_enc_get_key_size - 返回打开的模式所能支持的最长密钥
    • mcrypt_enc_get_modes_name - 返回打开的模式的名称
    • mcrypt_enc_get_supported_key_sizes - 以数组方式返回打开的算法所支持的密钥长度
    • mcrypt_enc_is_block_algorithm - 检测打开模式的算法是否为分组算法
    • mcrypt_enc_is_block_algorithm_mode - 检测打开的模式是否支持分组加密
    • mcrypt_enc_is_block_mode - 检测打开的模式是否以分组方式输出
    • mcrypt_enc_self_test - 在打开的模块上进行自检
    • mcrypt_generic - 加密数据
    • mcrypt_generic_deinit - 对加密模块进行清理工作
    • mcrypt_generic_end - 终止加密
    • mcrypt_generic_init - 初始化加密所需的缓冲区
    • mcrypt_get_block_size - 获得加密算法的分组大小
    • mcrypt_get_cipher_name - 获取加密算法名称
    • mcrypt_get_iv_size - 返回指定算法/模式组合的初始向量大小
    • mcrypt_get_key_size - 获取指定加密算法的密钥大小
    • mcrypt_list_algorithms - 获取支持的加密算法
    • mcrypt_list_modes - 获取所支持的模式
    • mcrypt_module_close - 关闭加密模块
    • mcrypt_module_get_algo_block_size - 返回指定算法的分组大小
    • mcrypt_module_get_algo_key_size - 获取打开模式所支持的最大密钥大小
    • mcrypt_module_get_supported_key_sizes - 以数组形式返回打开的算法所支持的密钥大小
    • mcrypt_module_is_block_algorithm - 检测指定算法是否为分组加密算法
    • mcrypt_module_is_block_algorithm_mode - 返回指定模块是否是分组加密模式
    • mcrypt_module_is_block_mode - 检测指定模式是否以分组方式输出
    • mcrypt_module_open - 打开算法和模式对应的模块
    • mcrypt_module_self_test - 在指定模块上执行自检
    • mcrypt_ofb - 使用 OFB 模式加密/解密数据
    • md5 - 计算字符串的 MD5 散列值
    • md5_file - 计算指定文件的 MD5 散列值
    • mdecrypt_generic - 解密数据
    • Memcache::add - 增加一个条目到缓存服务器
    • Memcache::addServer - 向连接池中添加一个memcache服务器
    • Memcache::close - 关闭memcache连接
    • Memcache::connect - 打开一个memcached服务端连接
    • Memcache::decrement - 减小元素的值
    • Memcache::delete - 从服务端删除一个元素
    • Memcache::flush - 清洗（删除）已经存储的所有的元素
    • Memcache::get - 从服务端检回一个元素
    • Memcache::getExtendedStats - 缓存服务器池中所有服务器统计信息
    • Memcache::getServerStatus - 用于获取一个服务器的在线/离线状态
    • Memcache::getStats - 获取服务器统计信息
    • Memcache::getVersion - 返回服务器版本信息
    • Memcache::increment - 增加一个元素的值
    • Memcache::pconnect - 打开一个到服务器的持久化连接
    • Memcache::replace - 替换已经存在的元素的值
    • Memcache::set - Store data at the server
    • Memcache::setCompressThreshold - 开启大值自动压缩
    • Memcache::setServerParams - 运行时修改服务器参数和状态
    • Memcached::add - 向一个新的key下面增加一个元素
    • Memcached::addByKey - 在指定服务器上的一个新的key下增加一个元素
    • Memcached::addServer - 向服务器池中增加一个服务器
    • Memcached::addServers - 向服务器池中增加多台服务器
    • Memcached::append - 向已存在元素后追加数据
    • Memcached::appendByKey - 向指定服务器上已存在元素后追加数据
    • Memcached::cas - 比较并交换值
    • Memcached::casByKey - 在指定服务器上比较并交换值
    • Memcached::decrement - 减小数值元素的值
    • Memcached::decrementByKey - Decrement numeric item's value, stored on a specific server
    • Memcached::delete - 删除一个元素
    • Memcached::deleteByKey - 从指定的服务器删除一个元素
    • Memcached::deleteMulti - Delete multiple items
    • Memcached::deleteMultiByKey - Delete multiple items from a specific server
    • Memcached::fetch - 抓取下一个结果
    • Memcached::fetchAll - 抓取所有剩余的结果
    • Memcached::flush - 作废缓存中的所有元素
    • Memcached::get - 检索一个元素
    • Memcached::getAllKeys - Gets the keys stored on all the servers
    • Memcached::getByKey - 从特定的服务器检索元素
    • Memcached::getDelayed - 请求多个元素
    • Memcached::getDelayedByKey - 从指定的服务器上请求多个元素
    • Memcached::getMulti - 检索多个元素
    • Memcached::getMultiByKey - 从特定服务器检索多个元素
    • Memcached::getOption - 获取Memcached的选项值
    • Memcached::getResultCode - 返回最后一次操作的结果代码
    • Memcached::getResultMessage - 返回最后一次操作的结果描述消息
    • Memcached::getServerByKey - 获取一个key所映射的服务器信息
    • Memcached::getServerList - 获取服务器池中的服务器列表
    • Memcached::getStats - 获取服务器池的统计信息
    • Memcached::getVersion - 获取服务器池中所有服务器的版本信息
    • Memcached::increment - 增加数值元素的值
    • Memcached::incrementByKey - Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent - Check if a persitent connection to memcache is being used
    • Memcached::isPristine - Check if the instance was recently created
    • Memcached::prepend - 向一个已存在的元素前面追加数据
    • Memcached::prependByKey - Prepend data to an existing item on a specific server
    • Memcached::quit - 关闭所有打开的链接。
    • Memcached::replace - 替换已存在key下的元素
    • Memcached::replaceByKey - Replace the item under an existing key on a specific server
    • Memcached::resetServerList - Clears all servers from the server list
    • Memcached::set - 存储一个元素
    • Memcached::setByKey - 将元素存储到指定的服务器上
    • Memcached::setMulti - 存储多个元素
    • Memcached::setMultiByKey - Store multiple items on a specific server
    • Memcached::setOption - 设置一个memcached选项
    • Memcached::setOptions - Set Memcached options
    • Memcached::setSaslAuthData - Set the credentials to use for authentication
    • Memcached::touch - Set a new expiration on an item
    • Memcached::touchByKey - Set a new expiration on an item on a specific server
    • Memcached::__construct - 创建一个Memcached实例
    • memcache_debug - 转换调试输出的开/关
    • memory_get_peak_usage - 返回分配给 PHP 内存的峰值
    • memory_get_usage - 返回分配给 PHP 的内存量
    • MessageFormatter::create - Constructs a new Message Formatter
    • MessageFormatter::format - Format the message
    • MessageFormatter::formatMessage - Quick format message
    • MessageFormatter::getErrorCode - Get the error code from last operation
    • MessageFormatter::getErrorMessage - Get the error text from the last operation
    • MessageFormatter::getLocale - Get the locale for which the formatter was created
    • MessageFormatter::getPattern - Get the pattern used by the formatter
    • MessageFormatter::parse - Parse input string according to pattern
    • MessageFormatter::parseMessage - Quick parse input string
    • MessageFormatter::setPattern - Set the pattern used by the formatter
    • metaphone - Calculate the metaphone key of a string
    • method_exists - 检查类的方法是否存在
    • mhash - Computes hash
    • mhash_count - Gets the highest available hash ID
    • mhash_get_block_size - Gets the block size of the specified hash
    • mhash_get_hash_name - Gets the name of the specified hash
    • mhash_keygen_s2k - Generates a key
    • microtime - 返回当前 Unix 时间戳和微秒数
    • mime_content_type - 检测文件的 MIME 类型
    • min - 找出最小值
    • mkdir - 新建目录
    • mktime - 取得一个日期的 Unix 时间戳
    • money_format - 将数字格式化成货币字符串
    • Mongo::connectUtil - Connects with a database server
    • Mongo::getPoolSize - Get pool size for connection pools
    • Mongo::getSlave - Returns the address being used by this for slaveOkay reads
    • Mongo::getSlaveOkay - Get slaveOkay setting for this connection
    • Mongo::poolDebug - Returns information about all connection pools
    • Mongo::setPoolSize - Set the size for future connection pools
    • Mongo::setSlaveOkay - Change slaveOkay setting for this connection
    • Mongo::switchSlave - Choose a new secondary for slaveOkay reads
    • Mongo::__construct - The __construct purpose
    • MongoBinData::__construct - 创建一个新的二进制数据对象
    • MongoBinData::__toString - 二进制数据对象的字符串表达形式。
    • MongoClient::close - 关闭连接
    • MongoClient::connect - 连接到数据库服务器
    • MongoClient::dropDB - 删除一个数据库 [已废弃]
    • MongoClient::getConnections - 返回所有已打开连接的信息
    • MongoClient::getHosts - 更新所有关联主机的状态信息
    • MongoClient::getReadPreference - 获取此连接的读取首选项
    • MongoClient::getWriteConcern - Get the write concern for this connection
    • MongoClient::killCursor - Kills a specific cursor on the server
    • MongoClient::listDBs - 列出所有有效数据库
    • MongoClient::selectCollection - 获取数据库的文档集
    • MongoClient::selectDB - 获取一个数据库
    • MongoClient::setReadPreference - 为该连接设置读取选项
    • MongoClient::setWriteConcern - Set the write concern for this connection
    • MongoClient::__construct - 创建一个新的数据库连接对象
    • MongoClient::__get - 取得一个数据库
    • MongoClient::__toString - 该连接的字符串表达方式
    • MongoCode::__construct - 创建一个新的代码对象
    • MongoCode::__toString - 返回代码的字符串形式
    • MongoCollection::aggregate - Perform an aggregation using the aggregation framework
    • MongoCollection::aggregateCursor - Execute an aggregation pipeline command and retrieve results through a cursor
    • MongoCollection::batchInsert - Inserts multiple documents into this collection
    • MongoCollection::count - 返回集合中的文档数量
    • MongoCollection::createDBRef - 创建一个数据库引用
    • MongoCollection::createIndex - Creates an index on the specified field(s) if it does not already exist
    • MongoCollection::deleteIndex - Deletes an index from this collection
    • MongoCollection::deleteIndexes - 删除集合的所有索引
    • MongoCollection::distinct - 获取集合里指定键的不同值的列表。
    • MongoCollection::drop - 删除该集合
    • MongoCollection::ensureIndex - Creates an index on the specified field(s) if it does not already exist
    • MongoCollection::find - 查询该集合，并返回结果集的 MongoCursor
    • MongoCollection::findAndModify - Update a document and return it
    • MongoCollection::findOne - Queries this collection, returning a single element
    • MongoCollection::getDBRef - Fetches the document pointed to by a database reference
    • MongoCollection::getIndexInfo - Returns information about indexes on this collection
    • MongoCollection::getName - 返回这个集合的名称
    • MongoCollection::getReadPreference - Get the read preference for this collection
    • MongoCollection::getSlaveOkay - Get slaveOkay setting for this collection
    • MongoCollection::getWriteConcern - Get the write concern for this collection
    • MongoCollection::group - Performs an operation similar to SQL's GROUP BY command
    • MongoCollection::insert - 插入文档到集合中
    • MongoCollection::parallelCollectionScan - Returns an array of cursors to iterator over a full collection in parallel
    • MongoCollection::remove - 从集合中删除记录
    • MongoCollection::save - 保存一个文档到集合
    • MongoCollection::setReadPreference - Set the read preference for this collection
    • MongoCollection::setSlaveOkay - Change slaveOkay setting for this collection
    • MongoCollection::setWriteConcern - Set the write concern for this database
    • MongoCollection::toIndexString - Converts keys specifying an index to its identifying string
    • MongoCollection::update - Update records based on a given criteria
    • MongoCollection::validate - Validates this collection
    • MongoCollection::__construct - 创建一个新的集合
    • MongoCollection::__get - Gets a collection
    • MongoCollection::__toString - String representation of this collection
    • MongoCommandCursor::batchSize - Limits the number of elements returned in one batch
    • MongoCommandCursor::createFromDocument - Create a new command cursor from an existing command response document
    • MongoCommandCursor::current - Returns the current element
    • MongoCommandCursor::dead - Checks if there are results that have not yet been sent from the database
    • MongoCommandCursor::getReadPreference - Get the read preference for this command
    • MongoCommandCursor::info - Gets information about the cursor's creation and iteration
    • MongoCommandCursor::key - Returns the current result's index within the result set
    • MongoCommandCursor::next - Advances the cursor to the next result
    • MongoCommandCursor::rewind - Executes the command and resets the cursor to the start of the result set
    • MongoCommandCursor::setReadPreference - Set the read preference for this command
    • MongoCommandCursor::timeout - Sets a client-side timeout for this command
    • MongoCommandCursor::valid - Checks if the cursor is reading a valid result
    • MongoCommandCursor::__construct - Create a new command cursor
    • MongoCursor::addOption - Adds a top-level key/value pair to a query
    • MongoCursor::awaitData - Sets whether this cursor will wait for a while for a tailable cursor to return more data
    • MongoCursor::batchSize - Limits the number of elements returned in one batch
    • MongoCursor::count - Counts the number of results for this query
    • MongoCursor::current - Returns the current element
    • MongoCursor::dead - Checks if there are results that have not yet been sent from the database
    • MongoCursor::doQuery - Execute the query
    • MongoCursor::explain - Return an explanation of the query, often useful for optimization and debugging
    • MongoCursor::fields - Sets the fields for a query
    • MongoCursor::getNext - Advances the cursor to the next result, and returns that result
    • MongoCursor::getReadPreference - Get the read preference for this query
    • MongoCursor::hasNext - Checks if there are any more elements in this cursor
    • MongoCursor::hint - Gives the database a hint about the query
    • MongoCursor::immortal - Sets whether this cursor will timeout
    • MongoCursor::info - Gets information about the cursor's creation and iteration
    • MongoCursor::key - Returns the current result's _id, or its index within the result set
    • MongoCursor::limit - Limits the number of results returned
    • MongoCursor::maxTimeMS - Sets a server-side timeout for this query
    • MongoCursor::next - Advances the cursor to the next result, and returns that result
    • MongoCursor::partial - If this query should fetch partial results from mongos if a shard is down
    • MongoCursor::reset - Clears the cursor
    • MongoCursor::rewind - Returns the cursor to the beginning of the result set
    • MongoCursor::setFlag - Sets arbitrary flags in case there is no method available the specific flag
    • MongoCursor::setReadPreference - Set the read preference for this query
    • MongoCursor::skip - Skips a number of results
    • MongoCursor::slaveOkay - Sets whether this query can be done on a secondary [deprecated]
    • MongoCursor::snapshot - Use snapshot mode for the query
    • MongoCursor::sort - Sorts the results by given fields
    • MongoCursor::tailable - Sets whether this cursor will be left open after fetching the last results
    • MongoCursor::timeout - Sets a client-side timeout for this query
    • MongoCursor::valid - Checks if the cursor is reading a valid result
    • MongoCursor::__construct - Create a new cursor
    • MongoCursorException::getHost - 遇到该错误的服务器的 hostname
    • MongoCursorInterface::batchSize - Limits the number of elements returned in one batch
    • MongoCursorInterface::dead - Checks if there are results that have not yet been sent from the database
    • MongoCursorInterface::getReadPreference - Get the read preference for this query
    • MongoCursorInterface::info - Gets information about the cursor's creation and iteration
    • MongoCursorInterface::setReadPreference - Set the read preference for this query
    • MongoCursorInterface::timeout - Sets a client-side timeout for this query
    • MongoDate::toDateTime - Returns a DateTime object representing this date
    • MongoDate::__construct - 创建一个新的日期。
    • MongoDate::__toString - 返回该日期的字符串形式的表达
    • MongoDB::authenticate - 登录到数据库
    • MongoDB::command - 执行一条 Mongo 指令
    • MongoDB::createCollection - 创建一个集合
    • MongoDB::createDBRef - 创建数据库引用
    • MongoDB::drop - 删除数据库
    • MongoDB::dropCollection - Drops a collection [deprecated]
    • MongoDB::execute - 在数据库服务器上运行JavaScript
    • MongoDB::forceError - Creates a database error
    • MongoDB::getCollectionInfo - Returns information about collections in this database
    • MongoDB::getCollectionNames - Gets an array of names for all collections in this database
    • MongoDB::getDBRef - Fetches the document pointed to by a database reference
    • MongoDB::getGridFS - Fetches toolkit for dealing with files stored in this database
    • MongoDB::getProfilingLevel - Gets this database's profiling level
    • MongoDB::getReadPreference - Get the read preference for this database
    • MongoDB::getSlaveOkay - Get slaveOkay setting for this database
    • MongoDB::getWriteConcern - Get the write concern for this database
    • MongoDB::lastError - Check if there was an error on the most recent db operation performed
    • MongoDB::listCollections - Gets an array of MongoCollection objects for all collections in this database
    • MongoDB::prevError - Checks for the last error thrown during a database operation
    • MongoDB::repair - Repairs and compacts this database
    • MongoDB::resetError - Clears any flagged errors on the database
    • MongoDB::selectCollection - Gets a collection
    • MongoDB::setProfilingLevel - Sets this database's profiling level
    • MongoDB::setReadPreference - Set the read preference for this database
    • MongoDB::setSlaveOkay - Change slaveOkay setting for this database
    • MongoDB::setWriteConcern - Set the write concern for this database
    • MongoDB::__construct - 选择一个数据库
    • MongoDB::__get - Gets a collection
    • MongoDB::__toString - The name of this database
    • MongoDB context options - MongoDB context option listing
    • MongoDBRef::create - 创建一个新的数据库引用
    • MongoDBRef::get - 获取引用所指向的对象
    • MongoDBRef::isRef - 检测数组是否为数据库引用
    • MongoDB\BSON\Binary::getData - Returns the Binary's data
    • MongoDB\BSON\Binary::getType - Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize - Serialize a Binary
    • MongoDB\BSON\Binary::unserialize - Unserialize a Binary
    • MongoDB\BSON\Binary::__construct - Construct a new Binary
    • MongoDB\BSON\Binary::__toString - Returns the Binary's data
    • MongoDB\BSON\BinaryInterface::getData - Returns the BinaryInterface's data
    • MongoDB\BSON\BinaryInterface::getType - Returns the BinaryInterface's type
    • MongoDB\BSON\BinaryInterface::__toString - Returns the BinaryInterface's data
    • MongoDB\BSON\DBPointer::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\DBPointer::serialize - Serialize a DBPointer
    • MongoDB\BSON\DBPointer::unserialize - Unserialize a DBPointer
    • MongoDB\BSON\DBPointer::__construct - Construct a new DBPointer (unused)
    • MongoDB\BSON\DBPointer::__toString - Returns an empty string
    • MongoDB\BSON\Decimal128::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Decimal128::serialize - Serialize a Decimal128
    • MongoDB\BSON\Decimal128::unserialize - Unserialize a Decimal128
    • MongoDB\BSON\Decimal128::__construct - Construct a new Decimal128
    • MongoDB\BSON\Decimal128::__toString - Returns the string representation of this Decimal128
    • MongoDB\BSON\Decimal128Interface::__toString - Returns the string representation of this Decimal128Interface
    • MongoDB\BSON\fromJSON - Returns the BSON representation of a JSON value
    • MongoDB\BSON\fromPHP - Returns the BSON representation of a PHP value
    • MongoDB\BSON\Int64::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Int64::serialize - Serialize an Int64
    • MongoDB\BSON\Int64::unserialize - Unserialize an Int64
    • MongoDB\BSON\Int64::__construct - Construct a new Int64 (unused)
    • MongoDB\BSON\Int64::__toString - Returns the string representation of this Int64
    • MongoDB\BSON\Javascript::getCode - Returns the Javascript's code
    • MongoDB\BSON\Javascript::getScope - Returns the Javascript's scope document
    • MongoDB\BSON\Javascript::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Javascript::serialize - Serialize a Javascript
    • MongoDB\BSON\Javascript::unserialize - Unserialize a Javascript
    • MongoDB\BSON\Javascript::__construct - Construct a new Javascript
    • MongoDB\BSON\Javascript::__toString - Returns the Javascript's code
    • MongoDB\BSON\JavascriptInterface::getCode - Returns the JavascriptInterface's code
    • MongoDB\BSON\JavascriptInterface::getScope - Returns the JavascriptInterface's scope document
    • MongoDB\BSON\JavascriptInterface::__toString - Returns the JavascriptInterface's code
    • MongoDB\BSON\MaxKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize - Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize - Unserialize a MaxKey
    • MongoDB\BSON\MaxKey::__construct - Construct a new MaxKey
    • MongoDB\BSON\MinKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize - Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize - Unserialize a MinKey
    • MongoDB\BSON\MinKey::__construct - Construct a new MinKey
    • MongoDB\BSON\ObjectId::getTimestamp - Returns the timestamp component of this ObjectId
    • MongoDB\BSON\ObjectId::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\ObjectId::serialize - Serialize an ObjectId
    • MongoDB\BSON\ObjectId::unserialize - Unserialize an ObjectId
    • MongoDB\BSON\ObjectId::__construct - Construct a new ObjectId
    • MongoDB\BSON\ObjectId::__toString - Returns the hexidecimal representation of this ObjectId
    • MongoDB\BSON\ObjectIdInterface::getTimestamp - Returns the timestamp component of this ObjectIdInterface
    • MongoDB\BSON\ObjectIdInterface::__toString - Returns the hexidecimal representation of this ObjectIdInterface
    • MongoDB\BSON\Regex::getFlags - Returns the Regex's flags
    • MongoDB\BSON\Regex::getPattern - Returns the Regex's pattern
    • MongoDB\BSON\Regex::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Regex::serialize - Serialize a Regex
    • MongoDB\BSON\Regex::unserialize - Unserialize a Regex
    • MongoDB\BSON\Regex::__construct - Construct a new Regex
    • MongoDB\BSON\Regex::__toString - Returns the string representation of this Regex
    • MongoDB\BSON\RegexInterface::getFlags - Returns the RegexInterface's flags
    • MongoDB\BSON\RegexInterface::getPattern - Returns the RegexInterface's pattern
    • MongoDB\BSON\RegexInterface::__toString - Returns the string representation of this RegexInterface
    • MongoDB\BSON\Serializable::bsonSerialize - Provides an array or document to serialize as BSON
    • MongoDB\BSON\Symbol::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Symbol::serialize - Serialize a Symbol
    • MongoDB\BSON\Symbol::unserialize - Unserialize a Symbol
    • MongoDB\BSON\Symbol::__construct - Construct a new Symbol (unused)
    • MongoDB\BSON\Symbol::__toString - Returns the Symbol as a string
    • MongoDB\BSON\Timestamp::getIncrement - Returns the increment component of this Timestamp
    • MongoDB\BSON\Timestamp::getTimestamp - Returns the timestamp component of this Timestamp
    • MongoDB\BSON\Timestamp::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Timestamp::serialize - Serialize a Timestamp
    • MongoDB\BSON\Timestamp::unserialize - Unserialize a Timestamp
    • MongoDB\BSON\Timestamp::__construct - Construct a new Timestamp
    • MongoDB\BSON\Timestamp::__toString - Returns the string representation of this Timestamp
    • MongoDB\BSON\TimestampInterface::getIncrement - Returns the increment component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::getTimestamp - Returns the timestamp component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::__toString - Returns the string representation of this TimestampInterface
    • MongoDB\BSON\toCanonicalExtendedJSON - Returns the Canonical Extended JSON representation of a BSON value
    • MongoDB\BSON\toJSON - Returns the Legacy Extended JSON representation of a BSON value
    • MongoDB\BSON\toPHP - Returns the PHP representation of a BSON value
    • MongoDB\BSON\toRelaxedExtendedJSON - Returns the Relaxed Extended JSON representation of a BSON value
    • MongoDB\BSON\Undefined::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Undefined::serialize - Serialize a Undefined
    • MongoDB\BSON\Undefined::unserialize - Unserialize a Undefined
    • MongoDB\BSON\Undefined::__construct - Construct a new Undefined (unused)
    • MongoDB\BSON\Undefined::__toString - Returns an empty string
    • MongoDB\BSON\Unserializable::bsonUnserialize - Constructs the object from a BSON array or document
    • MongoDB\BSON\UTCDateTime::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize - Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime - Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize - Unserialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::__construct - Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString - Returns the string representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTimeInterface::toDateTime - Returns the DateTime representation of this UTCDateTimeInterface
    • MongoDB\BSON\UTCDateTimeInterface::__toString - Returns the string representation of this UTCDateTimeInterface
    • MongoDB\Driver\BulkWrite::count - Count number of write operations in the bulk
    • MongoDB\Driver\BulkWrite::delete - Add a delete operation to the bulk
    • MongoDB\Driver\BulkWrite::insert - Add an insert operation to the bulk
    • MongoDB\Driver\BulkWrite::update - Add an update operation to the bulk
    • MongoDB\Driver\BulkWrite::__construct - Create a new BulkWrite
    • MongoDB\Driver\Command::__construct - Create a new Command
    • MongoDB\Driver\Cursor::current - Returns the current element
    • MongoDB\Driver\Cursor::getId - Returns the ID for this cursor
    • MongoDB\Driver\Cursor::getServer - Returns the server associated with this cursor
    • MongoDB\Driver\Cursor::isDead - Checks if the cursor is exhausted or may have additional results
    • MongoDB\Driver\Cursor::key - Returns the current result's index within the cursor
    • MongoDB\Driver\Cursor::next - Advances the cursor to the next result
    • MongoDB\Driver\Cursor::rewind - Rewind the cursor to the first result
    • MongoDB\Driver\Cursor::setTypeMap - Sets a type map to use for BSON unserialization
    • MongoDB\Driver\Cursor::toArray - Returns an array containing all results for this cursor
    • MongoDB\Driver\Cursor::valid - Checks if the current position in the cursor is valid
    • MongoDB\Driver\Cursor::__construct - Create a new Cursor (not used)
    • MongoDB\Driver\CursorId::serialize - Serialize a CursorId
    • MongoDB\Driver\CursorId::unserialize - Unserialize a CursorId
    • MongoDB\Driver\CursorId::__construct - Create a new CursorId (not used)
    • MongoDB\Driver\CursorId::__toString - String representation of the cursor ID
    • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel - Returns whether an error label is associated with an exception
    • MongoDB\Driver\Exception\WriteException::getWriteResult - Returns the WriteResult for the failed write operation
    • MongoDB\Driver\Manager::createClientEncryption - Create a new ClientEncryption object
    • MongoDB\Driver\Manager::executeBulkWrite - Execute one or more write operations
    • MongoDB\Driver\Manager::executeCommand - Execute a database command
    • MongoDB\Driver\Manager::executeQuery - Execute a database query
    • MongoDB\Driver\Manager::executeReadCommand - Execute a database command that reads
    • MongoDB\Driver\Manager::executeReadWriteCommand - Execute a database command that reads and writes
    • MongoDB\Driver\Manager::executeWriteCommand - Execute a database command that writes
    • MongoDB\Driver\Manager::getReadConcern - Return the ReadConcern for the Manager
    • MongoDB\Driver\Manager::getReadPreference - Return the ReadPreference for the Manager
    • MongoDB\Driver\Manager::getServers - Return the servers to which this manager is connected
    • MongoDB\Driver\Manager::getWriteConcern - Return the WriteConcern for the Manager
    • MongoDB\Driver\Manager::selectServer - Select a server matching a read preference
    • MongoDB\Driver\Manager::startSession - Start a new client session for use with this client
    • MongoDB\Driver\Manager::__construct - Create new MongoDB Manager
    • MongoDB\Driver\Monitoring\addSubscriber - Registers a new monitoring event subscriber
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName - Returns the command name
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros - Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getError - Returns the Exception associated with the failed command
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId - Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getReply - Returns the command reply document
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId - Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer - Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand - Returns the command document
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName - Returns the command name
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName - Returns the database on which the command was executed
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId - Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId - Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer - Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed - Notification method for a failed command
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted - Notification method for a started command
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded - Notification method for a successful command
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName - Returns the command name
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros - Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId - Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply - Returns the command reply document
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId - Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer - Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\removeSubscriber - Unregisters an existing monitoring event subscriber
    • MongoDB\Driver\Query::__construct - Create a new Query
    • MongoDB\Driver\ReadConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadConcern::getLevel - Returns the ReadConcern's "level" option
    • MongoDB\Driver\ReadConcern::isDefault - Checks if this is the default read concern
    • MongoDB\Driver\ReadConcern::serialize - Serialize a ReadConcern
    • MongoDB\Driver\ReadConcern::unserialize - Unserialize a ReadConcern
    • MongoDB\Driver\ReadConcern::__construct - Create a new ReadConcern
    • MongoDB\Driver\ReadPreference::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadPreference::getHedge - Returns the ReadPreference's "hedge" option
    • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds - Returns the ReadPreference's "maxStalenessSeconds" option
    • MongoDB\Driver\ReadPreference::getMode - Returns the ReadPreference's "mode" option
    • MongoDB\Driver\ReadPreference::getModeString - Returns the ReadPreference's "mode" option as a string
    • MongoDB\Driver\ReadPreference::getTagSets - Returns the ReadPreference's "tagSets" option
    • MongoDB\Driver\ReadPreference::serialize - Serialize a ReadPreference
    • MongoDB\Driver\ReadPreference::unserialize - Unserialize a ReadPreference
    • MongoDB\Driver\ReadPreference::__construct - Create a new ReadPreference
    • MongoDB\Driver\Server::executeBulkWrite - Execute one or more write operations on this server
    • MongoDB\Driver\Server::executeCommand - Execute a database command on this server
    • MongoDB\Driver\Server::executeQuery - Execute a database query on this server
    • MongoDB\Driver\Server::executeReadCommand - Execute a database command that reads on this server
    • MongoDB\Driver\Server::executeReadWriteCommand - Execute a database command that reads and writes on this server
    • MongoDB\Driver\Server::executeWriteCommand - Execute a database command that writes on this server
    • MongoDB\Driver\Server::getHost - Returns the hostname of this server
    • MongoDB\Driver\Server::getInfo - Returns an array of information about this server
    • MongoDB\Driver\Server::getLatency - Returns the latency of this server
    • MongoDB\Driver\Server::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Server::getTags - Returns an array of tags describing this server in a replica set
    • MongoDB\Driver\Server::getType - Returns an integer denoting the type of this server
    • MongoDB\Driver\Server::isArbiter - Checks if this server is an arbiter member of a replica set
    • MongoDB\Driver\Server::isHidden - Checks if this server is a hidden member of a replica set
    • MongoDB\Driver\Server::isPassive - Checks if this server is a passive member of a replica set
    • MongoDB\Driver\Server::isPrimary - Checks if this server is a primary member of a replica set
    • MongoDB\Driver\Server::isSecondary - Checks if this server is a secondary member of a replica set
    • MongoDB\Driver\Server::__construct - Create a new Server (not used)
    • MongoDB\Driver\WriteConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\WriteConcern::getJournal - Returns the WriteConcern's "journal" option
    • MongoDB\Driver\WriteConcern::getW - Returns the WriteConcern's "w" option
    • MongoDB\Driver\WriteConcern::getWtimeout - Returns the WriteConcern's "wtimeout" option
    • MongoDB\Driver\WriteConcern::isDefault - Checks if this is the default write concern
    • MongoDB\Driver\WriteConcern::serialize - Serialize a WriteConcern
    • MongoDB\Driver\WriteConcern::unserialize - Unserialize a WriteConcern
    • MongoDB\Driver\WriteConcern::__construct - Create a new WriteConcern
    • MongoDB\Driver\WriteConcernError::getCode - Returns the WriteConcernError's error code
    • MongoDB\Driver\WriteConcernError::getInfo - Returns metadata document for the WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage - Returns the WriteConcernError's error message
    • MongoDB\Driver\WriteError::getCode - Returns the WriteError's error code
    • MongoDB\Driver\WriteError::getIndex - Returns the index of the write operation corresponding to this WriteError
    • MongoDB\Driver\WriteError::getInfo - Returns metadata document for the WriteError
    • MongoDB\Driver\WriteError::getMessage - Returns the WriteError's error message
    • MongoDB\Driver\WriteResult::getDeletedCount - Returns the number of documents deleted
    • MongoDB\Driver\WriteResult::getInsertedCount - Returns the number of documents inserted (excluding upserts)
    • MongoDB\Driver\WriteResult::getMatchedCount - Returns the number of documents selected for update
    • MongoDB\Driver\WriteResult::getModifiedCount - Returns the number of existing documents updated
    • MongoDB\Driver\WriteResult::getServer - Returns the server associated with this write result
    • MongoDB\Driver\WriteResult::getUpsertedCount - Returns the number of documents inserted by an upsert
    • MongoDB\Driver\WriteResult::getUpsertedIds - Returns an array of identifiers for upserted documents
    • MongoDB\Driver\WriteResult::getWriteConcernError - Returns any write concern error that occurred
    • MongoDB\Driver\WriteResult::getWriteErrors - Returns any write errors that occurred
    • MongoDB\Driver\WriteResult::isAcknowledged - Returns whether the write was acknowledged
    • MongoGridFS::delete - Remove a file and its chunks from the database
    • MongoGridFS::drop - Drops the files and chunks collections
    • MongoGridFS::find - Queries for files
    • MongoGridFS::findOne - Returns a single file matching the criteria
    • MongoGridFS::get - Retrieve a file from the database
    • MongoGridFS::put - Stores a file in the database
    • MongoGridFS::remove - Remove files and their chunks from the database
    • MongoGridFS::storeBytes - Stores a string of bytes in the database
    • MongoGridFS::storeFile - Stores a file in the database
    • MongoGridFS::storeUpload - Stores an uploaded file in the database
    • MongoGridFS::__construct - Creates new file collections
    • MongoGridFSCursor::current - Returns the current file
    • MongoGridFSCursor::getNext - Return the next file to which this cursor points, and advance the cursor
    • MongoGridFSCursor::key - Returns the current result's filename
    • MongoGridFSCursor::__construct - Create a new cursor
    • MongoGridFSFile::getBytes - Returns this file's contents as a string of bytes
    • MongoGridFSFile::getFilename - Returns this file's filename
    • MongoGridFSFile::getResource - Returns a resource that can be used to read the stored file
    • MongoGridFSFile::getSize - Returns this file's size
    • MongoGridFSFile::write - Writes this file to the filesystem
    • MongoGridfsFile::__construct - Create a new GridFS file
    • MongoId::getHostname - 获取这台机器上 id 所使用的 hostname
    • MongoId::getInc - 返回用于创建 id 所增加的值
    • MongoId::getPID - 获取进程 ID
    • MongoId::getTimestamp - 获取新纪元时间到 id 创建时的秒数。
    • MongoId::isValid - Check if a value is a valid ObjectId
    • MongoId::__construct - 创建一个新的id
    • MongoId::__set_state - 创建一个假的 MongoId
    • MongoId::__toString - 返回该 id 十六进制的表示形式
    • MongoInt32::__construct - 创建一个新的 32位 integer。
    • MongoInt32::__toString - 返回该 32 位 integer 的字符串表示。
    • MongoInt64::__construct - 创建一个新的 64 位 integer。
    • MongoInt64::__toString - 返回该 64 位 integer 的字符串表示形式。
    • MongoLog::getCallback - Gets the previously set callback function
    • MongoLog::getLevel - Gets the level(s) currently being logged
    • MongoLog::getModule - Gets the module(s) currently being logged
    • MongoLog::setCallback - Sets a callback function to be invoked for events
    • MongoLog::setLevel - Sets the level(s) to be logged
    • MongoLog::setModule - Sets the module(s) to be logged
    • MongoPool::getSize - Get pool size for connection pools
    • MongoPool::info - Returns information about all connection pools
    • MongoPool::setSize - Set the size for future connection pools
    • MongoRegex::__construct - 创建一个新的正则表达式
    • MongoRegex::__toString - 正则表达式的字符串表达形式
    • MongoResultException::getDocument - 获取完整的结果文档
    • MongoTimestamp::__construct - 创建一个新的时间戳。
    • MongoTimestamp::__toString - 返回时间戳的字符串表示形式
    • MongoWriteConcernException::getDocument - Get the error document
    • move_uploaded_file - 将上传的文件移动到新位置
    • mqseries_back - MQSeries MQBACK
    • mqseries_begin - MQseries MQBEGIN
    • mqseries_close - MQSeries MQCLOSE
    • mqseries_cmit - MQSeries MQCMIT
    • mqseries_conn - MQSeries MQCONN
    • mqseries_connx - MQSeries MQCONNX
    • mqseries_disc - MQSeries MQDISC
    • mqseries_get - MQSeries MQGET
    • mqseries_inq - MQSeries MQINQ
    • mqseries_open - MQSeries MQOPEN
    • mqseries_put - MQSeries MQPUT
    • mqseries_put1 - MQSeries MQPUT1
    • mqseries_set - MQSeries MQSET
    • mqseries_strerror - Returns the error message corresponding to a result code (MQRC)
    • msg_get_queue - Create or attach to a message queue
    • msg_queue_exists - Check whether a message queue exists
    • msg_receive - Receive a message from a message queue
    • msg_remove_queue - Destroy a message queue
    • msg_send - Send a message to a message queue
    • msg_set_queue - Set information in the message queue data structure
    • msg_stat_queue - Returns information from the message queue data structure
    • mt_getrandmax - 显示随机数的最大可能值
    • mt_rand - 生成更好的随机数
    • mt_srand - 播下一个更好的随机数发生器种子
    • MultipleIterator::attachIterator - Attaches iterator information
    • MultipleIterator::containsIterator - Checks if an iterator is attached
    • MultipleIterator::countIterators - Gets the number of attached iterator instances
    • MultipleIterator::current - Gets the registered iterator instances
    • MultipleIterator::detachIterator - Detaches an iterator
    • MultipleIterator::getFlags - Gets the flag information
    • MultipleIterator::key - Gets the registered iterator instances
    • MultipleIterator::next - Moves all attached iterator instances forward
    • MultipleIterator::rewind - Rewinds all attached iterator instances
    • MultipleIterator::setFlags - Sets flags
    • MultipleIterator::valid - Checks the validity of sub iterators
    • MultipleIterator::__construct - Constructs a new MultipleIterator
    • Mutex::create - 创建一个互斥量
    • Mutex::destroy - 销毁互斥量
    • Mutex::lock - 给互斥量加锁
    • Mutex::trylock - 尝试给互斥量加锁
    • Mutex::unlock - 释放互斥量上的锁
    • mysqli::$affected_rows - Gets the number of affected rows in a previous MySQL operation
    • mysqli::$client_info - 获取 MySQL 客户端信息
    • mysqli::$connect_errno - Returns the error code from last connect call
    • mysqli::$connect_error - Returns a string description of the last connect error
    • mysqli::$error - Returns a string description of the last error
    • mysqli::$error_list - Returns a list of errors from the last command executed
    • mysqli::$field_count - Returns the number of columns for the most recent query
    • mysqli::$host_info - 返回一个表述使用的连接类型的字符串
    • mysqli::$info - 返回最近执行的 SQL 语句的信息
    • mysqli::$insert_id - 返回最后一条插入语句产生的自增 ID
    • mysqli::$protocol_version - 返回MySQL使用的协议版本号
    • mysqli::$server_info - 返回MySQL服务器的版本号
    • mysqli::$server_version - 作为一个整数返回MySQL服务器的版本
    • mysqli::$sqlstate - 返回上一次 SQL 操作的 SQLSTATE 错误信息
    • mysqli::$thread_id - 返回当前连接的线程 ID
    • mysqli::$warning_count - Returns the number of warnings from the last query for the given link
    • mysqli::autocommit - 打开或关闭本次数据库连接的自动命令提交事务模式
    • mysqli::begin_transaction - Starts a transaction
    • mysqli::change_user - Changes the user of the specified database connection
    • mysqli::character_set_name - 返回当前数据库连接的默认字符编码
    • mysqli::close - 关闭先前打开的数据库连接
    • mysqli::commit - 提交一个事务
    • mysqli::debug - Performs debugging operations
    • mysqli::dump_debug_info - 将调试信息输出到日志
    • mysqli::errno - 返回最近函数调用的错误代码
    • mysqli::get_charset - Returns a character set object
    • mysqli::get_connection_stats - 返回客户端连接的统计数据
    • mysqli::get_warnings - Get result of SHOW WARNINGS
    • mysqli::init - 初始化 MySQLi 并返回一个资源类型的值，这个值可以作为 mysqli_real_connect() 函数的传入参数
    • mysqli::kill - 让服务器杀掉一个 MySQL 线程
    • mysqli::more_results - 检查批量查询中是否还有查询结果
    • mysqli::multi_query - 执行查询
    • mysqli::next_result - 为读取 multi_query 执行之后的下一个结果集做准备
    • mysqli::options - 设置选项
    • mysqli::ping - ping 一个连接，或者如果连接处于断开状态，重新连接
    • mysqli::poll - 轮询连接
    • mysqli::prepare - 准备执行一个 SQL 语句
    • mysqli::query - 对数据库执行一次查询
    • mysqli::real_connect - 建立一个 MySQL 服务器连接
    • mysqli::real_escape_string - 根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义
    • mysqli::real_query - 执行一个mysql查询
    • mysqli::reap_async_query - 获取异步查询的结果
    • mysqli::refresh - 刷新
    • mysqli::release_savepoint - 从当前事务的保存点中移除一个命名保存点
    • mysqli::rollback - 回退当前事务
    • mysqli::savepoint - 在当前事务中增加一个命名保存点
    • mysqli::select_db - 选择用于数据库查询的默认数据库
    • mysqli::set_charset - 设置默认字符编码
    • mysqli::set_opt - Alias of mysqli_options
    • mysqli::ssl_set - 使用 SSL 建立到数据库之间的安全连接
    • mysqli::stat - 获取当前系统状态信息
    • mysqli::stmt_init - 初始化一条语句并返回一个用于mysqli_stmt_prepare(调用)的对象
    • mysqli::store_result - 转移上一次查询返回的结果集
    • mysqli::thread_safe - 返回是否是线程安全的
    • mysqli::use_result - Initiate a result set retrieval
    • mysqli::__construct - Open a new connection to the MySQL server
    • mysqli_connect - 别名 mysqli::__construct
    • mysqli_driver::$report_mode - Sets mysqli error reporting mode
    • mysqli_driver::embedded_server_end - Stop embedded server
    • mysqli_driver::embedded_server_start - Initialize and start embedded server
    • mysqli_escape_string - 别名 mysqli_real_escape_string
    • mysqli_execute - mysqli_stmt_execute 的别名
    • mysqli_get_client_stats - 返回客户端进程统计信息
    • mysqli_get_client_version - 作为一个整数返回MySQL客户端的版本
    • mysqli_get_links_stats - 返回打开和缓存的链接相关信息
    • mysqli_report - 别名 mysqli_driver->report_mode
    • mysqli_result::$current_field - Get current field offset of a result pointer
    • mysqli_result::$field_count - Get the number of fields in a result
    • mysqli_result::$lengths - Returns the lengths of the columns of the current row in the result set
    • mysqli_result::$num_rows - Gets the number of rows in a result
    • mysqli_result::data_seek - Adjusts the result pointer to an arbitrary row in the result
    • mysqli_result::fetch_all - Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array - Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc - Fetch a result row as an associative array
    • mysqli_result::fetch_field - Returns the next field in the result set
    • mysqli_result::fetch_fields - Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_field_direct - Fetch meta-data for a single field
    • mysqli_result::fetch_object - Returns the current row of a result set as an object
    • mysqli_result::fetch_row - Get a result row as an enumerated array
    • mysqli_result::field_seek - Set result pointer to a specified field offset
    • mysqli_result::free - Frees the memory associated with a result
    • mysqli_stmt::$affected_rows - Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • mysqli_stmt::$errno - Returns the error code for the most recent statement call
    • mysqli_stmt::$error - Returns a string description for last statement error
    • mysqli_stmt::$error_list - Returns a list of errors from the last statement executed
    • mysqli_stmt::$field_count - Returns the number of columns in the given statement
    • mysqli_stmt::$insert_id - Get the ID generated from the previous INSERT operation
    • mysqli_stmt::$num_rows - Return the number of rows in statements result set
    • mysqli_stmt::$param_count - Returns the number of parameters for the given statement
    • mysqli_stmt::$sqlstate - Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::attr_get - Used to get the current value of a statement attribute
    • mysqli_stmt::attr_set - Used to modify the behavior of a prepared statement
    • mysqli_stmt::bind_param - Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result - Binds variables to a prepared statement for result storage
    • mysqli_stmt::close - Closes a prepared statement
    • mysqli_stmt::data_seek - Seeks to an arbitrary row in statement result set
    • mysqli_stmt::execute - Executes a prepared Query
    • mysqli_stmt::fetch - Fetch results from a prepared statement into the bound variables
    • mysqli_stmt::free_result - Frees stored result memory for the given statement handle
    • mysqli_stmt::get_result - Gets a result set from a prepared statement
    • mysqli_stmt::get_warnings - Get result of SHOW WARNINGS
    • mysqli_stmt::more_results - Check if there are more query results from a multiple query
    • mysqli_stmt::next_result - Reads the next result from a multiple query
    • mysqli_stmt::prepare - Prepare an SQL statement for execution
    • mysqli_stmt::reset - Resets a prepared statement
    • mysqli_stmt::result_metadata - Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data - Send data in blocks
    • mysqli_stmt::store_result - Transfers a result set from a prepared statement
    • mysqli_stmt::__construct - Constructs a new mysqli_stmt object
    • mysqli_warning::next - Fetch next warning
    • MysqlndUhConnection::changeUser - Changes the user of the specified mysqlnd database connection
    • MysqlndUhConnection::charsetName - Returns the default character set for the database connection
    • MysqlndUhConnection::close - Closes a previously opened database connection
    • MysqlndUhConnection::connect - Open a new connection to the MySQL server
    • MysqlndUhConnection::endPSession - End a persistent connection
    • MysqlndUhConnection::escapeString - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • MysqlndUhConnection::getAffectedRows - Gets the number of affected rows in a previous MySQL operation
    • MysqlndUhConnection::getErrorNumber - Returns the error code for the most recent function call
    • MysqlndUhConnection::getErrorString - Returns a string description of the last error
    • MysqlndUhConnection::getFieldCount - Returns the number of columns for the most recent query
    • MysqlndUhConnection::getHostInformation - Returns a string representing the type of connection used
    • MysqlndUhConnection::getLastInsertId - Returns the auto generated id used in the last query
    • MysqlndUhConnection::getLastMessage - Retrieves information about the most recently executed query
    • MysqlndUhConnection::getProtocolInformation - Returns the version of the MySQL protocol used
    • MysqlndUhConnection::getServerInformation - Returns the version of the MySQL server
    • MysqlndUhConnection::getServerStatistics - Gets the current system status
    • MysqlndUhConnection::getServerVersion - Returns the version of the MySQL server as an integer
    • MysqlndUhConnection::getSqlstate - Returns the SQLSTATE error from previous MySQL operation
    • MysqlndUhConnection::getStatistics - Returns statistics about the client connection
    • MysqlndUhConnection::getThreadId - Returns the thread ID for the current connection
    • MysqlndUhConnection::getWarningCount - Returns the number of warnings from the last query for the given link
    • MysqlndUhConnection::init - Initialize mysqlnd connection
    • MysqlndUhConnection::killConnection - Asks the server to kill a MySQL thread
    • MysqlndUhConnection::listFields - List MySQL table fields
    • MysqlndUhConnection::listMethod - Wrapper for assorted list commands
    • MysqlndUhConnection::moreResults - Check if there are any more query results from a multi query
    • MysqlndUhConnection::nextResult - Prepare next result from multi_query
    • MysqlndUhConnection::ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • MysqlndUhConnection::query - Performs a query on the database
    • MysqlndUhConnection::queryReadResultsetHeader - Read a result set header
    • MysqlndUhConnection::reapQuery - Get result from async query
    • MysqlndUhConnection::refreshServer - Flush or reset tables and caches
    • MysqlndUhConnection::restartPSession - Restart a persistent mysqlnd connection
    • MysqlndUhConnection::selectDb - Selects the default database for database queries
    • MysqlndUhConnection::sendClose - Sends a close command to MySQL
    • MysqlndUhConnection::sendQuery - Sends a query to MySQL
    • MysqlndUhConnection::serverDumpDebugInformation - Dump debugging information into the log for the MySQL server
    • MysqlndUhConnection::setAutocommit - Turns on or off auto-committing database modifications
    • MysqlndUhConnection::setCharset - Sets the default client character set
    • MysqlndUhConnection::setClientOption - Sets a client option
    • MysqlndUhConnection::setServerOption - Sets a server option
    • MysqlndUhConnection::shutdownServer - The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand - Sends a basic COM_* command
    • MysqlndUhConnection::simpleCommandHandleResponse - Process a response for a basic COM_* command send to the client
    • MysqlndUhConnection::sslSet - Used for establishing secure connections using SSL
    • MysqlndUhConnection::stmtInit - Initializes a statement and returns a resource for use with mysqli_statement::prepare
    • MysqlndUhConnection::storeResult - Transfers a result set from the last query
    • MysqlndUhConnection::txCommit - Commits the current transaction
    • MysqlndUhConnection::txRollback - Rolls back current transaction
    • MysqlndUhConnection::useResult - Initiate a result set retrieval
    • MysqlndUhConnection::__construct - The __construct purpose
    • MysqlndUhPreparedStatement::execute - Executes a prepared Query
    • MysqlndUhPreparedStatement::prepare - Prepare an SQL statement for execution
    • MysqlndUhPreparedStatement::__construct - The __construct purpose
    • mysqlnd_memcache_get_config - Returns information about the plugin configuration
    • mysqlnd_memcache_set - Associate a MySQL connection with a Memcache connection
    • mysqlnd_ms_dump_servers - Returns a list of currently configured servers
    • mysqlnd_ms_fabric_select_global - Switch to global sharding server for a given table
    • mysqlnd_ms_fabric_select_shard - Switch to shard
    • mysqlnd_ms_get_last_gtid - 返回最后的全局同步 ID (GTID)
    • mysqlnd_ms_get_last_used_connection - Returns an array which describes the last used connection
    • mysqlnd_ms_get_stats - Returns query distribution and connection statistics
    • mysqlnd_ms_match_wild - Finds whether a table name matches a wildcard pattern or not
    • mysqlnd_ms_query_is_select - 查询给定的 SQL 会发送给 master、slave 还是最后使用的 MySQL server 执行。
    • mysqlnd_ms_set_qos - Sets the quality of service needed from the cluster
    • mysqlnd_ms_set_user_pick_server - Sets a callback for user-defined read/write splitting
    • mysqlnd_ms_xa_begin - Starts a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_commit - Commits a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_gc - Garbage collects unfinished XA transactions after severe errors
    • mysqlnd_ms_xa_rollback - Rolls back a distributed/XA transaction among MySQL servers
    • mysqlnd_qc_clear_cache - Flush all cache contents
    • mysqlnd_qc_get_available_handlers - Returns a list of available storage handler
    • mysqlnd_qc_get_cache_info - Returns information on the current handler, the number of cache entries and cache entries, if available
    • mysqlnd_qc_get_core_stats - Statistics collected by the core of the query cache
    • mysqlnd_qc_get_normalized_query_trace_log - Returns a normalized query trace log for each query inspected by the query cache
    • mysqlnd_qc_get_query_trace_log - Returns a backtrace for each query inspected by the query cache
    • mysqlnd_qc_set_cache_condition - Set conditions for automatic caching
    • mysqlnd_qc_set_is_select - Installs a callback which decides whether a statement is cached
    • mysqlnd_qc_set_storage_handler - Change current storage handler
    • mysqlnd_qc_set_user_handlers - Sets the callback functions for a user-defined procedural storage handler
    • mysqlnd_uh_convert_to_mysqlnd - Converts a MySQL connection handle into a mysqlnd connection handle
    • mysqlnd_uh_set_connection_proxy - Installs a proxy for mysqlnd connections
    • mysqlnd_uh_set_statement_proxy - Installs a proxy for mysqlnd statements
    • mysql_affected_rows - 取得前一次 MySQL 操作所影响的记录行数
    • mysql_client_encoding - 返回字符集的名称
    • mysql_close - 关闭 MySQL 连接
    • mysql_connect - 打开一个到 MySQL 服务器的连接
    • mysql_create_db - 新建一个 MySQL 数据库
    • mysql_data_seek - 移动内部结果的指针
    • mysql_db_name - 取得 mysql_list_dbs 返回的结果数据
    • mysql_db_query - 发送一条 MySQL 查询
    • mysql_drop_db - 丢弃（删除）一个 MySQL 数据库
    • mysql_errno - 返回上一个 MySQL 操作中的错误信息的数字编码
    • mysql_error - 返回上一个 MySQL 操作产生的文本错误信息
    • mysql_escape_string - 转义一个字符串用于 mysql_query
    • mysql_fetch_array - 从结果集中取得一行作为关联数组
    • mysql_fetch_assoc - 从结果集中取得一行作为关联数组
    • mysql_fetch_field - 从结果集中取得列信息并作为对象返回
    • mysql_fetch_lengths - 取得结果集中每个输出的长度
    • mysql_fetch_object - 从结果集中取得一行作为对象返回
    • mysql_fetch_row - 从结果集中取得一行作为枚举数组
    • mysql_field_flags - 从结果中取得和指定字段关联的标志
    • mysql_field_len - 返回指定字段的长度
    • mysql_field_name - 取得结果中指定字段的字段名
    • mysql_field_seek - 将结果集中的指针设定为制定的字段偏移量
    • mysql_field_table - 取得指定字段所在的表名
    • mysql_field_type - 取得结果集中指定字段的类型
    • mysql_free_result - 释放结果内存
    • mysql_get_client_info - 取得 MySQL 客户端信息
    • mysql_get_host_info - 取得 MySQL 主机信息
    • mysql_get_proto_info - 取得 MySQL 协议信息
    • mysql_get_server_info - 取得 MySQL 服务器信息
    • mysql_info - 取得最近一条查询的信息
    • mysql_insert_id - 取得上一步 INSERT 操作产生的 ID
    • mysql_list_dbs - 列出 MySQL 服务器中所有的数据库
    • mysql_list_fields - 列出 MySQL 结果中的字段
    • mysql_list_processes - 列出 MySQL 进程
    • mysql_list_tables - 列出 MySQL 数据库中的表
    • mysql_num_fields - 取得结果集中字段的数目
    • mysql_num_rows - 取得结果集中行的数目
    • mysql_pconnect - 打开一个到 MySQL 服务器的持久连接
    • mysql_ping - Ping 一个服务器连接，如果没有连接则重新连接
    • mysql_query - 发送一条 MySQL 查询
    • mysql_real_escape_string - 转义 SQL 语句中使用的字符串中的特殊字符，并考虑到连接的当前字符集
    • mysql_result - 取得结果数据
    • mysql_select_db - 选择 MySQL 数据库
    • mysql_set_charset - 设置客户端的字符集
    • mysql_stat - 取得当前系统状态
    • mysql_tablename - 取得表名
    • mysql_thread_id - 返回当前线程的 ID
    • mysql_unbuffered_query - 向 MySQL 发送一条 SQL 查询，并不获取和缓存结果的行
    • mysql_xdevapi\Client::close - Close client
  • n
    • natcasesort - 用“自然排序”算法对数组进行不区分大小写字母的排序
    • natsort - 用“自然排序”算法对数组排序
    • ncurses_addch - Add character at current position and advance cursor
    • ncurses_addchnstr - Add attributed string with specified length at current position
    • ncurses_addchstr - Add attributed string at current position
    • ncurses_addnstr - Add string with specified length at current position
    • ncurses_addstr - Output text at current position
    • ncurses_assume_default_colors - Define default colors for color 0
    • ncurses_attroff - Turn off the given attributes
    • ncurses_attron - Turn on the given attributes
    • ncurses_attrset - Set given attributes
    • ncurses_baudrate - Returns baudrate of terminal
    • ncurses_beep - Let the terminal beep
    • ncurses_bkgd - Set background property for terminal screen
    • ncurses_bkgdset - Control screen background
    • ncurses_border - Draw a border around the screen using attributed characters
    • ncurses_bottom_panel - Moves a visible panel to the bottom of the stack
    • ncurses_can_change_color - Checks if terminal color definitions can be changed
    • ncurses_cbreak - Switch off input buffering
    • ncurses_clear - Clear screen
    • ncurses_clrtobot - Clear screen from current position to bottom
    • ncurses_clrtoeol - Clear screen from current position to end of line
    • ncurses_color_content - Retrieves RGB components of a color
    • ncurses_color_set - Set active foreground and background colors
    • ncurses_curs_set - Set cursor state
    • ncurses_define_key - Define a keycode
    • ncurses_def_prog_mode - Saves terminals (program) mode
    • ncurses_def_shell_mode - Saves terminals (shell) mode
    • ncurses_delay_output - Delay output on terminal using padding characters
    • ncurses_delch - Delete character at current position, move rest of line left
    • ncurses_deleteln - Delete line at current position, move rest of screen up
    • ncurses_delwin - Delete a ncurses window
    • ncurses_del_panel - Remove panel from the stack and delete it (but not the associated window)
    • ncurses_doupdate - Write all prepared refreshes to terminal
    • ncurses_echo - Activate keyboard input echo
    • ncurses_echochar - Single character output including refresh
    • ncurses_end - Stop using ncurses, clean up the screen
    • ncurses_erase - Erase terminal screen
    • ncurses_erasechar - Returns current erase character
    • ncurses_filter - Set LINES for iniscr() and newterm() to 1
    • ncurses_flash - Flash terminal screen (visual bell)
    • ncurses_flushinp - Flush keyboard input buffer
    • ncurses_getch - Read a character from keyboard
    • ncurses_getmaxyx - Returns the size of a window
    • ncurses_getmouse - Reads mouse event
    • ncurses_getyx - Returns the current cursor position for a window
    • ncurses_halfdelay - Put terminal into halfdelay mode
    • ncurses_has_colors - Checks if terminal has color capabilities
    • ncurses_has_ic - Check for insert- and delete-capabilities
    • ncurses_has_il - Check for line insert- and delete-capabilities
    • ncurses_has_key - Check for presence of a function key on terminal keyboard
    • ncurses_hide_panel - Remove panel from the stack, making it invisible
    • ncurses_hline - Draw a horizontal line at current position using an attributed character and max. n characters long
    • ncurses_inch - Get character and attribute at current position
    • ncurses_init - Initialize ncurses
    • ncurses_init_color - Define a terminal color
    • ncurses_init_pair - Define a color pair
    • ncurses_insch - Insert character moving rest of line including character at current position
    • ncurses_insdelln - Insert lines before current line scrolling down (negative numbers delete and scroll up)
    • ncurses_insertln - Insert a line, move rest of screen down
    • ncurses_insstr - Insert string at current position, moving rest of line right
    • ncurses_instr - Reads string from terminal screen
    • ncurses_isendwin - Ncurses is in endwin mode, normal screen output may be performed
    • ncurses_keyok - Enable or disable a keycode
    • ncurses_keypad - Turns keypad on or off
    • ncurses_killchar - Returns current line kill character
    • ncurses_longname - Returns terminals description
    • ncurses_meta - Enables/Disable 8-bit meta key information
    • ncurses_mouseinterval - Set timeout for mouse button clicks
    • ncurses_mousemask - Sets mouse options
    • ncurses_mouse_trafo - Transforms coordinates
    • ncurses_move - Move output position
    • ncurses_move_panel - Moves a panel so that its upper-left corner is at [startx, starty]
    • ncurses_mvaddch - Move current position and add character
    • ncurses_mvaddchnstr - Move position and add attributed string with specified length
    • ncurses_mvaddchstr - Move position and add attributed string
    • ncurses_mvaddnstr - Move position and add string with specified length
    • ncurses_mvaddstr - Move position and add string
    • ncurses_mvcur - Move cursor immediately
    • ncurses_mvdelch - Move position and delete character, shift rest of line left
    • ncurses_mvgetch - Move position and get character at new position
    • ncurses_mvhline - Set new position and draw a horizontal line using an attributed character and max. n characters long
    • ncurses_mvinch - Move position and get attributed character at new position
    • ncurses_mvvline - Set new position and draw a vertical line using an attributed character and max. n characters long
    • ncurses_mvwaddstr - Add string at new position in window
    • ncurses_napms - Sleep
    • ncurses_newpad - Creates a new pad (window)
    • ncurses_newwin - Create a new window
    • ncurses_new_panel - Create a new panel and associate it with window
    • ncurses_nl - Translate newline and carriage return / line feed
    • ncurses_nocbreak - Switch terminal to cooked mode
    • ncurses_noecho - Switch off keyboard input echo
    • ncurses_nonl - Do not translate newline and carriage return / line feed
    • ncurses_noqiflush - Do not flush on signal characters
    • ncurses_noraw - Switch terminal out of raw mode
    • ncurses_pair_content - Retrieves foreground and background colors of a color pair
    • ncurses_panel_above - Returns the panel above panel
    • ncurses_panel_below - Returns the panel below panel
    • ncurses_panel_window - Returns the window associated with panel
    • ncurses_pnoutrefresh - Copies a region from a pad into the virtual screen
    • ncurses_prefresh - Copies a region from a pad into the virtual screen
    • ncurses_putp - Apply padding information to the string and output it
    • ncurses_qiflush - Flush on signal characters
    • ncurses_raw - Switch terminal into raw mode
    • ncurses_refresh - Refresh screen
    • ncurses_replace_panel - Replaces the window associated with panel
    • ncurses_resetty - Restores saved terminal state
    • ncurses_reset_prog_mode - Resets the prog mode saved by def_prog_mode
    • ncurses_reset_shell_mode - Resets the shell mode saved by def_shell_mode
    • ncurses_savetty - Saves terminal state
    • ncurses_scrl - Scroll window content up or down without changing current position
    • ncurses_scr_dump - Dump screen content to file
    • ncurses_scr_init - Initialize screen from file dump
    • ncurses_scr_restore - Restore screen from file dump
    • ncurses_scr_set - Inherit screen from file dump
    • ncurses_show_panel - Places an invisible panel on top of the stack, making it visible
    • ncurses_slk_attr - Returns current soft label key attribute
    • ncurses_slk_attroff - Turn off the given attributes for soft function-key labels
    • ncurses_slk_attron - Turn on the given attributes for soft function-key labels
    • ncurses_slk_attrset - Set given attributes for soft function-key labels
    • ncurses_slk_clear - Clears soft labels from screen
    • ncurses_slk_color - Sets color for soft label keys
    • ncurses_slk_init - Initializes soft label key functions
    • ncurses_slk_noutrefresh - Copies soft label keys to virtual screen
    • ncurses_slk_refresh - Copies soft label keys to screen
    • ncurses_slk_restore - Restores soft label keys
    • ncurses_slk_set - Sets function key labels
    • ncurses_slk_touch - Forces output when ncurses_slk_noutrefresh is performed
    • ncurses_standend - Stop using 'standout' attribute
    • ncurses_standout - Start using 'standout' attribute
    • ncurses_start_color - Initializes color functionality
    • ncurses_termattrs - Returns a logical OR of all attribute flags supported by terminal
    • ncurses_termname - Returns terminals (short)-name
    • ncurses_timeout - Set timeout for special key sequences
    • ncurses_top_panel - Moves a visible panel to the top of the stack
    • ncurses_typeahead - Specify different filedescriptor for typeahead checking
    • ncurses_ungetch - Put a character back into the input stream
    • ncurses_ungetmouse - Pushes mouse event to queue
    • ncurses_update_panels - Refreshes the virtual screen to reflect the relations between panels in the stack
    • ncurses_use_default_colors - Assign terminal default colors to color id -1
    • ncurses_use_env - Control use of environment information about terminal size
    • ncurses_use_extended_names - Control use of extended names in terminfo descriptions
    • ncurses_vidattr - Display the string on the terminal in the video attribute mode
    • ncurses_vline - Draw a vertical line at current position using an attributed character and max. n characters long
    • ncurses_waddch - Adds character at current position in a window and advance cursor
    • ncurses_waddstr - Outputs text at current postion in window
    • ncurses_wattroff - Turns off attributes for a window
    • ncurses_wattron - Turns on attributes for a window
    • ncurses_wattrset - Set the attributes for a window
    • ncurses_wborder - Draws a border around the window using attributed characters
    • ncurses_wclear - Clears window
    • ncurses_wcolor_set - Sets windows color pairings
    • ncurses_werase - Erase window contents
    • ncurses_wgetch - Reads a character from keyboard (window)
    • ncurses_whline - Draws a horizontal line in a window at current position using an attributed character and max. n characters long
    • ncurses_wmouse_trafo - Transforms window/stdscr coordinates
    • ncurses_wmove - Moves windows output position
    • ncurses_wnoutrefresh - Copies window to virtual screen
    • ncurses_wrefresh - Refresh window on terminal screen
    • ncurses_wstandend - End standout mode for a window
    • ncurses_wstandout - Enter standout mode for a window
    • ncurses_wvline - Draws a vertical line in a window at current position using an attributed character and max. n characters long
    • next - 将数组中的内部指针向前移动一位
    • ngettext - Plural version of gettext
    • nl2br - 在字符串所有新行之前插入 HTML 换行标记
    • nl_langinfo - Query language and locale information
    • NoRewindIterator::current - Get the current value
    • NoRewindIterator::getInnerIterator - Get the inner iterator
    • NoRewindIterator::key - Get the current key
    • NoRewindIterator::next - Forward to the next element
    • NoRewindIterator::rewind - Prevents the rewind operation on the inner iterator
    • NoRewindIterator::valid - Validates the iterator
    • NoRewindIterator::__construct - Construct a NoRewindIterator
    • Normalizer::getRawDecomposition - Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
    • Normalizer::isNormalized - Checks if the provided string is already in the specified normalization form
    • Normalizer::normalize - Normalizes the input provided and returns the normalized string
    • NumberFormatter::create - Create a number formatter
    • NumberFormatter::format - Format a number
    • NumberFormatter::formatCurrency - Format a currency value
    • NumberFormatter::getAttribute - Get an attribute
    • NumberFormatter::getErrorCode - Get formatter's last error code
    • NumberFormatter::getErrorMessage - Get formatter's last error message
    • NumberFormatter::getLocale - Get formatter locale
    • NumberFormatter::getPattern - Get formatter pattern
    • NumberFormatter::getSymbol - Get a symbol value
    • NumberFormatter::getTextAttribute - Get a text attribute
    • NumberFormatter::parse - Parse a number
    • NumberFormatter::parseCurrency - Parse a currency number
    • NumberFormatter::setAttribute - Set an attribute
    • NumberFormatter::setPattern - Set formatter pattern
    • NumberFormatter::setSymbol - Set a symbol value
    • NumberFormatter::setTextAttribute - Set a text attribute
    • number_format - 以千位分隔符方式格式化一个数字
  • o
    • OAuth::disableDebug - 关闭详细的调试
    • OAuth::disableRedirects - 关闭重定向
    • OAuth::disableSSLChecks - 关闭 SSL 检查
    • OAuth::enableDebug - 启用详细调试
    • OAuth::enableRedirects - 启用重定向
    • OAuth::enableSSLChecks - 启用 SSL 检查
    • OAuth::fetch - 获取一个 OAuth 受保护的资源
    • OAuth::generateSignature - 生成一个签名
    • OAuth::getAccessToken - 获取一个访问令牌
    • OAuth::getCAPath - 获取 CA 信息
    • OAuth::getLastResponse - 获取最后一次的响应
    • OAuth::getLastResponseHeaders - 获取最后一次响应的头信息
    • OAuth::getLastResponseInfo - 获取关于最后一次响应的 HTTP 信息
    • OAuth::getRequestHeader - 生成 OAuth 头信息字符串签名
    • OAuth::getRequestToken - 获取一个请求令牌
    • OAuth::setAuthType - 设置授权类型
    • OAuth::setCAPath - 设置 CA 路径和信息
    • OAuth::setNonce - 为后续请求设置现时标志
    • OAuth::setRequestEngine - 设置目标请求引擎
    • OAuth::setRSACertificate - 设置 RSA 证书
    • OAuth::setSSLChecks - 调整特定的SSL请求检查
    • OAuth::setTimestamp - 设置时间戳
    • OAuth::setToken - 设置令牌和 secret
    • OAuth::setVersion - 设置 OAuth 版本
    • OAuth::__construct - 新建一个 OAuth 对象
    • OAuth::__destruct - 析构函数
    • OAuthProvider::addRequiredParameter - 添加必需的参数
    • OAuthProvider::callconsumerHandler - 调用 consumerNonceHandler 回调函数
    • OAuthProvider::callTimestampNonceHandler - 调用 timestampNonceHandler 回调函数
    • OAuthProvider::calltokenHandler - 调用 tokenNonceHandler 回调函数
    • OAuthProvider::checkOAuthRequest - 检查一个 oauth 请求
    • OAuthProvider::consumerHandler - 设置 consumerHandler 句柄回调函数
    • OAuthProvider::generateToken - 生成一个随机令牌
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - 设置 isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - 移除一个必需的参数
    • OAuthProvider::reportProblem - 报告问题
    • OAuthProvider::setParam - 设置一个参数
    • OAuthProvider::setRequestTokenPath - 设置请求令牌路径
    • OAuthProvider::timestampNonceHandler - 设置 timestampNonceHandler 句柄回调函数
    • OAuthProvider::tokenHandler - 设置 tokenHandler 句柄回调函数
    • OAuthProvider::__construct - 新建一个 OAuthProvider 对象
    • oauth_get_sbs - 生成一个签名字符基串
    • oauth_urlencode - 将 URI 编码为 RFC 3986 规范
    • ob_clean - 清空（擦掉）输出缓冲区
    • ob_end_clean - 清空（擦除）缓冲区并关闭输出缓冲
    • ob_end_flush - 冲刷出（送出）输出缓冲区内容并关闭缓冲
    • ob_flush - 冲刷出（送出）输出缓冲区中的内容
    • ob_get_clean - 得到当前缓冲区的内容并删除当前输出缓。
    • ob_get_contents - 返回输出缓冲区的内容
    • ob_get_flush - 刷出（送出）缓冲区内容，以字符串形式返回内容，并关闭输出缓冲区。
    • ob_get_length - 返回输出缓冲区内容的长度
    • ob_get_level - 返回输出缓冲机制的嵌套级别
    • ob_get_status - 得到所有输出缓冲区的状态
    • ob_gzhandler - 在ob_start中使用的用来压缩输出缓冲区中内容的回调函数。ob_start callback function to gzip output buffer
    • ob_iconv_handler - 以输出缓冲处理程序转换字符编码
    • ob_implicit_flush - 打开/关闭绝对刷送
    • ob_list_handlers - 列出所有使用中的输出处理程序。
    • ob_start - 打开输出控制缓冲
    • ob_tidyhandler - ob_start callback function to repair the buffer
    • ocibindbyname - 别名 oci_bind_by_name
    • ocicancel - 别名 oci_cancel
    • ocicloselob - 别名 OCI-Lob::close
    • ocicollappend - 别名 OCICollection::append
    • ocicollassign - 别名 OCICollection::assign
    • ocicollassignelem - 别名 OCICollection::assignElem
    • OCICollection::append - Appends element to the collection
    • OCICollection::assign - Assigns a value to the collection from another existing collection
    • OCICollection::assignElem - Assigns a value to the element of the collection
    • OCICollection::free - Frees the resources associated with the collection object
    • OCICollection::getElem - Returns value of the element
    • OCICollection::max - Returns the maximum number of elements in the collection
    • OCICollection::size - Returns size of the collection
    • OCICollection::trim - Trims elements from the end of the collection
    • ocicollgetelem - 别名 OCICollection::getElem
    • ocicollmax - 别名 OCICollection::max
    • ocicollsize - 别名 OCICollection::size
    • ocicolltrim - 别名 OCICollection::trim
    • ocicolumnisnull - 别名 oci_field_is_null
    • ocicolumnname - 别名 oci_field_name
    • ocicolumnprecision - 别名 oci_field_precision
    • ocicolumnscale - 别名 oci_field_scale
    • ocicolumnsize - 别名 oci_field_size
    • ocicolumntype - 别名 oci_field_type
    • ocicolumntyperaw - 别名 oci_field_type_raw
    • ocicommit - 别名 oci_commit
    • ocidefinebyname - 别名 oci_define_by_name
    • ocierror - 别名 oci_error
    • ociexecute - 别名 oci_execute
    • ocifetch - 别名 oci_fetch
    • ocifetchinto - Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
    • ocifetchstatement - 别名 oci_fetch_all
    • ocifreecollection - 别名 OCICollection::free
    • ocifreecursor - 别名 oci_free_statement
    • ocifreedesc - 别名 OCI-Lob::free
    • ocifreestatement - 别名 oci_free_statement
    • ociinternaldebug - 别名 oci_internal_debug
    • ociloadlob - 别名 OCI-Lob::load
    • OCILob::append - Appends data from the large object to another large object
    • OCILob::close - Closes LOB descriptor
    • OCILob::eof - Tests for end-of-file on a large object's descriptor
    • OCILob::erase - Erases a specified portion of the internal LOB data
    • OCILob::export - Exports LOB's contents to a file
    • OCILob::flush - Flushes/writes buffer of the LOB to the server
    • OCILob::free - Frees resources associated with the LOB descriptor
    • OCILob::getBuffering - Returns current state of buffering for the large object
    • OCILob::import - Imports file data to the LOB
    • OCILob::load - Returns large object's contents
    • OCILob::read - Reads part of the large object
    • OCILob::rewind - Moves the internal pointer to the beginning of the large object
    • OCILob::save - Saves data to the large object
    • OCILob::saveFile - 别名 OCILob::import
    • OCILob::seek - Sets the internal pointer of the large object
    • OCILob::setBuffering - Changes current state of buffering for the large object
    • OCILob::size - Returns size of large object
    • OCILob::tell - Returns the current position of internal pointer of large object
    • OCILob::truncate - Truncates large object
    • OCILob::write - Writes data to the large object
    • OCILob::writeTemporary - Writes a temporary large object
    • OCILob::writeToFile - 别名 OCILob::export
    • ocilogoff - 别名 oci_close
    • ocilogon - 别名 oci_connect
    • ocinewcollection - 别名 oci_new_collection
    • ocinewcursor - 别名 oci_new_cursor
    • ocinewdescriptor - 别名 oci_new_descriptor
    • ocinlogon - 别名 oci_new_connect
    • ocinumcols - 别名 oci_num_fields
    • ociparse - 别名 oci_parse
    • ociplogon - 别名 oci_pconnect
    • ociresult - 别名 oci_result
    • ocirollback - 别名 oci_rollback
    • ocirowcount - 别名 oci_num_rows
    • ocisavelob - 别名 OCI-Lob::save
    • ocisavelobfile - 别名 OCI-Lob::import
    • ociserverversion - 别名 oci_server_version
    • ocisetprefetch - 别名 oci_set_prefetch
    • ocistatementtype - 别名 oci_statement_type
    • ociwritelobtofile - 别名 OCI-Lob::export
    • ociwritetemporarylob - 别名 OCI-Lob::writeTemporary
    • oci_bind_array_by_name - Binds a PHP array to an Oracle PL/SQL array parameter
    • oci_bind_by_name - 绑定一个 PHP 变量到一个 Oracle 位置标志符
    • oci_cancel - 中断游标读取数据
    • oci_client_version - Returns the Oracle client library version
    • oci_close - 关闭 Oracle 连接
    • oci_commit - 提交未执行的事务处理
    • oci_connect - 建立一个到 Oracle 服务器的连接
    • oci_define_by_name - 在 SELECT 中使用 PHP 变量作为定义的步骤
    • oci_error - 返回上一个错误
    • oci_execute - 执行一条语句
    • oci_fetch - Fetches the next row into result-buffer
    • oci_fetch_all - 获取结果数据的所有行到一个数组
    • oci_fetch_array - Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc - Returns the next row from a query as an associative array
    • oci_fetch_object - Returns the next row from a query as an object
    • oci_fetch_row - Returns the next row from a query as a numeric array
    • oci_field_is_null - 检查字段是否为 null
    • oci_field_name - 返回字段名
    • oci_field_precision - 返回字段精度
    • oci_field_scale - 返回字段范围
    • oci_field_size - 返回字段大小
    • oci_field_type - 返回字段的数据类型
    • oci_field_type_raw - 返回字段的原始 Oracle 数据类型
    • oci_free_descriptor - Frees a descriptor
    • oci_free_statement - 释放关联于语句或游标的所有资源
    • oci_get_implicit_resultset - Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets
    • oci_internal_debug - Enables or disables internal debug output
    • oci_lob_copy - Copies large object
    • oci_lob_is_equal - Compares two LOB/FILE locators for equality
    • oci_new_collection - 分配新的 collection 对象
    • oci_new_connect - 建定一个到 Oracle 服务器的新连接
    • oci_new_cursor - 分配并返回一个新的游标（语句句柄）
    • oci_new_descriptor - 初始化一个新的空 LOB 或 FILE 描述符
    • oci_num_fields - 返回结果列的数目
    • oci_num_rows - 返回语句执行后受影响的行数
    • oci_parse - 配置 Oracle 语句预备执行
    • oci_password_change - 修改 Oracle 用户的密码
    • oci_pconnect - 使用一个持久连接连到 Oracle 数据库
    • oci_register_taf_callback - Register a user-defined callback function for Oracle Database TAF
    • oci_result - 返回所取得行中字段的值
    • oci_rollback - 回滚未提交的事务
    • oci_server_version - 返回服务器版本信息
    • oci_set_action - Sets the action name
    • oci_set_call_timeout - Sets a millisecond timeout for database calls
    • oci_set_client_identifier - Sets the client identifier
    • oci_set_client_info - Sets the client information
    • oci_set_db_operation - Sets the database operation
    • oci_set_edition - Sets the database edition
    • oci_set_module_name - Sets the module name
    • oci_set_prefetch - 设置预提取行数
    • oci_statement_type - 返回 OCI 语句的类型
    • oci_unregister_taf_callback - Unregister a user-defined callback function for Oracle Database TAF
    • octdec - 八进制转换为十进制
    • odbc_autocommit - Toggle autocommit behaviour
    • odbc_binmode - Handling of binary column data
    • odbc_close - Close an ODBC connection
    • odbc_close_all - Close all ODBC connections
    • odbc_columnprivileges - Lists columns and associated privileges for the given table
    • odbc_columns - Lists the column names in specified tables
    • odbc_commit - Commit an ODBC transaction
    • odbc_connect - Connect to a datasource
    • odbc_cursor - Get cursorname
    • odbc_data_source - Returns information about available DSNs
    • odbc_do - 别名 odbc_exec
    • odbc_error - Get the last error code
    • odbc_errormsg - Get the last error message
    • odbc_exec - Directly execute an SQL statement
    • odbc_execute - Execute a prepared statement
    • odbc_fetch_array - Fetch a result row as an associative array
    • odbc_fetch_into - Fetch one result row into array
    • odbc_fetch_object - Fetch a result row as an object
    • odbc_fetch_row - Fetch a row
    • odbc_field_len - Get the length (precision) of a field
    • odbc_field_name - Get the columnname
    • odbc_field_num - Return column number
    • odbc_field_precision - 别名 odbc_field_len
    • odbc_field_scale - Get the scale of a field
    • odbc_field_type - Datatype of a field
    • odbc_foreignkeys - Retrieves a list of foreign keys
    • odbc_free_result - Free resources associated with a result
    • odbc_gettypeinfo - Retrieves information about data types supported by the data source
    • odbc_longreadlen - Handling of LONG columns
    • odbc_next_result - Checks if multiple results are available
    • odbc_num_fields - Number of columns in a result
    • odbc_num_rows - Number of rows in a result
    • odbc_pconnect - Open a persistent database connection
    • odbc_prepare - Prepares a statement for execution
    • odbc_primarykeys - Gets the primary keys for a table
    • odbc_procedurecolumns - Retrieve information about parameters to procedures
    • odbc_procedures - Get the list of procedures stored in a specific data source
    • odbc_result - Get result data
    • odbc_result_all - Print result as HTML table
    • odbc_rollback - Rollback a transaction
    • odbc_setoption - Adjust ODBC settings
    • odbc_specialcolumns - Retrieves special columns
    • odbc_statistics - Retrieve statistics about a table
    • odbc_tableprivileges - Lists tables and the privileges associated with each table
    • odbc_tables - Get the list of table names stored in a specific data source
    • ogg:// - 音频流
    • opcache_compile_file - 无需运行，即可编译并缓存 PHP 脚本
    • opcache_get_configuration - 获取缓存的配置信息
    • opcache_get_status - 获取缓存的状态信息
    • opcache_invalidate - 废除脚本缓存
    • opcache_is_script_cached - Tells whether a script is cached in OPCache
    • opcache_reset - 重置字节码缓存的内容
    • openal_buffer_create - Generate OpenAL buffer
    • openal_buffer_data - Load a buffer with data
    • openal_buffer_destroy - Destroys an OpenAL buffer
    • openal_buffer_get - Retrieve an OpenAL buffer property
    • openal_buffer_loadwav - Load a .wav file into a buffer
    • openal_context_create - Create an audio processing context
    • openal_context_current - Make the specified context current
    • openal_context_destroy - Destroys a context
    • openal_context_process - Process the specified context
    • openal_context_suspend - Suspend the specified context
    • openal_device_close - Close an OpenAL device
    • openal_device_open - Initialize the OpenAL audio layer
    • openal_listener_get - Retrieve a listener property
    • openal_listener_set - Set a listener property
    • openal_source_create - Generate a source resource
    • openal_source_destroy - Destroy a source resource
    • openal_source_get - Retrieve an OpenAL source property
    • openal_source_pause - Pause the source
    • openal_source_play - Start playing the source
    • openal_source_rewind - Rewind the source
    • openal_source_set - Set source property
    • openal_source_stop - Stop playing the source
    • openal_stream - Begin streaming on a source
    • opendir - 打开目录句柄
    • openlog - Open connection to system logger
    • openssl_cipher_iv_length - 获取密码iv长度
    • openssl_cms_decrypt - Decrypt a CMS message
    • openssl_cms_encrypt - Encrypt a CMS message
    • openssl_cms_read - Export the CMS file to an array of PEM certificates
    • openssl_cms_sign - Sign a file
    • openssl_cms_verify - Verify a CMS signature
    • openssl_csr_export - 将CSR作为字符串导出
    • openssl_csr_export_to_file - 将CSR导出到文件
    • openssl_csr_get_public_key - 返回CSR的公钥
    • openssl_csr_get_subject - 返回CSR的主题
    • openssl_csr_new - 生成一个 CSR
    • openssl_csr_sign - 用另一个证书签署 CSR (或者本身) 并且生成一个证书
    • openssl_decrypt - 解密数据
    • openssl_dh_compute_key - 计算远程DH密钥(公钥)和本地DH密钥的共享密钥
    • openssl_digest - 计算摘要
    • openssl_encrypt - 加密数据
    • openssl_error_string - 返回 openSSL 错误消息
    • openssl_free_key - 释放密钥资源
    • openssl_get_cert_locations - 检索可用的证书位置
    • openssl_get_cipher_methods - 获取可用的加密算法
    • openssl_get_curve_names - 获得ECC的可用曲线名称列表
    • openssl_get_md_methods - 获取可用的摘要算法
    • openssl_get_privatekey - 别名 openssl_pkey_get_private
    • openssl_get_publickey - 别名 openssl_pkey_get_public
    • openssl_open - 打开密封的数据
    • openssl_pbkdf2 - 生成一个 PKCS5 v2 PBKDF2 字符串
    • openssl_pkcs7_decrypt - 解密一个 S/MIME 加密的消息
    • openssl_pkcs7_encrypt - 加密一个 S/MIME 消息
    • openssl_pkcs7_read - 将PKCS7文件导出为PEM格式证书的数组
    • openssl_pkcs7_sign - 对一个 S/MIME 消息进行签名
    • openssl_pkcs7_verify - 校验一个已签名的 S/MIME 消息的签名
    • openssl_pkcs12_export - 将 PKCS#12 兼容证书存储文件导出到变量
    • openssl_pkcs12_export_to_file - 输出一个 PKCS#12 兼容的证书存储文件
    • openssl_pkcs12_read - 将 PKCS#12 证书存储区解析到数组中
    • openssl_pkey_derive - Computes shared secret for public value of remote and local DH or ECDH key
    • openssl_pkey_export - 将一个密钥的可输出表示转换为字符串
    • openssl_pkey_export_to_file - 将密钥导出到文件中
    • openssl_pkey_free - 释放一个私钥
    • openssl_pkey_get_details - 返回包含密钥详情的数组
    • openssl_pkey_get_private - 获取私钥
    • openssl_pkey_get_public - 从证书中解析公钥，以供使用。
    • openssl_pkey_new - 生成一个新的私钥
    • openssl_private_decrypt - 使用私钥解密数据
    • openssl_private_encrypt - 使用私钥加密数据
    • openssl_public_decrypt - 使用公钥解密数据
    • openssl_public_encrypt - 使用公钥加密数据
    • openssl_random_pseudo_bytes - 生成一个伪随机字节串
    • openssl_seal - 密封 (加密) 数据
    • openssl_sign - Generate signature
    • openssl_spki_export - 通过签名公钥和挑战导出一个可用的PEM格式的公钥
    • openssl_spki_export_challenge - 导出与签名公钥和挑战相关的挑战字符串
    • openssl_spki_new - 生成一个新的签名公钥和挑战
    • openssl_spki_verify - 验证签名公钥和挑战。
    • openssl_verify - 验证签名
    • openssl_x509_checkpurpose - 验证是否可以为特定目的使用证书
    • openssl_x509_check_private_key - 检查私钥是否对应于证书
    • openssl_x509_export - 以字符串格式导出证书
    • openssl_x509_export_to_file - 导出证书至文件
    • openssl_x509_fingerprint - 计算一个给定的x.509证书的指纹或摘要
    • openssl_x509_free - 释放证书资源
    • openssl_x509_parse - 解析一个X509证书并作为一个数组返回信息
    • openssl_x509_read - 解析一个x.509证书并返回一个资源标识符
    • openssl_x509_verify - Verifies digital signature of x509 certificate against a public key
    • ord - 转换字符串第一个字节为 0-255 之间的值
    • OuterIterator::getInnerIterator - Returns the inner iterator for the current entry
    • output_add_rewrite_var - 添加URL重写器的值（Add URL rewriter values）
    • output_reset_rewrite_vars - 重设URL重写器的值（Reset URL rewriter values）
  • p
    • pack - 将数据打包成二进制字符串
    • parallel\bootstrap - Bootstrapping
    • parallel\Channel::close - Closing
    • parallel\Channel::make - Access
    • parallel\Channel::open - Access
    • parallel\Channel::recv - Sharing
    • parallel\Channel::send - Sharing
    • parallel\Channel::__construct - Channel Construction
    • parallel\Events::addChannel - Targets
    • parallel\Events::addFuture - Targets
    • parallel\Events::poll - Polling
    • parallel\Events::remove - Targets
    • parallel\Events::setBlocking - Behaviour
    • parallel\Events::setInput - Input
    • parallel\Events::setTimeout - Behaviour
    • parallel\Events\Input::add - Inputs
    • parallel\Events\Input::clear - Inputs
    • parallel\Events\Input::remove - Inputs
    • parallel\Future::cancel - Cancellation
    • parallel\Future::cancelled - State Detection
    • parallel\Future::done - State Detection
    • parallel\Future::value - Resolution
    • parallel\run - Execution
    • parallel\Runtime::close - Runtime Graceful Join
    • parallel\Runtime::kill - Runtime Join
    • parallel\Runtime::run - Execution
    • parallel\Runtime::__construct - Runtime Construction
    • parallel\Sync::get - Access
    • parallel\Sync::notify - Synchronization
    • parallel\Sync::set - Access
    • parallel\Sync::wait - Synchronization
    • parallel\Sync::__construct - Construction
    • parallel\Sync::__invoke - Synchronization
    • ParentIterator::accept - Determines acceptability
    • ParentIterator::getChildren - Return the inner iterator's children contained in a ParentIterator
    • ParentIterator::hasChildren - Check whether the inner iterator's current element has children
    • ParentIterator::next - Move the iterator forward
    • ParentIterator::rewind - Rewind the iterator
    • ParentIterator::__construct - Constructs a ParentIterator
    • Parle\Lexer::advance - Process next lexer rule
    • Parle\Lexer::build - Finalize the lexer rule set
    • Parle\Lexer::callout - Define token callback
    • Parle\Lexer::consume - Pass the data for processing
    • Parle\Lexer::dump - Dump the state machine
    • Parle\Lexer::getToken - Retrieve the current token
    • Parle\Lexer::insertMacro - Insert regex macro
    • Parle\Lexer::push - Add a lexer rule
    • Parle\Lexer::reset - Reset lexer
    • Parle\Parser::advance - Process next parser rule
    • Parle\Parser::build - Finalize the grammar rules
    • Parle\Parser::consume - Consume the data for processing
    • Parle\Parser::dump - Dump the grammar
    • Parle\Parser::errorInfo - Retrieve the error information
    • Parle\Parser::left - Declare a token with left-associativity
    • Parle\Parser::nonassoc - Declare a token with no associativity
    • Parle\Parser::precedence - Declare a precedence rule
    • Parle\Parser::push - Add a grammar rule
    • Parle\Parser::reset - Reset parser state
    • Parle\Parser::right - Declare a token with right-associativity
    • Parle\Parser::sigil - Retrieve a matching part of a rule
    • Parle\Parser::token - Declare a token
    • Parle\Parser::tokenId - Get token id
    • Parle\Parser::trace - Trace the parser operation
    • Parle\Parser::validate - Validate input
    • Parle\RLexer::advance - Process next lexer rule
    • Parle\RLexer::build - Finalize the lexer rule set
    • Parle\RLexer::callout - Define token callback
    • Parle\RLexer::consume - Pass the data for processing
    • Parle\RLexer::dump - Dump the state machine
    • Parle\RLexer::getToken - Retrieve the current token
    • Parle\RLexer::insertMacro - Insert regex macro
    • Parle\RLexer::push - Add a lexer rule
    • Parle\RLexer::pushState - Push a new start state
    • Parle\RLexer::reset - Reset lexer
    • Parle\RParser::advance - Process next parser rule
    • Parle\RParser::build - Finalize the grammar rules
    • Parle\RParser::consume - Consume the data for processing
    • Parle\RParser::dump - Dump the grammar
    • Parle\RParser::errorInfo - Retrieve the error information
    • Parle\RParser::left - Declare a token with left-associativity
    • Parle\RParser::nonassoc - Declare a token with no associativity
    • Parle\RParser::precedence - Declare a precedence rule
    • Parle\RParser::push - Add a grammar rule
    • Parle\RParser::reset - Reset parser state
    • Parle\RParser::right - Declare a token with right-associativity
    • Parle\RParser::sigil - Retrieve a matching part of a rule
    • Parle\RParser::token - Declare a token
    • Parle\RParser::tokenId - Get token id
    • Parle\RParser::trace - Trace the parser operation
    • Parle\RParser::validate - Validate input
    • Parle\Stack::pop - Pop an item from the stack
    • Parle\Stack::push - Push an item into the stack
    • parse_ini_file - 解析一个配置文件
    • parse_ini_string - 解析配置字符串
    • parse_str - 将字符串解析成多个变量
    • parse_url - 解析 URL，返回其组成部分
    • passthru - 执行外部程序并且显示原始输出
    • password_algos - Get available password hashing algorithm IDs
    • password_get_info - 返回指定散列（hash）的相关信息
    • password_hash - 创建密码的散列（hash）
    • password_needs_rehash - 检测散列值是否匹配指定的选项
    • password_verify - 验证密码是否和散列值匹配
    • pathinfo - 返回文件路径的信息
    • pclose - 关闭进程文件指针
    • pcntl_alarm - 为进程设置一个alarm闹钟信号
    • pcntl_async_signals - Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno - 别名 pcntl_get_last_error
    • pcntl_exec - 在当前进程空间执行指定程序
    • pcntl_fork - 在当前进程当前位置产生分支（子进程）。译注：fork是创建了一个子进程，父进程和子进程 都从fork的位置开始向下继续执行，不同的是父进程执行过程中，得到的fork返回值为子进程 号，而子进程得到的是0。
    • pcntl_getpriority - 获取任意进程的优先级
    • pcntl_get_last_error - Retrieve the error number set by the last pcntl function which failed
    • pcntl_setpriority - 修改任意进程的优先级
    • pcntl_signal - 安装一个信号处理器
    • pcntl_signal_dispatch - 调用等待信号的处理器
    • pcntl_signal_get_handler - Get the current handler for specified signal
    • pcntl_sigprocmask - 设置或检索阻塞信号
    • pcntl_sigtimedwait - 带超时机制的信号等待
    • pcntl_sigwaitinfo - 等待信号
    • pcntl_strerror - Retrieve the system error message associated with the given errno
    • pcntl_wait - 等待或返回 fork 的子进程状态
    • pcntl_waitpid - 等待或返回fork的子进程状态
    • pcntl_wexitstatus - 返回一个中断的子进程的返回代码
    • pcntl_wifexited - 检查状态代码是否代表一个正常的退出。
    • pcntl_wifsignaled - 检查子进程状态码是否代表由于某个信号而中断
    • pcntl_wifstopped - 检查子进程当前是否已经停止
    • pcntl_wstopsig - 返回导致子进程停止的信号
    • pcntl_wtermsig - 返回导致子进程中断的信号
    • PDO::beginTransaction - 启动一个事务
    • PDO::commit - 提交一个事务
    • PDO::cubrid_schema - Get the requested schema information
    • PDO::errorCode - 获取跟数据库句柄上一次操作相关的 SQLSTATE
    • PDO::errorInfo - Fetch extended error information associated with the last operation on the database handle
    • PDO::exec - 执行一条 SQL 语句，并返回受影响的行数
    • PDO::getAttribute - 取回一个数据库连接的属性
    • PDO::getAvailableDrivers - 返回一个可用驱动的数组
    • PDO::inTransaction - 检查是否在一个事务内
    • PDO::lastInsertId - 返回最后插入行的ID或序列值
    • PDO::pgsqlCopyFromArray - Copy data from PHP array into table
    • PDO::pgsqlCopyFromFile - Copy data from file into table
    • PDO::pgsqlCopyToArray - Copy data from database table into PHP array
    • PDO::pgsqlCopyToFile - Copy data from table into file
    • PDO::pgsqlGetNotify - Get asynchronous notification
    • PDO::pgsqlGetPid - Get the server PID
    • PDO::pgsqlLOBCreate - Creates a new large object
    • PDO::pgsqlLOBOpen - Opens an existing large object stream
    • PDO::pgsqlLOBUnlink - Deletes the large object
    • PDO::prepare - 准备要执行的语句，并返回语句对象
    • PDO::query - 执行 SQL 语句，以 PDOStatement 对象形式返回结果集
    • PDO::quote - 为 SQL 查询里的字符串添加引号
    • PDO::rollBack - 回滚一个事务
    • PDO::setAttribute - 设置属性
    • PDO::sqliteCreateAggregate - Registers an aggregating User Defined Function for use in SQL statements
    • PDO::sqliteCreateCollation - Registers a User Defined Function for use as a collating function in SQL statements
    • PDO::sqliteCreateFunction - Registers a User Defined Function for use in SQL statements
    • PDO::__construct - 创建一个表示数据库连接的 PDO 实例
    • PDOStatement::bindColumn - 绑定一列到一个 PHP 变量
    • PDOStatement::bindParam - 绑定一个参数到指定的变量名
    • PDOStatement::bindValue - 把一个值绑定到一个参数
    • PDOStatement::closeCursor - 关闭游标，使语句能再次被执行。
    • PDOStatement::columnCount - 返回结果集中的列数
    • PDOStatement::debugDumpParams - 打印一条 SQL 预处理命令
    • PDOStatement::errorCode - 获取跟上一次语句句柄操作相关的 SQLSTATE
    • PDOStatement::errorInfo - 获取跟上一次语句句柄操作相关的扩展错误信息
    • PDOStatement::execute - 执行一条预处理语句
    • PDOStatement::fetch - 从结果集中获取下一行
    • PDOStatement::fetchAll - 返回一个包含结果集中所有行的数组
    • PDOStatement::fetchColumn - 从结果集中的下一行返回单独的一列。
    • PDOStatement::fetchObject - 获取下一行并作为一个对象返回。
    • PDOStatement::getAttribute - 检索一个语句属性
    • PDOStatement::getColumnMeta - 返回结果集中一列的元数据
    • PDOStatement::nextRowset - 在一个多行集语句句柄中推进到下一个行集
    • PDOStatement::rowCount - 返回受上一个 SQL 语句影响的行数
    • PDOStatement::setAttribute - 设置一个语句属性
    • PDOStatement::setFetchMode - 为语句设置默认的获取模式。
    • PDO_CUBRID DSN - Connecting to CUBRID databases
    • PDO_DBLIB DSN - Connecting to Microsoft SQL Server and Sybase databases
    • PDO_FIREBIRD DSN - Connecting to Firebird databases
    • PDO_IBM DSN - Connecting to IBM databases
    • PDO_INFORMIX DSN - Connecting to Informix databases
    • PDO_MYSQL DSN - Connecting to MySQL databases
    • PDO_OCI DSN - Connecting to Oracle databases
    • PDO_ODBC DSN - Connecting to ODBC or DB2 databases
    • PDO_PGSQL DSN - Connecting to PostgreSQL databases
    • PDO_SQLITE DSN - Connecting to SQLite databases
    • PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
    • pfsockopen - 打开一个持久的网络连接或者Unix套接字连接。
    • pg_affected_rows - 返回受影响的记录数目
    • pg_cancel_query - 取消异步查询
    • pg_client_encoding - 取得客户端编码方式
    • pg_close - 关闭一个 PostgreSQL 连接
    • pg_connect - 打开一个 PostgreSQL 连接
    • pg_connection_busy - 获知连接是否为忙
    • pg_connection_reset - 重置连接（再次连接）
    • pg_connection_status - 获得连接状态
    • pg_connect_poll - 正在进行尝试轮询 PostgreSQL 链接状态。
    • pg_consume_input - Reads input on the connection
    • pg_convert - 将关联的数组值转换为适合 SQL 语句的格式。
    • pg_copy_from - 根据数组将记录插入表中
    • pg_copy_to - 将一个表拷贝到数组中
    • pg_dbname - 获得数据库名
    • pg_delete - 删除记录
    • pg_end_copy - 与 PostgreSQL 后端同步
    • pg_escape_bytea - 转义 bytea 类型的二进制数据
    • pg_escape_identifier - Escape a identifier for insertion into a text field
    • pg_escape_literal - Escape a literal for insertion into a text field
    • pg_escape_string - 转义 text/char 类型的字符串
    • pg_execute - Sends a request to execute a prepared statement with given parameters, and waits for the result
    • pg_fetch_all - 从结果中提取所有行作为一个数组
    • pg_fetch_all_columns - Fetches all rows in a particular result column as an array
    • pg_fetch_array - 提取一行作为数组
    • pg_fetch_assoc - 提取一行作为关联数组
    • pg_fetch_object - 提取一行作为对象
    • pg_fetch_result - 从结果资源中返回值
    • pg_fetch_row - 提取一行作为枚举数组
    • pg_field_is_null - 测试字段是否为 null
    • pg_field_name - 返回字段的名字
    • pg_field_num - 返回字段的编号
    • pg_field_prtlen - 返回打印出来的长度
    • pg_field_size - 返回指定字段占用内部存储空间的大小
    • pg_field_table - Returns the name or oid of the tables field
    • pg_field_type - 返回相应字段的类型名称
    • pg_field_type_oid - Returns the type ID (OID) for the corresponding field number
    • pg_flush - 刷新链接中已处理的数据查询
    • pg_free_result - 释放查询结果占用的内存
    • pg_get_notify - Ping 数据库连接
    • pg_get_pid - Ping 数据库连接
    • pg_get_result - 取得异步查询结果
    • pg_host - 返回和某连接关联的主机名
    • pg_insert - 将数组插入到表中
    • pg_last_error - 得到某连接的最后一条错误信息
    • pg_last_notice - 返回 PostgreSQL 服务器最新一条公告信息
    • pg_last_oid - 返回上一个对象的 oid
    • pg_lo_close - 关闭一个大型对象
    • pg_lo_create - 新建一个大型对象
    • pg_lo_export - 将大型对象导出到文件
    • pg_lo_import - 将文件导入为大型对象
    • pg_lo_open - 打开一个大型对象
    • pg_lo_read - 从大型对象中读入数据
    • pg_lo_read_all - 读入整个大型对象并直接发送给浏览器
    • pg_lo_seek - 移动大型对象中的指针
    • pg_lo_tell - 返回大型对象的当前指针位置
    • pg_lo_truncate - Truncates a large object
    • pg_lo_unlink - 删除一个大型对象
    • pg_lo_write - 向大型对象写入数据
    • pg_meta_data - 获得表的元数据
    • pg_num_fields - 返回字段的数目
    • pg_num_rows - 返回行的数目
    • pg_options - 获得和连接有关的选项
    • pg_parameter_status - Looks up a current parameter setting of the server
    • pg_pconnect - 打开一个持久的 PostgreSQL 连接
    • pg_ping - Ping 数据库连接
    • pg_port - 返回该连接的端口号
    • pg_prepare - Submits a request to create a prepared statement with the given parameters, and waits for completion
    • pg_put_line - 向 PostgreSQL 后端发送以 NULL 结尾的字符串
    • pg_query - 执行查询
    • pg_query_params - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
    • pg_result_error - 获得查询结果的错误信息
    • pg_result_error_field - Returns an individual field of an error report
    • pg_result_seek - 在结果资源中设定内部行偏移量
    • pg_result_status - 获得查询结果的状态
    • pg_select - 选择记录
    • pg_send_execute - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
    • pg_send_prepare - Sends a request to create a prepared statement with the given parameters, without waiting for completion
    • pg_send_query - 发送异步查询
    • pg_send_query_params - Submits a command and separate parameters to the server without waiting for the result(s)
    • pg_set_client_encoding - 设定客户端编码
    • pg_set_error_verbosity - Determines the verbosity of messages returned by pg_last_error and pg_result_error
    • pg_socket - Get a read only handle to the socket underlying a PostgreSQL connection
    • pg_trace - 启动一个 PostgreSQL 连接的追踪功能
    • pg_transaction_status - Returns the current in-transaction status of the server
    • pg_tty - 返回该连接的 tty 号
    • pg_unescape_bytea - 取消 bytea 类型中的字符串转义
    • pg_untrace - 关闭 PostgreSQL 连接的追踪功能
    • pg_update - 更新表
    • pg_version - Returns an array with client, protocol and server version (when available)
    • phar:// - PHP 归档
    • Phar::addEmptyDir - 添加一个空目录到 phar 档案
    • Phar::addFile - 将一个文件从文件系统添加到 phar 档案中
    • Phar::addFromString - 以字符串的形式添加一个文件到 phar 档案
    • Phar::apiVersion - Returns the api version
    • Phar::buildFromDirectory - Construct a phar archive from the files within a directory
    • Phar::buildFromIterator - Construct a phar archive from an iterator
    • Phar::canCompress - Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite - Returns whether phar extension supports writing and creating phars
    • Phar::compress - Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::compressFiles - Compresses all files in the current Phar archive
    • Phar::convertToData - Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable - Convert a phar archive to another executable phar archive file format
    • Phar::copy - Copy a file internal to the phar archive to another new file within the phar
    • Phar::count - Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub - Create a phar-file format specific stub
    • Phar::decompress - Decompresses the entire Phar archive
    • Phar::decompressFiles - Decompresses all files in the current Phar archive
    • Phar::delete - 删除 phar 档案中的一个文件
    • Phar::delMetadata - Deletes the global metadata of the phar
    • Phar::extractTo - Extract the contents of a phar archive to a directory
    • Phar::getAlias - Get the alias for Phar
    • Phar::getMetadata - Returns phar archive meta-data
    • Phar::getModified - Return whether phar was modified
    • Phar::getPath - Get the real path to the Phar archive on disk
    • Phar::getSignature - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub - Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression - Return array of supported compression algorithms
    • Phar::getSupportedSignatures - Return array of supported signature types
    • Phar::getVersion - Return version info of Phar archive
    • Phar::hasMetadata - Returns whether phar has global meta-data
    • Phar::interceptFileFuncs - Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat - Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename - Returns whether the given filename is a valid phar filename
    • Phar::isWritable - Returns true if the phar archive can be modified
    • Phar::loadPhar - Loads any phar archive with an alias
    • Phar::mapPhar - Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount - Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer - Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists - Determines whether a file exists in the phar
    • Phar::offsetGet - Gets a PharFileInfo object for a specific file
    • Phar::offsetSet - Set the contents of an internal file to those of an external file
    • Phar::offsetUnset - Remove a file from a phar
    • Phar::running - Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias - Set the alias for the Phar archive
    • Phar::setDefaultStub - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata - Sets phar archive meta-data
    • Phar::setSignatureAlgorithm - Set the signature algorithm for a phar and apply it
    • Phar::setStub - Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering - Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering - Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::unlinkArchive - Completely remove a phar archive from disk and from memory
    • Phar::webPhar - mapPhar for web-based phars. front controller for web applications
    • Phar::__construct - Construct a Phar archive object
    • PharData::addEmptyDir - Add an empty directory to the tar/zip archive
    • PharData::addFile - Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString - Add a file from the filesystem to the tar/zip archive
    • PharData::buildFromDirectory - Construct a tar/zip archive from the files within a directory
    • PharData::buildFromIterator - Construct a tar or zip archive from an iterator
    • PharData::compress - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles - Compresses all files in the current tar/zip archive
    • PharData::convertToData - Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable - Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy - Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress - Decompresses the entire Phar archive
    • PharData::decompressFiles - Decompresses all files in the current zip archive
    • PharData::delete - Delete a file within a tar/zip archive
    • PharData::delMetadata - Deletes the global metadata of a zip archive
    • PharData::extractTo - Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable - Returns true if the tar/zip archive can be modified
    • PharData::offsetSet - Set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset - Remove a file from a tar/zip archive
    • PharData::setAlias - Dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub - Dummy function (Phar::setDefaultStub is not valid for PharData)
    • PharData::setMetadata - Sets phar archive meta-data
    • PharData::setSignatureAlgorithm - Set the signature algorithm for a phar and apply it
    • PharData::setStub - Dummy function (Phar::setStub is not valid for PharData)
    • PharData::__construct - Construct a non-executable tar or zip archive object
    • PharFileInfo::chmod - Sets file-specific permission bits
    • PharFileInfo::compress - Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::decompress - Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata - Deletes the metadata of the entry
    • PharFileInfo::getCompressedSize - Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getContent - Get the complete file contents of the entry
    • PharFileInfo::getCRC32 - Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getMetadata - Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags - Returns the Phar file entry flags
    • PharFileInfo::hasMetadata - Returns the metadata of the entry
    • PharFileInfo::isCompressed - Returns whether the entry is compressed
    • PharFileInfo::isCRCChecked - Returns whether file entry has had its CRC verified
    • PharFileInfo::setMetadata - Sets file-specific meta-data saved with a file
    • PharFileInfo::__construct - Construct a Phar entry object
    • Phar 上下文（context）选项 - Phar 上下文（context）选项列表
    • php:// - 访问各个输入/输出流（I/O streams）
    • phpcredits - 打印 PHP 贡献者名单
    • phpdbg_break_file - Inserts a breakpoint at a line in a file
    • phpdbg_break_function - Inserts a breakpoint at entry to a function
    • phpdbg_break_method - Inserts a breakpoint at entry to a method
    • phpdbg_break_next - Inserts a breakpoint at the next opcode
    • phpdbg_clear - Clears all breakpoints
    • phpdbg_color - Sets the color of certain elements
    • phpdbg_end_oplog - 说明
    • phpdbg_exec - Attempts to set the execution context
    • phpdbg_get_executable - 说明
    • phpdbg_prompt - Sets the command prompt
    • phpdbg_start_oplog - 说明
    • phpinfo - 输出关于 PHP 配置的信息
    • PhpToken::getTokenName - Returns the name of the token.
    • PhpToken::is - Tells whether the token is of given kind.
    • PhpToken::isIgnorable - Tells whether the token would be ignored by the PHP parser.
    • PhpToken::tokenize - Splits given source into PHP tokens, represented by PhpToken objects.
    • PhpToken::__construct - Returns a new PhpToken object
    • PhpToken::__toString - Returns the textual content of the token.
    • phpversion - 获取当前的PHP版本
    • php_ini_loaded_file - 取得已加载的 php.ini 文件的路径
    • php_ini_scanned_files - 返回从额外 ini 目录里解析的 .ini 文件列表
    • php_sapi_name - 返回 web 服务器和 PHP 之间的接口类型
    • php_strip_whitespace - 返回删除注释和空格后的PHP源码
    • php_uname - 返回运行 PHP 的系统的有关信息
    • php_user_filter::filter - Called when applying the filter
    • php_user_filter::onClose - Called when closing the filter
    • php_user_filter::onCreate - Called when creating the filter
    • pht\AtomicInteger::dec - Decrements the atomic integer's value by one
    • pht\AtomicInteger::get - Gets the atomic integer's value
    • pht\AtomicInteger::inc - Increments the atomic integer's value by one
    • pht\AtomicInteger::lock - Acquires the atomic integer's mutex lock
    • pht\AtomicInteger::set - Sets the atomic integer's value
    • pht\AtomicInteger::unlock - Releases the atomic integer's mutex lock
    • pht\AtomicInteger::__construct - AtomicInteger creation
    • pht\HashTable::lock - Acquires the hash table's mutex lock
    • pht\HashTable::size - Gets the size of the hash table
    • pht\HashTable::unlock - Releases the hash table's mutex lock
    • pht\Queue::front - Returns the first value from a queue
    • pht\Queue::lock - Acquires the queue's mutex lock
    • pht\Queue::pop - Pops a value off of the front of a queue
    • pht\Queue::push - Pushes a value to the end of a queue
    • pht\Queue::size - Gets the size of the queue
    • pht\Queue::unlock - Releases the queue's mutex lock
    • pht\Runnable::run - The entry point of a threaded class
    • pht\Thread::addClassTask - Class threading
    • pht\Thread::addFileTask - File threading
    • pht\Thread::addFunctionTask - Function threading
    • pht\Thread::join - Joins a thread
    • pht\Thread::start - Starts the new thread
    • pht\Thread::taskCount - Gets a thread's task count
    • pht\Threaded::lock - Acquires the mutex lock
    • pht\Threaded::unlock - Releases the mutex lock
    • pht\Vector::deleteAt - Deletes a value in the vector
    • pht\Vector::insertAt - Inserts a value into the vector
    • pht\Vector::lock - Acquires the vector's mutex lock
    • pht\Vector::pop - Pops a value to the vector
    • pht\Vector::push - Pushes a value to the vector
    • pht\Vector::resize - Resizes a vector
    • pht\Vector::shift - Shifts a value from the vector
    • pht\Vector::size - Gets the size of the vector
    • pht\Vector::unlock - Releases the vector's mutex lock
    • pht\Vector::unshift - Unshifts a value to the vector front
    • pht\Vector::updateAt - Updates a value in the vector
    • pht\Vector::__construct - Vector creation
    • pi - 得到圆周率值
    • png2wbmp - 将 PNG 图像文件转换为 WBMP 图像文件
    • Pool::collect - 回收已完成任务的引用
    • Pool::resize - 改变 Pool 对象的可容纳 Worker 对象的数量
    • Pool::shutdown - 停止所有的 Worker 对象
    • Pool::submit - 提交对象以执行
    • Pool::submitTo - 提交一个任务到特定的 Worker 以执行
    • Pool::__construct - 创建新的 Worker 对象池
    • popen - 打开进程文件指针
    • pos - current 的别名
    • posix_access - Determine accessibility of a file
    • posix_ctermid - Get path name of controlling terminal
    • posix_errno - 别名 posix_get_last_error
    • posix_getcwd - Pathname of current directory
    • posix_getegid - Return the effective group ID of the current process
    • posix_geteuid - Return the effective user ID of the current process
    • posix_getgid - Return the real group ID of the current process
    • posix_getgrgid - Return info about a group by group id
    • posix_getgrnam - Return info about a group by name
    • posix_getgroups - Return the group set of the current process
    • posix_getlogin - Return login name
    • posix_getpgid - Get process group id for job control
    • posix_getpgrp - Return the current process group identifier
    • posix_getpid - 返回当前进程 id
    • posix_getppid - Return the parent process identifier
    • posix_getpwnam - Return info about a user by username
    • posix_getpwuid - Return info about a user by user id
    • posix_getrlimit - Return info about system resource limits
    • posix_getsid - Get the current sid of the process
    • posix_getuid - Return the real user ID of the current process
    • posix_get_last_error - Retrieve the error number set by the last posix function that failed
    • posix_initgroups - Calculate the group access list
    • posix_isatty - Determine if a file descriptor is an interactive terminal
    • posix_kill - Send a signal to a process
    • posix_mkfifo - Create a fifo special file (a named pipe)
    • posix_mknod - Create a special or ordinary file (POSIX.1)
    • posix_setegid - Set the effective GID of the current process
    • posix_seteuid - Set the effective UID of the current process
    • posix_setgid - Set the GID of the current process
    • posix_setpgid - Set process group id for job control
    • posix_setrlimit - Set system resource limits
    • posix_setsid - Make the current process a session leader
    • posix_setuid - Set the UID of the current process
    • posix_strerror - Retrieve the system error message associated with the given errno
    • posix_times - Get process times
    • posix_ttyname - Determine terminal device name
    • posix_uname - Get system name
    • pow - 指数表达式
    • preg_filter - 执行一个正则表达式搜索和替换
    • preg_grep - 返回匹配模式的数组条目
    • preg_last_error - 返回最后一个PCRE正则执行产生的错误代码
    • preg_last_error_msg - Returns the error message of the last PCRE regex execution
    • preg_match - 执行匹配正则表达式
    • preg_match_all - 执行一个全局正则表达式匹配
    • preg_quote - 转义正则表达式字符
    • preg_replace - 执行一个正则表达式的搜索和替换
    • preg_replace_callback - 执行一个正则表达式搜索并且使用一个回调进行替换
    • preg_replace_callback_array - Perform a regular expression search and replace using callbacks
    • preg_split - 通过一个正则表达式分隔字符串
    • prev - 将数组的内部指针倒回一位
    • print - 输出字符串
    • printf - 输出格式化字符串
    • print_r - 以易于理解的格式打印变量。
    • proc_close - 关闭由 proc_open 打开的进程并且返回进程退出码
    • proc_get_status - 获取由 proc_open 函数打开的进程的信息
    • proc_nice - 修改当前进程的优先级
    • proc_open - 执行一个命令，并且打开用来输入/输出的文件指针。
    • proc_terminate - 杀除由 proc_open 打开的进程
    • property_exists - 检查对象或类是否具有该属性
    • pspell_add_to_personal - Add the word to a personal wordlist
    • pspell_add_to_session - Add the word to the wordlist in the current session
    • pspell_check - Check a word
    • pspell_clear_session - Clear the current session
    • pspell_config_create - Create a config used to open a dictionary
    • pspell_config_data_dir - Location of language data files
    • pspell_config_dict_dir - Location of the main word list
    • pspell_config_ignore - Ignore words less than N characters long
    • pspell_config_mode - Change the mode number of suggestions returned
    • pspell_config_personal - Set a file that contains personal wordlist
    • pspell_config_repl - Set a file that contains replacement pairs
    • pspell_config_runtogether - Consider run-together words as valid compounds
    • pspell_config_save_repl - Determine whether to save a replacement pairs list along with the wordlist
    • pspell_new - Load a new dictionary
    • pspell_new_config - Load a new dictionary with settings based on a given config
    • pspell_new_personal - Load a new dictionary with personal wordlist
    • pspell_save_wordlist - Save the personal wordlist to a file
    • pspell_store_replacement - Store a replacement pair for a word
    • pspell_suggest - Suggest spellings of a word
    • ps_add_bookmark - Add bookmark to current page
    • ps_add_launchlink - Adds link which launches file
    • ps_add_locallink - Adds link to a page in the same document
    • ps_add_note - Adds note to current page
    • ps_add_pdflink - Adds link to a page in a second pdf document
    • ps_add_weblink - Adds link to a web location
    • ps_arc - Draws an arc counterclockwise
    • ps_arcn - Draws an arc clockwise
    • ps_begin_page - Start a new page
    • ps_begin_pattern - Start a new pattern
    • ps_begin_template - Start a new template
    • ps_circle - Draws a circle
    • ps_clip - Clips drawing to current path
    • ps_close - Closes a PostScript document
    • ps_closepath - Closes path
    • ps_closepath_stroke - Closes and strokes path
    • ps_close_image - Closes image and frees memory
    • ps_continue_text - Continue text in next line
    • ps_curveto - Draws a curve
    • ps_delete - Deletes all resources of a PostScript document
    • ps_end_page - End a page
    • ps_end_pattern - End a pattern
    • ps_end_template - End a template
    • ps_fill - Fills the current path
    • ps_fill_stroke - Fills and strokes the current path
    • ps_findfont - Loads a font
    • ps_get_buffer - Fetches the full buffer containig the generated PS data
    • ps_get_parameter - Gets certain parameters
    • ps_get_value - Gets certain values
    • ps_hyphenate - Hyphenates a word
    • ps_include_file - Reads an external file with raw PostScript code
    • ps_lineto - Draws a line
    • ps_makespotcolor - Create spot color
    • ps_moveto - Sets current point
    • ps_new - Creates a new PostScript document object
    • ps_open_file - Opens a file for output
    • ps_open_image - Reads an image for later placement
    • ps_open_image_file - Opens image from file
    • ps_open_memory_image - Takes an GD image and returns an image for placement in a PS document
    • ps_place_image - Places image on the page
    • ps_rect - Draws a rectangle
    • ps_restore - Restore previously save context
    • ps_rotate - Sets rotation factor
    • ps_save - Save current context
    • ps_scale - Sets scaling factor
    • ps_setcolor - Sets current color
    • ps_setdash - Sets appearance of a dashed line
    • ps_setflat - Sets flatness
    • ps_setfont - Sets font to use for following output
    • ps_setgray - Sets gray value
    • ps_setlinecap - Sets appearance of line ends
    • ps_setlinejoin - Sets how contected lines are joined
    • ps_setlinewidth - Sets width of a line
    • ps_setmiterlimit - Sets the miter limit
    • ps_setoverprintmode - Sets overprint mode
    • ps_setpolydash - Sets appearance of a dashed line
    • ps_set_border_color - Sets color of border for annotations
    • ps_set_border_dash - Sets length of dashes for border of annotations
    • ps_set_border_style - Sets border style of annotations
    • ps_set_info - Sets information fields of document
    • ps_set_parameter - Sets certain parameters
    • ps_set_text_pos - Sets position for text output
    • ps_set_value - Sets certain values
    • ps_shading - Creates a shading for later use
    • ps_shading_pattern - Creates a pattern based on a shading
    • ps_shfill - Fills an area with a shading
    • ps_show - Output text
    • ps_show2 - Output a text at current position
    • ps_show_boxed - Output text in a box
    • ps_show_xy - Output text at given position
    • ps_show_xy2 - Output text at position
    • ps_stringwidth - Gets width of a string
    • ps_string_geometry - Gets geometry of a string
    • ps_stroke - Draws the current path
    • ps_symbol - Output a glyph
    • ps_symbol_name - Gets name of a glyph
    • ps_symbol_width - Gets width of a glyph
    • ps_translate - Sets translation
    • putenv - 设置环境变量的值
    • px_close - Closes a paradox database
    • px_create_fp - Create a new paradox database
    • px_date2string - Converts a date into a string
    • px_delete - Deletes resource of paradox database
    • px_delete_record - Deletes record from paradox database
    • px_get_field - Returns the specification of a single field
    • px_get_info - Return lots of information about a paradox file
    • px_get_parameter - Gets a parameter
    • px_get_record - Returns record of paradox database
    • px_get_schema - Returns the database schema
    • px_get_value - Gets a value
    • px_insert_record - Inserts record into paradox database
    • px_new - Create a new paradox object
    • px_numfields - Returns number of fields in a database
    • px_numrecords - Returns number of records in a database
    • px_open_fp - Open paradox database
    • px_put_record - Stores record into paradox database
    • px_retrieve_record - Returns record of paradox database
    • px_set_blob_file - Sets the file where blobs are read from
    • px_set_parameter - Sets a parameter
    • px_set_tablename - Sets the name of a table (deprecated)
    • px_set_targetencoding - Sets the encoding for character fields (deprecated)
    • px_set_value - Sets a value
    • px_timestamp2string - Converts the timestamp into a string
    • px_update_record - Updates record in paradox database
  • q
    • QuickHashIntHash::add - This method adds a new entry to the hash
    • QuickHashIntHash::delete - This method deletes am entry from the hash
    • QuickHashIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize - Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntHash::__construct - Creates a new QuickHashIntHash object
    • QuickHashIntSet::add - This method adds a new entry to the set
    • QuickHashIntSet::delete - This method deletes an entry from the set
    • QuickHashIntSet::exists - This method checks whether a key is part of the set
    • QuickHashIntSet::getSize - Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile - This factory method creates a set from a file
    • QuickHashIntSet::loadFromString - This factory method creates a set from a string
    • QuickHashIntSet::saveToFile - This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString - This method returns a serialized version of the set
    • QuickHashIntSet::__construct - Creates a new QuickHashIntSet object
    • QuickHashIntStringHash::add - This method adds a new entry to the hash
    • QuickHashIntStringHash::delete - This method deletes am entry from the hash
    • QuickHashIntStringHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize - Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntStringHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntStringHash::__construct - Creates a new QuickHashIntStringHash object
    • QuickHashStringIntHash::add - This method adds a new entry to the hash
    • QuickHashStringIntHash::delete - This method deletes am entry from the hash
    • QuickHashStringIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize - Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashStringIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashStringIntHash::__construct - Creates a new QuickHashStringIntHash object
    • quoted_printable_decode - 将 quoted-printable 字符串转换为 8-bit 字符串
    • quoted_printable_encode - 将 8-bit 字符串转换成 quoted-printable 字符串
    • quotemeta - 转义元字符集
  • r
    • rad2deg - 将弧度数转换为相应的角度数
    • radius_acct_open - Creates a Radius handle for accounting
    • radius_add_server - Adds a server
    • radius_auth_open - Creates a Radius handle for authentication
    • radius_close - Frees all ressources
    • radius_config - Causes the library to read the given configuration file
    • radius_create_request - Create accounting or authentication request
    • radius_cvt_addr - Converts raw data to IP-Address
    • radius_cvt_int - Converts raw data to integer
    • radius_cvt_string - Converts raw data to string
    • radius_demangle - Demangles data
    • radius_demangle_mppe_key - Derives mppe-keys from mangled data
    • radius_get_attr - Extracts an attribute
    • radius_get_tagged_attr_data - Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag - Extracts the tag from a tagged attribute
    • radius_get_vendor_attr - Extracts a vendor specific attribute
    • radius_put_addr - Attaches an IP address attribute
    • radius_put_attr - Attaches a binary attribute
    • radius_put_int - Attaches an integer attribute
    • radius_put_string - Attaches a string attribute
    • radius_put_vendor_addr - Attaches a vendor specific IP address attribute
    • radius_put_vendor_attr - Attaches a vendor specific binary attribute
    • radius_put_vendor_int - Attaches a vendor specific integer attribute
    • radius_put_vendor_string - Attaches a vendor specific string attribute
    • radius_request_authenticator - Returns the request authenticator
    • radius_salt_encrypt_attr - Salt-encrypts a value
    • radius_send_request - Sends the request and waits for a reply
    • radius_server_secret - Returns the shared secret
    • radius_strerror - Returns an error message
    • rand - 产生一个随机整数
    • random_bytes - Generates cryptographically secure pseudo-random bytes
    • random_int - Generates cryptographically secure pseudo-random integers
    • range - 根据范围创建数组，包含指定的元素
    • rar:// - RAR
    • RarArchive::close - Close RAR archive and free all resources
    • RarArchive::getComment - Get comment text from the RAR archive
    • RarArchive::getEntries - Get full list of entries from the RAR archive
    • RarArchive::getEntry - Get entry object from the RAR archive
    • RarArchive::isBroken - Test whether an archive is broken (incomplete)
    • RarArchive::isSolid - Check whether the RAR archive is solid
    • RarArchive::open - Open RAR archive
    • RarArchive::setAllowBroken - Whether opening broken archives is allowed
    • RarArchive::__toString - Get text representation
    • RarEntry::extract - Extract entry from the archive
    • RarEntry::getAttr - Get attributes of the entry
    • RarEntry::getCrc - Get CRC of the entry
    • RarEntry::getFileTime - Get entry last modification time
    • RarEntry::getHostOs - Get entry host OS
    • RarEntry::getMethod - Get pack method of the entry
    • RarEntry::getName - Get name of the entry
    • RarEntry::getPackedSize - Get packed size of the entry
    • RarEntry::getStream - Get file handler for entry
    • RarEntry::getUnpackedSize - Get unpacked size of the entry
    • RarEntry::getVersion - Get minimum version of RAR program required to unpack the entry
    • RarEntry::isDirectory - Test whether an entry represents a directory
    • RarEntry::isEncrypted - Test whether an entry is encrypted
    • RarEntry::__toString - Get text representation of entry
    • RarException::isUsingExceptions - Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions - Activate and deactivate error handling with exceptions
    • rar_wrapper_cache_stats - Cache hits and misses for the URL wrapper
    • rawurldecode - 对已编码的 URL 字符串进行解码
    • rawurlencode - 按照 RFC 3986 对 URL 进行编码
    • readdir - 从目录句柄中读取条目
    • readfile - 输出文件
    • readgzfile - Output a gz-file
    • readline - 读取一行
    • readline_add_history - 添加一行命令行历史记录
    • readline_callback_handler_install - 初始化一个 readline 回调接口，然后终端输出提示信息并立即返回
    • readline_callback_handler_remove - 移除上一个安装的回调函数句柄并且恢复终端设置
    • readline_callback_read_char - 当一个行被接收时读取一个字符并且通知 readline 调用回调函数
    • readline_clear_history - 清除历史
    • readline_completion_function - 注册一个完成函数
    • readline_info - 获取/设置readline内部的各个变量
    • readline_list_history - 获取命令历史列表
    • readline_on_new_line - 通知readline将光标移动到新行
    • readline_read_history - 读取命令历史
    • readline_redisplay - 重绘显示区
    • readline_write_history - 写入历史记录
    • readlink - 返回符号连接指向的目标
    • read_exif_data - 别名 exif_read_data
    • realpath - 返回规范化的绝对路径名
    • realpath_cache_get - 获取真实目录缓存的详情
    • realpath_cache_size - 获取真实路径缓冲区的大小
    • recode - 别名 recode_string
    • recode_file - Recode from file to file according to recode request
    • recode_string - Recode a string according to a recode request
    • RecursiveArrayIterator::getChildren - Returns an iterator for the current entry if it is an array or an object
    • RecursiveArrayIterator::hasChildren - Returns whether current entry is an array or an object
    • RecursiveCachingIterator::getChildren - Return the inner iterator's children as a RecursiveCachingIterator
    • RecursiveCachingIterator::hasChildren - Check whether the current element of the inner iterator has children
    • RecursiveCachingIterator::__construct - Construct
    • RecursiveCallbackFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveCallbackFilterIterator::__construct - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Returns an iterator for the current entry if it is a directory
    • RecursiveDirectoryIterator::getSubPath - Get sub path
    • RecursiveDirectoryIterator::getSubPathname - Get sub path and name
    • RecursiveDirectoryIterator::hasChildren - Returns whether current entry is a directory and not '.' or '..'
    • RecursiveDirectoryIterator::key - Return path and filename of current dir entry
    • RecursiveDirectoryIterator::next - Move to next entry
    • RecursiveDirectoryIterator::rewind - Rewind dir back to the start
    • RecursiveDirectoryIterator::__construct - Constructs a RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveFilterIterator::__construct - Create a RecursiveFilterIterator from a RecursiveIterator
    • RecursiveIterator::getChildren - Returns an iterator for the current entry
    • RecursiveIterator::hasChildren - Returns if an iterator can be created for the current entry
    • RecursiveIteratorIterator::beginChildren - Begin children
    • RecursiveIteratorIterator::beginIteration - Begin Iteration
    • RecursiveIteratorIterator::callGetChildren - Get children
    • RecursiveIteratorIterator::callHasChildren - Has children
    • RecursiveIteratorIterator::current - Access the current element value
    • RecursiveIteratorIterator::endChildren - End children
    • RecursiveIteratorIterator::endIteration - End Iteration
    • RecursiveIteratorIterator::getDepth - Get the current depth of the recursive iteration
    • RecursiveIteratorIterator::getInnerIterator - Get inner iterator
    • RecursiveIteratorIterator::getMaxDepth - Get max depth
    • RecursiveIteratorIterator::getSubIterator - The current active sub iterator
    • RecursiveIteratorIterator::key - Access the current key
    • RecursiveIteratorIterator::next - Move forward to the next element
    • RecursiveIteratorIterator::nextElement - Next element
    • RecursiveIteratorIterator::rewind - Rewind the iterator to the first element of the top level inner iterator
    • RecursiveIteratorIterator::setMaxDepth - Set max depth
    • RecursiveIteratorIterator::valid - Check whether the current position is valid
    • RecursiveIteratorIterator::__construct - Construct a RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Returns an iterator for the current entry
    • RecursiveRegexIterator::hasChildren - Returns whether an iterator can be obtained for the current entry
    • RecursiveRegexIterator::__construct - Creates a new RecursiveRegexIterator
    • RecursiveTreeIterator::beginChildren - Begin children
    • RecursiveTreeIterator::beginIteration - Begin iteration
    • RecursiveTreeIterator::callGetChildren - Get children
    • RecursiveTreeIterator::callHasChildren - Has children
    • RecursiveTreeIterator::current - Get current element
    • RecursiveTreeIterator::endChildren - End children
    • RecursiveTreeIterator::endIteration - End iteration
    • RecursiveTreeIterator::getEntry - Get current entry
    • RecursiveTreeIterator::getPostfix - Get the postfix
    • RecursiveTreeIterator::getPrefix - Get the prefix
    • RecursiveTreeIterator::key - Get the key of the current element
    • RecursiveTreeIterator::next - Move to next element
    • RecursiveTreeIterator::nextElement - Next element
    • RecursiveTreeIterator::rewind - Rewind iterator
    • RecursiveTreeIterator::setPostfix - Set postfix
    • RecursiveTreeIterator::setPrefixPart - Set a part of the prefix
    • RecursiveTreeIterator::valid - Check validity
    • RecursiveTreeIterator::__construct - Construct a RecursiveTreeIterator
    • Reflection::export - Exports
    • Reflection::getModifierNames - 获取修饰符的名称
    • ReflectionClass::export - 导出一个类
    • ReflectionClass::getConstant - 获取定义过的一个常量
    • ReflectionClass::getConstants - 获取一组常量
    • ReflectionClass::getConstructor - 获取类的构造函数
    • ReflectionClass::getDefaultProperties - 获取默认属性
    • ReflectionClass::getDocComment - 获取文档注释
    • ReflectionClass::getEndLine - 获取最后一行的行数
    • ReflectionClass::getExtension - 根据已定义的类获取所在扩展的 ReflectionExtension 对象
    • ReflectionClass::getExtensionName - 获取定义的类所在的扩展的名称
    • ReflectionClass::getFileName - 获取定义类的文件名
    • ReflectionClass::getInterfaceNames - 获取接口（interface）名称
    • ReflectionClass::getInterfaces - 获取接口
    • ReflectionClass::getMethod - 获取一个类方法的 ReflectionMethod。
    • ReflectionClass::getMethods - 获取方法的数组
    • ReflectionClass::getModifiers - 获取类的修饰符
    • ReflectionClass::getName - 获取类名
    • ReflectionClass::getNamespaceName - 获取命名空间的名称
    • ReflectionClass::getParentClass - 获取父类
    • ReflectionClass::getProperties - 获取一组属性
    • ReflectionClass::getProperty - 获取类的一个属性的 ReflectionProperty
    • ReflectionClass::getReflectionConstant - Gets a ReflectionClassConstant for a class's constant
    • ReflectionClass::getReflectionConstants - Gets class constants
    • ReflectionClass::getShortName - 获取短名
    • ReflectionClass::getStartLine - 获取起始行号
    • ReflectionClass::getStaticProperties - 获取静态（static）属性
    • ReflectionClass::getStaticPropertyValue - 获取静态（static）属性的值
    • ReflectionClass::getTraitAliases - 返回 trait 别名的一个数组
    • ReflectionClass::getTraitNames - 返回这个类所使用 traits 的名称的数组
    • ReflectionClass::getTraits - 返回这个类所使用的 traits 数组
    • ReflectionClass::hasConstant - 检查常量是否已经定义
    • ReflectionClass::hasMethod - 检查方法是否已定义
    • ReflectionClass::hasProperty - 检查属性是否已定义
    • ReflectionClass::implementsInterface - 接口的实现
    • ReflectionClass::inNamespace - 检查是否位于命名空间中
    • ReflectionClass::isAbstract - 检查类是否是抽象类（abstract）
    • ReflectionClass::isAnonymous - 检查类是否是匿名类
    • ReflectionClass::isCloneable - 返回了一个类是否可复制
    • ReflectionClass::isFinal - 检查类是否声明为 final
    • ReflectionClass::isInstance - 检查类的实例
    • ReflectionClass::isInstantiable - 检查类是否可实例化
    • ReflectionClass::isInterface - 检查类是否是一个接口（interface）
    • ReflectionClass::isInternal - 检查类是否由扩展或核心在内部定义
    • ReflectionClass::isIterable - Check whether this class is iterable
    • ReflectionClass::isIterateable - 检查是否可迭代（iterateable）
    • ReflectionClass::isSubclassOf - 检查是否为一个子类
    • ReflectionClass::isTrait - 返回了是否为一个 trait
    • ReflectionClass::isUserDefined - 检查是否由用户定义的
    • ReflectionClass::newInstance - 从指定的参数创建一个新的类实例
    • ReflectionClass::newInstanceArgs - 从给出的参数创建一个新的类实例。
    • ReflectionClass::newInstanceWithoutConstructor - 创建一个新的类实例而不调用它的构造函数
    • ReflectionClass::setStaticPropertyValue - 设置静态属性的值
    • ReflectionClass::__construct - 初始化 ReflectionClass 类
    • ReflectionClass::__toString - 返回 ReflectionClass 对象字符串的表示形式。
    • ReflectionClassConstant::export - Export
    • ReflectionClassConstant::getDeclaringClass - Gets declaring class
    • ReflectionClassConstant::getDocComment - Gets doc comments
    • ReflectionClassConstant::getModifiers - Gets the class constant modifiers
    • ReflectionClassConstant::getName - Get name of the constant
    • ReflectionClassConstant::getValue - Gets value
    • ReflectionClassConstant::isPrivate - Checks if class constant is private
    • ReflectionClassConstant::isProtected - Checks if class constant is protected
    • ReflectionClassConstant::isPublic - Checks if class constant is public
    • ReflectionClassConstant::__construct - Constructs a ReflectionClassConstant
    • ReflectionClassConstant::__toString - Returns the string representation of the ReflectionClassConstant object
    • ReflectionExtension::export - Export
    • ReflectionExtension::getClasses - Gets classes
    • ReflectionExtension::getClassNames - 获取类名称
    • ReflectionExtension::getConstants - 获取常量
    • ReflectionExtension::getDependencies - 获取依赖
    • ReflectionExtension::getFunctions - 获取扩展中的函数
    • ReflectionExtension::getINIEntries - 获取ini配置
    • ReflectionExtension::getName - 获取扩展名称
    • ReflectionExtension::getVersion - 获取扩展版本号
    • ReflectionExtension::info - 输出扩展信息
    • ReflectionExtension::isPersistent - 返回扩展是否持久化载入
    • ReflectionExtension::isTemporary - 返回扩展是否是临时载入
    • ReflectionExtension::__clone - Clones
    • ReflectionExtension::__construct - Constructs a ReflectionExtension
    • ReflectionExtension::__toString - To string
    • ReflectionFunction::export - Exports function
    • ReflectionFunction::getClosure - Returns a dynamically created closure for the function
    • ReflectionFunction::invoke - Invokes function
    • ReflectionFunction::invokeArgs - Invokes function args
    • ReflectionFunction::isDisabled - Checks if function is disabled
    • ReflectionFunction::__construct - Constructs a ReflectionFunction object
    • ReflectionFunction::__toString - To string
    • ReflectionFunctionAbstract::getClosureScopeClass - Returns the scope associated to the closure
    • ReflectionFunctionAbstract::getClosureThis - 返回本身的匿名函数
    • ReflectionFunctionAbstract::getDocComment - 获取注释内容
    • ReflectionFunctionAbstract::getEndLine - 获取结束行号
    • ReflectionFunctionAbstract::getExtension - 获取扩展信息
    • ReflectionFunctionAbstract::getExtensionName - 获取扩展名称
    • ReflectionFunctionAbstract::getFileName - 获取文件名称
    • ReflectionFunctionAbstract::getName - 获取函数名称
    • ReflectionFunctionAbstract::getNamespaceName - 获取命名空间
    • ReflectionFunctionAbstract::getNumberOfParameters - 获取参数数目
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters - 获取必须输入参数个数
    • ReflectionFunctionAbstract::getParameters - 获取参数
    • ReflectionFunctionAbstract::getReturnType - Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName - 获取函数短名称
    • ReflectionFunctionAbstract::getStartLine - 获取开始行号
    • ReflectionFunctionAbstract::getStaticVariables - 获取静态变量
    • ReflectionFunctionAbstract::hasReturnType - Checks if the function has a specified return type
    • ReflectionFunctionAbstract::inNamespace - 检查是否处于命名空间
    • ReflectionFunctionAbstract::isClosure - 检查是否是匿名函数
    • ReflectionFunctionAbstract::isDeprecated - 检查是否已经弃用
    • ReflectionFunctionAbstract::isGenerator - 判断函数是否是一个生成器函数
    • ReflectionFunctionAbstract::isInternal - 判断函数是否是内置函数
    • ReflectionFunctionAbstract::isUserDefined - 检查是否是用户定义
    • ReflectionFunctionAbstract::isVariadic - Checks if the function is variadic
    • ReflectionFunctionAbstract::returnsReference - 检查是否返回参考信息
    • ReflectionFunctionAbstract::__clone - 复制函数
    • ReflectionFunctionAbstract::__toString - 字符串化
    • ReflectionGenerator::getExecutingFile - Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator - Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine - Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction - Gets the function name of the generator
    • ReflectionGenerator::getThis - Gets the $this value of the generator
    • ReflectionGenerator::getTrace - Gets the trace of the executing generator
    • ReflectionGenerator::__construct - Constructs a ReflectionGenerator object
    • ReflectionMethod::export - 输出一个回调方法
    • ReflectionMethod::getClosure - 返回一个动态建立的方法调用接口，译者注：可以使用这个返回值直接调用非公开方法。
    • ReflectionMethod::getDeclaringClass - 获取被反射的方法所在类的反射实例
    • ReflectionMethod::getModifiers - 获取方法的修饰符
    • ReflectionMethod::getPrototype - 返回方法原型 (如果存在)
    • ReflectionMethod::invoke - Invoke
    • ReflectionMethod::invokeArgs - 带参数执行
    • ReflectionMethod::isAbstract - 判断方法是否是抽象方法
    • ReflectionMethod::isConstructor - 判断方法是否是构造方法
    • ReflectionMethod::isDestructor - 判断方法是否是析构方法
    • ReflectionMethod::isFinal - 判断方法是否定义 final
    • ReflectionMethod::isPrivate - 判断方法是否是私有方法
    • ReflectionMethod::isProtected - 判断方法是否是保护方法 (protected)
    • ReflectionMethod::isPublic - 判断方法是否是公开方法
    • ReflectionMethod::isStatic - 判断方法是否是静态方法
    • ReflectionMethod::setAccessible - 设置方法是否访问
    • ReflectionMethod::__construct - ReflectionMethod 的构造函数
    • ReflectionMethod::__toString - 返回反射方法对象的字符串表达
    • ReflectionObject::export - Export
    • ReflectionObject::__construct - Constructs a ReflectionObject
    • ReflectionParameter::allowsNull - Checks if null is allowed
    • ReflectionParameter::canBePassedByValue - Returns whether this parameter can be passed by value
    • ReflectionParameter::export - Exports
    • ReflectionParameter::getClass - 获得类型提示类。
    • ReflectionParameter::getDeclaringClass - Gets declaring class
    • ReflectionParameter::getDeclaringFunction - Gets declaring function
    • ReflectionParameter::getDefaultValue - Gets default parameter value
    • ReflectionParameter::getDefaultValueConstantName - Returns the default value's constant name if default value is constant or null
    • ReflectionParameter::getName - Gets parameter name
    • ReflectionParameter::getPosition - Gets parameter position
    • ReflectionParameter::getType - Gets a parameter's type
    • ReflectionParameter::hasType - Checks if parameter has a type
    • ReflectionParameter::isArray - Checks if parameter expects an array
    • ReflectionParameter::isCallable - Returns whether parameter MUST be callable
    • ReflectionParameter::isDefaultValueAvailable - 检查是否有默认值。
    • ReflectionParameter::isDefaultValueConstant - Returns whether the default value of this parameter is a constant
    • ReflectionParameter::isOptional - Checks if optional
    • ReflectionParameter::isPassedByReference - Checks if passed by reference
    • ReflectionParameter::isVariadic - Checks if the parameter is variadic
    • ReflectionParameter::__clone - Clone
    • ReflectionParameter::__construct - Construct
    • ReflectionParameter::__toString - To string
    • ReflectionProperty::export - Export
    • ReflectionProperty::getDeclaringClass - Gets declaring class
    • ReflectionProperty::getDefaultValue - Returns the default value declared for a property
    • ReflectionProperty::getDocComment - Gets the property doc comment
    • ReflectionProperty::getModifiers - Gets the property modifiers
    • ReflectionProperty::getName - Gets property name
    • ReflectionProperty::getType - Gets a property's type
    • ReflectionProperty::getValue - Gets value
    • ReflectionProperty::hasDefaultValue - Checks if property has a default value declared
    • ReflectionProperty::hasType - Checks if property has a type
    • ReflectionProperty::isDefault - Checks if property is a default property
    • ReflectionProperty::isInitialized - Checks whether a property is initialized
    • ReflectionProperty::isPrivate - Checks if property is private
    • ReflectionProperty::isProtected - Checks if property is protected
    • ReflectionProperty::isPublic - Checks if property is public
    • ReflectionProperty::isStatic - Checks if property is static
    • ReflectionProperty::setAccessible - Set property accessibility
    • ReflectionProperty::setValue - Set property value
    • ReflectionProperty::__clone - Clone
    • ReflectionProperty::__construct - Construct a ReflectionProperty object
    • ReflectionProperty::__toString - To string
    • ReflectionType::allowsNull - Checks if null is allowed
    • ReflectionType::__toString - To string
    • ReflectionZendExtension::export - Export
    • ReflectionZendExtension::getAuthor - Gets author
    • ReflectionZendExtension::getCopyright - Gets copyright
    • ReflectionZendExtension::getName - Gets name
    • ReflectionZendExtension::getURL - Gets URL
    • ReflectionZendExtension::getVersion - Gets version
    • ReflectionZendExtension::__clone - Clone handler
    • ReflectionZendExtension::__construct - Constructor
    • ReflectionZendExtension::__toString - To string handler
    • Reflector::export - Exports
    • Reflector::__toString - 转化成字符串
    • RegexIterator::accept - Get accept status
    • RegexIterator::getFlags - Get flags
    • RegexIterator::getMode - Returns operation mode
    • RegexIterator::getPregFlags - Returns the regular expression flags
    • RegexIterator::getRegex - Returns current regular expression
    • RegexIterator::setFlags - Sets the flags
    • RegexIterator::setMode - Sets the operation mode
    • RegexIterator::setPregFlags - Sets the regular expression flags
    • RegexIterator::__construct - Create a new RegexIterator
    • register_shutdown_function - 注册一个会在php中止时执行的函数
    • register_tick_function - Register a function for execution on each tick
    • rename - 重命名一个文件或目录
    • reset - 将数组的内部指针指向第一个单元
    • ResourceBundle::count - Get number of elements in the bundle
    • ResourceBundle::create - Create a resource bundle
    • ResourceBundle::get - Get data from the bundle
    • ResourceBundle::getErrorCode - Get bundle's last error code
    • ResourceBundle::getErrorMessage - Get bundle's last error message
    • ResourceBundle::getLocales - Get supported locales
    • restore_error_handler - 还原之前的错误处理函数
    • restore_exception_handler - 恢复之前定义过的异常处理函数。
    • restore_include_path - 还原 include_path 配置选项的值
    • Result::getAffectedItemsCount - Get affected row count
    • Result::getAutoIncrementValue - Get autoincremented value
    • Result::getGeneratedIds - Get generated ids
    • Result::getWarnings - Get warnings from last operation
    • Result::getWarningsCount - Get warning count from last operation
    • Result::__construct - Result constructor
    • rewind - 倒回文件指针的位置
    • rewinddir - 倒回目录句柄
    • rmdir - 删除目录
    • round - 对浮点数进行四舍五入
    • RowResult::fetchAll - Get all rows from result
    • RowResult::fetchOne - Get row from result
    • RowResult::getColumnNames - Get all column names
    • RowResult::getColumns - Get column metadata
    • RowResult::getColumnsCount - Get column count
    • RowResult::getWarnings - Get warnings from last operation
    • RowResult::getWarningsCount - Get warning count from last operation
    • RowResult::__construct - RowResult constructor
    • rpmaddtag - Add tag retrieved in query
    • rpmdbinfo - Get information from installed RPM
    • rpmdbsearch - Search RPM packages
    • rpminfo - Get information from a RPM file
    • rpmvercmp - RPM version comparison
    • RRDCreator::addArchive - Adds RRA - archive of data values for each data source
    • RRDCreator::addDataSource - Adds data source definition for RRD database
    • RRDCreator::save - Saves the RRD database to a file
    • RRDCreator::__construct - Creates new RRDCreator instance
    • rrdc_disconnect - Close any outstanding connection to rrd caching daemon
    • RRDGraph::save - Saves the result of query into image
    • RRDGraph::saveVerbose - Saves the RRD database query into image and returns the verbose information about generated graph
    • RRDGraph::setOptions - Sets the options for rrd graph export
    • RRDGraph::__construct - Creates new RRDGraph instance
    • RRDUpdater::update - Update the RRD database file
    • RRDUpdater::__construct - Creates new RRDUpdater instance
    • rrd_create - Creates rrd database file
    • rrd_error - Gets latest error message
    • rrd_fetch - Fetch the data for graph as array
    • rrd_first - Gets the timestamp of the first sample from rrd file
    • rrd_graph - Creates image from a data
    • rrd_info - Gets information about rrd file
    • rrd_last - Gets unix timestamp of the last sample
    • rrd_lastupdate - Gets information about last updated data
    • rrd_restore - Restores the RRD file from XML dump
    • rrd_tune - Tunes some RRD database file header options
    • rrd_update - Updates the RRD database
    • rrd_version - Gets information about underlying rrdtool library
    • rrd_xport - Exports the information about RRD database
    • rsort - 对数组逆向排序
    • rtrim - 删除字符串末端的空白字符（或者其他字符）
    • runkit7_constant_add - Similar to define(), but allows defining in class definitions as well
    • runkit7_constant_redefine - Redefine an already defined constant
    • runkit7_constant_remove - Remove/Delete an already defined constant
    • runkit7_function_add - Add a new function, similar to create_function
    • runkit7_function_copy - Copy a function to a new function name
    • runkit7_function_redefine - Replace a function definition with a new implementation
    • runkit7_function_remove - Remove a function definition
    • runkit7_function_rename - Change a function's name
    • runkit7_import - Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit7_method_add - Dynamically adds a new method to a given class
    • runkit7_method_copy - Copies a method from class to another
    • runkit7_method_redefine - Dynamically changes the code of the given method
    • runkit7_method_remove - Dynamically removes the given method
    • runkit7_method_rename - Dynamically changes the name of the given method
    • runkit7_object_id - Return the integer object handle for given object
    • runkit7_superglobals - Return numerically indexed array of registered superglobals
    • runkit7_zval_inspect - Returns information about the passed in value with data types, reference counts, etc
  • s
    • sapi_windows_cp_conv - Convert string from one codepage to another
    • sapi_windows_cp_get - Get current codepage
    • sapi_windows_cp_is_utf8 - Indicates whether the codepage is UTF-8 compatible
    • sapi_windows_cp_set - Set process codepage
    • sapi_windows_generate_ctrl_event - Send a CTRL event to another process
    • sapi_windows_set_ctrl_handler - Set or remove a CTRL event handler
    • sapi_windows_vt100_support - Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
    • scandir - 列出指定路径中的文件和目录
    • Schema::createCollection - Add collection to schema
    • Schema::dropCollection - Drop collection from schema
    • Schema::existsInDatabase - Check if exists in database
    • Schema::getCollection - Get collection from schema
    • Schema::getCollectionAsTable - Get collection table object
    • Schema::getCollections - Get all schema collections
    • Schema::getName - Get schema name
    • Schema::getSession - Get schema session
    • Schema::getTable - Get schema table
    • Schema::getTables - Get schema tables
    • Schema::__construct - constructor
    • SchemaObject::getSchema - Get schema object
    • scoutapm_get_calls - Returns a list of instrumented calls that have occurred
    • scoutapm_list_instrumented_functions - List functions scoutapm will instrument.
    • SeasLog::alert - 记录 alert 日志
    • SeasLog::analyzerCount - Get log count by level, log_path and key_word
    • SeasLog::analyzerDetail - Get log detail by level, log_path, key_word, start, limit, order
    • SeasLog::closeLoggerStream - Manually release stream flow from logger
    • SeasLog::critical - 记录 critical 日志
    • SeasLog::debug - 记录 debug 日志
    • SeasLog::emergency - 记录 emergency 日志
    • SeasLog::error - 记录 error 日志
    • SeasLog::flushBuffer - 将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址。
    • SeasLog::getBasePath - 获得 SeasLog 根目录
    • SeasLog::getBuffer - 获取内存中的日志缓存数组
    • SeasLog::getBufferEnabled - Determin if buffer enabled
    • SeasLog::getDatetimeFormat - 获取 SeasLog 日期格式
    • SeasLog::getLastLogger - 获得 SeasLog 最近的一次 Logger 名称
    • SeasLog::getRequestID - 获得当前 SeasLog 中用于区分请求的 request_id
    • SeasLog::getRequestVariable - Get SeasLog request variable
    • SeasLog::info - Record info log information
    • SeasLog::log - 公共的日志记录函数
    • SeasLog::notice - 记录 notice 日志
    • SeasLog::setBasePath - 设置 SeasLog 根目录
    • SeasLog::setDatetimeFormat - 设置 SeasLog 日期格式
    • SeasLog::setLogger - 设置 SeasLog 的 Logger 名
    • SeasLog::setRequestID - 设置可以由 SeasLog 用于区分请求的 request_id
    • SeasLog::setRequestVariable - Manually set SeasLog request variable
    • SeasLog::warning - Record warning log information
    • SeasLog::__construct - Description
    • SeasLog::__destruct - Description
    • seaslog_get_author - 获取 SeasLog 作者
    • seaslog_get_version - 获取 SeasLog 的版本
    • SeekableIterator::seek - Seeks to a position
    • sem_acquire - Acquire a semaphore
    • sem_get - Get a semaphore id
    • sem_release - Release a semaphore
    • sem_remove - Remove a semaphore
    • Serializable::serialize - 对象的字符串表示
    • Serializable::unserialize - 构造对象
    • serialize - 产生一个可存储的值的表示
    • Session::close - Close session
    • Session::createSchema - Create new schema
    • Session::dropSchema - Drop a schema
    • Session::generateUUID - Get new UUID
    • Session::getDefaultSchema - Get default schema name
    • Session::getSchema - Get a new schema object
    • Session::getSchemas - Get the schemas
    • Session::getServerVersion - Get server version
    • Session::listClients - Get client list
    • Session::quoteName - Add quotes
    • Session::releaseSavepoint - Release set savepoint
    • Session::rollback - Rollback transaction
    • Session::rollbackTo - Rollback transaction to savepoint
    • Session::setSavepoint - Create savepoint
    • Session::sql - Execute SQL query
    • Session::startTransaction - Start transaction
    • Session::__construct - Description constructor
    • SessionHandler::close - Close the session
    • SessionHandler::create_sid - Return a new session ID
    • SessionHandler::destroy - Destroy a session
    • SessionHandler::gc - Cleanup old sessions
    • SessionHandler::open - Initialize session
    • SessionHandler::read - Read session data
    • SessionHandler::write - Write session data
    • SessionHandlerInterface::close - Close the session
    • SessionHandlerInterface::destroy - Destroy a session
    • SessionHandlerInterface::gc - Cleanup old sessions
    • SessionHandlerInterface::open - Initialize session
    • SessionHandlerInterface::read - Read session data
    • SessionHandlerInterface::write - Write session data
    • session_abort - Discard session array changes and finish session
    • session_cache_expire - 返回当前缓存的到期时间
    • session_cache_limiter - 读取/设置缓存限制器
    • session_commit - session_write_close 的别名
    • session_create_id - Create new session id
    • session_decode - 解码会话数据
    • session_destroy - 销毁一个会话中的全部数据
    • session_encode - 将当前会话数据编码为一个字符串
    • session_gc - Perform session data garbage collection
    • session_get_cookie_params - 获取会话 cookie 参数
    • session_id - 获取/设置当前会话 ID
    • session_is_registered - 检查变量是否在会话中已经注册
    • session_module_name - 获取/设置会话模块名称
    • session_name - 读取/设置会话名称
    • session_regenerate_id - 使用新生成的会话 ID 更新现有会话 ID
    • session_register_shutdown - 关闭会话
    • session_reset - Re-initialize session array with original values
    • session_save_path - 读取/设置当前会话的保存路径
    • session_set_cookie_params - 设置会话 cookie 参数
    • session_set_save_handler - 设置用户自定义会话存储函数
    • session_start - 启动新会话或者重用现有会话
    • session_status - 返回当前会话状态
    • session_unregister - Unregister a global variable from the current session
    • session_unset - 释放所有的会话变量
    • session_write_close - Write session data and end session
    • setcookie - 发送 Cookie
    • setlocale - 设置地区信息
    • setproctitle - Set the process title
    • setrawcookie - 发送未经 URL 编码的 cookie
    • setthreadtitle - Set the thread title
    • settype - 设置变量的类型
    • set_error_handler - 设置用户自定义的错误处理函数
    • set_exception_handler - 设置用户自定义的异常处理函数
    • set_file_buffer - stream_set_write_buffer 的别名
    • set_include_path - 设置 include_path 配置选项
    • set_time_limit - 设置脚本最大执行时间
    • sha1 - 计算字符串的 sha1 散列值
    • sha1_file - 计算文件的 sha1 散列值
    • shell_exec - 通过 shell 环境执行命令，并且将完整的输出以字符串的方式返回。
    • shmop_close - Close shared memory block
    • shmop_delete - Delete shared memory block
    • shmop_open - Create or open shared memory block
    • shmop_read - Read data from shared memory block
    • shmop_size - Get size of shared memory block
    • shmop_write - Write data into shared memory block
    • shm_attach - Creates or open a shared memory segment
    • shm_detach - Disconnects from shared memory segment
    • shm_get_var - Returns a variable from shared memory
    • shm_has_var - Check whether a specific entry exists
    • shm_put_var - Inserts or updates a variable in shared memory
    • shm_remove - Removes shared memory from Unix systems
    • shm_remove_var - Removes a variable from shared memory
    • show_source - 别名 highlight_file
    • shuffle - 打乱数组
    • similar_text - 计算两个字符串的相似度
    • SimpleXMLElement::addAttribute - Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild - Adds a child element to the XML node
    • SimpleXMLElement::asXML - Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes - Identifies an element's attributes
    • SimpleXMLElement::children - Finds children of given node
    • SimpleXMLElement::count - Counts the children of an element
    • SimpleXMLElement::getDocNamespaces - Returns namespaces declared in document
    • SimpleXMLElement::getName - Gets the name of the XML element
    • SimpleXMLElement::getNamespaces - Returns namespaces used in document
    • SimpleXMLElement::registerXPathNamespace - Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::saveXML - 别名 SimpleXMLElement::asXML
    • SimpleXMLElement::xpath - Runs XPath query on XML data
    • SimpleXMLElement::__construct - Creates a new SimpleXMLElement object
    • SimpleXMLElement::__toString - Returns the string content
    • SimpleXMLIterator::current - Returns the current element
    • SimpleXMLIterator::getChildren - Returns the sub-elements of the current element
    • SimpleXMLIterator::hasChildren - Checks whether the current element has sub elements
    • SimpleXMLIterator::key - Return current key
    • SimpleXMLIterator::next - Move to next element
    • SimpleXMLIterator::rewind - Rewind to the first element
    • SimpleXMLIterator::valid - Check whether the current element is valid
    • simplexml_import_dom - Get a SimpleXMLElement object from a DOM node
    • simplexml_load_file - Interprets an XML file into an object
    • simplexml_load_string - Interprets a string of XML into an object
    • sin - 正弦
    • sinh - 双曲正弦
    • sizeof - count 的别名
    • sleep - 延缓执行
    • snmp2_get - Fetch an SNMP object
    • snmp2_getnext - Fetch the SNMP object which follows the given object id
    • snmp2_real_walk - Return all objects including their respective object ID within the specified one
    • snmp2_set - Set the value of an SNMP object
    • snmp2_walk - Fetch all the SNMP objects from an agent
    • snmp3_get - Fetch an SNMP object
    • snmp3_getnext - Fetch the SNMP object which follows the given object id
    • snmp3_real_walk - Return all objects including their respective object ID within the specified one
    • snmp3_set - Set the value of an SNMP object
    • snmp3_walk - Fetch all the SNMP objects from an agent
    • SNMP::close - Close SNMP session
    • SNMP::get - Fetch an SNMP object
    • SNMP::getErrno - Get last error code
    • SNMP::getError - Get last error message
    • SNMP::getnext - Fetch an SNMP object which follows the given object id
    • SNMP::set - Set the value of an SNMP object
    • SNMP::setSecurity - Configures security-related SNMPv3 session parameters
    • SNMP::walk - Fetch SNMP object subtree
    • SNMP::__construct - Creates SNMP instance representing session to remote SNMP agent
    • snmpget - 获取一个 SNMP 对象
    • snmpgetnext - Fetch the SNMP object which follows the given object id
    • snmprealwalk - 返回指定的所有对象，包括它们各自的对象 ID
    • snmpset - 设置一个 SNMP 对象
    • snmpwalk - 从代理返回所有的 SNMP 对象
    • snmpwalkoid - 查询关于网络实体的信息树
    • snmp_get_quick_print - 返回 UCD 库中 quick_print 设置的当前值
    • snmp_get_valueretrieval - Return the method how the SNMP values will be returned
    • snmp_read_mib - Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print - Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print - Set the OID output format
    • snmp_set_oid_output_format - Set the OID output format
    • snmp_set_quick_print - 设置 UCD SNMP 库中 quick_print 的值
    • snmp_set_valueretrieval - Specify the method how the SNMP values will be returned
    • SoapClient::__call - Calls a SOAP function (deprecated)
    • SoapClient::__construct - SoapClient constructor
    • SoapClient::__doRequest - Performs a SOAP request
    • SoapClient::__getCookies - Get list of cookies
    • SoapClient::__getFunctions - Returns list of available SOAP functions
    • SoapClient::__getLastRequest - Returns last SOAP request
    • SoapClient::__getLastRequestHeaders - Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse - Returns last SOAP response
    • SoapClient::__getLastResponseHeaders - Returns the SOAP headers from the last response
    • SoapClient::__getTypes - Returns a list of SOAP types
    • SoapClient::__setCookie - Defines a cookie for SOAP requests
    • SoapClient::__setLocation - Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders - Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall - Calls a SOAP function
    • SoapFault::__construct - SoapFault constructor
    • SoapFault::__toString - Obtain a string representation of a SoapFault
    • SoapHeader::__construct - SoapHeader constructor
    • SoapParam::__construct - SoapParam constructor
    • SoapServer::addFunction - 添加一个或多个函数来处理SOAP请求
    • SoapServer::addSoapHeader - Add a SOAP header to the response
    • SoapServer::fault - Issue SoapServer fault indicating an error
    • SoapServer::getFunctions - Returns list of defined functions
    • SoapServer::handle - Handles a SOAP request
    • SoapServer::setClass - Sets the class which handles SOAP requests
    • SoapServer::setObject - Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence - Sets SoapServer persistence mode
    • SoapServer::__construct - SoapServer constructor
    • SoapVar::__construct - SoapVar constructor
    • socket_accept - Accepts a connection on a socket
    • socket_addrinfo_bind - Create and bind to a socket from a given addrinfo
    • socket_addrinfo_connect - Create and connect to a socket from a given addrinfo
    • socket_addrinfo_explain - Get information about addrinfo
    • socket_addrinfo_lookup - Get array with contents of getaddrinfo about the given hostname
    • socket_bind - 给套接字绑定名字
    • socket_clear_error - 清除套接字或者最后的错误代码上的错误
    • socket_close - 关闭套接字资源
    • socket_cmsg_space - Calculate message buffer size
    • socket_connect - 开启一个套接字连接
    • socket_create - 创建一个套接字（通讯节点）
    • socket_create_listen - Opens a socket on port to accept connections
    • socket_create_pair - Creates a pair of indistinguishable sockets and stores them in an array
    • socket_export_stream - Export a socket into a stream that encapsulates a socket
    • socket_getopt - 别名 socket_get_option
    • socket_getpeername - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_get_option - Gets socket options for the socket
    • socket_get_status - 别名 stream_get_meta_data
    • socket_import_stream - Import a stream
    • socket_last_error - Returns the last error on the socket
    • socket_listen - Listens for a connection on a socket
    • socket_read - Reads a maximum of length bytes from a socket
    • socket_recv - 从已连接的socket接收数据
    • socket_recvfrom - Receives data from a socket whether or not it is connection-oriented
    • socket_recvmsg - Read a message
    • socket_select - Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send - Sends data to a connected socket
    • socket_sendmsg - Send a message
    • socket_sendto - Sends a message to a socket, whether it is connected or not
    • socket_setopt - 别名 socket_set_option
    • socket_set_block - Sets blocking mode on a socket
    • socket_set_blocking - 别名 stream_set_blocking
    • socket_set_nonblock - Sets nonblocking mode for file descriptor fd
    • socket_set_option - Sets socket options for the socket
    • socket_set_timeout - 别名 stream_set_timeout
    • socket_shutdown - Shuts down a socket for receiving, sending, or both
    • socket_strerror - Return a string describing a socket error
    • socket_write - Write to a socket
    • socket_wsaprotocol_info_export - Exports the WSAPROTOCOL_INFO Structure
    • socket_wsaprotocol_info_import - Imports a Socket from another Process
    • socket_wsaprotocol_info_release - Releases an exported WSAPROTOCOL_INFO Structure
    • sodium_add - Add large numbers
    • sodium_base642bin - Description
    • sodium_bin2base64 - Description
    • sodium_bin2hex - Encode to hexadecimal
    • sodium_compare - Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt - Decrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_encrypt - Encrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_is_available - Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen - Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_decrypt - Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_encrypt - Encrypt a message
    • sodium_crypto_aead_chacha20poly1305_ietf_decrypt - Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_ietf_encrypt - Encrypt a message
    • sodium_crypto_aead_chacha20poly1305_ietf_keygen - Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_keygen - Get random bytes for key
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt - Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt - Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen - Description
    • sodium_crypto_auth - Compute a tag for the message
    • sodium_crypto_auth_keygen - Get random bytes for key
    • sodium_crypto_auth_verify - Verifies that the tag is valid for the message
    • sodium_crypto_box - Encrypt a message
    • sodium_crypto_box_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_keypair_from_secretkey_and_publickey - Description
    • sodium_crypto_box_open - Verify and decrypt a ciphertext
    • sodium_crypto_box_publickey - Description
    • sodium_crypto_box_publickey_from_secretkey - Description
    • sodium_crypto_box_seal - Encrypt a message
    • sodium_crypto_box_seal_open - Decrypt the ciphertext
    • sodium_crypto_box_secretkey - Description
    • sodium_crypto_box_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_generichash - Get a hash of the message
    • sodium_crypto_generichash_final - Complete the hash
    • sodium_crypto_generichash_init - Initialize a hash
    • sodium_crypto_generichash_keygen - Get random bytes for key
    • sodium_crypto_generichash_update - Add message to a hash
    • sodium_crypto_kdf_derive_from_key - Derive a subkey
    • sodium_crypto_kdf_keygen - Get random bytes for key
    • sodium_crypto_kx_client_session_keys - Description
    • sodium_crypto_kx_keypair - Creates a new sodium keypair
    • sodium_crypto_kx_publickey - Description
    • sodium_crypto_kx_secretkey - Description
    • sodium_crypto_kx_seed_keypair - Description
    • sodium_crypto_kx_server_session_keys - Description
    • sodium_crypto_pwhash - Derive a key from a password
    • sodium_crypto_pwhash_scryptsalsa208sha256 - Derives a key from a password
    • sodium_crypto_pwhash_scryptsalsa208sha256_str - Get an ASCII encoded hash
    • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify - Verify that the password is a valid password verification string
    • sodium_crypto_pwhash_str - Get an ASCII-encoded hash
    • sodium_crypto_pwhash_str_needs_rehash - Description
    • sodium_crypto_pwhash_str_verify - Verifies that a password matches a hash
    • sodium_crypto_scalarmult - Compute a shared secret given a user's secret key and another user's public key
    • sodium_crypto_scalarmult_base - 别名 sodium_crypto_box_publickey_from_secretkey
    • sodium_crypto_secretbox - Encrypt a message
    • sodium_crypto_secretbox_keygen - Get random bytes for key
    • sodium_crypto_secretbox_open - Verify and decrypt a ciphertext
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull - Description
    • sodium_crypto_secretstream_xchacha20poly1305_init_push - Description
    • sodium_crypto_secretstream_xchacha20poly1305_keygen - Description
    • sodium_crypto_secretstream_xchacha20poly1305_pull - Description
    • sodium_crypto_secretstream_xchacha20poly1305_push - Description
    • sodium_crypto_secretstream_xchacha20poly1305_rekey - Description
    • sodium_crypto_shorthash - Compute a fixed-size fingerprint for the message
    • sodium_crypto_shorthash_keygen - Get random bytes for key
    • sodium_crypto_sign - Sign a message
    • sodium_crypto_sign_detached - Sign the message
    • sodium_crypto_sign_ed25519_pk_to_curve25519 - Convert an Ed25519 public key to a Curve25519 public key
    • sodium_crypto_sign_ed25519_sk_to_curve25519 - Convert an Ed25519 secret key to a Curve25519 secret key
    • sodium_crypto_sign_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_sign_keypair_from_secretkey_and_publickey - Description
    • sodium_crypto_sign_open - Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey - Description
    • sodium_crypto_sign_publickey_from_secretkey - Extract the public key from the secret key
    • sodium_crypto_sign_secretkey - Description
    • sodium_crypto_sign_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_sign_verify_detached - Verify signature for the message
    • sodium_crypto_stream - Generate a deterministic sequence of bytes from a seed
    • sodium_crypto_stream_keygen - Get random bytes for key
    • sodium_crypto_stream_xor - Encrypt a message
    • sodium_hex2bin - Decodes a hexadecimally encoded binary string
    • sodium_increment - Increment large number
    • sodium_memcmp - Test for equality in constant-time
    • sodium_memzero - Overwrite buf with zeros
    • sodium_pad - Add padding data
    • sodium_unpad - Remove padding data
    • SolrClient::addDocument - Adds a document to the index
    • SolrClient::addDocuments - Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit - Finalizes all add/deletes made to the index
    • SolrClient::deleteById - Delete by Id
    • SolrClient::deleteByIds - Deletes by Ids
    • SolrClient::deleteByQueries - Removes all documents matching any of the queries
    • SolrClient::deleteByQuery - Deletes all documents matching the given query
    • SolrClient::getById - Get Document By Id. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getByIds - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getDebug - Returns the debug data for the last connection attempt
    • SolrClient::getOptions - Returns the client options set internally
    • SolrClient::optimize - Defragments the index
    • SolrClient::ping - Checks if Solr server is still up
    • SolrClient::query - Sends a query to the server
    • SolrClient::request - Sends a raw update request
    • SolrClient::rollback - Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter - Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet - Changes the specified servlet type to a new value
    • SolrClient::system - Retrieve Solr Server information
    • SolrClient::threads - Checks the threads status
    • SolrClient::__construct - Constructor for the SolrClient object
    • SolrClient::__destruct - Destructor for SolrClient
    • SolrClientException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrCollapseFunction::getField - Returns the field that is being collapsed on
    • SolrCollapseFunction::getHint - Returns collapse hint
    • SolrCollapseFunction::getMax - Returns max parameter
    • SolrCollapseFunction::getMin - Returns min parameter
    • SolrCollapseFunction::getNullPolicy - Returns null policy
    • SolrCollapseFunction::getSize - Returns size parameter
    • SolrCollapseFunction::setField - Sets the field to collapse on
    • SolrCollapseFunction::setHint - Sets collapse hint
    • SolrCollapseFunction::setMax - Selects the group heads by the max value of a numeric field or function query
    • SolrCollapseFunction::setMin - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy - Sets the NULL Policy
    • SolrCollapseFunction::setSize - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::__construct - Constructor
    • SolrCollapseFunction::__toString - Returns a string representing the constructed collapse function
    • SolrDisMaxQuery::addBigramPhraseField - Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery - Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField - Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField - Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField - Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField - Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::removeBigramPhraseField - Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery - Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField - Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField - Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField - Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField - Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop - Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction - Sets a Boost Function (bf parameter)
    • SolrDisMaxQuery::setBoostQuery - Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch - Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields - Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop - Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt - Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop - Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker - Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields - Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop - Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields - Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser - Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser - Switch QueryParser to be EDisMax
    • SolrDisMaxQuery::__construct - Class Constructor
    • SolrDocument::addField - Adds a field to the document
    • SolrDocument::clear - Drops all the fields in the document
    • SolrDocument::current - Retrieves the current field
    • SolrDocument::deleteField - Removes a field from the document
    • SolrDocument::fieldExists - Checks if a field exists in the document
    • SolrDocument::getChildDocuments - Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrDocument::getField - Retrieves a field by name
    • SolrDocument::getFieldCount - Returns the number of fields in this document
    • SolrDocument::getFieldNames - Returns an array of fields names in the document
    • SolrDocument::getInputDocument - Returns a SolrInputDocument equivalent of the object
    • SolrDocument::hasChildDocuments - Checks whether the document has any child documents
    • SolrDocument::key - Retrieves the current key
    • SolrDocument::merge - Merges source to the current SolrDocument
    • SolrDocument::next - Moves the internal pointer to the next field
    • SolrDocument::offsetExists - Checks if a particular field exists
    • SolrDocument::offsetGet - Retrieves a field
    • SolrDocument::offsetSet - Adds a field to the document
    • SolrDocument::offsetUnset - Removes a field
    • SolrDocument::reset - This is an alias to SolrDocument::clear()
    • SolrDocument::rewind - Resets the internal pointer to the beginning
    • SolrDocument::serialize - Used for custom serialization
    • SolrDocument::sort - Sorts the fields in the document
    • SolrDocument::toArray - Returns an array representation of the document
    • SolrDocument::unserialize - Custom serialization of SolrDocument objects
    • SolrDocument::valid - Checks if the current position internally is still valid
    • SolrDocument::__clone - Creates a copy of a SolrDocument object
    • SolrDocument::__construct - Constructor
    • SolrDocument::__destruct - Destructor
    • SolrDocument::__get - Access the field as a property
    • SolrDocument::__isset - Checks if a field exists
    • SolrDocument::__set - Adds another field to the document
    • SolrDocument::__unset - Removes a field from the document
    • SolrDocumentField::__construct - Constructor
    • SolrDocumentField::__destruct - Destructor
    • SolrException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrGenericResponse::__construct - Constructor
    • SolrGenericResponse::__destruct - Destructor
    • SolrIllegalArgumentException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrIllegalOperationException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrInputDocument::addChildDocument - Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments - Adds an array of child documents
    • SolrInputDocument::addField - Adds a field to the document
    • SolrInputDocument::clear - Resets the input document
    • SolrInputDocument::deleteField - Removes a field from the document
    • SolrInputDocument::fieldExists - Checks if a field exists
    • SolrInputDocument::getBoost - Retrieves the current boost value for the document
    • SolrInputDocument::getChildDocuments - Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrInputDocument::getField - Retrieves a field by name
    • SolrInputDocument::getFieldBoost - Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount - Returns the number of fields in the document
    • SolrInputDocument::getFieldNames - Returns an array containing all the fields in the document
    • SolrInputDocument::hasChildDocuments - Returns true if the document has any child documents
    • SolrInputDocument::merge - Merges one input document into another
    • SolrInputDocument::reset - This is an alias of SolrInputDocument::clear
    • SolrInputDocument::setBoost - Sets the boost value for this document
    • SolrInputDocument::setFieldBoost - Sets the index-time boost value for a field
    • SolrInputDocument::sort - Sorts the fields within the document
    • SolrInputDocument::toArray - Returns an array representation of the input document
    • SolrInputDocument::__clone - Creates a copy of a SolrDocument
    • SolrInputDocument::__construct - Constructor
    • SolrInputDocument::__destruct - Destructor
    • SolrModifiableParams::__construct - Constructor
    • SolrModifiableParams::__destruct - Destructor
    • SolrObject::getPropertyNames - Returns an array of all the names of the properties
    • SolrObject::offsetExists - Checks if the property exists
    • SolrObject::offsetGet - Used to retrieve a property
    • SolrObject::offsetSet - Sets the value for a property
    • SolrObject::offsetUnset - Unsets the value for the property
    • SolrObject::__construct - Creates Solr object
    • SolrObject::__destruct - Destructor
    • SolrParams::add - This is an alias for SolrParams::addParam
    • SolrParams::addParam - Adds a parameter to the object
    • SolrParams::get - This is an alias for SolrParams::getParam
    • SolrParams::getParam - Returns a parameter value
    • SolrParams::getParams - Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams - Returns an array of URL-encoded parameters
    • SolrParams::serialize - Used for custom serialization
    • SolrParams::set - An alias of SolrParams::setParam
    • SolrParams::setParam - Sets the parameter to the specified value
    • SolrParams::toString - Returns all the name-value pair parameters in the object
    • SolrParams::unserialize - Used for custom serialization
    • SolrPingResponse::getResponse - Returns the response from the server
    • SolrPingResponse::__construct - Constructor
    • SolrPingResponse::__destruct - Destructor
    • SolrQuery::addExpandFilterQuery - Overrides main filter query, determines which documents to include in the main group
    • SolrQuery::addExpandSortField - Orders the documents within the expanded groups (expand.sort parameter)
    • SolrQuery::addFacetDateField - Maps to facet.date
    • SolrQuery::addFacetDateOther - Adds another facet.date.other parameter
    • SolrQuery::addFacetField - Adds another field to the facet
    • SolrQuery::addFacetQuery - Adds a facet query
    • SolrQuery::addField - Specifies which fields to return in the result
    • SolrQuery::addFilterQuery - Specifies a filter query
    • SolrQuery::addGroupField - Add a field to be used to group results
    • SolrQuery::addGroupFunction - Allows grouping results based on the unique values of a function query (group.func parameter)
    • SolrQuery::addGroupQuery - Allows grouping of documents that match the given query
    • SolrQuery::addGroupSortField - Add a group sort field (group.sort parameter)
    • SolrQuery::addHighlightField - Maps to hl.fl
    • SolrQuery::addMltField - Sets a field to use for similarity
    • SolrQuery::addMltQueryField - Maps to mlt.qf
    • SolrQuery::addSortField - Used to control how the results should be sorted
    • SolrQuery::addStatsFacet - Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField - Maps to stats.field parameter
    • SolrQuery::collapse - Collapses the result set to a single document per group
    • SolrQuery::getExpand - Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries - Returns the expand filter queries
    • SolrQuery::getExpandQuery - Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows - Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields - Returns an array of fields
    • SolrQuery::getFacet - Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd - Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields - Returns all the facet.date fields
    • SolrQuery::getFacetDateGap - Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd - Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther - Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart - Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields - Returns all the facet fields
    • SolrQuery::getFacetLimit - Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod - Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount - Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing - Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset - Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix - Returns the facet prefix
    • SolrQuery::getFacetQueries - Returns all the facet queries
    • SolrQuery::getFacetSort - Returns the facet sort type
    • SolrQuery::getFields - Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries - Returns an array of filter queries
    • SolrQuery::getGroup - Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent - Returns group cache percent value
    • SolrQuery::getGroupFacet - Returns the group.facet parameter value
    • SolrQuery::getGroupFields - Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat - Returns the group.format value
    • SolrQuery::getGroupFunctions - Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit - Returns the group.limit value
    • SolrQuery::getGroupMain - Returns the group.main value
    • SolrQuery::getGroupNGroups - Returns the group.ngroups value
    • SolrQuery::getGroupOffset - Returns the group.offset value
    • SolrQuery::getGroupQueries - Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields - Returns the group.sort value
    • SolrQuery::getGroupTruncate - Returns the group.truncate value
    • SolrQuery::getHighlight - Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField - Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields - Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter - Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter - Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize - Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm - Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength - Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars - Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous - Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern - Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop - Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch - Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost - Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre - Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets - Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter - Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt - Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost - Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount - Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields - Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms - Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens - Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength - Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency - Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency - Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength - Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields - Returns the query fields and their boosts
    • SolrQuery::getQuery - Returns the main query
    • SolrQuery::getRows - Returns the maximum number of documents
    • SolrQuery::getSortFields - Returns all the sort fields
    • SolrQuery::getStart - Returns the offset in the complete result set
    • SolrQuery::getStats - Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets - Returns all the stats facets that were set
    • SolrQuery::getStatsFields - Returns all the statistics fields
    • SolrQuery::getTerms - Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField - Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound - Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound - Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit - Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound - Returns the term to start at
    • SolrQuery::getTermsMaxCount - Returns the maximum document frequency
    • SolrQuery::getTermsMinCount - Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix - Returns the term prefix
    • SolrQuery::getTermsReturnRaw - Whether or not to return raw characters
    • SolrQuery::getTermsSort - Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound - Returns the term to stop at
    • SolrQuery::getTimeAllowed - Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeExpandFilterQuery - Removes an expand filter query
    • SolrQuery::removeExpandSortField - Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField - Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther - Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField - Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery - Removes one of the facet.query parameters
    • SolrQuery::removeField - Removes a field from the list of fields
    • SolrQuery::removeFilterQuery - Removes a filter query
    • SolrQuery::removeHighlightField - Removes one of the fields used for highlighting
    • SolrQuery::removeMltField - Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField - Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField - Removes one of the sort fields
    • SolrQuery::removeStatsFacet - Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField - Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler - Toggles the echoHandler parameter
    • SolrQuery::setEchoParams - Determines what kind of parameters to include in the response
    • SolrQuery::setExpand - Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery - Sets the expand.q parameter
    • SolrQuery::setExpandRows - Sets the number of rows to display in each group (expand.rows). Server Default 5
    • SolrQuery::setExplainOther - Sets the explainOther common query parameter
    • SolrQuery::setFacet - Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd - Maps to facet.date.end
    • SolrQuery::setFacetDateGap - Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart - Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit - Maps to facet.limit
    • SolrQuery::setFacetMethod - Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount - Maps to facet.mincount
    • SolrQuery::setFacetMissing - Maps to facet.missing
    • SolrQuery::setFacetOffset - Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix - Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort - Determines the ordering of the facet field constraints
    • SolrQuery::setGroup - Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent - Enables caching for result grouping
    • SolrQuery::setGroupFacet - Sets group.facet parameter
    • SolrQuery::setGroupFormat - Sets the group format, result structure (group.format parameter)
    • SolrQuery::setGroupLimit - Specifies the number of results to return for each group. The server default value is 1
    • SolrQuery::setGroupMain - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
    • SolrQuery::setGroupNGroups - If true, Solr includes the number of groups that have matched the query in the results
    • SolrQuery::setGroupOffset - Sets the group.offset parameter
    • SolrQuery::setGroupTruncate - If true, facet counts are based on the most relevant document of each group matching the query
    • SolrQuery::setHighlight - Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField - Specifies the backup field to use
    • SolrQuery::setHighlightFormatter - Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter - Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize - The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm - Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength - Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars - Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous - Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern - Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop - Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch - Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost - Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre - Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets - Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter - Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt - Enables or disables moreLikeThis
    • SolrQuery::setMltBoost - Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount - Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms - Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens - Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength - Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency - Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency - Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength - Sets the minimum word length
    • SolrQuery::setOmitHeader - Exclude the header from the returned results
    • SolrQuery::setQuery - Sets the search query
    • SolrQuery::setRows - Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo - Flag to show debug information
    • SolrQuery::setStart - Specifies the number of rows to skip
    • SolrQuery::setStats - Enables or disables the Stats component
    • SolrQuery::setTerms - Enables or disables the TermsComponent
    • SolrQuery::setTermsField - Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound - Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound - Include the upper bound term in the result set
    • SolrQuery::setTermsLimit - Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound - Specifies the Term to start from
    • SolrQuery::setTermsMaxCount - Sets the maximum document frequency
    • SolrQuery::setTermsMinCount - Sets the minimum document frequency
    • SolrQuery::setTermsPrefix - Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw - Return the raw characters of the indexed term
    • SolrQuery::setTermsSort - Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound - Sets the term to stop at
    • SolrQuery::setTimeAllowed - The time allowed for search to finish
    • SolrQuery::__construct - Constructor
    • SolrQuery::__destruct - Destructor
    • SolrQueryResponse::__construct - Constructor
    • SolrQueryResponse::__destruct - Destructor
    • SolrResponse::getDigestedResponse - Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus - Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage - Returns more details on the HTTP status
    • SolrResponse::getRawRequest - Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders - Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse - Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders - Returns the raw response headers from the server
    • SolrResponse::getRequestUrl - Returns the full URL the request was sent to
    • SolrResponse::getResponse - Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode - Sets the parse mode
    • SolrResponse::success - Was the request a success
    • SolrServerException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrUpdateResponse::__construct - Constructor
    • SolrUpdateResponse::__destruct - Destructor
    • SolrUtils::digestXmlResponse - Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars - Escapes a lucene query string
    • SolrUtils::getSolrVersion - Returns the current version of the Solr extension
    • SolrUtils::queryPhrase - Prepares a phrase from an unescaped lucene string
    • solr_get_version - 返回当前Solr扩展的版本
    • sort - 对数组排序
    • soundex - Calculate the soundex key of a string
    • SphinxClient::addQuery - Add query to multi-query batch
    • SphinxClient::buildExcerpts - Build text snippets
    • SphinxClient::buildKeywords - Extract keywords from query
    • SphinxClient::close - 关闭先前打开的持久连接
    • SphinxClient::escapeString - Escape special characters
    • SphinxClient::getLastError - Get the last error message
    • SphinxClient::getLastWarning - Get the last warning
    • SphinxClient::open - 建立到搜索服务端的持久连接
    • SphinxClient::query - 执行搜索查询
    • SphinxClient::resetFilters - Clear all filters
    • SphinxClient::resetGroupBy - Clear all group-by settings
    • SphinxClient::runQueries - Run a batch of search queries
    • SphinxClient::setArrayResult - 控制搜索结果集的返回格式
    • SphinxClient::setConnectTimeout - Set connection timeout
    • SphinxClient::setFieldWeights - Set field weights
    • SphinxClient::setFilter - 增加整数值过滤器
    • SphinxClient::setFilterFloatRange - Add new float range filter
    • SphinxClient::setFilterRange - Add new integer range filter
    • SphinxClient::setGeoAnchor - Set anchor point for a geosphere distance calculations
    • SphinxClient::setGroupBy - Set grouping attribute
    • SphinxClient::setGroupDistinct - Set attribute name for per-group distinct values count calculations
    • SphinxClient::setIDRange - Set a range of accepted document IDs
    • SphinxClient::setIndexWeights - Set per-index weights
    • SphinxClient::setLimits - 设置返回结果集偏移量和数目
    • SphinxClient::setMatchMode - 设置全文查询的匹配模式
    • SphinxClient::setMaxQueryTime - Set maximum query time
    • SphinxClient::setOverride - Sets temporary per-document attribute value overrides
    • SphinxClient::setRankingMode - Set ranking mode
    • SphinxClient::setRetries - Set retry count and delay
    • SphinxClient::setSelect - Set select clause
    • SphinxClient::setServer - 设置searchd的主机名和TCP端口
    • SphinxClient::setSortMode - Set matches sorting mode
    • SphinxClient::status - Queries searchd status
    • SphinxClient::updateAttributes - Update document attributes
    • SphinxClient::__construct - Create a new SphinxClient object
    • SplDoublyLinkedList::add - Add/insert a new value at the specified index
    • SplDoublyLinkedList::bottom - Peeks at the node from the beginning of the doubly linked list
    • SplDoublyLinkedList::count - Counts the number of elements in the doubly linked list
    • SplDoublyLinkedList::current - Return current array entry
    • SplDoublyLinkedList::getIteratorMode - Returns the mode of iteration
    • SplDoublyLinkedList::isEmpty - Checks whether the doubly linked list is empty
    • SplDoublyLinkedList::key - Return current node index
    • SplDoublyLinkedList::next - Move to next entry
    • SplDoublyLinkedList::offsetExists - Returns whether the requested $index exists
    • SplDoublyLinkedList::offsetGet - Returns the value at the specified $index
    • SplDoublyLinkedList::offsetSet - Sets the value at the specified $index to $newval
    • SplDoublyLinkedList::offsetUnset - Unsets the value at the specified $index
    • SplDoublyLinkedList::pop - Pops a node from the end of the doubly linked list
    • SplDoublyLinkedList::prev - Move to previous entry
    • SplDoublyLinkedList::push - Pushes an element at the end of the doubly linked list
    • SplDoublyLinkedList::rewind - Rewind iterator back to the start
    • SplDoublyLinkedList::serialize - Serializes the storage
    • SplDoublyLinkedList::setIteratorMode - Sets the mode of iteration
    • SplDoublyLinkedList::shift - Shifts a node from the beginning of the doubly linked list
    • SplDoublyLinkedList::top - Peeks at the node from the end of the doubly linked list
    • SplDoublyLinkedList::unserialize - Unserializes the storage
    • SplDoublyLinkedList::unshift - Prepends the doubly linked list with an element
    • SplDoublyLinkedList::valid - Check whether the doubly linked list contains more nodes
    • SplDoublyLinkedList::__construct - Constructs a new doubly linked list
    • SplFileInfo::getATime - Gets last access time of the file
    • SplFileInfo::getBasename - Gets the base name of the file
    • SplFileInfo::getCTime - 获取文件 inode 修改时间
    • SplFileInfo::getExtension - Gets the file extension
    • SplFileInfo::getFileInfo - Gets an SplFileInfo object for the file
    • SplFileInfo::getFilename - Gets the filename
    • SplFileInfo::getGroup - Gets the file group
    • SplFileInfo::getInode - Gets the inode for the file
    • SplFileInfo::getLinkTarget - Gets the target of a link
    • SplFileInfo::getMTime - Gets the last modified time
    • SplFileInfo::getOwner - Gets the owner of the file
    • SplFileInfo::getPath - Gets the path without filename
    • SplFileInfo::getPathInfo - Gets an SplFileInfo object for the path
    • SplFileInfo::getPathname - Gets the path to the file
    • SplFileInfo::getPerms - Gets file permissions
    • SplFileInfo::getRealPath - Gets absolute path to file
    • SplFileInfo::getSize - Gets file size
    • SplFileInfo::getType - Gets file type
    • SplFileInfo::isDir - Tells if the file is a directory
    • SplFileInfo::isExecutable - Tells if the file is executable
    • SplFileInfo::isFile - Tells if the object references a regular file
    • SplFileInfo::isLink - Tells if the file is a link
    • SplFileInfo::isReadable - Tells if file is readable
    • SplFileInfo::isWritable - Tells if the entry is writable
    • SplFileInfo::openFile - Gets an SplFileObject object for the file
    • SplFileInfo::setFileClass - Sets the class used with SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
    • SplFileInfo::__construct - 构建一个新的 SplFileInfo 对象
    • SplFileInfo::__toString - Returns the path to the file as a string
    • SplFileObject::current - Retrieve current line of file
    • SplFileObject::eof - Reached end of file
    • SplFileObject::fflush - Flushes the output to the file
    • SplFileObject::fgetc - Gets character from file
    • SplFileObject::fgetcsv - Gets line from file and parse as CSV fields
    • SplFileObject::fgets - Gets line from file
    • SplFileObject::fgetss - Gets line from file and strip HTML tags
    • SplFileObject::flock - Portable file locking
    • SplFileObject::fpassthru - Output all remaining data on a file pointer
    • SplFileObject::fputcsv - Write a field array as a CSV line
    • SplFileObject::fread - Read from file
    • SplFileObject::fscanf - Parses input from file according to a format
    • SplFileObject::fseek - Seek to a position
    • SplFileObject::fstat - Gets information about the file
    • SplFileObject::ftell - Return current file position
    • SplFileObject::ftruncate - Truncates the file to a given length
    • SplFileObject::fwrite - Write to file
    • SplFileObject::getChildren - No purpose
    • SplFileObject::getCsvControl - Get the delimiter, enclosure and escape character for CSV
    • SplFileObject::getCurrentLine - Alias of SplFileObject::fgets
    • SplFileObject::getFlags - Gets flags for the SplFileObject
    • SplFileObject::getMaxLineLen - Get maximum line length
    • SplFileObject::hasChildren - SplFileObject does not have children
    • SplFileObject::key - Get line number
    • SplFileObject::next - Read next line
    • SplFileObject::rewind - Rewind the file to the first line
    • SplFileObject::seek - Seek to specified line
    • SplFileObject::setCsvControl - Set the delimiter, enclosure and escape character for CSV
    • SplFileObject::setFlags - Sets flags for the SplFileObject
    • SplFileObject::setMaxLineLen - Set maximum line length
    • SplFileObject::valid - Not at EOF
    • SplFileObject::__construct - Construct a new file object
    • SplFileObject::__toString - Alias of SplFileObject::fgets
    • SplFixedArray::count - Returns the size of the array
    • SplFixedArray::current - Return current array entry
    • SplFixedArray::fromArray - Import a PHP array in a SplFixedArray instance
    • SplFixedArray::getSize - Gets the size of the array
    • SplFixedArray::key - Return current array index
    • SplFixedArray::next - Move to next entry
    • SplFixedArray::offsetExists - Returns whether the requested index exists
    • SplFixedArray::offsetGet - Returns the value at the specified index
    • SplFixedArray::offsetSet - Sets a new value at a specified index
    • SplFixedArray::offsetUnset - Unsets the value at the specified $index
    • SplFixedArray::rewind - Rewind iterator back to the start
    • SplFixedArray::setSize - Change the size of an array
    • SplFixedArray::toArray - Returns a PHP array from the fixed array
    • SplFixedArray::valid - Check whether the array contains more elements
    • SplFixedArray::__construct - Constructs a new fixed array
    • SplFixedArray::__wakeup - Reinitialises the array after being unserialised
    • SplHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplHeap::count - Counts the number of elements in the heap
    • SplHeap::current - Return current node pointed by the iterator
    • SplHeap::extract - Extracts a node from top of the heap and sift up
    • SplHeap::insert - Inserts an element in the heap by sifting it up
    • SplHeap::isCorrupted - Tells if the heap is in a corrupted state
    • SplHeap::isEmpty - Checks whether the heap is empty
    • SplHeap::key - Return current node index
    • SplHeap::next - Move to the next node
    • SplHeap::recoverFromCorruption - Recover from the corrupted state and allow further actions on the heap
    • SplHeap::rewind - Rewind iterator back to the start (no-op)
    • SplHeap::top - Peeks at the node from the top of the heap
    • SplHeap::valid - Check whether the heap contains more nodes
    • SplHeap::__construct - Constructs a new empty heap
    • split - 用正则表达式将字符串分割到数组中
    • spliti - 用正则表达式不区分大小写将字符串分割到数组中
    • SplMaxHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplMinHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplObjectStorage::addAll - Adds all objects from another storage
    • SplObjectStorage::attach - Adds an object in the storage
    • SplObjectStorage::contains - Checks if the storage contains a specific object
    • SplObjectStorage::count - Returns the number of objects in the storage
    • SplObjectStorage::current - Returns the current storage entry
    • SplObjectStorage::detach - Removes an object from the storage
    • SplObjectStorage::getHash - Calculate a unique identifier for the contained objects
    • SplObjectStorage::getInfo - Returns the data associated with the current iterator entry
    • SplObjectStorage::key - Returns the index at which the iterator currently is
    • SplObjectStorage::next - Move to the next entry
    • SplObjectStorage::offsetExists - Checks whether an object exists in the storage
    • SplObjectStorage::offsetGet - Returns the data associated with an object
    • SplObjectStorage::offsetSet - Associates data to an object in the storage
    • SplObjectStorage::offsetUnset - Removes an object from the storage
    • SplObjectStorage::removeAll - Removes objects contained in another storage from the current storage
    • SplObjectStorage::removeAllExcept - Removes all objects except for those contained in another storage from the current storage
    • SplObjectStorage::rewind - Rewind the iterator to the first storage element
    • SplObjectStorage::serialize - Serializes the storage
    • SplObjectStorage::setInfo - Sets the data associated with the current iterator entry
    • SplObjectStorage::unserialize - Unserializes a storage from its string representation
    • SplObjectStorage::valid - Returns if the current iterator entry is valid
    • SplObserver::update - Receive update from subject
    • SplPriorityQueue::compare - Compare priorities in order to place elements correctly in the heap while sifting up
    • SplPriorityQueue::count - Counts the number of elements in the queue
    • SplPriorityQueue::current - Return current node pointed by the iterator
    • SplPriorityQueue::extract - Extracts a node from top of the heap and sift up
    • SplPriorityQueue::getExtractFlags - Get the flags of extraction
    • SplPriorityQueue::insert - Inserts an element in the queue by sifting it up
    • SplPriorityQueue::isCorrupted - Tells if the priority queue is in a corrupted state
    • SplPriorityQueue::isEmpty - Checks whether the queue is empty
    • SplPriorityQueue::key - Return current node index
    • SplPriorityQueue::next - Move to the next node
    • SplPriorityQueue::recoverFromCorruption - Recover from the corrupted state and allow further actions on the queue
    • SplPriorityQueue::rewind - Rewind iterator back to the start (no-op)
    • SplPriorityQueue::setExtractFlags - Sets the mode of extraction
    • SplPriorityQueue::top - Peeks at the node from the top of the queue
    • SplPriorityQueue::valid - Check whether the queue contains more nodes
    • SplPriorityQueue::__construct - Constructs a new empty queue
    • SplQueue::dequeue - Dequeues a node from the queue
    • SplQueue::enqueue - Adds an element to the queue
    • SplQueue::setIteratorMode - Sets the mode of iteration
    • SplQueue::__construct - Constructs a new queue implemented using a doubly linked list
    • SplStack::setIteratorMode - Sets the mode of iteration
    • SplStack::__construct - Constructs a new stack implemented using a doubly linked list
    • SplSubject::attach - Attach an SplObserver
    • SplSubject::detach - Detach an observer
    • SplSubject::notify - Notify an observer
    • SplTempFileObject::__construct - Construct a new temporary file object
    • spl_autoload - __autoload()函数的默认实现
    • spl_autoload_call - 尝试调用所有已注册的 __autoload() 函数来装载请求类
    • spl_autoload_extensions - 注册并返回 spl_autoload 函数使用的默认文件扩展名
    • spl_autoload_functions - 返回所有已注册的 __autoload() 函数
    • spl_autoload_register - 注册给定的函数作为 __autoload 的实现
    • spl_autoload_unregister - 注销已注册的 __autoload() 函数
    • spl_classes - 返回所有可用的SPL类
    • spl_object_hash - 返回指定对象的hash id
    • spl_object_id - Return the integer object handle for given object
    • Spoofchecker::areConfusable - Checks if given strings can be confused
    • Spoofchecker::isSuspicious - Checks if a given text contains any suspicious characters
    • Spoofchecker::setAllowedLocales - Locales to use when running checks
    • Spoofchecker::setChecks - Set the checks to run
    • Spoofchecker::__construct - Constructor
    • sprintf - Return a formatted string
    • SQLite3::backup - Backup one database to another database
    • SQLite3::busyTimeout - Sets the busy connection handler
    • SQLite3::changes - Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close - Closes the database connection
    • SQLite3::createAggregate - Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createCollation - Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction - Registers a PHP function for use as an SQL scalar function
    • SQLite3::enableExceptions - Enable throwing exceptions
    • SQLite3::escapeString - Returns a string that has been properly escaped
    • SQLite3::exec - Executes a result-less query against a given database
    • SQLite3::lastErrorCode - Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg - Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID - Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension - Attempts to load an SQLite extension library
    • SQLite3::open - Opens an SQLite database
    • SQLite3::openBlob - Opens a stream resource to read a BLOB
    • SQLite3::prepare - Prepares an SQL statement for execution
    • SQLite3::query - Executes an SQL query
    • SQLite3::querySingle - Executes a query and returns a single result
    • SQLite3::setAuthorizer - Configures a callback to be used as an authorizer to limit what a statement can do
    • SQLite3::version - Returns the SQLite3 library version as a string constant and as a number
    • SQLite3::__construct - Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3Result::columnName - Returns the name of the nth column
    • SQLite3Result::columnType - Returns the type of the nth column
    • SQLite3Result::fetchArray - Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize - Closes the result set
    • SQLite3Result::numColumns - Returns the number of columns in the result set
    • SQLite3Result::reset - Resets the result set back to the first row
    • SQLite3Stmt::bindParam - Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue - Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear - Clears all current bound parameters
    • SQLite3Stmt::close - Closes the prepared statement
    • SQLite3Stmt::execute - Executes a prepared statement and returns a result set object
    • SQLite3Stmt::getSQL - Get the SQL of the statement
    • SQLite3Stmt::paramCount - Returns the number of parameters within the prepared statement
    • SQLite3Stmt::readOnly - Returns whether a statement is definitely read only
    • SQLite3Stmt::reset - Resets the prepared statement
    • sqlsrv_begin_transaction - Begins a database transaction
    • sqlsrv_cancel - Cancels a statement
    • sqlsrv_client_info - Returns information about the client and specified connection
    • sqlsrv_close - Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit - Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure - Changes the driver error handling and logging configurations
    • sqlsrv_connect - Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors - Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute - Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch - Makes the next row in a result set available for reading
    • sqlsrv_fetch_array - Returns a row as an array
    • sqlsrv_fetch_object - Retrieves the next row of data in a result set as an object
    • sqlsrv_field_metadata - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt - Frees all resources for the specified statement
    • sqlsrv_get_config - Returns the value of the specified configuration setting
    • sqlsrv_get_field - Gets field data from the currently selected row
    • sqlsrv_has_rows - Indicates whether the specified statement has rows
    • sqlsrv_next_result - Makes the next result of the specified statement active
    • sqlsrv_num_fields - Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows - Retrieves the number of rows in a result set
    • sqlsrv_prepare - Prepares a query for execution
    • sqlsrv_query - Prepares and executes a query
    • sqlsrv_rollback - Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data - Sends data from parameter streams to the server
    • sqlsrv_server_info - Returns information about the server
    • SqlStatement::bind - Bind statement parameters
    • SqlStatement::execute - Execute the operation
    • SqlStatement::getNextResult - Get next result
    • SqlStatement::getResult - Get result
    • SqlStatement::hasMoreResults - Check for more results
    • SqlStatement::__construct - Description constructor
    • SqlStatementResult::fetchAll - Get all rows from result
    • SqlStatementResult::fetchOne - Get single row
    • SqlStatementResult::getAffectedItemsCount - Get affected row count
    • SqlStatementResult::getColumnNames - Get column names
    • SqlStatementResult::getColumns - Get columns
    • SqlStatementResult::getColumnsCount - Get column count
    • SqlStatementResult::getGeneratedIds - Get generated ids
    • SqlStatementResult::getLastInsertId - Get last insert id
    • SqlStatementResult::getWarnings - Get warnings from last operation
    • SqlStatementResult::getWarningsCount - Get warning count from last operation
    • SqlStatementResult::hasData - Check if result has data
    • SqlStatementResult::nextResult - Get next result
    • SqlStatementResult::__construct - Description constructor
    • sql_regcase - 产生用于不区分大小的匹配的正则表达式
    • sqrt - 平方根
    • srand - 播下随机数发生器种子
    • sscanf - 根据指定格式解析输入的字符
    • ssdeep_fuzzy_compare - Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash - Create a fuzzy hash from a string
    • ssdeep_fuzzy_hash_filename - Create a fuzzy hash from a file
    • ssh2:// - Secure Shell 2
    • ssh2_auth_agent - Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file - Authenticate using a public hostkey
    • ssh2_auth_none - Authenticate as "none"
    • ssh2_auth_password - Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file - Authenticate using a public key
    • ssh2_connect - Connect to an SSH server
    • ssh2_disconnect - Close a connection to a remote SSH server
    • ssh2_exec - Execute a command on a remote server
    • ssh2_fetch_stream - Fetch an extended data stream
    • ssh2_fingerprint - Retrieve fingerprint of remote server
    • ssh2_forward_accept - Accept a connection created by a listener
    • ssh2_forward_listen - Bind a port on the remote server and listen for connections
    • ssh2_methods_negotiated - Return list of negotiated methods
    • ssh2_poll - Poll the channels/listeners/streams for events
    • ssh2_publickey_add - Add an authorized publickey
    • ssh2_publickey_init - Initialize Publickey subsystem
    • ssh2_publickey_list - List currently authorized publickeys
    • ssh2_publickey_remove - Remove an authorized publickey
    • ssh2_scp_recv - Request a file via SCP
    • ssh2_scp_send - Send a file via SCP
    • ssh2_sftp - Initialize SFTP subsystem
    • ssh2_sftp_chmod - Changes file mode
    • ssh2_sftp_lstat - Stat a symbolic link
    • ssh2_sftp_mkdir - Create a directory
    • ssh2_sftp_readlink - Return the target of a symbolic link
    • ssh2_sftp_realpath - Resolve the realpath of a provided path string
    • ssh2_sftp_rename - Rename a remote file
    • ssh2_sftp_rmdir - Remove a directory
    • ssh2_sftp_stat - Stat a file on a remote filesystem
    • ssh2_sftp_symlink - Create a symlink
    • ssh2_sftp_unlink - Delete a file
    • ssh2_shell - Request an interactive shell
    • ssh2_tunnel - Open a tunnel through a remote server
    • SSL 上下文选项 - SSL 上下文选项清单
    • stat - 给出文件的信息
    • Statement::getNextResult - Get next result
    • Statement::getResult - Get result
    • Statement::hasMoreResults - Check if more results
    • Statement::__construct - Description constructor
    • stats_absolute_deviation - Returns the absolute deviation of an array of values
    • stats_cdf_beta - Calculates any one parameter of the beta distribution given values for the others
    • stats_cdf_binomial - Calculates any one parameter of the binomial distribution given values for the others
    • stats_cdf_cauchy - Calculates any one parameter of the Cauchy distribution given values for the others
    • stats_cdf_chisquare - Calculates any one parameter of the chi-square distribution given values for the others
    • stats_cdf_exponential - Calculates any one parameter of the exponential distribution given values for the others
    • stats_cdf_f - Calculates any one parameter of the F distribution given values for the others
    • stats_cdf_gamma - Calculates any one parameter of the gamma distribution given values for the others
    • stats_cdf_laplace - Calculates any one parameter of the Laplace distribution given values for the others
    • stats_cdf_logistic - Calculates any one parameter of the logistic distribution given values for the others
    • stats_cdf_negative_binomial - Calculates any one parameter of the negative binomial distribution given values for the others
    • stats_cdf_noncentral_chisquare - Calculates any one parameter of the non-central chi-square distribution given values for the others
    • stats_cdf_noncentral_f - Calculates any one parameter of the non-central F distribution given values for the others
    • stats_cdf_noncentral_t - Calculates any one parameter of the non-central t-distribution give values for the others
    • stats_cdf_normal - Calculates any one parameter of the normal distribution given values for the others
    • stats_cdf_poisson - Calculates any one parameter of the Poisson distribution given values for the others
    • stats_cdf_t - Calculates any one parameter of the t-distribution given values for the others
    • stats_cdf_uniform - Calculates any one parameter of the uniform distribution given values for the others
    • stats_cdf_weibull - Calculates any one parameter of the Weibull distribution given values for the others
    • stats_covariance - Computes the covariance of two data sets
    • stats_dens_beta - Probability density function of the beta distribution
    • stats_dens_cauchy - Probability density function of the Cauchy distribution
    • stats_dens_chisquare - Probability density function of the chi-square distribution
    • stats_dens_exponential - Probability density function of the exponential distribution
    • stats_dens_f - Probability density function of the F distribution
    • stats_dens_gamma - Probability density function of the gamma distribution
    • stats_dens_laplace - Probability density function of the Laplace distribution
    • stats_dens_logistic - Probability density function of the logistic distribution
    • stats_dens_normal - Probability density function of the normal distribution
    • stats_dens_pmf_binomial - Probability mass function of the binomial distribution
    • stats_dens_pmf_hypergeometric - Probability mass function of the hypergeometric distribution
    • stats_dens_pmf_negative_binomial - Probability mass function of the negative binomial distribution
    • stats_dens_pmf_poisson - Probability mass function of the Poisson distribution
    • stats_dens_t - Probability density function of the t-distribution
    • stats_dens_uniform - Probability density function of the uniform distribution
    • stats_dens_weibull - Probability density function of the Weibull distribution
    • stats_harmonic_mean - Returns the harmonic mean of an array of values
    • stats_kurtosis - Computes the kurtosis of the data in the array
    • stats_rand_gen_beta - Generates a random deviate from the beta distribution
    • stats_rand_gen_chisquare - Generates a random deviate from the chi-square distribution
    • stats_rand_gen_exponential - Generates a random deviate from the exponential distribution
    • stats_rand_gen_f - Generates a random deviate from the F distribution
    • stats_rand_gen_funiform - Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma - Generates a random deviate from the gamma distribution
    • stats_rand_gen_ibinomial - Generates a random deviate from the binomial distribution
    • stats_rand_gen_ibinomial_negative - Generates a random deviate from the negative binomial distribution
    • stats_rand_gen_int - Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson - Generates a single random deviate from a Poisson distribution
    • stats_rand_gen_iuniform - Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncentral_chisquare - Generates a random deviate from the non-central chi-square distribution
    • stats_rand_gen_noncentral_f - Generates a random deviate from the noncentral F distribution
    • stats_rand_gen_noncentral_t - Generates a single random deviate from a non-central t-distribution
    • stats_rand_gen_normal - Generates a single random deviate from a normal distribution
    • stats_rand_gen_t - Generates a single random deviate from a t-distribution
    • stats_rand_get_seeds - Get the seed values of the random number generator
    • stats_rand_phrase_to_seeds - Generate two seeds for the RGN random number generator
    • stats_rand_ranf - Generates a random floating point number between 0 and 1
    • stats_rand_setall - Set seed values to the random generator
    • stats_skew - Computes the skewness of the data in the array
    • stats_standard_deviation - Returns the standard deviation
    • stats_stat_binomial_coef - Returns a binomial coefficient
    • stats_stat_correlation - Returns the Pearson correlation coefficient of two data sets
    • stats_stat_factorial - Returns the factorial of an integer
    • stats_stat_independent_t - Returns the t-value from the independent two-sample t-test
    • stats_stat_innerproduct - Returns the inner product of two vectors
    • stats_stat_paired_t - Returns the t-value of the dependent t-test for paired samples
    • stats_stat_percentile - Returns the percentile value
    • stats_stat_powersum - Returns the power sum of a vector
    • stats_variance - Returns the variance
    • Stomp::abort - Rolls back a transaction in progress
    • Stomp::ack - Acknowledges consumption of a message
    • Stomp::begin - Starts a transaction
    • Stomp::commit - Commits a transaction in progress
    • Stomp::error - Gets the last stomp error
    • Stomp::getReadTimeout - Gets read timeout
    • Stomp::getSessionId - Gets the current stomp session ID
    • Stomp::hasFrame - Indicates whether or not there is a frame ready to read
    • Stomp::readFrame - Reads the next frame
    • Stomp::send - Sends a message
    • Stomp::setReadTimeout - Sets read timeout
    • Stomp::subscribe - Registers to listen to a given destination
    • Stomp::unsubscribe - Removes an existing subscription
    • Stomp::__construct - 打开一个连接
    • Stomp::__destruct - Closes stomp connection
    • StompException::getDetails - Get exception details
    • StompFrame::__construct - Constructor
    • stomp_connect_error - Returns a string description of the last connect error
    • stomp_version - Gets the current stomp extension version
    • strcasecmp - 二进制安全比较字符串（不区分大小写）
    • strchr - 别名 strstr
    • strcmp - 二进制安全字符串比较
    • strcoll - 基于区域设置的字符串比较
    • strcspn - 获取不匹配遮罩的起始子字符串的长度
    • streamWrapper::dir_closedir - Close directory handle
    • streamWrapper::dir_opendir - Open directory handle
    • streamWrapper::dir_readdir - Read entry from directory handle
    • streamWrapper::dir_rewinddir - Rewind directory handle
    • streamWrapper::mkdir - Create a directory
    • streamWrapper::rename - Renames a file or directory
    • streamWrapper::rmdir - Removes a directory
    • streamWrapper::stream_cast - Retrieve the underlaying resource
    • streamWrapper::stream_close - Close a resource
    • streamWrapper::stream_eof - Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush - Flushes the output
    • streamWrapper::stream_lock - Advisory file locking
    • streamWrapper::stream_metadata - Change stream metadata
    • streamWrapper::stream_open - Opens file or URL
    • streamWrapper::stream_read - Read from stream
    • streamWrapper::stream_seek - Seeks to specific location in a stream
    • streamWrapper::stream_set_option - Change stream options
    • streamWrapper::stream_stat - Retrieve information about a file resource
    • streamWrapper::stream_tell - Retrieve the current position of a stream
    • streamWrapper::stream_truncate - Truncate stream
    • streamWrapper::stream_write - Write to stream
    • streamWrapper::unlink - Delete a file
    • streamWrapper::url_stat - Retrieve information about a file
    • streamWrapper::__construct - Constructs a new stream wrapper
    • streamWrapper::__destruct - Destructs an existing stream wrapper
    • stream_bucket_append - Append bucket to brigade
    • stream_bucket_make_writeable - Return a bucket object from the brigade for operating on
    • stream_bucket_new - Create a new bucket for use on the current stream
    • stream_bucket_prepend - Prepend bucket to brigade
    • stream_context_create - 创建资源流上下文
    • stream_context_get_default - Retrieve the default stream context
    • stream_context_get_options - 获取资源流/数据包/上下文的参数
    • stream_context_get_params - Retrieves parameters from a context
    • stream_context_set_default - Set the default stream context
    • stream_context_set_option - 对资源流、数据包或者上下文设置参数
    • stream_context_set_params - Set parameters for a stream/wrapper/context
    • stream_copy_to_stream - Copies data from one stream to another
    • stream_filter_append - Attach a filter to a stream
    • stream_filter_prepend - Attach a filter to a stream
    • stream_filter_register - Register a user defined stream filter
    • stream_filter_remove - 从资源流里移除某个过滤器
    • stream_get_contents - 读取资源流到一个字符串
    • stream_get_filters - 获取已注册的数据流过滤器列表
    • stream_get_line - 从资源流里读取一行直到给定的定界符
    • stream_get_meta_data - 从封装协议文件指针中取得报头／元数据
    • stream_get_transports - 获取已注册的套接字传输协议列表
    • stream_get_wrappers - 获取已注册的流类型
    • stream_isatty - Check if a stream is a TTY
    • stream_is_local - Checks if a stream is a local stream
    • stream_notification_callback - A callback function for the notification context parameter
    • stream_register_wrapper - 别名 stream_wrapper_register
    • stream_resolve_include_path - Resolve filename against the include path
    • stream_select - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
    • stream_set_blocking - 为资源流设置阻塞或者阻塞模式
    • stream_set_chunk_size - 设置资源流区块大小
    • stream_set_read_buffer - Set read file buffering on the given stream
    • stream_set_timeout - Set timeout period on a stream
    • stream_set_write_buffer - Sets write file buffering on the given stream
    • stream_socket_accept - 接受由 stream_socket_server 创建的套接字连接
    • stream_socket_client - Open Internet or Unix domain socket connection
    • stream_socket_enable_crypto - Turns encryption on/off on an already connected socket
    • stream_socket_get_name - 获取本地或者远程的套接字名称
    • stream_socket_pair - 创建一对完全一样的网络套接字连接流
    • stream_socket_recvfrom - Receives data from a socket, connected or not
    • stream_socket_sendto - Sends a message to a socket, whether it is connected or not
    • stream_socket_server - Create an Internet or Unix domain server socket
    • stream_socket_shutdown - Shutdown a full-duplex connection
    • stream_supports_lock - Tells whether the stream supports locking
    • stream_wrapper_register - 注册一个用 PHP 类实现的 URL 封装协议
    • stream_wrapper_restore - Restores a previously unregistered built-in wrapper
    • stream_wrapper_unregister - Unregister a URL wrapper
    • strftime - 根据区域设置格式化本地时间／日期
    • stripcslashes - 反引用一个使用 addcslashes 转义的字符串
    • stripos - 查找字符串首次出现的位置（不区分大小写）
    • stripslashes - 反引用一个引用字符串
    • strip_tags - 从字符串中去除 HTML 和 PHP 标记
    • stristr - strstr 函数的忽略大小写版本
    • strlen - 获取字符串长度
    • strnatcasecmp - 使用“自然顺序”算法比较字符串（不区分大小写）
    • strnatcmp - 使用自然排序算法比较字符串
    • strncasecmp - 二进制安全比较字符串开头的若干个字符（不区分大小写）
    • strncmp - 二进制安全比较字符串开头的若干个字符
    • strpbrk - 在字符串中查找一组字符的任何一个字符
    • strpos - 查找字符串首次出现的位置
    • strptime - 解析由 strftime 生成的日期／时间
    • strrchr - 查找指定字符在字符串中的最后一次出现
    • strrev - 反转字符串
    • strripos - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
    • strrpos - 计算指定字符串在目标字符串中最后一次出现的位置
    • strspn - 计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度。
    • strstr - 查找字符串的首次出现
    • strtok - 标记分割字符串
    • strtolower - 将字符串转化为小写
    • strtotime - 将任何字符串的日期时间描述解析为 Unix 时间戳
    • strtoupper - 将字符串转化为大写
    • strtr - 转换指定字符
    • strval - 获取变量的字符串值
    • str_contains - Determine if a string contains a given substring
    • str_ends_with - Checks if a string ends with a given substring
    • str_getcsv - 解析 CSV 字符串为一个数组
    • str_ireplace - str_replace 的忽略大小写版本
    • str_pad - 使用另一个字符串填充字符串为指定长度
    • str_repeat - 重复一个字符串
    • str_replace - 子字符串替换
    • str_rot13 - 对字符串执行 ROT13 转换
    • str_shuffle - 随机打乱一个字符串
    • str_split - 将字符串转换为数组
    • str_starts_with - Checks if a string starts with a given substring
    • str_word_count - 返回字符串中单词的使用情况
    • substr - 返回字符串的子串
    • substr_compare - 二进制安全比较字符串（从偏移位置比较指定长度）
    • substr_count - 计算字串出现的次数
    • substr_replace - 替换字符串的子串
    • SVM::crossvalidate - Test training params on subsets of the training data
    • SVM::getOptions - Return the current training parameters
    • SVM::setOptions - Set training parameters
    • SVM::train - Create a SVMModel based on training data
    • SVM::__construct - Construct a new SVM object
    • SVMModel::checkProbabilityModel - Returns true if the model has probability information
    • SVMModel::getLabels - Get the labels the model was trained on
    • SVMModel::getNrClass - Returns the number of classes the model was trained with
    • SVMModel::getSvmType - Get the SVM type the model was trained with
    • SVMModel::getSvrProbability - Get the sigma value for regression types
    • SVMModel::load - Load a saved SVM Model
    • SVMModel::predict - Predict a value for previously unseen data
    • SVMModel::predict_probability - Return class probabilities for previous unseen data
    • SVMModel::save - Save a model to a file
    • SVMModel::__construct - Construct a new SVMModel
    • svn_add - 计划在工作目录添加项
    • svn_auth_get_parameter - Retrieves authentication parameter
    • svn_auth_set_parameter - Sets an authentication parameter
    • svn_blame - Get the SVN blame for a file
    • svn_cat - Returns the contents of a file in a repository
    • svn_checkout - Checks out a working copy from the repository
    • svn_cleanup - Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version - Returns the version of the SVN client libraries
    • svn_commit - 将修改的本地文件副本发送至版本库
    • svn_delete - Delete items from a working copy or repository
    • svn_diff - Recursively diffs two paths
    • svn_export - Export the contents of a SVN directory
    • svn_fs_abort_txn - Abort a transaction, returns true if everything is okay, false otherwise
    • svn_fs_apply_text - Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 - Create a new transaction
    • svn_fs_change_node_prop - Return true if everything is ok, false otherwise
    • svn_fs_check_path - Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed - Return true if content is different, false otherwise
    • svn_fs_copy - Copies a file or a directory, returns true if all is ok, false otherwise
    • svn_fs_delete - Deletes a file or a directory, return true if all is ok, false otherwise
    • svn_fs_dir_entries - Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents - Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length - Returns the length of a file from a given version of the fs
    • svn_fs_is_dir - Return true if the path points to a directory, false otherwise
    • svn_fs_is_file - Return true if the path points to a file, false otherwise
    • svn_fs_make_dir - Creates a new empty directory, returns true if all is ok, false otherwise
    • svn_fs_make_file - Creates a new empty file, returns true if all is ok, false otherwise
    • svn_fs_node_created_rev - Returns the revision in which path under fsroot was created
    • svn_fs_node_prop - Returns the value of a property for a node
    • svn_fs_props_changed - Return true if props are different, false otherwise
    • svn_fs_revision_prop - Fetches the value of a named property
    • svn_fs_revision_root - Get a handle on a specific version of the repository root
    • svn_fs_txn_root - Creates and returns a transaction root
    • svn_fs_youngest_rev - Returns the number of the youngest revision in the filesystem
    • svn_import - Imports an unversioned path into a repository
    • svn_log - Returns the commit log messages of a repository URL
    • svn_ls - Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir - Creates a directory in a working copy or repository
    • svn_repos_create - Create a new subversion repository at path
    • svn_repos_fs - Gets a handle on the filesystem for a repository
    • svn_repos_fs_begin_txn_for_commit - Create a new transaction
    • svn_repos_fs_commit_txn - Commits a transaction and returns the new revision
    • svn_repos_hotcopy - Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open - Open a shared lock on a repository
    • svn_repos_recover - Run recovery procedures on the repository located at path
    • svn_revert - Revert changes to the working copy
    • svn_status - Returns the status of working copy files and directories
    • svn_update - Update working copy
    • Swoole\Async::dnsLookup - Async and non-blocking hostname to IP lookup.
    • Swoole\Async::read - Read file stream asynchronously.
    • Swoole\Async::readFile - Read a file asynchronously.
    • Swoole\Async::set - Update the async I/O options.
    • Swoole\Async::write - Write data to a file stream asynchronously.
    • Swoole\Async::writeFile - Description
    • Swoole\Atomic::add - Add a number to the value to the atomic object.
    • Swoole\Atomic::cmpset - Compare and set the value of the atomic object.
    • Swoole\Atomic::get - Get the current value of the atomic object.
    • Swoole\Atomic::set - Set a new value to the atomic object.
    • Swoole\Atomic::sub - Subtract a number to the value of the atomic object.
    • Swoole\Atomic::__construct - Construct a swoole atomic object.
    • Swoole\Buffer::append - Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
    • Swoole\Buffer::clear - Reset the memory buffer.
    • Swoole\Buffer::expand - Expand the size of memory buffer.
    • Swoole\Buffer::read - Read data from the memory buffer based on offset and length.
    • Swoole\Buffer::recycle - Release the memory to OS which is not used by the memory buffer.
    • Swoole\Buffer::substr - Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
    • Swoole\Buffer::write - Write data to the memory buffer. The memory allocated for the buffer will not be changed.
    • Swoole\Buffer::__construct - Fixed size memory blocks allocation.
    • Swoole\Buffer::__destruct - Destruct the Swoole memory buffer.
    • Swoole\Buffer::__toString - Get the string value of the memory buffer.
    • Swoole\Channel::pop - Read and pop data from swoole channel.
    • Swoole\Channel::push - Write and push data into Swoole channel.
    • Swoole\Channel::stats - Get stats of swoole channel.
    • Swoole\Channel::__construct - Construct a Swoole Channel
    • Swoole\Channel::__destruct - Destruct a Swoole channel.
    • Swoole\Client::close - Close the connection established.
    • Swoole\Client::connect - Connect to the remote TCP or UDP port.
    • Swoole\Client::getpeername - Get the remote socket name of the connection.
    • Swoole\Client::getsockname - Get the local socket name of the connection.
    • Swoole\Client::isConnected - Check if the connection is established.
    • Swoole\Client::on - Add callback functions triggered by events.
    • Swoole\Client::pause - Pause receiving data.
    • Swoole\Client::pipe - Redirect the data to another file descriptor.
    • Swoole\Client::recv - Receive data from the remote socket.
    • Swoole\Client::resume - Resume receiving data.
    • Swoole\Client::send - Send data to the remote TCP socket.
    • Swoole\Client::sendfile - Send file to the remote TCP socket.
    • Swoole\Client::sendto - Send data to the remote UDP address.
    • Swoole\Client::set - Set the Swoole client parameters before the connection is established.
    • Swoole\Client::sleep - Remove the TCP client from system event loop.
    • Swoole\Client::wakeup - Add the TCP client back into the system event loop.
    • Swoole\Client::__construct - Create Swoole sync or async TCP/UDP client, with or without SSL.
    • Swoole\Client::__destruct - Destruct the Swoole client.
    • Swoole\Connection\Iterator::count - Count connections.
    • Swoole\Connection\Iterator::current - Return current connection entry.
    • Swoole\Connection\Iterator::key - Return key of the current connection.
    • Swoole\Connection\Iterator::next - Move to the next connection.
    • Swoole\Connection\Iterator::offsetExists - Check if offet exists.
    • Swoole\Connection\Iterator::offsetGet - Offset to retrieve.
    • Swoole\Connection\Iterator::offsetSet - Assign a Connection to the specified offset.
    • Swoole\Connection\Iterator::offsetUnset - Unset an offset.
    • Swoole\Connection\Iterator::rewind - Rewinds iterator
    • Swoole\Connection\Iterator::valid - Check if current position is valid.
    • Swoole\Coroutine::call_user_func - Call a callback given by the first parameter
    • Swoole\Coroutine::call_user_func_array - Call a callback with an array of parameters
    • Swoole\Coroutine::cli_wait - Description
    • Swoole\Coroutine::create - Description
    • Swoole\Coroutine::getuid - Description
    • Swoole\Coroutine::resume - Description
    • Swoole\Coroutine::suspend - Description
    • Swoole\Coroutine\Client::close - Description
    • Swoole\Coroutine\Client::connect - Description
    • Swoole\Coroutine\Client::getpeername - Description
    • Swoole\Coroutine\Client::getsockname - Description
    • Swoole\Coroutine\Client::isConnected - Description
    • Swoole\Coroutine\Client::recv - Description
    • Swoole\Coroutine\Client::send - Description
    • Swoole\Coroutine\Client::sendfile - Description
    • Swoole\Coroutine\Client::sendto - Description
    • Swoole\Coroutine\Client::set - Description
    • Swoole\Coroutine\Client::__construct - Description
    • Swoole\Coroutine\Client::__destruct - Description
    • Swoole\Coroutine\Http\Client::addFile - Description
    • Swoole\Coroutine\Http\Client::close - Description
    • Swoole\Coroutine\Http\Client::execute - Description
    • Swoole\Coroutine\Http\Client::get - Description
    • Swoole\Coroutine\Http\Client::getDefer - Description
    • Swoole\Coroutine\Http\Client::isConnected - Description
    • Swoole\Coroutine\Http\Client::post - Description
    • Swoole\Coroutine\Http\Client::recv - Description
    • Swoole\Coroutine\Http\Client::set - Description
    • Swoole\Coroutine\Http\Client::setCookies - Description
    • Swoole\Coroutine\Http\Client::setData - Description
    • Swoole\Coroutine\Http\Client::setDefer - Description
    • Swoole\Coroutine\Http\Client::setHeaders - Description
    • Swoole\Coroutine\Http\Client::setMethod - Description
    • Swoole\Coroutine\Http\Client::__construct - Description
    • Swoole\Coroutine\Http\Client::__destruct - Description
    • Swoole\Coroutine\MySQL::close - Description
    • Swoole\Coroutine\MySQL::connect - Description
    • Swoole\Coroutine\MySQL::getDefer - Description
    • Swoole\Coroutine\MySQL::query - Description
    • Swoole\Coroutine\MySQL::recv - Description
    • Swoole\Coroutine\MySQL::setDefer - Description
    • Swoole\Coroutine\MySQL::__construct - Description
    • Swoole\Coroutine\MySQL::__destruct - Description
    • Swoole\Event::add - Add new callback functions of a socket into the EventLoop.
    • Swoole\Event::defer - Add a callback function to the next event loop.
    • Swoole\Event::del - Remove all event callback functions of a socket.
    • Swoole\Event::exit - Exit the eventloop, only available at client side.
    • Swoole\Event::set - Update the event callback functions of a socket.
    • Swoole\Event::wait - Description
    • Swoole\Event::write - Write data to the socket.
    • Swoole\Http\Client::addFile - Add a file to the post form.
    • Swoole\Http\Client::close - Close the http connection.
    • Swoole\Http\Client::download - Download a file from the remote server.
    • Swoole\Http\Client::execute - Send the HTTP request after setting the parameters.
    • Swoole\Http\Client::get - Send GET http request to the remote server.
    • Swoole\Http\Client::isConnected - Check if the HTTP connection is connected.
    • Swoole\Http\Client::on - Register callback function by event name.
    • Swoole\Http\Client::post - Send POST http request to the remote server.
    • Swoole\Http\Client::push - Push data to websocket client.
    • Swoole\Http\Client::set - Update the HTTP client paramters.
    • Swoole\Http\Client::setCookies - Set the http request cookies.
    • Swoole\Http\Client::setData - Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders - Set the HTTP request headers.
    • Swoole\Http\Client::setMethod - Set the HTTP request method.
    • Swoole\Http\Client::upgrade - Upgrade to websocket protocol.
    • Swoole\Http\Client::__construct - Construct the async HTTP client.
    • Swoole\Http\Client::__destruct - Destruct the HTTP client.
    • Swoole\Http\Request::rawcontent - Get the raw HTTP POST body.
    • Swoole\Http\Request::__destruct - Destruct the HTTP request.
    • Swoole\Http\Response::cookie - Set the cookies of the HTTP response.
    • Swoole\Http\Response::end - Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip - Enable the gzip of response content.
    • Swoole\Http\Response::header - Set the HTTP response headers.
    • Swoole\Http\Response::initHeader - Init the HTTP response header.
    • Swoole\Http\Response::rawcookie - Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile - Send file through the HTTP response.
    • Swoole\Http\Response::status - Set the status code of the HTTP response.
    • Swoole\Http\Response::write - Append HTTP body content to the HTTP response.
    • Swoole\Http\Response::__destruct - Destruct the HTTP response.
    • Swoole\Http\Server::on - Bind callback function to HTTP server by event name.
    • Swoole\Http\Server::start - Start the swoole http server.
    • Swoole\Lock::lock - Try to acquire the lock. It will block if the lock is not available.
    • Swoole\Lock::lock_read - Lock a read-write lock for reading.
    • Swoole\Lock::trylock - Try to acquire the lock and return straight away even the lock is not available.
    • Swoole\Lock::trylock_read - Try to lock a read-write lock for reading and return straight away even the lock is not available.
    • Swoole\Lock::unlock - Release the lock.
    • Swoole\Lock::__construct - Construct a memory lock.
    • Swoole\Lock::__destruct - Destory a Swoole memory lock.
    • Swoole\Mmap::open - Map a file into memory and return the stream resource which can be used by PHP stream operations.
    • Swoole\MySQL::close - Close the async MySQL connection.
    • Swoole\MySQL::connect - Connect to the remote MySQL server.
    • Swoole\MySQL::getBuffer - Description
    • Swoole\MySQL::on - Register callback function based on event name.
    • Swoole\MySQL::query - Run the SQL query.
    • Swoole\MySQL::__construct - Construct an async MySQL client.
    • Swoole\MySQL::__destruct - Destory the async MySQL client.
    • Swoole\Process::alarm - High precision timer which triggers signal with fixed interval.
    • Swoole\Process::close - Close the pipe to the child process.
    • Swoole\Process::daemon - Change the process to be a daemon process.
    • Swoole\Process::exec - Execute system commands.
    • Swoole\Process::exit - Stop the child processes.
    • Swoole\Process::freeQueue - Destroy the message queue created by swoole_process::useQueue.
    • Swoole\Process::kill - Send signal to the child process.
    • Swoole\Process::name - Set name of the process.
    • Swoole\Process::pop - Read and pop data from the message queue.
    • Swoole\Process::push - Write and push data into the message queue.
    • Swoole\Process::read - Read data sending to the process.
    • Swoole\Process::signal - Send signal to the child processes.
    • Swoole\Process::start - Start the process.
    • Swoole\Process::statQueue - Get the stats of the message queue used as the communication method between processes.
    • Swoole\Process::useQueue - Create a message queue as the communication method between the parent process and child processes.
    • Swoole\Process::wait - Wait for the events of child processes.
    • Swoole\Process::write - Write data into the pipe and communicate with the parent process or child processes.
    • Swoole\Process::__construct - Construct a process.
    • Swoole\Process::__destruct - Destory the process.
    • Swoole\Redis\Server::format - Description
    • Swoole\Redis\Server::setHandler - Description
    • Swoole\Redis\Server::start - Description
    • Swoole\Serialize::pack - Serialize the data.
    • Swoole\Serialize::unpack - Unserialize the data.
    • Swoole\Server::addlistener - Add a new listener to the server.
    • Swoole\Server::addProcess - Add a user defined swoole_process to the server.
    • Swoole\Server::after - Trigger a callback function after a period of time.
    • Swoole\Server::bind - Bind the connection to a user defined user ID.
    • Swoole\Server::clearTimer - Stop and destory a timer.
    • Swoole\Server::close - Close a connection to the client.
    • Swoole\Server::confirm - Check status of the connection.
    • Swoole\Server::connection_info - Get the connection info by file description.
    • Swoole\Server::connection_list - Get all of the established connections.
    • Swoole\Server::defer - Delay execution of the callback function at the end of current EventLoop.
    • Swoole\Server::exist - Check if the connection is existed.
    • Swoole\Server::finish - Used in task process for sending result to the worker process when the task is finished.
    • Swoole\Server::getClientInfo - Get the connection info by file description.
    • Swoole\Server::getClientList - Get all of the established connections.
    • Swoole\Server::getLastError - Get the error code of the most recent error.
    • Swoole\Server::heartbeat - Check all the connections on the server.
    • Swoole\Server::listen - Listen on the given IP and port, socket type.
    • Swoole\Server::on - Register a callback function by event name.
    • Swoole\Server::pause - Stop receiving data from the connection.
    • Swoole\Server::protect - Set the connection to be protected mode.
    • Swoole\Server::reload - Restart all the worker process.
    • Swoole\Server::resume - Start receving data from the connection.
    • Swoole\Server::send - Send data to the client.
    • Swoole\Server::sendfile - Send file to the connection.
    • Swoole\Server::sendMessage - Send message to worker processes by ID.
    • Swoole\Server::sendto - Send data to the remote UDP address.
    • Swoole\Server::sendwait - Send data to the remote socket in the blocking way.
    • Swoole\Server::set - Set the runtime settings of the swoole server.
    • Swoole\Server::shutdown - Shutdown the master server process, this function can be called in worker processes.
    • Swoole\Server::start - Start the Swoole server.
    • Swoole\Server::stats - Get the stats of the Swoole server.
    • Swoole\Server::stop - Stop the Swoole server.
    • Swoole\Server::task - Send data to the task worker processes.
    • Swoole\Server::taskwait - Send data to the task worker processes in blocking way.
    • Swoole\Server::taskWaitMulti - Execute multiple tasks concurrently.
    • Swoole\Server::tick - Repeats a given function at every given time-interval.
    • Swoole\Server::__construct - Construct a Swoole server.
    • Swoole\Server\Port::on - Register callback functions by event.
    • Swoole\Server\Port::set - Set protocol of the server port.
    • Swoole\Server\Port::__construct - Construct a server port
    • Swoole\Server\Port::__destruct - Destory server port
    • Swoole\Table::column - Set the data type and size of the columns.
    • Swoole\Table::count - Count the rows in the table, or count all the elements in the table if $mode = 1.
    • Swoole\Table::create - Create the swoole memory table.
    • Swoole\Table::current - Get the current row.
    • Swoole\Table::decr - Decrement the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::del - Delete a row in the Swoole table by $row_key.
    • Swoole\Table::destroy - Destroy the Swoole table.
    • Swoole\Table::exist - Check if a row is existed by $row_key.
    • Swoole\Table::get - Get the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::incr - Increment the value by $row_key and $column_key.
    • Swoole\Table::key - Get the key of current row.
    • Swoole\Table::next - Iterator the next row.
    • Swoole\Table::rewind - Rewind the iterator.
    • Swoole\Table::set - Update a row of the table by $row_key.
    • Swoole\Table::valid - Check current if the current row is valid.
    • Swoole\Table::__construct - Construct a Swoole memory table with fixed size.
    • Swoole\Timer::after - Trigger a callback function after a period of time.
    • Swoole\Timer::clear - Delete a timer by timer ID.
    • Swoole\Timer::exists - Check if a timer is existed.
    • Swoole\Timer::tick - Repeats a given function at every given time-interval.
    • Swoole\WebSocket\Server::exist - Check if the file descriptor exists.
    • Swoole\WebSocket\Server::on - Register event callback function
    • Swoole\WebSocket\Server::pack - Get a pack of binary data to send in a single frame.
    • Swoole\WebSocket\Server::push - Push data to the remote client.
    • Swoole\WebSocket\Server::unpack - Unpack the binary data received from the client.
    • swoole_async_dns_lookup - Async and non-blocking hostname to IP lookup
    • swoole_async_read - Read file stream asynchronously
    • swoole_async_readfile - Read a file asynchronously
    • swoole_async_set - Update the async I/O options
    • swoole_async_write - Write data to a file stream asynchronously
    • swoole_async_writefile - Write data to a file asynchronously
    • swoole_client_select - Get the file description which are ready to read/write or error
    • swoole_cpu_num - Get the number of CPU
    • swoole_errno - Get the error code of the latest system call
    • swoole_event_add - Add new callback functions of a socket into the EventLoop
    • swoole_event_defer - Add callback function to the next event loop
    • swoole_event_del - Remove all event callback functions of a socket
    • swoole_event_exit - Exit the eventloop, only available at the client side
    • swoole_event_set - Update the event callback functions of a socket
    • swoole_event_wait - Start the event loop
    • swoole_event_write - Write data to a socket
    • swoole_get_local_ip - Get the IPv4 IP addresses of each NIC on the machine
    • swoole_last_error - Get the lastest error message
    • swoole_load_module - Load a swoole extension
    • swoole_select - Select the file descriptions which are ready to read/write or error in the eventloop
    • swoole_set_process_name - Set the process name
    • swoole_strerror - Convert the Errno into error messages
    • swoole_timer_after - Trigger a one time callback function in the future
    • swoole_timer_exists - Check if a timer callback function is existed
    • swoole_timer_tick - Trigger a timer tick callback function by time interval
    • swoole_version - Get the version of Swoole
    • symlink - 建立符号连接
    • SyncEvent::fire - Fires/sets the event
    • SyncEvent::reset - Resets a manual event
    • SyncEvent::wait - Waits for the event to be fired/set
    • SyncEvent::__construct - Constructs a new SyncEvent object
    • SyncMutex::lock - Waits for an exclusive lock
    • SyncMutex::unlock - Unlocks the mutex
    • SyncMutex::__construct - Constructs a new SyncMutex object
    • SyncReaderWriter::readlock - Waits for a read lock
    • SyncReaderWriter::readunlock - Releases a read lock
    • SyncReaderWriter::writelock - Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock - Releases a write lock
    • SyncReaderWriter::__construct - Constructs a new SyncReaderWriter object
    • SyncSemaphore::lock - Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock - Increases the count of the semaphore
    • SyncSemaphore::__construct - Constructs a new SyncSemaphore object
    • SyncSharedMemory::first - Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read - Copy data from named shared memory
    • SyncSharedMemory::size - Returns the size of the named shared memory
    • SyncSharedMemory::write - Copy data to named shared memory
    • SyncSharedMemory::__construct - Constructs a new SyncSharedMemory object
    • syslog - Generate a system log message
    • system - 执行外部程序，并且显示输出
    • sys_getloadavg - 获取系统的负载（load average）
    • sys_get_temp_dir - 返回用于临时文件的目录
  • t
    • Table::count - Get row count
    • Table::delete - Delete rows from table
    • Table::existsInDatabase - Check if table exists in database
    • Table::getName - Get table name
    • Table::getSchema - Get table schema
    • Table::getSession - Get table session
    • Table::insert - Insert table rows
    • Table::isView - Check if table is view
    • Table::select - Select rows from table
    • Table::update - Update rows in table
    • Table::__construct - Table constructor
    • TableDelete::bind - Bind delete query parameters
    • TableDelete::execute - Execute delete query
    • TableDelete::limit - Limit deleted rows
    • TableDelete::orderby - Set delete sort criteria
    • TableDelete::where - Set delete search condition
    • TableDelete::__construct - TableDelete constructor
    • TableInsert::execute - Execute insert query
    • TableInsert::values - Add insert row values
    • TableInsert::__construct - TableInsert constructor
    • TableSelect::bind - Bind select query parameters
    • TableSelect::execute - Execute select statement
    • TableSelect::groupBy - Set select grouping criteria
    • TableSelect::having - Set select having condition
    • TableSelect::limit - Limit selected rows
    • TableSelect::lockExclusive - Execute EXCLUSIVE LOCK
    • TableSelect::lockShared - Execute SHARED LOCK
    • TableSelect::offset - Set limit offset
    • TableSelect::orderby - Set select sort criteria
    • TableSelect::where - Set select search condition
    • TableSelect::__construct - TableSelect constructor
    • TableUpdate::bind - Bind update query parameters
    • TableUpdate::execute - Execute update query
    • TableUpdate::limit - Limit update row count
    • TableUpdate::orderby - Set sorting criteria
    • TableUpdate::set - Add field to be updated
    • TableUpdate::where - Set search filter
    • TableUpdate::__construct - TableUpdate constructor
    • taint - Taint a string
    • tan - 正切
    • tanh - 双曲正切
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - 建立一个具有唯一文件名的文件
    • textdomain - Sets the default domain
    • Thread::detach - 执行
    • Thread::getCreatorId - 识别
    • Thread::getCurrentThread - 识别
    • Thread::getCurrentThreadId - 识别
    • Thread::getThreadId - 识别
    • Thread::globally - 执行
    • Thread::isJoined - 状态监测
    • Thread::isStarted - 状态检测
    • Thread::join - 同步
    • Thread::kill - 执行
    • Thread::start - 执行
    • Threaded::chunk - 操作
    • Threaded::count - 操作
    • Threaded::extend - Runtime Manipulation
    • Threaded::from - Creation
    • Threaded::getTerminationInfo - 错误检测
    • Threaded::isRunning - 状态检测
    • Threaded::isTerminated - 状态检测
    • Threaded::isWaiting - 状态检测
    • Threaded::lock - 同步控制
    • Threaded::merge - 操作
    • Threaded::notify - 同步控制
    • Threaded::notifyOne - Synchronization
    • Threaded::pop - 操作
    • Threaded::run - 执行
    • Threaded::shift - Manipulation
    • Threaded::synchronized - 同步控制
    • Threaded::unlock - 同步控制
    • Threaded::wait - Synchronization
    • tidy::$errorBuffer - Return warnings and errors which occurred parsing the specified document
    • tidy::body - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair - Execute configured cleanup and repair operations on parsed markup
    • tidy::diagnose - Run configured diagnostics on parsed and repaired markup
    • tidy::getConfig - Get current Tidy configuration
    • tidy::getHtmlVer - Get the Detected HTML version for the specified document
    • tidy::getOpt - Returns the value of the specified configuration option for the tidy document
    • tidy::getOptDoc - Returns the documentation for the given option name
    • tidy::getRelease - Get release date (version) for Tidy library
    • tidy::getStatus - Get status of specified document
    • tidy::head - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html - Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml - Indicates if the document is a XHTML document
    • tidy::isXml - Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile - Parse markup in file or URI
    • tidy::parseString - Parse a document stored in a string
    • tidy::repairFile - Repair a file and return it as a string
    • tidy::repairString - Repair a string using an optionally provided configuration file
    • tidy::root - Returns a tidyNode object representing the root of the tidy parse tree
    • tidy::__construct - Constructs a new tidy object
    • tidyNode::getParent - Returns the parent node of the current node
    • tidyNode::hasChildren - Checks if a node has children
    • tidyNode::hasSiblings - Checks if a node has siblings
    • tidyNode::isAsp - Checks if this node is ASP
    • tidyNode::isComment - Checks if a node represents a comment
    • tidyNode::isHtml - Checks if a node is an element node
    • tidyNode::isJste - Checks if this node is JSTE
    • tidyNode::isPhp - Checks if a node is PHP
    • tidyNode::isText - Checks if a node represents text (no markup)
    • tidyNode::__construct - Private constructor to disallow direct instantiation
    • tidy_access_count - Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count - Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count - Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output - Return a string representing the parsed tidy markup
    • tidy_warning_count - Returns the Number of Tidy warnings encountered for specified document
    • time - 返回当前的 Unix 时间戳
    • timezone_abbreviations_list - 别名 DateTimeZone::listAbbreviations
    • timezone_identifiers_list - 别名 DateTimeZone::listIdentifiers
    • timezone_location_get - 别名 DateTimeZone::getLocation
    • timezone_name_from_abbr - Returns the timezone name from abbreviation
    • timezone_name_get - 别名 DateTimeZone::getName
    • timezone_offset_get - 别名 DateTimeZone::getOffset
    • timezone_open - 别名 DateTimeZone::__construct
    • timezone_transitions_get - 别名 DateTimeZone::getTransitions
    • timezone_version_get - 获取 timezonedb 的版本
    • time_nanosleep - 延缓执行若干秒和纳秒
    • time_sleep_until - 使脚本睡眠到指定的时间为止。
    • tmpfile - 建立一个临时文件
    • token_get_all - 将提供的源码按 PHP 标记进行分割
    • token_name - 获取提供的 PHP 解析器代号的符号名称
    • TokyoTyrant::add - Adds to a numeric key
    • TokyoTyrant::connect - Connect to a database
    • TokyoTyrant::connectUri - Connects to a database
    • TokyoTyrant::copy - Copies the database
    • TokyoTyrant::ext - Execute a remote script
    • TokyoTyrant::fwmKeys - Returns the forward matching keys
    • TokyoTyrant::get - The get purpose
    • TokyoTyrant::getIterator - Get an iterator
    • TokyoTyrant::num - Number of records in the database
    • TokyoTyrant::out - Removes records
    • TokyoTyrant::put - Puts values
    • TokyoTyrant::putCat - Concatenates to a record
    • TokyoTyrant::putKeep - Puts a record
    • TokyoTyrant::putNr - Puts value
    • TokyoTyrant::putShl - Concatenates to a record
    • TokyoTyrant::restore - Restore the database
    • TokyoTyrant::setMaster - Set the replication master
    • TokyoTyrant::size - Returns the size of the value
    • TokyoTyrant::stat - Get statistics
    • TokyoTyrant::sync - Synchronize the database
    • TokyoTyrant::tune - Tunes connection values
    • TokyoTyrant::vanish - Empties the database
    • TokyoTyrant::__construct - Construct a new TokyoTyrant object
    • TokyoTyrantIterator::current - Get the current value
    • TokyoTyrantIterator::key - Returns the current key
    • TokyoTyrantIterator::next - Move to next key
    • TokyoTyrantIterator::rewind - Rewinds the iterator
    • TokyoTyrantIterator::valid - Rewinds the iterator
    • TokyoTyrantIterator::__construct - Construct an iterator
    • TokyoTyrantQuery::addCond - Adds a condition to the query
    • TokyoTyrantQuery::count - Counts records
    • TokyoTyrantQuery::current - Returns the current element
    • TokyoTyrantQuery::hint - Get the hint string of the query
    • TokyoTyrantQuery::key - Returns the current key
    • TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries
    • TokyoTyrantQuery::next - Moves the iterator to next entry
    • TokyoTyrantQuery::out - Removes records based on query
    • TokyoTyrantQuery::rewind - Rewinds the iterator
    • TokyoTyrantQuery::search - Searches records
    • TokyoTyrantQuery::setLimit - Limit results
    • TokyoTyrantQuery::setOrder - Orders results
    • TokyoTyrantQuery::valid - Checks the validity of current item
    • TokyoTyrantQuery::__construct - Construct a new query
    • TokyoTyrantTable::add - Adds a record
    • TokyoTyrantTable::genUid - Generate unique id
    • TokyoTyrantTable::get - Get a row
    • TokyoTyrantTable::getIterator - Get an iterator
    • TokyoTyrantTable::getQuery - Get a query object
    • TokyoTyrantTable::out - Remove records
    • TokyoTyrantTable::put - Store a row
    • TokyoTyrantTable::putCat - Concatenates to a row
    • TokyoTyrantTable::putKeep - Put a new record
    • TokyoTyrantTable::putNr - Puts value
    • TokyoTyrantTable::putShl - Concatenates to a record
    • TokyoTyrantTable::setIndex - Sets index
    • touch - 设定文件的访问和修改时间
    • trader_acos - Vector Trigonometric ACos
    • trader_ad - Chaikin A/D Line
    • trader_add - Vector Arithmetic Add
    • trader_adosc - Chaikin A/D Oscillator
    • trader_adx - Average Directional Movement Index
    • trader_adxr - Average Directional Movement Index Rating
    • trader_apo - Absolute Price Oscillator
    • trader_aroon - Aroon
    • trader_aroonosc - Aroon Oscillator
    • trader_asin - Vector Trigonometric ASin
    • trader_atan - Vector Trigonometric ATan
    • trader_atr - Average True Range
    • trader_avgprice - Average Price
    • trader_bbands - Bollinger Bands
    • trader_beta - Beta
    • trader_bop - Balance Of Power
    • trader_cci - Commodity Channel Index
    • trader_cdl2crows - Two Crows
    • trader_cdl3blackcrows - Three Black Crows
    • trader_cdl3inside - Three Inside Up/Down
    • trader_cdl3linestrike - Three-Line Strike
    • trader_cdl3outside - Three Outside Up/Down
    • trader_cdl3starsinsouth - Three Stars In The South
    • trader_cdl3whitesoldiers - Three Advancing White Soldiers
    • trader_cdlabandonedbaby - Abandoned Baby
    • trader_cdladvanceblock - Advance Block
    • trader_cdlbelthold - Belt-hold
    • trader_cdlbreakaway - Breakaway
    • trader_cdlclosingmarubozu - Closing Marubozu
    • trader_cdlconcealbabyswall - Concealing Baby Swallow
    • trader_cdlcounterattack - Counterattack
    • trader_cdldarkcloudcover - Dark Cloud Cover
    • trader_cdldoji - Doji
    • trader_cdldojistar - Doji Star
    • trader_cdldragonflydoji - Dragonfly Doji
    • trader_cdlengulfing - Engulfing Pattern
    • trader_cdleveningdojistar - Evening Doji Star
    • trader_cdleveningstar - Evening Star
    • trader_cdlgapsidesidewhite - Up/Down-gap side-by-side white lines
    • trader_cdlgravestonedoji - Gravestone Doji
    • trader_cdlhammer - Hammer
    • trader_cdlhangingman - Hanging Man
    • trader_cdlharami - Harami Pattern
    • trader_cdlharamicross - Harami Cross Pattern
    • trader_cdlhighwave - High-Wave Candle
    • trader_cdlhikkake - Hikkake Pattern
    • trader_cdlhikkakemod - Modified Hikkake Pattern
    • trader_cdlhomingpigeon - Homing Pigeon
    • trader_cdlidentical3crows - Identical Three Crows
    • trader_cdlinneck - In-Neck Pattern
    • trader_cdlinvertedhammer - Inverted Hammer
    • trader_cdlkicking - Kicking
    • trader_cdlkickingbylength - Kicking - bull/bear determined by the longer marubozu
    • trader_cdlladderbottom - Ladder Bottom
    • trader_cdllongleggeddoji - Long Legged Doji
    • trader_cdllongline - Long Line Candle
    • trader_cdlmarubozu - Marubozu
    • trader_cdlmatchinglow - Matching Low
    • trader_cdlmathold - Mat Hold
    • trader_cdlmorningdojistar - Morning Doji Star
    • trader_cdlmorningstar - Morning Star
    • trader_cdlonneck - On-Neck Pattern
    • trader_cdlpiercing - Piercing Pattern
    • trader_cdlrickshawman - Rickshaw Man
    • trader_cdlrisefall3methods - Rising/Falling Three Methods
    • trader_cdlseparatinglines - Separating Lines
    • trader_cdlshootingstar - Shooting Star
    • trader_cdlshortline - Short Line Candle
    • trader_cdlspinningtop - Spinning Top
    • trader_cdlstalledpattern - Stalled Pattern
    • trader_cdlsticksandwich - Stick Sandwich
    • trader_cdltakuri - Takuri (Dragonfly Doji with very long lower shadow)
    • trader_cdltasukigap - Tasuki Gap
    • trader_cdlthrusting - Thrusting Pattern
    • trader_cdltristar - Tristar Pattern
    • trader_cdlunique3river - Unique 3 River
    • trader_cdlupsidegap2crows - Upside Gap Two Crows
    • trader_cdlxsidegap3methods - Upside/Downside Gap Three Methods
    • trader_ceil - Vector Ceil
    • trader_cmo - Chande Momentum Oscillator
    • trader_correl - Pearson's Correlation Coefficient (r)
    • trader_cos - Vector Trigonometric Cos
    • trader_cosh - Vector Trigonometric Cosh
    • trader_dema - Double Exponential Moving Average
    • trader_div - Vector Arithmetic Div
    • trader_dx - Directional Movement Index
    • trader_ema - Exponential Moving Average
    • trader_errno - Get error code
    • trader_exp - Vector Arithmetic Exp
    • trader_floor - Vector Floor
    • trader_get_compat - Get compatibility mode
    • trader_get_unstable_period - Get unstable period
    • trader_ht_dcperiod - Hilbert Transform - Dominant Cycle Period
    • trader_ht_dcphase - Hilbert Transform - Dominant Cycle Phase
    • trader_ht_phasor - Hilbert Transform - Phasor Components
    • trader_ht_sine - Hilbert Transform - SineWave
    • trader_ht_trendline - Hilbert Transform - Instantaneous Trendline
    • trader_ht_trendmode - Hilbert Transform - Trend vs Cycle Mode
    • trader_kama - Kaufman Adaptive Moving Average
    • trader_linearreg - Linear Regression
    • trader_linearreg_angle - Linear Regression Angle
    • trader_linearreg_intercept - Linear Regression Intercept
    • trader_linearreg_slope - Linear Regression Slope
    • trader_ln - Vector Log Natural
    • trader_log10 - Vector Log10
    • trader_ma - Moving average
    • trader_macd - Moving Average Convergence/Divergence
    • trader_macdext - MACD with controllable MA type
    • trader_macdfix - Moving Average Convergence/Divergence Fix 12/26
    • trader_mama - MESA Adaptive Moving Average
    • trader_mavp - Moving average with variable period
    • trader_max - Highest value over a specified period
    • trader_maxindex - Index of highest value over a specified period
    • trader_medprice - Median Price
    • trader_mfi - Money Flow Index
    • trader_midpoint - MidPoint over period
    • trader_midprice - Midpoint Price over period
    • trader_min - Lowest value over a specified period
    • trader_minindex - Index of lowest value over a specified period
    • trader_minmax - Lowest and highest values over a specified period
    • trader_minmaxindex - Indexes of lowest and highest values over a specified period
    • trader_minus_di - Minus Directional Indicator
    • trader_minus_dm - Minus Directional Movement
    • trader_mom - Momentum
    • trader_mult - Vector Arithmetic Mult
    • trader_natr - Normalized Average True Range
    • trader_obv - On Balance Volume
    • trader_plus_di - Plus Directional Indicator
    • trader_plus_dm - Plus Directional Movement
    • trader_ppo - Percentage Price Oscillator
    • trader_roc - Rate of change : ((price/prevPrice)-1)*100
    • trader_rocp - Rate of change Percentage: (price-prevPrice)/prevPrice
    • trader_rocr - Rate of change ratio: (price/prevPrice)
    • trader_rocr100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    • trader_rsi - Relative Strength Index
    • trader_sar - Parabolic SAR
    • trader_sarext - Parabolic SAR - Extended
    • trader_set_compat - Set compatibility mode
    • trader_set_unstable_period - Set unstable period
    • trader_sin - Vector Trigonometric Sin
    • trader_sinh - Vector Trigonometric Sinh
    • trader_sma - Simple Moving Average
    • trader_sqrt - Vector Square Root
    • trader_stddev - Standard Deviation
    • trader_stoch - Stochastic
    • trader_stochf - Stochastic Fast
    • trader_stochrsi - Stochastic Relative Strength Index
    • trader_sub - Vector Arithmetic Subtraction
    • trader_sum - Summation
    • trader_t3 - Triple Exponential Moving Average (T3)
    • trader_tan - Vector Trigonometric Tan
    • trader_tanh - Vector Trigonometric Tanh
    • trader_tema - Triple Exponential Moving Average
    • trader_trange - True Range
    • trader_trima - Triangular Moving Average
    • trader_trix - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    • trader_tsf - Time Series Forecast
    • trader_typprice - Typical Price
    • trader_ultosc - Ultimate Oscillator
    • trader_var - Variance
    • trader_wclprice - Weighted Close Price
    • trader_willr - Williams' %R
    • trader_wma - Weighted Moving Average
    • trait_exists - 检查指定的 trait 是否存在
    • Transliterator::create - Create a transliterator
    • Transliterator::createFromRules - Create transliterator from rules
    • Transliterator::createInverse - Create an inverse transliterator
    • Transliterator::getErrorCode - Get last error code
    • Transliterator::getErrorMessage - Get last error message
    • Transliterator::listIDs - Get transliterator IDs
    • Transliterator::transliterate - Transliterate a string
    • Transliterator::__construct - Private constructor to deny instantiation
    • trigger_error - 产生一个用户级别的 error/warning/notice 信息
    • trim - 去除字符串首尾处的空白字符（或者其他字符）
  • u
    • uasort - 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
    • ucfirst - 将字符串的首字母转换为大写
    • UConverter::convert - Convert string from one charset to another
    • UConverter::fromUCallback - Default "from" callback function
    • UConverter::getAliases - Get the aliases of the given name
    • UConverter::getAvailable - Get the available canonical converter names
    • UConverter::getDestinationEncoding - Get the destination encoding
    • UConverter::getDestinationType - Get the destination converter type
    • UConverter::getErrorCode - Get last error code on the object
    • UConverter::getErrorMessage - Get last error message on the object
    • UConverter::getSourceEncoding - Get the source encoding
    • UConverter::getSourceType - Get the source converter type
    • UConverter::getStandards - Get standards associated to converter names
    • UConverter::getSubstChars - Get substitution chars
    • UConverter::reasonText - Get string representation of the callback reason
    • UConverter::setDestinationEncoding - Set the destination encoding
    • UConverter::setSourceEncoding - Set the source encoding
    • UConverter::setSubstChars - Set the substitution chars
    • UConverter::toUCallback - Default "to" callback function
    • UConverter::transcode - Convert string from one charset to another
    • UConverter::__construct - Create UConverter object
    • ucwords - 将字符串中每个单词的首字母转换为大写
    • UI\Area::onDraw - Draw Callback
    • UI\Area::onKey - Key Callback
    • UI\Area::onMouse - Mouse Callback
    • UI\Area::redraw - Redraw Area
    • UI\Area::scrollTo - Area Scroll
    • UI\Area::setSize - Set Size
    • UI\Control::destroy - Destroy Control
    • UI\Control::disable - Disable Control
    • UI\Control::enable - Enable Control
    • UI\Control::getParent - Get Parent Control
    • UI\Control::getTopLevel - Get Top Level
    • UI\Control::hide - Hide Control
    • UI\Control::isEnabled - Determine if Control is enabled
    • UI\Control::isVisible - Determine if Control is visible
    • UI\Control::setParent - Set Parent Control
    • UI\Control::show - Control Show
    • UI\Controls\Box::append - Append Control
    • UI\Controls\Box::delete - Delete Control
    • UI\Controls\Box::getOrientation - Get Orientation
    • UI\Controls\Box::isPadded - Padding Detection
    • UI\Controls\Box::setPadded - Set Padding
    • UI\Controls\Box::__construct - Construct a new Box
    • UI\Controls\Button::getText - Get Text
    • UI\Controls\Button::onClick - Click Handler
    • UI\Controls\Button::setText - Set Text
    • UI\Controls\Button::__construct - Construct a new Button
    • UI\Controls\Check::getText - Get Text
    • UI\Controls\Check::isChecked - Checked Detection
    • UI\Controls\Check::onToggle - Toggle Callback
    • UI\Controls\Check::setChecked - Set Checked
    • UI\Controls\Check::setText - Set Text
    • UI\Controls\Check::__construct - Construct a new Check
    • UI\Controls\ColorButton::getColor - Get Color
    • UI\Controls\ColorButton::onChange - Change Handler
    • UI\Controls\ColorButton::setColor - Set Color
    • UI\Controls\Combo::append - Append Option
    • UI\Controls\Combo::getSelected - Get Selected Option
    • UI\Controls\Combo::onSelected - Selected Handler
    • UI\Controls\Combo::setSelected - Set Selected Option
    • UI\Controls\EditableCombo::append - Append Option
    • UI\Controls\EditableCombo::getText - Get Text
    • UI\Controls\EditableCombo::onChange - Change Handler
    • UI\Controls\EditableCombo::setText - Set Text
    • UI\Controls\Entry::getText - Get Text
    • UI\Controls\Entry::isReadOnly - Detect Read Only
    • UI\Controls\Entry::onChange - Change Handler
    • UI\Controls\Entry::setReadOnly - Set Read Only
    • UI\Controls\Entry::setText - Set Text
    • UI\Controls\Entry::__construct - Construct a new Entry
    • UI\Controls\Form::append - Append Control
    • UI\Controls\Form::delete - Delete Control
    • UI\Controls\Form::isPadded - Padding Detection
    • UI\Controls\Form::setPadded - Set Padding
    • UI\Controls\Grid::append - Append Control
    • UI\Controls\Grid::isPadded - Padding Detection
    • UI\Controls\Grid::setPadded - Set Padding
    • UI\Controls\Group::append - Append Control
    • UI\Controls\Group::getTitle - Get Title
    • UI\Controls\Group::hasMargin - Margin Detection
    • UI\Controls\Group::setMargin - Set Margin
    • UI\Controls\Group::setTitle - Set Title
    • UI\Controls\Group::__construct - Construct a new Group
    • UI\Controls\Label::getText - Get Text
    • UI\Controls\Label::setText - Set Text
    • UI\Controls\Label::__construct - Construct a new Label
    • UI\Controls\MultilineEntry::append - Append Text
    • UI\Controls\MultilineEntry::getText - Get Text
    • UI\Controls\MultilineEntry::isReadOnly - Read Only Detection
    • UI\Controls\MultilineEntry::onChange - Change Handler
    • UI\Controls\MultilineEntry::setReadOnly - Set Read Only
    • UI\Controls\MultilineEntry::setText - Set Text
    • UI\Controls\MultilineEntry::__construct - Construct a new Multiline Entry
    • UI\Controls\Picker::__construct - Construct a new Picker
    • UI\Controls\Progress::getValue - Get Value
    • UI\Controls\Progress::setValue - Set Value
    • UI\Controls\Radio::append - Append Option
    • UI\Controls\Radio::getSelected - Get Selected Option
    • UI\Controls\Radio::onSelected - Selected Handler
    • UI\Controls\Radio::setSelected - Set Selected Option
    • UI\Controls\Separator::__construct - Construct a new Separator
    • UI\Controls\Slider::getValue - Get Value
    • UI\Controls\Slider::onChange - Change Handler
    • UI\Controls\Slider::setValue - Set Value
    • UI\Controls\Slider::__construct - Construct a new Slider
    • UI\Controls\Spin::getValue - Get Value
    • UI\Controls\Spin::onChange - Change Handler
    • UI\Controls\Spin::setValue - Set Value
    • UI\Controls\Spin::__construct - Construct a new Spin
    • UI\Controls\Tab::append - Append Page
    • UI\Controls\Tab::delete - Delete Page
    • UI\Controls\Tab::hasMargin - Margin Detection
    • UI\Controls\Tab::insertAt - Insert Page
    • UI\Controls\Tab::pages - Page Count
    • UI\Controls\Tab::setMargin - Set Margin
    • UI\Draw\Brush::getColor - Get Color
    • UI\Draw\Brush::setColor - Set Color
    • UI\Draw\Brush::__construct - Construct a new Brush
    • UI\Draw\Brush\Gradient::addStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop - Stop Manipulation
    • UI\Draw\Brush\LinearGradient::__construct - Construct a Linear Gradient
    • UI\Draw\Brush\RadialGradient::__construct - Construct a new Radial Gradient
    • UI\Draw\Color::getChannel - Color Manipulation
    • UI\Draw\Color::setChannel - Color Manipulation
    • UI\Draw\Color::__construct - Construct new Color
    • UI\Draw\Matrix::invert - Invert Matrix
    • UI\Draw\Matrix::isInvertible - Invertible Detection
    • UI\Draw\Matrix::multiply - Multiply Matrix
    • UI\Draw\Matrix::rotate - Rotate Matrix
    • UI\Draw\Matrix::scale - Scale Matrix
    • UI\Draw\Matrix::skew - Skew Matrix
    • UI\Draw\Matrix::translate - Translate Matrix
    • UI\Draw\Path::addRectangle - Draw a Rectangle
    • UI\Draw\Path::arcTo - Draw an Arc
    • UI\Draw\Path::bezierTo - Draw Bezier Curve
    • UI\Draw\Path::closeFigure - Close Figure
    • UI\Draw\Path::end - Finalize Path
    • UI\Draw\Path::lineTo - Draw a Line
    • UI\Draw\Path::newFigure - Draw Figure
    • UI\Draw\Path::newFigureWithArc - Draw Figure with Arc
    • UI\Draw\Path::__construct - Construct a new Path
    • UI\Draw\Pen::clip - Clip a Path
    • UI\Draw\Pen::fill - Fill a Path
    • UI\Draw\Pen::restore - Restore
    • UI\Draw\Pen::save - Save
    • UI\Draw\Pen::stroke - Stroke a Path
    • UI\Draw\Pen::transform - Matrix Transform
    • UI\Draw\Pen::write - Draw Text at Point
    • UI\Draw\Stroke::getCap - Get Line Cap
    • UI\Draw\Stroke::getJoin - Get Line Join
    • UI\Draw\Stroke::getMiterLimit - Get Miter Limit
    • UI\Draw\Stroke::getThickness - Get Thickness
    • UI\Draw\Stroke::setCap - Set Line Cap
    • UI\Draw\Stroke::setJoin - Set Line Join
    • UI\Draw\Stroke::setMiterLimit - Set Miter Limit
    • UI\Draw\Stroke::setThickness - Set Thickness
    • UI\Draw\Stroke::__construct - Construct a new Stroke
    • UI\Draw\Text\Font::getAscent - Font Metrics
    • UI\Draw\Text\Font::getDescent - Font Metrics
    • UI\Draw\Text\Font::getLeading - Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition - Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness - Font Metrics
    • UI\Draw\Text\Font::__construct - Construct a new Font
    • UI\Draw\Text\Font\Descriptor::getFamily - Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic - Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize - Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch - Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight - Weight Detection
    • UI\Draw\Text\Font\Descriptor::__construct - Construct a new Font Descriptor
    • UI\Draw\Text\Font\fontFamilies - Retrieve Font Families
    • UI\Draw\Text\Layout::setColor - Set Color
    • UI\Draw\Text\Layout::setWidth - Set Width
    • UI\Draw\Text\Layout::__construct - Construct a new Text Layout
    • UI\Executor::kill - Stop Executor
    • UI\Executor::onExecute - Execution Callback
    • UI\Executor::setInterval - Interval Manipulation
    • UI\Executor::__construct - Construct a new Executor
    • UI\Menu::append - Append Menu Item
    • UI\Menu::appendAbout - Append About Menu Item
    • UI\Menu::appendCheck - Append Checkable Menu Item
    • UI\Menu::appendPreferences - Append Preferences Menu Item
    • UI\Menu::appendQuit - Append Quit Menu Item
    • UI\Menu::appendSeparator - Append Menu Item Separator
    • UI\Menu::__construct - Construct a new Menu
    • UI\MenuItem::disable - Disable Menu Item
    • UI\MenuItem::enable - Enable Menu Item
    • UI\MenuItem::isChecked - Detect Checked
    • UI\MenuItem::onClick - On Click Callback
    • UI\MenuItem::setChecked - Set Checked
    • UI\Point::at - Size Coercion
    • UI\Point::getX - Retrieves X
    • UI\Point::getY - Retrieves Y
    • UI\Point::setX - Set X
    • UI\Point::setY - Set Y
    • UI\Point::__construct - Construct a new Point
    • UI\quit - Quit UI Loop
    • UI\run - Enter UI Loop
    • UI\Size::getHeight - Retrieves Height
    • UI\Size::getWidth - Retrives Width
    • UI\Size::of - Point Coercion
    • UI\Size::setHeight - Set Height
    • UI\Size::setWidth - Set Width
    • UI\Size::__construct - Construct a new Size
    • UI\Window::add - Add a Control
    • UI\Window::error - Show Error Box
    • UI\Window::getSize - Get Window Size
    • UI\Window::getTitle - Get Title
    • UI\Window::hasBorders - Border Detection
    • UI\Window::hasMargin - Margin Detection
    • UI\Window::isFullScreen - Full Screen Detection
    • UI\Window::msg - Show Message Box
    • UI\Window::onClosing - Closing Callback
    • UI\Window::open - Open Dialog
    • UI\Window::save - Save Dialog
    • UI\Window::setBorders - Border Use
    • UI\Window::setFullScreen - Full Screen Use
    • UI\Window::setMargin - Margin Use
    • UI\Window::setSize - Set Size
    • UI\Window::setTitle - Window Title
    • UI\Window::__construct - Construct a new Window
    • uksort - 使用用户自定义的比较函数对数组中的键名进行排序
    • umask - 改变当前的 umask
    • uniqid - 生成一个唯一ID
    • unixtojd - 转变Unix时间戳为Julian Day计数
    • unlink - 删除文件
    • unpack - Unpack data from binary string
    • unregister_tick_function - De-register a function for execution on each tick
    • unserialize - 从已存储的表示中创建 PHP 的值
    • unset - 释放给定的变量
    • untaint - Untaint strings
    • uopz_add_function - Adds non-existent function or method
    • uopz_allow_exit - Allows control over disabled exit opcode
    • uopz_backup - Backup a function
    • uopz_compose - Compose a class
    • uopz_copy - Copy a function
    • uopz_delete - Delete a function
    • uopz_del_function - Deletes previously added function or method
    • uopz_extend - Extend a class at runtime
    • uopz_flags - Get or set flags on function or class
    • uopz_function - Creates a function at runtime
    • uopz_get_exit_status - Retrieve the last set exit status
    • uopz_get_hook - Gets previously set hook on function or method
    • uopz_get_mock - Get the current mock for a class
    • uopz_get_property - Gets value of class or instance property
    • uopz_get_return - Gets a previous set return value for a function
    • uopz_get_static - Gets the static variables from function or method scope
    • uopz_implement - Implements an interface at runtime
    • uopz_overload - Overload a VM opcode
    • uopz_redefine - Redefine a constant
    • uopz_rename - Rename a function at runtime
    • uopz_restore - Restore a previously backed up function
    • uopz_set_hook - Sets hook to execute when entering a function or method
    • uopz_set_mock - Use mock instead of class for new objects
    • uopz_set_property - Sets value of existing class or instance property
    • uopz_set_return - Provide a return value for an existing function
    • uopz_set_static - Sets the static variables in function or method scope
    • uopz_undefine - Undefine a constant
    • uopz_unset_hook - Removes previously set hook on function or method
    • uopz_unset_mock - Unset previously set mock
    • uopz_unset_return - Unsets a previously set return value for a function
    • urldecode - 解码已编码的 URL 字符串
    • urlencode - 编码 URL 字符串
    • user_error - trigger_error 的别名
    • use_soap_error_handler - Set whether to use the SOAP error handler
    • usleep - 以指定的微秒数延迟执行
    • usort - 使用用户自定义的比较函数对数组中的值进行排序
    • utf8_decode - 将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。
    • utf8_encode - 将 ISO-8859-1 编码的字符串转换为 UTF-8 编码
  • v
    • V8Js::executeString - Execute a string as Javascript code
    • V8Js::getExtensions - Return an array of registered extensions
    • V8Js::getPendingException - Return pending uncaught Javascript exception
    • V8Js::registerExtension - Register Javascript extensions for V8Js
    • V8Js::__construct - Construct a new V8Js object
    • V8JsException::getJsFileName - The getJsFileName purpose
    • V8JsException::getJsLineNumber - The getJsLineNumber purpose
    • V8JsException::getJsSourceLine - The getJsSourceLine purpose
    • V8JsException::getJsTrace - The getJsTrace purpose
    • variant::__construct - variant class constructor
    • variant_abs - Returns the absolute value of a variant
    • variant_add - "Adds" two variant values together and returns the result
    • variant_and - Performs a bitwise AND operation between two variants
    • variant_cast - Convert a variant into a new variant object of another type
    • variant_cat - Concatenates two variant values together and returns the result
    • variant_cmp - Compares two variants
    • variant_date_from_timestamp - Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp - Converts a variant date/time value to Unix timestamp
    • variant_div - Returns the result from dividing two variants
    • variant_eqv - Performs a bitwise equivalence on two variants
    • variant_fix - Returns the integer portion of a variant
    • variant_get_type - Returns the type of a variant object
    • variant_idiv - Converts variants to integers and then returns the result from dividing them
    • variant_imp - Performs a bitwise implication on two variants
    • variant_int - Returns the integer portion of a variant
    • variant_mod - Divides two variants and returns only the remainder
    • variant_mul - Multiplies the values of the two variants
    • variant_neg - Performs logical negation on a variant
    • variant_not - Performs bitwise not negation on a variant
    • variant_or - Performs a logical disjunction on two variants
    • variant_pow - Returns the result of performing the power function with two variants
    • variant_round - Rounds a variant to the specified number of decimal places
    • variant_set - Assigns a new value for a variant object
    • variant_set_type - Convert a variant into another type "in-place"
    • variant_sub - Subtracts the value of the right variant from the left variant value
    • variant_xor - Performs a logical exclusion on two variants
    • VarnishAdmin::auth - Authenticate on a varnish instance
    • VarnishAdmin::ban - Ban URLs using a VCL expression
    • VarnishAdmin::banUrl - Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic - Clear varnish instance panic messages
    • VarnishAdmin::connect - Connect to a varnish instance administration interface
    • VarnishAdmin::disconnect - Disconnect from a varnish instance administration interface
    • VarnishAdmin::getPanic - Get the last panic message on a varnish instance
    • VarnishAdmin::getParams - Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning - Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat - Set the class compat configuration param
    • VarnishAdmin::setHost - Set the class host configuration param
    • VarnishAdmin::setIdent - Set the class ident configuration param
    • VarnishAdmin::setParam - Set configuration param on the current varnish instance
    • VarnishAdmin::setPort - Set the class port configuration param
    • VarnishAdmin::setSecret - Set the class secret configuration param
    • VarnishAdmin::setTimeout - Set the class timeout configuration param
    • VarnishAdmin::start - Start varnish worker process
    • VarnishAdmin::stop - Stop varnish worker process
    • VarnishAdmin::__construct - VarnishAdmin constructor
    • VarnishLog::getLine - Get next log line
    • VarnishLog::getTagName - Get the log tag string representation by its index
    • VarnishLog::__construct - Varnishlog constructor
    • VarnishStat::getSnapshot - Get the current varnish instance statistics snapshot
    • VarnishStat::__construct - VarnishStat constructor
    • var_dump - 打印变量的相关信息
    • var_export - 输出或返回一个变量的字符串表示
    • version_compare - 对比两个「PHP 规范化」的版本数字字符串
    • vfprintf - 将格式化字符串写入流
    • virtual - 执行 Apache 子请求
    • vprintf - 输出格式化字符串
    • vsprintf - 返回格式化字符串
    • Vtiful\Kernel\Excel::addSheet - Vtiful\Kernel\Excel addSheet
    • Vtiful\Kernel\Excel::autoFilter - Vtiful\Kernel\Excel autoFilter
    • Vtiful\Kernel\Excel::constMemory - Vtiful\Kernel\Excel constMemory
    • Vtiful\Kernel\Excel::data - Vtiful\Kernel\Excel data
    • Vtiful\Kernel\Excel::fileName - Vtiful\Kernel\Excel fileName
    • Vtiful\Kernel\Excel::getHandle - Vtiful\Kernel\Excel getHandle
    • Vtiful\Kernel\Excel::header - Vtiful\Kernel\Excel header
    • Vtiful\Kernel\Excel::insertFormula - Vtiful\Kernel\Excel insertFormula
    • Vtiful\Kernel\Excel::insertImage - Vtiful\Kernel\Excel insertImage
    • Vtiful\Kernel\Excel::insertText - Vtiful\Kernel\Excel insertText
    • Vtiful\Kernel\Excel::mergeCells - Vtiful\Kernel\Excel mergeCells
    • Vtiful\Kernel\Excel::output - Vtiful\Kernel\Excel output
    • Vtiful\Kernel\Excel::setColumn - Vtiful\Kernel\Excel setColumn
    • Vtiful\Kernel\Excel::setRow - Vtiful\Kernel\Excel setRow
    • Vtiful\Kernel\Excel::__construct - Vtiful\Kernel\Excel constructor
    • Vtiful\Kernel\Format::align - Vtiful\Kernel\Format align
    • Vtiful\Kernel\Format::bold - Vtiful\Kernel\Format bold
    • Vtiful\Kernel\Format::italic - Vtiful\Kernel\Format italic
    • Vtiful\Kernel\Format::underline - Vtiful\Kernel\Format underline
  • w
    • Warning::__construct - Warning constructor
    • wddx_add_vars - Add variables to a WDDX packet with the specified ID
    • wddx_deserialize - Unserializes a WDDX packet
    • wddx_packet_end - Ends a WDDX packet with the specified ID
    • wddx_packet_start - Starts a new WDDX packet with structure inside it
    • wddx_serialize_value - Serialize a single value into a WDDX packet
    • wddx_serialize_vars - Serialize variables into a WDDX packet
    • WeakMap::count - Counts the number of live entries in the map
    • WeakMap::current - Returns the current value under iteration
    • WeakMap::key - Returns the current key under iteration
    • WeakMap::next - Advances to the next map element
    • WeakMap::offsetExists - Checks whether a certain object is in the map
    • WeakMap::offsetGet - Returns the value pointed to by a certain object
    • WeakMap::offsetSet - Updates the map with a new key-value pair
    • WeakMap::offsetUnset - Removes an entry from the map
    • WeakMap::rewind - Rewinds the iterator to the beginning of the map
    • WeakMap::valid - Returns whether the iterator is still on a valid map element
    • WeakMap::__construct - Constructs a new map
    • Weakref::acquire - Acquires a strong reference on that object
    • Weakref::get - Returns the object pointed to by the weak reference
    • Weakref::release - Releases a previously acquired reference
    • Weakref::valid - Checks whether the object referenced still exists
    • Weakref::__construct - Constructs a new weak reference
    • win32_continue_service - Resumes a paused service
    • win32_create_service - Creates a new service entry in the SCM database
    • win32_delete_service - Deletes a service entry from the SCM database
    • win32_get_last_control_message - Returns the last control message that was sent to this service
    • win32_pause_service - Pauses a service
    • win32_query_service_status - Queries the status of a service
    • win32_send_custom_control - Send a custom control to the service
    • win32_set_service_exit_code - Define or return the exit code for the current running service
    • win32_set_service_exit_mode - Define or return the exit mode for the current running service
    • win32_set_service_status - Update the service status
    • win32_start_service - Starts a service
    • win32_start_service_ctrl_dispatcher - Registers the script with the SCM, so that it can act as the service with the given name
    • win32_stop_service - Stops a service
    • wincache_fcache_fileinfo - Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo - Retrieves information about file cache memory usage
    • wincache_lock - Acquires an exclusive lock on a given key
    • wincache_ocache_fileinfo - Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo - Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed - Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo - Retrieves information about resolve file path cache
    • wincache_rplist_meminfo - Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info - Retrieves information about files cached in the session cache
    • wincache_scache_meminfo - Retrieves information about session cache memory usage
    • wincache_ucache_add - Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas - Compares the variable with old value and assigns new value to it
    • wincache_ucache_clear - Deletes entire content of the user cache
    • wincache_ucache_dec - Decrements the value associated with the key
    • wincache_ucache_delete - Deletes variables from the user cache
    • wincache_ucache_exists - Checks if a variable exists in the user cache
    • wincache_ucache_get - Gets a variable stored in the user cache
    • wincache_ucache_inc - Increments the value associated with the key
    • wincache_ucache_info - Retrieves information about data stored in the user cache
    • wincache_ucache_meminfo - Retrieves information about user cache memory usage
    • wincache_ucache_set - Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock - Releases an exclusive lock on a given key
    • wkhtmltox\Image\Converter::convert - Perform Image conversion
    • wkhtmltox\Image\Converter::getVersion - Determine version of Converter
    • wkhtmltox\Image\Converter::__construct - Create a new Image converter
    • wkhtmltox\PDF\Converter::add - Add an object for conversion
    • wkhtmltox\PDF\Converter::convert - Perform PDF conversion
    • wkhtmltox\PDF\Converter::getVersion - Determine version of Converter
    • wkhtmltox\PDF\Converter::__construct - Create a new PDF converter
    • wkhtmltox\PDF\Object::__construct - Create a new PDF Object
    • wordwrap - 打断字符串为指定数量的字串
    • Worker::collect - Collect references to completed tasks
    • Worker::getStacked - 获取剩余的栈大小
    • Worker::isShutdown - 状态检测
    • Worker::isWorking - 状态检测
    • Worker::shutdown - 关闭 Worker
    • Worker::stack - 将要执行的任务入栈
    • Worker::unstack - 将要执行的任务出栈
  • x
    • xattr_get - Get an extended attribute
    • xattr_list - Get a list of extended attributes
    • xattr_remove - Remove an extended attribute
    • xattr_set - Set an extended attribute
    • xattr_supported - Check if filesystem supports extended attributes
    • xdiff_file_bdiff - Make binary diff of two files
    • xdiff_file_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_file_bpatch - Patch a file with a binary diff
    • xdiff_file_diff - Make unified diff of two files
    • xdiff_file_diff_binary - Alias of xdiff_file_bdiff
    • xdiff_file_merge3 - Merge 3 files into one
    • xdiff_file_patch - Patch a file with an unified diff
    • xdiff_file_patch_binary - Alias of xdiff_file_bpatch
    • xdiff_file_rabdiff - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff - Make binary diff of two strings
    • xdiff_string_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_string_bpatch - Patch a string with a binary diff
    • xdiff_string_diff - Make unified diff of two strings
    • xdiff_string_diff_binary - Alias of xdiff_string_bdiff
    • xdiff_string_merge3 - Merge 3 strings into one
    • xdiff_string_patch - Patch a string with an unified diff
    • xdiff_string_patch_binary - Alias of xdiff_string_bpatch
    • xdiff_string_rabdiff - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
    • xhprof_disable - 停止 xhprof 分析器
    • xhprof_enable - 启动 xhprof 性能分析器
    • xhprof_sample_disable - 停止 xhprof 性能采样分析器
    • xhprof_sample_enable - 以采样模式启动 XHProf 性能分析
    • XMLDiff\Base::diff - Produce diff of two XML documents
    • XMLDiff\Base::merge - Produce new XML document based on diff
    • XMLDiff\Base::__construct - Constructor
    • XMLDiff\DOM::diff - Diff two DOMDocument objects
    • XMLDiff\DOM::merge - Produce merged DOMDocument
    • XMLDiff\File::diff - Diff two XML files
    • XMLDiff\File::merge - Produce merged XML document
    • XMLDiff\Memory::diff - Diff two XML documents
    • XMLDiff\Memory::merge - Produce merged XML document
    • XMLReader::close - Close the XMLReader input
    • XMLReader::expand - Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute - Get the value of a named attribute
    • XMLReader::getAttributeNo - Get the value of an attribute by index
    • XMLReader::getAttributeNs - Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty - Indicates if specified property has been set
    • XMLReader::isValid - Indicates if the parsed document is valid
    • XMLReader::lookupNamespace - Lookup namespace for a prefix
    • XMLReader::moveToAttribute - Move cursor to a named attribute
    • XMLReader::moveToAttributeNo - Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs - Move cursor to a named attribute
    • XMLReader::moveToElement - Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute - Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute - Position cursor on the next Attribute
    • XMLReader::next - Move cursor to next node skipping all subtrees
    • XMLReader::open - Set the URI containing the XML to parse
    • XMLReader::read - Move to next node in document
    • XMLReader::readInnerXml - Retrieve XML from current node
    • XMLReader::readOuterXml - Retrieve XML from current node, including itself
    • XMLReader::readString - Reads the contents of the current node as a string
    • XMLReader::setParserProperty - Set parser options
    • XMLReader::setRelaxNGSchema - Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource - Set the data containing a RelaxNG Schema
    • XMLReader::setSchema - Validate document against XSD
    • XMLReader::XML - Set the data containing the XML to parse
    • xmlrpc_decode - 将 XML 译码为 PHP 本身的类型
    • xmlrpc_decode_request - 将 XML 译码为 PHP 本身的类型
    • xmlrpc_encode - 为 PHP 的值生成 XML
    • xmlrpc_encode_request - 为 PHP 的值生成 XML
    • xmlrpc_get_type - 为 PHP 的值获取 xmlrpc 的类型
    • xmlrpc_is_fault - Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions - 将 XML 译码成方法描述的列表
    • xmlrpc_server_add_introspection_data - 添加自我描述的文档
    • xmlrpc_server_call_method - 解析 XML 请求同时调用方法
    • xmlrpc_server_create - 创建一个 xmlrpc 服务端
    • xmlrpc_server_destroy - 销毁服务端资源
    • xmlrpc_server_register_introspection_callback - 注册一个 PHP 函数用于生成文档
    • xmlrpc_server_register_method - 注册一个 PHP 函数用于匹配 xmlrpc 方法名
    • xmlrpc_set_type - 为一个 PHP 字符串值设置 xmlrpc 的类型、base64 或日期时间
    • XMLWriter::endAttribute - End attribute
    • XMLWriter::endCdata - End current CDATA
    • XMLWriter::endComment - Create end comment
    • XMLWriter::endDocument - End current document
    • XMLWriter::endDtd - End current DTD
    • XMLWriter::endDtdAttlist - End current DTD AttList
    • XMLWriter::endDtdElement - End current DTD element
    • XMLWriter::endDtdEntity - End current DTD Entity
    • XMLWriter::endElement - End current element
    • XMLWriter::endPi - End current PI
    • XMLWriter::flush - Flush current buffer
    • XMLWriter::fullEndElement - End current element
    • XMLWriter::openMemory - Create new xmlwriter using memory for string output
    • XMLWriter::openUri - Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory - Returns current buffer
    • XMLWriter::setIndent - Toggle indentation on/off
    • XMLWriter::setIndentString - Set string used for indenting
    • XMLWriter::startAttribute - Create start attribute
    • XMLWriter::startAttributeNs - Create start namespaced attribute
    • XMLWriter::startCdata - Create start CDATA tag
    • XMLWriter::startComment - Create start comment
    • XMLWriter::startDocument - Create document tag
    • XMLWriter::startDtd - Create start DTD tag
    • XMLWriter::startDtdAttlist - Create start DTD AttList
    • XMLWriter::startDtdElement - Create start DTD element
    • XMLWriter::startDtdEntity - Create start DTD Entity
    • XMLWriter::startElement - Create start element tag
    • XMLWriter::startElementNs - Create start namespaced element tag
    • XMLWriter::startPi - Create start PI tag
    • XMLWriter::text - Write text
    • XMLWriter::writeAttribute - Write full attribute
    • XMLWriter::writeAttributeNs - Write full namespaced attribute
    • XMLWriter::writeCdata - Write full CDATA tag
    • XMLWriter::writeComment - Write full comment tag
    • XMLWriter::writeDtd - Write full DTD tag
    • XMLWriter::writeDtdAttlist - Write full DTD AttList tag
    • XMLWriter::writeDtdElement - Write full DTD element tag
    • XMLWriter::writeDtdEntity - Write full DTD Entity tag
    • XMLWriter::writeElement - Write full element tag
    • XMLWriter::writeElementNs - Write full namespaced element tag
    • XMLWriter::writePi - Writes a PI
    • XMLWriter::writeRaw - Write a raw XML text
    • xml_error_string - 获取 XML 解析器的错误字符串
    • xml_get_current_byte_index - 获取 XML 解析器的当前字节索引
    • xml_get_current_column_number - 获取 XML 解析器的当前列号
    • xml_get_current_line_number - 获取 XML 解析器的当前行号
    • xml_get_error_code - 获取 XML 解析器错误代码
    • xml_parse - 开始解析一个 XML 文档
    • xml_parser_create - 建立一个 XML 解析器
    • xml_parser_create_ns - 生成一个支持命名空间的 XML 解析器
    • xml_parser_free - 释放指定的 XML 解析器
    • xml_parser_get_option - 从 XML 解析器获取选项设置信息
    • xml_parser_set_option - 为指定 XML 解析进行选项设置
    • xml_parse_into_struct - 将 XML 数据解析到数组中
    • xml_set_character_data_handler - 建立字符数据处理器
    • xml_set_default_handler - 建立默认处理器
    • xml_set_element_handler - 建立起始和终止元素处理器
    • xml_set_end_namespace_decl_handler - 建立终止命名空间声明处理器
    • xml_set_external_entity_ref_handler - 建立外部实体指向处理器
    • xml_set_notation_decl_handler - 建立注释声明处理器
    • xml_set_object - 在对象中使用 XML 解析器
    • xml_set_processing_instruction_handler - 建立处理指令（PI）处理器
    • xml_set_start_namespace_decl_handler - 建立起始命名空间声明处理器
    • xml_set_unparsed_entity_decl_handler - 建立未解析实体定义声明处理器
    • XSLTProcessor::getParameter - Get value of a parameter
    • XSLTProcessor::getSecurityPrefs - Get security preferences
    • XSLTProcessor::hasExsltSupport - Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet - Import stylesheet
    • XSLTProcessor::registerPHPFunctions - Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter - Remove parameter
    • XSLTProcessor::setParameter - Set value for a parameter
    • XSLTProcessor::setProfiling - Sets profiling output file
    • XSLTProcessor::setSecurityPrefs - Set security preferences
    • XSLTProcessor::transformToDoc - Transform to a DOMDocument
    • XSLTProcessor::transformToUri - Transform to URI
    • XSLTProcessor::transformToXml - Transform to XML
    • XSLTProcessor::__construct - Creates a new XSLTProcessor object
  • y
    • Yac::add - Store into cache
    • Yac::delete - Remove items from cache
    • Yac::dump - Dump cache
    • Yac::flush - Flush the cache
    • Yac::get - Retrieve values from cache
    • Yac::info - Status of cache
    • Yac::set - Store into cache
    • Yac::__construct - Constructor
    • Yac::__get - Getter
    • Yac::__set - Setter
    • Yaconf::get - Retrieve a item
    • Yaconf::has - Determine if a item exists
    • Yaf_Action_Abstract::execute - 执行动作
    • Yaf_Action_Abstract::getController - 得到控制器实例
    • Yaf_Action_Abstract::getControllerName - Get controller name
    • Yaf_Application::app - 获取当前的Yaf_Application实例
    • Yaf_Application::bootstrap - 调用bootstrap
    • Yaf_Application::clearLastError - 清除最后的错误信息
    • Yaf_Application::environ - 获取当前Yaf_Application的环境名
    • Yaf_Application::execute - 运行回调函数
    • Yaf_Application::getAppDirectory - 获取应用的目录
    • Yaf_Application::getConfig - 获取 Yaf_Config_Abstract 的实例
    • Yaf_Application::getDispatcher - 获取 Yaf_Dispatcher 的实例
    • Yaf_Application::getLastErrorMsg - 获取最近产生的错误的错误信息
    • Yaf_Application::getLastErrorNo - 获取最后产生的错误的错误代码
    • Yaf_Application::getModules - 获取在配置文件中申明的模块
    • Yaf_Application::run - 运行 Yaf_Application
    • Yaf_Application::setAppDirectory - 改变应用目录
    • Yaf_Application::__construct - Yaf_Application的构造函数
    • Yaf_Application::__destruct - 析构函数
    • Yaf_Config_Abstract::get - Getter
    • Yaf_Config_Abstract::readonly - 寻找只读配置
    • Yaf_Config_Abstract::set - Setter
    • Yaf_Config_Abstract::toArray - 转换为数组
    • Yaf_Config_Ini::count - 返回配置的节数量
    • Yaf_Config_Ini::current - 返回当前节点
    • Yaf_Config_Ini::key - 返回当前元素的键
    • Yaf_Config_Ini::next - 向前移动到下一个元素
    • Yaf_Config_Ini::offsetExists - 检查一个偏移位置是否存在
    • Yaf_Config_Ini::offsetGet - 获取一个偏移位置的值
    • Yaf_Config_Ini::offsetSet - 设置一个偏移位置的值
    • Yaf_Config_Ini::offsetUnset - 复位一个偏移位置的值
    • Yaf_Config_Ini::readonly - 检查配置是否只读
    • Yaf_Config_Ini::rewind - 检查当前位置是否有效
    • Yaf_Config_Ini::toArray - 转换为数组的格式
    • Yaf_Config_Ini::valid - 检查迭代器是否有效
    • Yaf_Config_Ini::__construct - 构造函数
    • Yaf_Config_Ini::__get - 读取节点配置
    • Yaf_Config_Ini::__isset - 检查节点是否存在
    • Yaf_Config_Ini::__set - The __set purpose
    • Yaf_Config_Simple::count - 返回配置的节数量
    • Yaf_Config_Simple::current - 返回当前节点
    • Yaf_Config_Simple::key - 返回当前元素的键
    • Yaf_Config_Simple::next - 向前移动到下一个元素
    • Yaf_Config_Simple::offsetExists - 检查一个偏移位置是否存在
    • Yaf_Config_Simple::offsetGet - 获取一个偏移位置的值
    • Yaf_Config_Simple::offsetSet - 设置一个偏移位置的值
    • Yaf_Config_Simple::offsetUnset - 复位一个偏移位置的值
    • Yaf_Config_Simple::readonly - 检查配置是否只读
    • Yaf_Config_Simple::rewind - 检查当前位置是否有效
    • Yaf_Config_Simple::toArray - 转换为数组的格式
    • Yaf_Config_Simple::valid - 检查迭代器是否有效
    • Yaf_Config_Simple::__construct - 构造函数
    • Yaf_Config_Simple::__get - 读取节点配置
    • Yaf_Config_Simple::__isset - 检查节点是否存在
    • Yaf_Config_Simple::__set - 设置节点配置
    • Yaf_Controller_Abstract::display - The display purpose
    • Yaf_Controller_Abstract::forward - The forward purpose
    • Yaf_Controller_Abstract::getInvokeArg - The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs - The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName - 获取当前控制器所属的模块名
    • Yaf_Controller_Abstract::getName - Get self name
    • Yaf_Controller_Abstract::getRequest - The getRequest purpose
    • Yaf_Controller_Abstract::getResponse - The getResponse purpose
    • Yaf_Controller_Abstract::getView - 获取当前的视图引擎
    • Yaf_Controller_Abstract::getViewpath - The getViewpath purpose
    • Yaf_Controller_Abstract::init - 控制器初始化
    • Yaf_Controller_Abstract::initView - The initView purpose
    • Yaf_Controller_Abstract::redirect - The redirect purpose
    • Yaf_Controller_Abstract::render - 渲染视图模板
    • Yaf_Controller_Abstract::setViewpath - The setViewpath purpose
    • Yaf_Controller_Abstract::__construct - Yaf_Controller_Abstract constructor
    • Yaf_Dispatcher::autoRender - 开启/关闭自动渲染功能
    • Yaf_Dispatcher::catchException - 开启/关闭自动异常捕获功能
    • Yaf_Dispatcher::disableView - 关闭自动渲染
    • Yaf_Dispatcher::dispatch - 分发请求
    • Yaf_Dispatcher::enableView - 开启自动渲染
    • Yaf_Dispatcher::flushInstantly - 打开关闭自动响应
    • Yaf_Dispatcher::getApplication - 获取当前的Yaf_Application实例
    • Yaf_Dispatcher::getDefaultAction - Retrive the default action name
    • Yaf_Dispatcher::getDefaultController - Retrive the default controller name
    • Yaf_Dispatcher::getDefaultModule - Retrive the default module name
    • Yaf_Dispatcher::getInstance - 获取当前的Yaf_Dispatcher实例
    • Yaf_Dispatcher::getRequest - 获取当前的请求实例
    • Yaf_Dispatcher::getRouter - 获取路由器
    • Yaf_Dispatcher::initView - 初始化视图引擎并返回它
    • Yaf_Dispatcher::registerPlugin - 注册一个插件
    • Yaf_Dispatcher::returnResponse - The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction - 设置路由的默认动作
    • Yaf_Dispatcher::setDefaultController - 设置路由的默认控制器
    • Yaf_Dispatcher::setDefaultModule - 设置路由的默认模块
    • Yaf_Dispatcher::setErrorHandler - 设置错误处理函数
    • Yaf_Dispatcher::setRequest - The setRequest purpose
    • Yaf_Dispatcher::setView - 设置视图引擎
    • Yaf_Dispatcher::throwException - 开启/关闭异常抛出
    • Yaf_Dispatcher::__construct - Yaf_Dispatcher 构造函数
    • Yaf_Exception::getPrevious - The getPrevious purpose
    • Yaf_Exception::__construct - The __construct purpose
    • Yaf_Loader::autoload - The autoload purpose
    • Yaf_Loader::clearLocalNamespace - The clearLocalNamespace purpose
    • Yaf_Loader::getInstance - The getInstance purpose
    • Yaf_Loader::getLibraryPath - get the library path
    • Yaf_Loader::getLocalNamespace - Retrive all register namespaces info
    • Yaf_Loader::getNamespacePath - Retieve path of a registered namespace
    • Yaf_Loader::import - The import purpose
    • Yaf_Loader::isLocalName - The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace - 注册本地类前缀
    • Yaf_Loader::registerNamespace - Register namespace with searching path
    • Yaf_Loader::setLibraryPath - 改变library路径
    • Yaf_Loader::__construct - The __construct purpose
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup - The dispatchLoopStartup purpose
    • Yaf_Plugin_Abstract::postDispatch - The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch - The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse - The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown - The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup - RouterStartup hook
    • Yaf_Registry::del - Remove an item from registry
    • Yaf_Registry::get - Retrieve an item from registry
    • Yaf_Registry::has - Check whether an item exists
    • Yaf_Registry::set - Add an item into registry
    • Yaf_Registry::__construct - Yaf_Registry implements singleton
    • Yaf_Request_Abstract::clearParams - Remove all params
    • Yaf_Request_Abstract::getActionName - The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri - The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName - The getControllerName purpose
    • Yaf_Request_Abstract::getEnv - 取得ENV变量的值
    • Yaf_Request_Abstract::getException - The getException purpose
    • Yaf_Request_Abstract::getLanguage - The getLanguage purpose
    • Yaf_Request_Abstract::getMethod - The getMethod purpose
    • Yaf_Request_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Request_Abstract::getParam - The getParam purpose
    • Yaf_Request_Abstract::getParams - The getParams purpose
    • Yaf_Request_Abstract::getRequestUri - The getRequestUri purpose
    • Yaf_Request_Abstract::getServer - 返回SERVER变量的值
    • Yaf_Request_Abstract::isCli - The isCli purpose
    • Yaf_Request_Abstract::isDispatched - The isDispatched purpose
    • Yaf_Request_Abstract::isGet - The isGet purpose
    • Yaf_Request_Abstract::isHead - The isHead purpose
    • Yaf_Request_Abstract::isOptions - The isOptions purpose
    • Yaf_Request_Abstract::isPost - The isPost purpose
    • Yaf_Request_Abstract::isPut - The isPut purpose
    • Yaf_Request_Abstract::isRouted - The isRouted purpose
    • Yaf_Request_Abstract::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Abstract::setActionName - The setActionName purpose
    • Yaf_Request_Abstract::setBaseUri - The setBaseUri purpose
    • Yaf_Request_Abstract::setControllerName - The setControllerName purpose
    • Yaf_Request_Abstract::setDispatched - The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName - The setModuleName purpose
    • Yaf_Request_Abstract::setParam - The setParam purpose
    • Yaf_Request_Abstract::setRequestUri - The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted - The setRouted purpose
    • Yaf_Request_Http::get - 从客户端返回变量
    • Yaf_Request_Http::getCookie - 返回Cookie变量
    • Yaf_Request_Http::getFiles - The getFiles purpose
    • Yaf_Request_Http::getPost - 返回POST变量
    • Yaf_Request_Http::getQuery - fetch a query parameter
    • Yaf_Request_Http::getRaw - Retrieve Raw request body
    • Yaf_Request_Http::getRequest - The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest - 是否为Ajax请求
    • Yaf_Request_Http::__construct - The __construct purpose
    • Yaf_Request_Simple::get - The get purpose
    • Yaf_Request_Simple::getCookie - The getCookie purpose
    • Yaf_Request_Simple::getFiles - The getFiles purpose
    • Yaf_Request_Simple::getPost - The getPost purpose
    • Yaf_Request_Simple::getQuery - The getQuery purpose
    • Yaf_Request_Simple::getRequest - The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Simple::__construct - The __construct purpose
    • Yaf_Response_Abstract::appendBody - 往已有的响应body后附加新的内容
    • Yaf_Response_Abstract::clearBody - 清除已经设置的响应body
    • Yaf_Response_Abstract::clearHeaders - The clearHeaders purpose
    • Yaf_Response_Abstract::getBody - 获取已经设置的响应body
    • Yaf_Response_Abstract::getHeader - The getHeader purpose
    • Yaf_Response_Abstract::prependBody - The prependBody purpose
    • Yaf_Response_Abstract::response - send response
    • Yaf_Response_Abstract::setAllHeaders - The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody - 设置响应的Body
    • Yaf_Response_Abstract::setHeader - The setHeader purpose
    • Yaf_Response_Abstract::setRedirect - The setRedirect purpose
    • Yaf_Response_Abstract::__construct - The __construct purpose
    • Yaf_Response_Abstract::__destruct - The __destruct purpose
    • Yaf_Response_Abstract::__toString - The __toString purpose
    • Yaf_Router::addConfig - 向Router中添加配置文件中定义的路由
    • Yaf_Router::addRoute - 往Router中添加新的路由
    • Yaf_Router::getCurrentRoute - 取得当前有效的路由名
    • Yaf_Router::getRoute - The getRoute purpose
    • Yaf_Router::getRoutes - The getRoutes purpose
    • Yaf_Router::route - The route purpose
    • Yaf_Router::__construct - Yaf_Router constructor
    • Yaf_Route_Interface::assemble - 将指定路由规则组合成一个url
    • Yaf_Route_Interface::route - route a request
    • Yaf_Route_Map::assemble - 组合url
    • Yaf_Route_Map::route - The route purpose
    • Yaf_Route_Map::__construct - The __construct purpose
    • Yaf_Route_Regex::assemble - 组合url
    • Yaf_Route_Regex::route - The route purpose
    • Yaf_Route_Regex::__construct - The __construct purpose
    • Yaf_Route_Rewrite::assemble - 组合url
    • Yaf_Route_Rewrite::route - The route purpose
    • Yaf_Route_Rewrite::__construct - The __construct purpose
    • Yaf_Route_Simple::assemble - 组合url
    • Yaf_Route_Simple::route - Route a request
    • Yaf_Route_Simple::__construct - Yaf_Route_Simple constructor
    • Yaf_Route_Static::assemble - 组合url
    • Yaf_Route_Static::match - The match purpose
    • Yaf_Route_Static::route - Route a request
    • Yaf_Route_Supervar::assemble - 组合url
    • Yaf_Route_Supervar::route - The route purpose
    • Yaf_Route_Supervar::__construct - The __construct purpose
    • Yaf_Session::count - The count purpose
    • Yaf_Session::current - The current purpose
    • Yaf_Session::del - The del purpose
    • Yaf_Session::getInstance - The getInstance purpose
    • Yaf_Session::has - The has purpose
    • Yaf_Session::key - The key purpose
    • Yaf_Session::next - The next purpose
    • Yaf_Session::offsetExists - The offsetExists purpose
    • Yaf_Session::offsetGet - The offsetGet purpose
    • Yaf_Session::offsetSet - The offsetSet purpose
    • Yaf_Session::offsetUnset - The offsetUnset purpose
    • Yaf_Session::rewind - The rewind purpose
    • Yaf_Session::start - The start purpose
    • Yaf_Session::valid - The valid purpose
    • Yaf_Session::__construct - The __construct purpose
    • Yaf_Session::__get - The __get purpose
    • Yaf_Session::__isset - The __isset purpose
    • Yaf_Session::__set - The __set purpose
    • Yaf_Session::__unset - The __unset purpose
    • Yaf_View_Interface::assign - 为视图引擎分配一个模板变量
    • Yaf_View_Interface::display - 渲染一个视图模板, 并直接输出给请求端
    • Yaf_View_Interface::getScriptPath - The getScriptPath purpose
    • Yaf_View_Interface::render - 渲染一个视图模板
    • Yaf_View_Interface::setScriptPath - The setScriptPath purpose
    • Yaf_View_Simple::assign - 为视图引擎分配一个模板变量
    • Yaf_View_Simple::assignRef - The assignRef purpose
    • Yaf_View_Simple::clear - Clear Assigned values
    • Yaf_View_Simple::display - 渲染一个视图模板, 并直接输出给请求端
    • Yaf_View_Simple::eval - 渲染模板
    • Yaf_View_Simple::getScriptPath - 获取模板目录
    • Yaf_View_Simple::render - 渲染模板
    • Yaf_View_Simple::setScriptPath - 设置模板的目录
    • Yaf_View_Simple::__construct - Constructor of Yaf_View_Simple
    • Yaf_View_Simple::__get - 获取视图引擎的一个模板变量值
    • Yaf_View_Simple::__isset - The __isset purpose
    • Yaf_View_Simple::__set - 为视图引擎分配一个模板变量
    • yaml_emit - Returns the YAML representation of a value
    • yaml_emit_file - Send the YAML representation of a value to a file
    • yaml_parse - Parse a YAML stream
    • yaml_parse_file - Parse a YAML stream from a file
    • yaml_parse_url - Parse a Yaml stream from a URL
    • Yar_Client::setOpt - 设置调用的配置
    • Yar_Client::__call - 调用远程服务
    • Yar_Client::__construct - 创建一个客户端实例
    • Yar_Client_Exception::getType - The getType purpose
    • Yar_Concurrent_Client::call - 注册一个并行的服务调用
    • Yar_Concurrent_Client::loop - 发送所有注册的并行调用
    • Yar_Server::handle - 启动HTTP RPC Server
    • Yar_Server::__construct - 创建一个HTTP RPC Server
    • Yar_Server_Exception::getType - 获取异常的原始类型
    • yaz_addinfo - Returns additional error information
    • yaz_ccl_conf - Configure CCL parser
    • yaz_ccl_parse - Invoke CCL Parser
    • yaz_close - Close YAZ connection
    • yaz_connect - Prepares for a connection to a Z39.50 server
    • yaz_database - Specifies the databases within a session
    • yaz_element - Specifies Element-Set Name for retrieval
    • yaz_errno - Returns error number
    • yaz_error - Returns error description
    • yaz_es - Prepares for an Extended Service Request
    • yaz_es_result - Inspects Extended Services Result
    • yaz_get_option - Returns value of option for connection
    • yaz_hits - Returns number of hits for last search
    • yaz_itemorder - Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present - Prepares for retrieval (Z39.50 present)
    • yaz_range - Specifies a range of records to retrieve
    • yaz_record - Returns a record
    • yaz_scan - Prepares for a scan
    • yaz_scan_result - Returns Scan Response result
    • yaz_schema - Specifies schema for retrieval
    • yaz_search - Prepares for a search
    • yaz_set_option - Sets one or more options for connection
    • yaz_sort - Sets sorting criteria
    • yaz_syntax - Specifies the preferred record syntax for retrieval
    • yaz_wait - Wait for Z39.50 requests to complete
  • z
    • zend_thread_id - 返回当前线程的唯一识别符
    • zend_version - 获取当前 Zend 引擎的版本
    • ZipArchive::addEmptyDir - Add a new directory
    • ZipArchive::addFile - Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString - Add a file to a ZIP archive using its contents
    • ZipArchive::addGlob - Add files from a directory by glob pattern
    • ZipArchive::addPattern - Add files from a directory by PCRE pattern
    • ZipArchive::close - Close the active archive (opened or newly created)
    • ZipArchive::count - Counts the number of files in the archive
    • ZipArchive::deleteIndex - Delete an entry in the archive using its index
    • ZipArchive::deleteName - Delete an entry in the archive using its name
    • ZipArchive::extractTo - 解压缩文件
    • ZipArchive::getArchiveComment - Returns the Zip archive comment
    • ZipArchive::getCommentIndex - Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName - Returns the comment of an entry using the entry name
    • ZipArchive::getExternalAttributesIndex - Retrieve the external attributes of an entry defined by its index
    • ZipArchive::getExternalAttributesName - Retrieve the external attributes of an entry defined by its name
    • ZipArchive::getFromIndex - Returns the entry contents using its index
    • ZipArchive::getFromName - Returns the entry contents using its name
    • ZipArchive::getNameIndex - Returns the name of an entry using its index
    • ZipArchive::getStatusString - Returns the status error message, system and/or zip messages
    • ZipArchive::getStream - Get a file handler to the entry defined by its name (read only)
    • ZipArchive::isCompressionMethodSupported - Check if a compression method is supported by libzip
    • ZipArchive::isEncryptionMethodSupported - Check if a encryption method is supported by libzip
    • ZipArchive::locateName - Returns the index of the entry in the archive
    • ZipArchive::open - Open a ZIP file archive
    • ZipArchive::registerCancelCallback - Register a callback to allow cancellation during archive close.
    • ZipArchive::registerProgressCallback - Register a callback to provide updates during archive close.
    • ZipArchive::renameIndex - Renames an entry defined by its index
    • ZipArchive::renameName - Renames an entry defined by its name
    • ZipArchive::replaceFile - Replace file in ZIP archive with a given path
    • ZipArchive::setArchiveComment - Set the comment of a ZIP archive
    • ZipArchive::setCommentIndex - Set the comment of an entry defined by its index
    • ZipArchive::setCommentName - Set the comment of an entry defined by its name
    • ZipArchive::setCompressionIndex - Set the compression method of an entry defined by its index
    • ZipArchive::setCompressionName - Set the compression method of an entry defined by its name
    • ZipArchive::setEncryptionIndex - Set the encryption method of an entry defined by its index
    • ZipArchive::setEncryptionName - Set the encryption method of an entry defined by its name
    • ZipArchive::setExternalAttributesIndex - Set the external attributes of an entry defined by its index
    • ZipArchive::setExternalAttributesName - Set the external attributes of an entry defined by its name
    • ZipArchive::setMtimeIndex - Set the modification time of an entry defined by its index
    • ZipArchive::setMtimeName - Set the modification time of an entry defined by its name
    • ZipArchive::setPassword - Set the password for the active archive
    • ZipArchive::statIndex - Get the details of an entry defined by its index
    • ZipArchive::statName - Get the details of an entry defined by its name
    • ZipArchive::unchangeAll - Undo all changes done in the archive
    • ZipArchive::unchangeArchive - Revert all global changes done in the archive
    • ZipArchive::unchangeIndex - Revert all changes done to an entry at the given index
    • ZipArchive::unchangeName - Revert all changes done to an entry with the given name
    • Zip context options - Zip context option listing
    • zip_close - 关闭一个ZIP档案文件
    • zip_entry_close - 关闭目录项
    • zip_entry_compressedsize - 检索目录项压缩过后的大小
    • zip_entry_compressionmethod - 检索目录实体的压缩方法
    • zip_entry_filesize - 检索目录实体的实际大小
    • zip_entry_name - 检索目录项的名称
    • zip_entry_open - 打开用于读取的目录实体
    • zip_entry_read - 读取一个打开了的压缩目录实体
    • zip_open - 打开ZIP存档文件
    • zip_read - 读取ZIP存档文件中下一项
    • zlib:// - 压缩流
    • zlib_decode - Uncompress any raw/gzip/zlib encoded data
    • zlib_encode - Compress data with the specified encoding
    • zlib_get_coding_type - Returns the coding type used for output compression
    • ZMQ::__construct - ZMQ constructor
    • ZMQContext::getOpt - Get context option
    • ZMQContext::getSocket - Create a new socket
    • ZMQContext::isPersistent - Whether the context is persistent
    • ZMQContext::setOpt - Set a socket option
    • ZMQContext::__construct - Construct a new ZMQContext object
    • ZMQDevice::getIdleTimeout - Get the idle timeout
    • ZMQDevice::getTimerTimeout - Get the timer timeout
    • ZMQDevice::run - Run the new device
    • ZMQDevice::setIdleCallback - Set the idle callback function
    • ZMQDevice::setIdleTimeout - Set the idle timeout
    • ZMQDevice::setTimerCallback - Set the timer callback function
    • ZMQDevice::setTimerTimeout - Set the timer timeout
    • ZMQDevice::__construct - Construct a new device
    • ZMQPoll::add - Add item to the poll set
    • ZMQPoll::clear - Clear the poll set
    • ZMQPoll::count - Count items in the poll set
    • ZMQPoll::getLastErrors - Get poll errors
    • ZMQPoll::poll - Poll the items
    • ZMQPoll::remove - Remove item from poll set
    • ZMQSocket::bind - Bind the socket
    • ZMQSocket::connect - Connect the socket
    • ZMQSocket::disconnect - Disconnect a socket
    • ZMQSocket::getEndpoints - Get list of endpoints
    • ZMQSocket::getPersistentId - Get the persistent id
    • ZMQSocket::getSocketType - Get the socket type
    • ZMQSocket::getSockOpt - Get socket option
    • ZMQSocket::isPersistent - Whether the socket is persistent
    • ZMQSocket::recv - Receives a message
    • ZMQSocket::recvMulti - Receives a multipart message
    • ZMQSocket::send - Sends a message
    • ZMQSocket::sendmulti - Sends a multipart message
    • ZMQSocket::setSockOpt - Set a socket option
    • ZMQSocket::unbind - Unbind the socket
    • ZMQSocket::__construct - Construct a new ZMQSocket
    • Zookeeper::addAuth - Specify application credentials
    • Zookeeper::close - Close the zookeeper handle and free up any resources
    • Zookeeper::connect - Create a handle to used communicate with zookeeper
    • Zookeeper::create - Create a node synchronously
    • Zookeeper::delete - Delete a node in zookeeper synchronously
    • Zookeeper::exists - Checks the existence of a node in zookeeper synchronously
    • Zookeeper::get - Gets the data associated with a node synchronously
    • Zookeeper::getAcl - Gets the acl associated with a node synchronously
    • Zookeeper::getChildren - Lists the children of a node synchronously
    • Zookeeper::getClientId - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
    • Zookeeper::getConfig - Get instance of ZookeeperConfig
    • Zookeeper::getRecvTimeout - Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect
    • Zookeeper::getState - Get the state of the zookeeper connection
    • Zookeeper::isRecoverable - Checks if the current zookeeper connection state can be recovered
    • Zookeeper::set - Sets the data associated with a node
    • Zookeeper::setAcl - Sets the acl associated with a node synchronously
    • Zookeeper::setDebugLevel - Sets the debugging level for the library
    • Zookeeper::setDeterministicConnOrder - Enable/disable quorum endpoint order randomization
    • Zookeeper::setLogStream - Sets the stream to be used by the library for logging
    • Zookeeper::setWatcher - Set a watcher function
    • Zookeeper::__construct - Create a handle to used communicate with zookeeper
    • ZookeeperConfig::add - Add servers to the ensemble
    • ZookeeperConfig::get - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
    • ZookeeperConfig::remove - Remove servers from the ensemble
    • ZookeeperConfig::set - Change ZK cluster ensemble membership and roles of ensemble peers
    • zookeeper_dispatch - Calls callbacks for pending operations
  • _
    • __autoload - 尝试加载未定义的类
    • __halt_compiler - 中断编译器的执行
  • ?
    • 套接字上下文选项 - 套接字上下文选项列表

User Contributed Notes

tudorsfatosu at yahoo dot dot com 20-Jun-2019 01:18
A new update regarding the number of entries in the list. We are currently at 11033 entries, in June 2019
crabovwik at yandex dot ru 07-Jan-2019 04:40
Today 07-01-2019 [dd.mm.yyyy]

10934 functions in this list ??
valbou26 at hotmail dot com 13-Apr-2018 09:29
Today : 2018-04-13
10641 functions in this list !

Keep growing ;)
Pieter Bootsma 10-Nov-2017 10:11
As of today, 10-11-2017 [dd-mm-yyyy], there are exactly 10102 functions listed above.
Geordy James 21-Apr-2017 06:18
In case anybody wondering as of 21/04/2017 [dd/mm/yyyy] there are exactly 9957 Functions listed above.
php at vanviegen dot net 14-Feb-2017 08:23
Here's a little script that scrapes all PHP function names from this page, and outputs a prefix-compressed Perl Compatible Regular Expression matching them. Useful for syntax highlighting.

<?php

$html = file_get_contents('http://php.net/manual/en/indexes.functions.php');

preg_match_all('/<li><a href="function.[^>]*>([a-zA-Z0-9_]*)<\/a>/', $html, $matches);
$funcs = $matches[1];

print '\b(?:';
$prefixes = [''];

foreach($funcs as $i => $func) {
    while(substr($func, 0, strlen($prefixes[0])) !== $prefixes[0]) {
        print ")";
        array_shift($prefixes);
    }
    if ($i) print '|';

    while(true) {
        $common = $func;
        for($j = $i+1; $j < count($funcs); $j++) {
            $lookAhead = $funcs[$j];
            $maxLen = min(strlen($lookAhead), strlen($func));
            for($ch = 0; $ch < $maxLen; $ch++) {
                if ($lookAhead[$ch] !== $func[$ch]) break;
            }
            $newCommon = substr($common, 0, $ch);
            if (strlen($newCommon) < strlen($prefixes[0])+2) break;
            $common = $newCommon;
        }
        if ($j < $i+4) break; // at least 4 functions with a common prefix of at least 2 chars
        print substr($common, strlen($prefixes[0])) . "(?:";
        array_unshift($prefixes, $common);
    }

    print substr($func, strlen($prefixes[0]));
}

print ')\b';
pn at bptv dot eu 13-Jul-2016 09:02
There are (07/13/2016 [mm/dd/yyyy]) exactly 9455 Functions listed above.
DIA 14-Apr-2016 09:42
Total number of functions listed above: 9450.
(04/14/2016 [mm/dd/yyyy])
M.A.Y 01-Jan-2016 07:39
Total number of php functions/methods listed above are 9634.
Today's date is 1/1/2016. (mm/dd/yy)
counter at county dot co 07-Apr-2015 02:17
In case anyone was wondering, the total function/method count in this list as of this date is exactly 9457


示例列表

手册中所有示例的列表

  • Example#0 - 一个介绍性的范例
  • Example#1 - 第一个 PHP 脚本：hello.php
  • Example#2 - 从 PHP 获取系统信息
  • Example#3 - 打印一个变量（数组元素）
  • Example#4 - 流程控制与函数的使用
  • Example#5 - 混和 HTML 和 PHP 模式
  • Example#6 - 一个简单的 HTML 表单
  • Example#7 - 打印来自表单的数据
  • Example#8 - PHP 的 Apache 共享模块版本安装说明
  • Example#9 - PHP 的 Apache 静态模块版本安装说明
  • Example#10 - 重启动 Apache 的示例命令
  • Example#11 -
  • Example#12 -
  • Example#13 -
  • Example#14 -
  • Example#15 -
  • Example#16 -
  • Example#17 -
  • Example#18 -
  • Example#19 -
  • Example#20 -
  • Example#21 -
  • Example#22 -
  • Example#23 -
  • Example#24 - Partial lighttpd.conf
  • Example#25 - 产生 FastCGI 应答器
  • Example#26 - 连接远程 php-fastcgi 实例
  • Example#27 -
  • Example#28 -
  • Example#29 - 在 OpenBSD 系统下的软件包的安装示例
  • Example#30 - Debian 下将 PHP 安装入 Apache 2 的例子
  • Example#31 - 安装完 PHP 后停止并启动 Apache
  • Example#32 - 取得 PHP 附加软件包的列表
  • Example#33 - 安装 PHP 的 MySQL 和 cURL 支持
  • Example#34 - 推荐的 OpCache 配置
  • Example#35 - 推荐的 WinCache 配置
  • Example#36 - 命令行下配置 IIS 和 PHP
  • Example#37 - PHP 5 压缩包的结构
  • Example#38 - php.ini 中的 CGI 和 FastCGI 设定
  • Example#39 - 配置 FastCGI 扩展以处理 PHP 请求
  • Example#40 - 配置文件访问权限
  • Example#41 - 配置 FastCGI 和 PHP 的回收
  • Example#42 - 配置 FastCGI 超时设定
  • Example#43 - 改变 php.ini 文件的位置
  • Example#44 - php.ini 中的 CGI 和 FastCGI 设定
  • Example#45 - 创建 IIS FastCGI 处理池
  • Example#46 - 创建对应于 PHP 请求的处理程序映射
  • Example#47 - 确定用于 IIS 匿名认证的用户帐号
  • Example#48 - 配置文件访问权限
  • Example#49 - 将 index.php 设为 IIS 的默认文档
  • Example#50 - 配置 FastCGI 和 PHP 的回收
  • Example#51 - 配置 FastCGI 超时设定
  • Example#52 - 改变 php.ini 文件的位置
  • Example#53 - PHP 作为 Apache 1.3.x 的一个模块
  • Example#54 - PHP 以 CGI 方式运行在 Apache 1.3.x
  • Example#55 - PHP 在 Apache 2.x 中作为 handler
  • Example#56 -
  • Example#57 - Apache 2.x 下 CGI 方式的 PHP
  • Example#58 - 配置 Apache 以 FastCGI 方式运行 PHP
  • Example#59 - Sambar 的 ISAPI 设置
  • Example#60 - 在 Windows 下启用 Bzip2 扩展库
  • Example#61 - 注册表变化
  • Example#62 - 给运行池传递环境变量和设置 PHP 的配置值
  • Example#63 - 在 nginx.conf 中设定 PHP
  • Example#64 - phpinfo call
  • Example#65 - php.ini 中的环境变量
  • Example#66 - php.ini 例子
  • Example#67 - Apache 配置例子
  • Example#68 - PHP 开始和结束标记
  • Example#69 - 使用条件的高级分离术
  • Example#70 - 包含末尾换行符的结束标记的例子
  • Example#71 - 整数文字表达
  • Example#72 - 32 位系统下的整数溢出
  • Example#73 - 64 位系统下的整数溢出
  • Example#74 - 非法的示例
  • Example#75 - Heredoc 结构的字符串示例
  • Example#76 - Heredoc 结构在参数中的示例
  • Example#77 - 使用 Heredoc 结构来初始化静态值
  • Example#78 - 在 heredoc 结构中使用双引号
  • Example#79 - Nowdoc 结构字符串示例
  • Example#80 - 静态数据的示例
  • Example#81 - 简单语法示例
  • Example#82 - 一些字符串示例
  • Example#83 - PHP 5.3 和 PHP 5.4 的区别
  • Example#84 - 一个简单数组
  • Example#85 - 类型强制与覆盖示例
  • Example#86 - 混合 integer 和 string 键名
  • Example#87 - 没有键名的索引数组
  • Example#88 - 仅对部分单元指定键名
  • Example#89 - 访问数组单元
  • Example#90 - 数组解引用
  • Example#91 - 使用 array()
  • Example#92 - 集合
  • Example#93 - 在循环中改变单元
  • Example#94 - 下标从 1 开始的数组
  • Example#95 - 填充数组
  • Example#96 - 数组排序
  • Example#97 - 递归和多维数组
  • Example#98 - Iterable 可迭代参数类型示例
  • Example#99 - 可迭代参数默认值示例
  • Example#100 - 可迭代返回类型示例
  • Example#101 - 可迭代生成器返回类型的示例
  • Example#102 - 可迭代的类型协变示例
  • Example#103 - 回调函数示例
  • Example#104 - 使用 Closure 的示例
  • Example#105 -
  • Example#106 - 在类中使用类型声明
  • Example#107 - 在接口中使用类型声明
  • Example#108 - 返回类型声明
  • Example#109 - 返回一个对象
  • Example#110 - 定义可空（Nullable）的参数类型
  • Example#111 - 定义可空（Nullable）的返回类型
  • Example#112 - 旧版本中实现允许为空参数的示例
  • Example#113 - 参数值的严格类型
  • Example#114 - 参数值的类型强制转化
  • Example#115 - 返回值的严格类型
  • Example#116 - 类型强制转换为联合类型的例子
  • Example#117 - 传引用参数的类型
  • Example#118 - 捕获 TypeError
  • Example#119 - 未初始化变量的默认值
  • Example#120 - 使用 global
  • Example#121 - 使用 $GLOBALS 替代 global
  • Example#122 - 演示超全局变量和作用域的例子
  • Example#123 - 演示需要静态变量的例子
  • Example#124 - 使用静态变量的例子
  • Example#125 - 静态变量与递归函数
  • Example#126 - 声明静态变量
  • Example#127 - 可变属性示例
  • Example#128 - 一个简单的 HTML 表单
  • Example#129 - 从一个简单的 POST HTML 表单访问数据
  • Example#130 - 更复杂的表单变量
  • Example#131 - 一个 setcookie 的示例
  • Example#132 - 合法与非法的常量名
  • Example#133 - 定义常量
  • Example#134 - 使用关键字 const 定义常量
  • Example#135 - 结合方向
  • Example#136 - Undefined order of evaluation
  • Example#137 - +、- 、. 具有相同的优先级
  • Example#138 - 引用赋值
  • Example#139 - 整数的 AND，OR 和 XOR 位运算符
  • Example#140 - 字符串的 XOR 运算符
  • Example#141 - 整数的位移
  • Example#142 - Boolean/null comparison
  • Example#143 - 标准数组比较代码
  • Example#144 - 赋默认值
  • Example#145 - 不清晰的三元运算符行为
  • Example#146 - 设置默认值
  • Example#147 - 嵌套 NULL 合并运算符
  • Example#148 - 涉及字符变量的算数运算
  • Example#149 - 逻辑运算符示例
  • Example#150 - 比较数组
  • Example#151 - 对类使用 instanceof
  • Example#152 - 对继承类使用 instanceof
  • Example#153 - 使用 instanceof 检查对象不是某个类的实例
  • Example#154 - 对接口使用 instanceof
  • Example#155 - 对其它变量使用 instanceof
  • Example#156 - 用 instanceof 检测其它变量
  • Example#157 - 使用 instanceof 测试常量
  • Example#158 - switch 结构
  • Example#159 - switch 结构可以用 string
  • Example#160 - Structure of a match expression
  • Example#161 - Example of an unhandled match expression
  • Example#162 - Using a generalized match expressions to branch on integer ranges
  • Example#163 - Using a generalized match expressions to branch on string content
  • Example#164 - Tick 的用法示例
  • Example#165 - Ticks 的用法示例
  • Example#166 - 对脚本指定编码方式
  • Example#167 - 基本的 include 例子
  • Example#168 - 函数中的包含
  • Example#169 - 通过 HTTP 进行的 include
  • Example#170 - 比较 include 的返回值
  • Example#171 - include 和 return 语句
  • Example#172 - 使用输出缓冲来将 PHP 文件包含入一个字符串
  • Example#173 - goto 示例
  • Example#174 - goto 跳出循环示例
  • Example#175 - 以下写法无效
  • Example#176 - 展示函数用途的伪代码
  • Example#177 - 有条件的函数
  • Example#178 - 函数中的函数
  • Example#179 - 递归函数
  • Example#180 - 向函数传递数组
  • Example#181 - 函数参数使用尾部逗号
  • Example#182 - Passing optional arguments after mandatory arguments
  • Example#183 - 用引用传递函数参数
  • Example#184 - 在函数中使用默认参数
  • Example#185 - 使用非标量类型作为默认参数
  • Example#186 - 函数默认参数的不正确用法
  • Example#187 - 函数默认参数正确的用法
  • Example#188 - 使用 ... 来访问变量参数
  • Example#189 - 使用 ... 来传递参数
  • Example#190 - 输入提示的变量参数
  • Example#191 - 在 PHP 早期版本中访问可变参数
  • Example#192 - 命名参数的语法
  • Example#193 - 通过位置传参与命名参数的对比
  • Example#194 - 参数顺序不同的示例（同上例）
  • Example#195 - 命名参数与位置参数结合使用
  • Example#196 - Error exception when passing the same parameter multiple times
  • Example#197 - return 的使用
  • Example#198 - 返回一个数组以得到多个返回值
  • Example#199 - 从函数返回一个引用
  • Example#200 - 可变函数示例
  • Example#201 - 可变方法范例
  • Example#202 - Variable 方法和静态属性示例
  • Example#203 - Complex callables
  • Example#204 - 匿名函数示例
  • Example#205 - 匿名函数变量赋值示例
  • Example#206 - 从父作用域继承变量
  • Example#207 - Closures 和作用域
  • Example#208 - 自动绑定 $this
  • Example#209 - 试图在静态匿名函数中使用 $this
  • Example#210 - 试图将对象绑定到静态匿名函数
  • Example#211 - 箭头函数自动捕捉变量的值
  • Example#212 - 箭头函数自动捕捉变量的值，即使在嵌套的情况下
  • Example#213 - 合法的箭头函数例子
  • Example#214 - 来自外部范围的值不能在箭头函数内修改
  • Example#215 - 简单的类定义
  • Example#216 - 使用 $this 伪变量的示例
  • Example#217 - 创建实例
  • Example#218 - 对象赋值
  • Example#219 - 创建新对象
  • Example#220 - 访问新创建对象的成员
  • Example#221 - 访问类属性 vs. 调用类方法
  • Example#222 - 类属性被赋值为匿名函数时的调用示例
  • Example#223 - 简单的类继承
  • Example#224 - Compatible child methods
  • Example#225 - Fatal error when a child method removes a parameter
  • Example#226 - Fatal error when a child method makes an optional parameter mandatory
  • Example#227 - Error when using named arguments and parameters were renamed in a child class
  • Example#228 - 类名的解析
  • Example#229 - 解析不存在的类名
  • Example#230 - 类名解析
  • Example#231 - Nullsafe 操作符
  • Example#232 - 属性声明
  • Example#233 - 示例：使用 nowdoc 初始化属性
  • Example#234 - 定义和使用一个类常量
  • Example#235 - 静态数据示例
  • Example#236 - 自动加载示例
  • Example#237 - 另一个例子
  • Example#238 - 自动加载在 PHP 5.3.0+ 中的异常处理
  • Example#239 - 自动加载在 PHP 5.3.0+ 中的异常处理 - 没有自定义异常机制
  • Example#240 - 继承中的构造函数
  • Example#241 - 使用构造器参数
  • Example#242 - 使用构造器属性提升
  • Example#243 - 使用 static 创造方法
  • Example#244 - 析构函数示例
  • Example#245 - 属性声明
  • Example#246 - 方法声明
  • Example#247 - PHP 7.1.0 中的常量声明
  • Example#248 - 访问同一个对象类型的私有成员
  • Example#249 - 继承示例
  • Example#250 - 在类的外部使用 :: 操作符
  • Example#251 - 在类定义内部使用 ::
  • Example#252 - 调用父类的方法
  • Example#253 - 静态方法示例
  • Example#254 - 静态属性示例
  • Example#255 - 抽象类示例
  • Example#256 - 抽象类示例
  • Example#257 - 接口示例
  • Example#258 - 可扩充的接口
  • Example#259 - 继承多个接口
  • Example#260 - 使用接口常量
  • Example#261 - Trait 示例
  • Example#262 - 优先顺序示例
  • Example#263 - 另一个优先级顺序的例子
  • Example#264 - 多个 trait 的用法
  • Example#265 - 冲突的解决
  • Example#266 - 修改方法的访问控制
  • Example#267 - 从 trait 来组成 trait
  • Example#268 - 表示通过抽象方法来进行强制要求
  • Example#269 - 静态变量
  • Example#270 - 静态方法
  • Example#271 - 定义属性
  • Example#272 - 解决冲突
  • Example#273 - 使用 __get()，__set()，__isset() 和 __unset() 进行属性重载
  • Example#274 - 使用 __call() 和 __callStatic() 对方法重载
  • Example#275 - 简单的对象遍历
  • Example#276 - 实现 Iterator 接口的对象遍历
  • Example#277 - 通过实现 IteratorAggregate 来遍历对象
  • Example#278 - Sleep 和 wakeup
  • Example#279 - 序列化和反序列化
  • Example#280 - 简单示例
  • Example#281 - 使用 __invoke()
  • Example#282 - 使用 __set_state()>（PHP 5.1.0 起）
  • Example#283 - Using __debugInfo()
  • Example#284 - Final 方法示例
  • Example#285 - Final 类示例
  • Example#286 - 复制一个对象
  • Example#287 - PHP 5 的对象比较
  • Example#288 - self:: 用法
  • Example#289 - static:: 简单用法
  • Example#290 - 非静态环境下使用 static::
  • Example#291 - 转发和非转发调用
  • Example#292 - 引用和对象
  • Example#293 - 命名空间语法示例
  • Example#294 - 声明单个命名空间
  • Example#295 - 声明单个命名空间
  • Example#296 - 声明分层次的单个命名空间
  • Example#297 - 定义多个命名空间，简单组合语法
  • Example#298 - 定义多个命名空间，大括号语法
  • Example#299 - 定义多个命名空间和不包含在命名空间中的代码
  • Example#300 - 定义多个命名空间和不包含在命名空间中的代码
  • Example#301 - 在命名空间内部访问全局类、函数和常量
  • Example#302 - 动态访问元素
  • Example#303 - 动态访问命名空间的元素
  • Example#304 - __NAMESPACE__ 示例, 在命名空间中的代码
  • Example#305 - __NAMESPACE__ 示例，全局代码
  • Example#306 - 使用 __NAMESPACE__ 动态创建名称
  • Example#307 - namespace 操作符，命名空间中的代码
  • Example#308 - namespace 操作符, 全局代码
  • Example#309 - 使用 use 操作符导入/使用别名
  • Example#310 - 通过 use 操作符导入/使用别名，一行中包含多个 use 语句
  • Example#311 - 导入和动态名称
  • Example#312 - 导入和完全限定名称
  • Example#313 - Illegal importing rule
  • Example#314 - 使用全局空间说明
  • Example#315 - 在命名空间中访问全局类
  • Example#316 - 命名空间中后备的全局函数/常量
  • Example#317 - 名称解析示例
  • Example#318 - Accessing global classes outside a namespace
  • Example#319 - Accessing global classes outside a namespace
  • Example#320 - Accessing internal classes in namespaces
  • Example#321 - Accessing internal classes, functions or constants in namespaces
  • Example#322 - Fully Qualified names
  • Example#323 - Qualified names
  • Example#324 - Unqualified class names
  • Example#325 - Unqualified function or constant names
  • Example#326 - Dangers of using namespaced names inside a double-quoted string
  • Example#327 - Undefined constants
  • Example#328 - Undefined constants
  • Example#329 - 内置的异常处理类
  • Example#330 - 扩展 PHP 内置的异常处理类
  • Example#331 - 将错误报告转成异常
  • Example#332 - 抛出一个异常
  • Example#333 - 带 finally 块的异常处理
  • Example#334 - finally 和 return 相互之间的影响
  • Example#335 - 异常嵌套
  • Example#336 - 多个异常的捕获处理
  • Example#337 - 忽略捕获的变量
  • Example#338 - 以表达式的形式抛出
  • Example#339 - 将 range 实现为生成器
  • Example#340 - 一个简单的生成值的例子
  • Example#341 - 生成一个键值对
  • Example#342 - 生成nulls
  • Example#343 - 使用引用来生成值
  • Example#344 - yield from with iterator_to_array
  • Example#345 - yield from 的基本用法
  • Example#346 - yield from 并返回多个值
  • Example#347 - 用注解实现接口的可选方法
  • Example#348 - 注解语法
  • Example#349 - 通过反射 API 读取注解
  • Example#350 - 使用反射 API 读取指定的注解
  • Example#351 - 目标限定使用的注解
  • Example#352 - 简单的 Attribute 类
  • Example#353 - 使用 IS_REPEATABLE 允许注解在声明中出现多次
  • Example#354 - 对未定义的变量使用引用
  • Example#355 - 在函数内引用全局变量
  • Example#356 - 引用与 foreach 语句
  • Example#357 - $GLOBALS 范例
  • Example#358 - $_SERVER 范例
  • Example#359 - $_GET 范例
  • Example#360 - $_POST 范例
  • Example#361 - $_ENV 范例
  • Example#362 - $_COOKIE 范例
  • Example#363 - $php_errormsg 范例
  • Example#364 - $http_response_header 范例
  • Example#365 - $argc 范例
  • Example#366 - $argv 范例
  • Example#367 - Exception::getMessage示例
  • Example#368 - Exception::getPrevious示例
  • Example#369 - Exception::getCode示例
  • Example#370 - Exception::getFile示例
  • Example#371 - Exception::getLine示例
  • Example#372 - Exception::getTrace示例
  • Example#373 - Exception::getTraceAsString示例
  • Example#374 - Exception::__toString示例
  • Example#375 - 使用set_error_handler函数将错误信息托管至ErrorException
  • Example#376 - ErrorException::getSeverity 例子
  • Example#377 - Error::getMessage 例子
  • Example#378 - Error::getPrevious 例子
  • Example#379 - Error::getCode 例子
  • Example#380 - Error::getFile 例子
  • Example#381 - Error::getLine 例子
  • Example#382 - Error::getTrace 例子
  • Example#383 - Error::getTraceAsString 例子
  • Example#384 - Error::__toString 例子
  • Example#385 - 基本用法
  • Example#386 - 基本用法
  • Example#387 - Basic usage
  • Example#388 - ArrayAccess::offsetExists 范例
  • Example#389 - Basic usage
  • Example#390 - Closure::bind 实例
  • Example#391 - Closure::bindTo 实例
  • Example#392 - Generator::key example
  • Example#393 - 用 Generator::send 向生成器函数中传值
  • Example#394 - Basic bindto usage example
  • Example#395 - 获取一个页面并发送 POST 数据
  • Example#396 - 忽略重定向并获取 header 和内容
  • Example#397 - 获取一个页面，并以POST发送数据
  • Example#398 - Basic password usage example
  • Example#399 - 检测重定向后最终的 URL
  • Example#400 - php://temp/maxmemory
  • Example#401 - php://filter/resource=<待过滤的数据流>
  • Example#402 - php://filter/read=<读链需要应用的过滤器列表>
  • Example#403 - php://filter/write=<写链需要应用的过滤器列表>
  • Example#404 - php://memory 和 php://temp 是一次性的
  • Example#405 - 打印 data:// 的内容
  • Example#406 - 获取媒体类型
  • Example#407 - 基本用法
  • Example#408 - 从一个活动连接中打开字节流
  • Example#409 - This $session variable must be kept available!
  • Example#410 - Traversing a RAR archive
  • Example#411 - Opening an encrypted file (header encryption)
  • Example#412 - 不对变量进行安全检查会导致……
  • Example#413 - ……文件系统攻击
  • Example#414 - 更安全的文件名检查
  • Example#415 - 更安全的文件名检查
  • Example#416 - 会被 Null 字符问题攻击的代码
  • Example#417 - 验证输入的正确做法
  • Example#418 - Hashing password field
  • Example#419 - 一段实现数据分页显示的代码…… 也可以被用作创建一个超级用户（PostgreSQL 数据库）。
  • Example#420 - 显示文章……以及一些密码（任何数据库系统）
  • Example#421 - 从重设密码……到获得更多权限（任何数据库系统）
  • Example#422 - 攻击数据库所在主机的操作系统（MSSQL Server 数据库）
  • Example#423 - 一个实现分页更安全的方法
  • Example#424 - 用自定义的 HTML 页面攻击变量
  • Example#425 - 利用变量打开调式功能
  • Example#426 - 用 E_ALL 来查找危险的变量
  • Example#427 - 危险的变量用法
  • Example#428 - 把 PHP 隐藏为另一种语言
  • Example#429 - 使用未知的扩展名作为 PHP 的扩展名
  • Example#430 - 用 HTML 做 PHP 的文件后缀
  • Example#431 - Basic HTTP 认证范例
  • Example#432 - Digest HTTP 认证范例
  • Example#433 - 强迫重新输入用户名和密码的 HTTP 认证的范例
  • Example#434 - 一个简单的 XForms 搜索表单
  • Example#435 - 使用 XForm 来产生 $_POST
  • Example#436 - 文件上传表单
  • Example#437 - 验证上传的文件
  • Example#438 - 上传一组文件
  • Example#439 - 上传多个文件
  • Example#440 - 保存 HTTP PUT 文件
  • Example#441 - 获取远程文件的标题
  • Example#442 - 将数据保存到远程服务器
  • Example#443 -
  • Example#444 - 使用该参数，PHP 将打印出内置以及已加载的 PHP 及 Zend 模块：
  • Example#445 - 显示双引号语法解析错误的范例
  • Example#446 - Using single quotes to prevent the shell's variable substitution
  • Example#447 - 使用 -B，-R 和 -E 选项来计算一个项目总行数的例子。
  • Example#448 - 使用 -v 将 PHP、SAPI 名称和 Zend 的版本信息写入标准输出。
  • Example#449 - --ini example
  • Example#450 - basic --rf usage
  • Example#451 - --rc example
  • Example#452 - --re example
  • Example#453 - --ri example
  • Example#454 - Execute PHP script as shell script
  • Example#455 - 试图以命令行方式运行的 PHP 脚本（script.php）
  • Example#456 - 运行 PHP 命令行脚本的批处理文件（script.bat）
  • Example#457 - Executing code using the interactive shell
  • Example#458 - Tab completion
  • Example#459 - Setting php.ini settings in the interactive shell
  • Example#460 - 启动Web服务器
  • Example#461 - 启动时指定根目录
  • Example#462 - 使用路由（Router）脚本
  • Example#463 - 生成一个新的zval容器
  • Example#464 - 显示zval信息
  • Example#465 - 增加一个zval的引用计数
  • Example#466 - 减少引用计数
  • Example#467 - Creating a array zval
  • Example#468 - 添加一个已经存在的元素到数组中
  • Example#469 - 从数组中删除一个元素
  • Example#470 - 把数组作为一个元素添加到自己
  • Example#471 - Unsetting $a
  • Example#472 - Memory usage example
  • Example#473 - GC性能影响
  • Example#474 - 执行以上脚本
  • Example#475 - 重新编译PHP以启用GC benchmarking
  • Example#476 - GC 统计数据
  • Example#477 - all_probes.d for tracing all PHP Static Probes with DTrace
  • Example#478 - all_probes.stp for tracing all PHP Static Probes with SystemTap
  • Example#479 - A apcu_add example
  • Example#480 - A apcu_cache_info example
  • Example#481 - apcu_cas example
  • Example#482 - apcu_dec example
  • Example#483 - A apcu_delete example
  • Example#484 - An apcu_entry example
  • Example#485 - apcu_exists example
  • Example#486 - A apcu_fetch example
  • Example#487 - apcu_inc example
  • Example#488 - A apcu_key_info example
  • Example#489 - A apcu_sma_info example
  • Example#490 - A apcu_store example
  • Example#491 - A APCUIterator::__construct example
  • Example#492 - 在脚本中使用错误句柄
  • Example#493 - debug_backtrace 范例
  • Example#494 - debug_print_backtrace 范例
  • Example#495 - error_clear_last 例子
  • Example#496 - An error_get_last 范例
  • Example#497 - error_log 范例
  • Example#498 - error_reporting 范例
  • Example#499 - restore_error_handler 范例
  • Example#500 - restore_exception_handler 范例
  • Example#501 - 用 set_error_handler 和 trigger_error 进行错误处理
  • Example#502 - set_exception_handler 范例
  • Example#503 - trigger_error 示例
  • Example#504 - Calling a function from shared library
  • Example#505 - Calling a function, returning a structure through an argument
  • Example#506 - Accessing existing C variables
  • Example#507 - Creating and Modifying C variables
  • Example#508 - Working with C arrays
  • Example#509 - Working with C enums
  • Example#510 -
  • Example#511 -
  • Example#512 - Creating large array in a function
  • Example#513 - 输出控制举例
  • Example#514 - ob_end_clean example
  • Example#515 - ob_end_flush example
  • Example#516 - A simple ob_get_clean example
  • Example#517 - A simple ob_get_contents example
  • Example#518 - ob_get_flush example
  • Example#519 - A simple ob_get_length example
  • Example#520 - ob_gzhandler example
  • Example#521 - ob_list_handlers example
  • Example#522 - 用户自定义回调函数的例子
  • Example#523 - 以兼容 PHP 5.3 和 5.4 的方式创建一个不可擦除的输出缓冲区
  • Example#524 - output_add_rewrite_var example
  • Example#525 - output_reset_rewrite_vars example
  • Example#526 - assert_options 例子
  • Example#527 - 使用自定义处理程序处理失败的断言
  • Example#528 - 使用自定义处理器打印描述信息
  • Example#529 - Expectations without a custom exception
  • Example#530 - Expectations with a custom exception
  • Example#531 - cli_get_process_title example
  • Example#532 - cli_set_process_title example
  • Example#533 - dl 例子
  • Example#534 - extension_loaded 例子
  • Example#535 - 一个 gc_enabled 例子
  • Example#536 - gc_status Usage
  • Example#537 - get_current_user 例子
  • Example#538 - get_defined_constants 例子
  • Example#539 - 打印 XML 函数
  • Example#540 - get_include_path 例子
  • Example#541 - get_included_files 范例
  • Example#542 - get_loaded_extensions 范例
  • Example#543 - get_magic_quotes_runtime 例子
  • Example#544 - Unfiltered get_resources
  • Example#545 - Filtered get_resources
  • Example#546 - getenv 例子
  • Example#547 - getlastmod 例子
  • Example#548 - getopt 例子：基本用法
  • Example#549 - getopt 例子：引入长选项
  • Example#550 - getopt 例子：传递同一多个选项
  • Example#551 - getopt 例子：使用 optind
  • Example#552 - getrusage 例子
  • Example#553 - ini_get_all 例子
  • Example#554 - 禁用 details
  • Example#555 - 一些 ini_get 例子
  • Example#556 - ini_restore 例子
  • Example#557 - 设置一个 ini 选项
  • Example#558 - 一个 memory_get_usage 例子
  • Example#559 - php_ini_loaded_file 例子
  • Example#560 - 列出返回的 ini 文件的简单例子
  • Example#561 - php_sapi_name 例子
  • Example#562 - 一些 php_uname 的例子
  • Example#563 - 一些系统相关常量的例子
  • Example#564 - 打印普遍名单
  • Example#565 - 打印核心开发者和文档组
  • Example#566 - 打印所有贡献者
  • Example#567 - phpinfo 范例
  • Example#568 - phpversion 范例
  • Example#569 - PHP_VERSION_ID 范例和用法
  • Example#570 - 设置一个环境变量
  • Example#571 - restore_include_path 例子
  • Example#572 - set_include_path 例子
  • Example#573 - 添加到include path
  • Example#574 - sys_get_temp_dir 例子
  • Example#575 - version_compare examples
  • Example#576 - zend_thread_id 例子
  • Example#577 - zend_version 例子
  • Example#578 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#579 - A runkit7_function_add example
  • Example#580 - A runkit7_function_copy example
  • Example#581 - A runkit7_function_redefine example
  • Example#582 - runkit7_method_add example
  • Example#583 - runkit7_method_copy example
  • Example#584 - runkit7_method_redefine example
  • Example#585 - runkit7_method_remove example
  • Example#586 - runkit7_method_rename example
  • Example#587 - Basic uopz_add_function Usage
  • Example#588 - uopz_allow_exit example
  • Example#589 - uopz_backup example
  • Example#590 - uopz_compose example
  • Example#591 - uopz_copy example
  • Example#592 - Basic uopz_del_function Usage
  • Example#593 - uopz_delete example
  • Example#594 - uopz_delete class example
  • Example#595 - uopz_extend example
  • Example#596 - uopz_flags example
  • Example#597 - "Unfinalize" a Class
  • Example#598 - uopz_function example
  • Example#599 - uopz_function class example
  • Example#600 - uopz_get_exit_status example
  • Example#601 - Basic uopz_get_hook Usage
  • Example#602 - uopz_get_mock example
  • Example#603 - Basic uopz_get_property Usage
  • Example#604 - uopz_get_return example
  • Example#605 - Basic uopz_get_static Usage
  • Example#606 - uopz_implement example
  • Example#607 - uopz_overload example
  • Example#608 - uopz_redefine example
  • Example#609 - uopz_rename example
  • Example#610 - uopz_rename class example
  • Example#611 - uopz_restore example
  • Example#612 - Basic uopz_set_hook Usage
  • Example#613 - uopz_set_mock example
  • Example#614 - uopz_set_mock example
  • Example#615 - uopz_set_mock and static members
  • Example#616 - Basic uopz_set_property Usage
  • Example#617 - uopz_set_return example
  • Example#618 - uopz_set_return example
  • Example#619 - uopz_set_return class example
  • Example#620 - Basic uopz_set_static Usage
  • Example#621 - uopz_undefine example
  • Example#622 - Basic uopz_unset_hook Usage
  • Example#623 - uopz_unset_mock example
  • Example#624 - uopz_unset_return example
  • Example#625 - Weakref usage example
  • Example#626 - WeakRef usage example
  • Example#627 - Weakref::acquire example
  • Example#628 - Nested acquire/release example
  • Example#629 - Weakref::__construct example
  • Example#630 - Weakref::release example
  • Example#631 - Weakmap usage example
  • Example#632 - wincache.ignorelist example
  • Example#633 - Authentication configuration for wincache.php
  • Example#634 - Enabling WinCache session handler
  • Example#635 - Enabling WinCache functions reroutes
  • Example#636 - Reroute.ini file content
  • Example#637 - A wincache_fcache_fileinfo example
  • Example#638 - A wincache_fcache_meminfo example
  • Example#639 - Using wincache_lock
  • Example#640 - A wincache_ocache_fileinfo example
  • Example#641 - A wincache_ocache_meminfo example
  • Example#642 - A wincache_refresh_if_changed example
  • Example#643 - A wincache_rplist_fileinfo example
  • Example#644 - A wincache_rplist_meminfo example
  • Example#645 - A wincache_scache_info example
  • Example#646 - A wincache_scache_meminfo example
  • Example#647 - wincache_ucache_add with key as a string
  • Example#648 - wincache_ucache_add with key as an array
  • Example#649 - Using wincache_ucache_cas
  • Example#650 - using wincache_ucache_clear
  • Example#651 - Using wincache_ucache_dec
  • Example#652 - Using wincache_ucache_delete with key as a string
  • Example#653 - Usingwincache_ucache_delete with key as an array
  • Example#654 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#655 - Using wincache_ucache_exists
  • Example#656 - wincache_ucache_get with key as a string
  • Example#657 - wincache_ucache_get with key as an array
  • Example#658 - Using wincache_ucache_inc
  • Example#659 - Using wincache_ucache_info
  • Example#660 - A wincache_ucache_meminfo example
  • Example#661 - wincache_ucache_set with key as a string
  • Example#662 - wincache_ucache_set with key as an array
  • Example#663 - Using wincache_unlock
  • Example#664 - Xhprof 范例，可选使用图形界面
  • Example#665 - xhprof_disable 范例
  • Example#666 - xhprof_enable 范例
  • Example#667 - xhprof_sample_disable 范例
  • Example#668 - Make sure the item is stored
  • Example#669 - Using CHAP passwords
  • Example#670 - radius_acct_open example
  • Example#671 - radius_add_server example
  • Example#672 - radius_auth_open example
  • Example#673 - radius_create_request example
  • Example#674 - radius_cvt_addr example
  • Example#675 - radius_cvt_int example
  • Example#676 - radius_cvt_string example
  • Example#677 - radius_get_attr example
  • Example#678 - radius_get_tagged_attr_data example
  • Example#679 - radius_get_tagged_attr_tag example
  • Example#680 - radius_get_vendor_attr example
  • Example#681 - radius_put_attr example
  • Example#682 - radius_put_int example
  • Example#683 - radius_put_string example
  • Example#684 - radius_put_vendor_attr example
  • Example#685 - Writing a string with a specified color to the screen
  • Example#686 - ncurses_getmouse example
  • Example#687 - Writing a string with a specified color to the screen
  • Example#688 - Writing a string with a specified color to the screen
  • Example#689 - ncurses_mousemask example
  • Example#690 - Writing a string with a specified color to the screen
  • Example#691 - Readline Callback Interface Example
  • Example#692 - readline Example
  • Example#693 - bzip2 小例子
  • Example#694 - 压缩数据
  • Example#695 - 解压一个字符串
  • Example#696 - bzerror 范例
  • Example#697 - bzopen 范例
  • Example#698 - bzread 范例
  • Example#699 - bzwrite 范例
  • Example#700 - Using an external file
  • Example#701 - Using a file within a phar archive
  • Example#702 - Converting a phar archive from phar to tar file format
  • Example#703 - phar.cache_list usage example
  • Example#704 - 一个 Phar::addEmptyDir 示例
  • Example#705 - 一个 Phar::addFile 示例
  • Example#706 - 一个 Phar::addFromString 示例
  • Example#707 - A Phar::apiVersion example
  • Example#708 - A Phar::buildFromDirectory example
  • Example#709 - A Phar::buildFromIterator with SplFileInfo
  • Example#710 - A Phar::buildFromIterator with other iterators
  • Example#711 - A Phar::canCompress example
  • Example#712 - A Phar::canWrite example
  • Example#713 - A Phar::compress example
  • Example#714 - A Phar::compressFiles example
  • Example#715 - A Phar::__construct example
  • Example#716 - A Phar::convertToData example
  • Example#717 - A Phar::convertToExecutable example
  • Example#718 - A Phar::copy example
  • Example#719 - A Phar::count example
  • Example#720 - A Phar::createDefaultStub example
  • Example#721 - A Phar::decompress example
  • Example#722 - A Phar::decompressFiles example
  • Example#723 - A Phar::delMetaData example
  • Example#724 - 一个 Phar::delete 示例
  • Example#725 - A Phar::extractTo example
  • Example#726 - A Phar::getMetadata example
  • Example#727 - A Phar::getStub example
  • Example#728 - A Phar::hasMetadata example
  • Example#729 - A Phar::interceptFileFuncs example
  • Example#730 - A Phar::interceptFileFuncs example
  • Example#731 - A Phar::isBuffering example
  • Example#732 - A Phar::isCompressed example
  • Example#733 - A Phar::loadPhar example
  • Example#734 - A Phar::mapPhar example
  • Example#735 - A Phar::mount example
  • Example#736 - A Phar::mungServer example
  • Example#737 - A Phar::offsetExists example
  • Example#738 - Phar::offsetGet example
  • Example#739 - A Phar::offsetSet example
  • Example#740 - A Phar::offsetUnset example
  • Example#741 - A Phar::running example
  • Example#742 - A Phar::setAlias example
  • Example#743 - A Phar::setDefaultStub example
  • Example#744 - A Phar::setMetadata example
  • Example#745 - A Phar::setStub example
  • Example#746 - A Phar::startBuffering example
  • Example#747 - A Phar::stopBuffering example
  • Example#748 - A Phar::unlinkArchive example
  • Example#749 - A Phar::webPhar example
  • Example#750 - A PharData::addEmptyDir example
  • Example#751 - A PharData::addFile example
  • Example#752 - A PharData::addFromString example
  • Example#753 - A PharData::buildFromDirectory example
  • Example#754 - A PharData::buildFromIterator with SplFileInfo
  • Example#755 - A PharData::buildFromIterator with other iterators
  • Example#756 - A PharData::compress example
  • Example#757 - A PharData::compressFiles example
  • Example#758 - A PharData::__construct example
  • Example#759 - A PharData::convertToData example
  • Example#760 - A PharData::convertToExecutable example
  • Example#761 - A PharData::copy example
  • Example#762 - A PharData::decompress example
  • Example#763 - A PharData::decompressFiles example
  • Example#764 - A PharData::delMetaData example
  • Example#765 - A PharData::delete example
  • Example#766 - A PharData::extractTo example
  • Example#767 - A PharData::offsetSet example
  • Example#768 - A PharData::offsetUnset example
  • Example#769 - A Phar::setMetadata example
  • Example#770 - A PharFileInfo::chmod example
  • Example#771 - A PharFileInfo::compress example
  • Example#772 - A PharFileInfo::__construct example
  • Example#773 - A PharFileInfo::decompress example
  • Example#774 - A PharFileInfo::delMetaData example
  • Example#775 - A PharFileInfo::getCRC32 example
  • Example#776 - A PharFileInfo::getCompressedSize example
  • Example#777 - A PharFileInfo::getMetadata example
  • Example#778 - A PharFileInfo::getPharFlags example
  • Example#779 - A PharFileInfo::isCRCChecked example
  • Example#780 - A PharFileInfo::isCompressed example
  • Example#781 - A PharFileInfo::setMetadata example
  • Example#782 - Rar installation
  • Example#783 - On-the-fly decompression
  • Example#784 - RAR extension filesystem extraction example
  • Example#785 - 面向对象风格
  • Example#786 - 过程化风格
  • Example#787 - 面向对象风格
  • Example#788 - 过程化风格
  • Example#789 - 面向对象风格
  • Example#790 - 过程化风格
  • Example#791 - 面向对象风格
  • Example#792 - 过程化风格
  • Example#793 - 面向对象风格
  • Example#794 - 过程化风格
  • Example#795 - 面向对象风格
  • Example#796 - 过程化风格
  • Example#797 - 面向对象风格
  • Example#798 - 过程化风格
  • Example#799 - Volume Callback
  • Example#800 - 面向对象风格
  • Example#801 - 过程化风格
  • Example#802 - RarArchive::__toString example
  • Example#803 - RarEntry::extract example
  • Example#804 - How to extract all files in archive:
  • Example#805 - RarEntry::getAttr example
  • Example#806 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#807 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#808 - RarEntry::getMethod example
  • Example#809 - RarEntry::getName example
  • Example#810 - RarEntry::getPackedSize example
  • Example#811 - RarEntry::getStream example
  • Example#812 - RarEntry::getUnpackedSize example
  • Example#813 - RarEntry::getVersion example
  • Example#814 - RarException::isUsingExceptions example
  • Example#815 - RarException::setUsingExceptions example
  • Example#816 - 创建一个 Zip 归档
  • Example#817 - 输出文档细节和列表
  • Example#818 - Zip 流封装，读取一个 OpenOffice 文件的元信息
  • Example#819 - Zip 使用范例
  • Example#820 - Create a new directory in an archive
  • Example#821 - Open and add
  • Example#822 - Add an entry to a new archive
  • Example#823 - Add file to a directory inside an archive
  • Example#824 - ZipArchive::addGlob example
  • Example#825 - ZipArchive::addPattern example
  • Example#826 - Delete file from archive using its index
  • Example#827 - Deleting a file and directory from an archive, using names
  • Example#828 - Extract all entries
  • Example#829 - Extract two entries
  • Example#830 - Dump an archive comment
  • Example#831 - Dump an entry comment
  • Example#832 - Dump an entry comment
  • Example#833 - Extract all entries with Unix rights
  • Example#834 - Get the file contents
  • Example#835 - Get the file contents
  • Example#836 - Convert an image from a zip entry
  • Example#837 - ZipArchive::getNameIndex example
  • Example#838 - Get the entry contents with fread and store it
  • Example#839 - Same as the previous example but with fopen and the zip stream wrapper
  • Example#840 - Stream wrapper and image, can be used with the xml function as well
  • Example#841 - Create an archive and then use it with ZipArchive::locateName
  • Example#842 - Open and extract
  • Example#843 - Create an archive
  • Example#844 - Create an temporary archive
  • Example#845 - Archive a file
  • Example#846 - Archive a file
  • Example#847 - Rename one entry
  • Example#848 - Rename one entry
  • Example#849 - Open and replace
  • Example#850 - Create an archive and set a comment
  • Example#851 - Open an archive and set a comment for an entry
  • Example#852 - Open an archive and set a comment for an entry
  • Example#853 - Add files with different compression methods to an archive
  • Example#854 - Add files with different compression methods to an archive
  • Example#855 - Add file and set compression method
  • Example#856 - Archive and encrypt a file
  • Example#857 - Archive a file, with its Unix rights
  • Example#858 - Archive a file
  • Example#859 - Archive a file
  • Example#860 - Dump the stat info of an entry
  • Example#861 - Dump the stat info of an entry
  • Example#862 - Small Zlib Example
  • Example#863 - Working with the incremental compression and decompression API as of PHP 7.0.0
  • Example#864 - gzclose example
  • Example#865 - gzcompress example
  • Example#866 - gzdeflate example
  • Example#867 - Creating a gzip file
  • Example#868 - gzeof example
  • Example#869 - gzfile example
  • Example#870 - gzgetc example
  • Example#871 - gzgets example
  • Example#872 - gzgetss example
  • Example#873 - gzinflate example
  • Example#874 - gzopen Example
  • Example#875 - gzpassthru example
  • Example#876 - gzread example
  • Example#877 - gzseek example
  • Example#878 - gzuncompress example
  • Example#879 - gzwrite example
  • Example#880 - zlib_encode example
  • Example#881 - random_bytes example
  • Example#882 - random_int example
  • Example#883 - hash_algos 例程
  • Example#884 - hash_copy 例程
  • Example#885 - hash_equals 例程
  • Example#886 - 使用 hash_file
  • Example#887 - hash_final 例程
  • Example#888 - hash_hkdf example
  • Example#889 - hash_hmac_algos example
  • Example#890 - hash_hmac_file 例程
  • Example#891 - hash_hmac 例程
  • Example#892 - 增量哈希运算例程
  • Example#893 - hash_pbkdf2 例程，基础用法
  • Example#894 - hash_update_stream 例程
  • Example#895 - 一个 hash 例程
  • Example#896 - 使用 PHP 5.4 或者更高版本计算 tiger 哈希值
  • Example#897 - 在 2.4.x 或更高版本，使用 256 比特的密钥，AES 算法和 CBC 模式来加密输入数据
  • Example#898 - mcrypt_create_iv 例程
  • Example#899 - mcrypt_enc_get_algorithms_name 例程
  • Example#900 - mcrypt_enc_get_modes_name 例程
  • Example#901 - mcrypt_enc_get_supported_key_sizes 例程
  • Example#902 - mcrypt_encrypt 例程
  • Example#903 - mcrypt_get_block_size 例程
  • Example#904 - mcrypt_get_cipher_name 例程
  • Example#905 - mcrypt_get_iv_size 例程
  • Example#906 - mcrypt_get_key_size 例程
  • Example#907 - mcrypt_list_algorithms 例程
  • Example#908 - mcrypt_list_modes 例程
  • Example#909 - mcrypt_module_open 例程
  • Example#910 - 在加密中使用 mcrypt_module_open
  • Example#911 - mcrypt_module_self_test 例程
  • Example#912 - mdecrypt_generic 例程
  • Example#913 - Computes the MD5 digest and hmac and print it out as hex
  • Example#914 - Traversing all hashes
  • Example#915 - mhash_get_block_size Example
  • Example#916 - mhash_get_hash_name Example
  • Example#917 - openssl_cipher_iv_length 范例
  • Example#918 - openssl_csr_export_to_file() 范例
  • Example#919 - openssl_csr_export() 范例
  • Example#920 - openssl_csr_get_public_key() example
  • Example#921 - openssl_csr_get_subject() 范例
  • Example#922 - 创建一个自签名的证书
  • Example#923 - 在PHP 7.1+版本中创建一个自签名的ECC证书
  • Example#924 - openssl_csr_sign example - signing a CSR (how to implement your own CA)
  • Example#925 - PHP 7.1+ 下 GCM 模式的 AES 认证加密例子
  • Example#926 - PHP 5.6+ 的 AES 认证加密例子
  • Example#927 - openssl_error_string example
  • Example#928 - openssl_get_cert_locations 范例
  • Example#929 - openssl_get_cipher_methods example
  • Example#930 - openssl_get_curve_names 范例
  • Example#931 - openssl_get_md_methods 范例：
  • Example#932 - openssl_open 范例
  • Example#933 - openssl_pbkdf2() 范例
  • Example#934 - openssl_pkcs12_read 范例
  • Example#935 - openssl_pkcs7_decrypt 范例
  • Example#936 - openssl_pkcs7_encrypt 范例
  • Example#937 - openssl_pkcs7_sign 范例
  • Example#938 - openssl_pkey_derive example
  • Example#939 - Obtain the public key from a private key
  • Example#940 - openssl_random_pseudo_bytes 范例：
  • Example#941 - openssl_seal 范例：
  • Example#942 - openssl_sign example
  • Example#943 - openssl_sign example
  • Example#944 - openssl_spki_export_challenge 范例：
  • Example#945 - openssl_spki_export_challenge 来自 <keygen> 元素的范例：
  • Example#946 - openssl_spki_export 范例：
  • Example#947 - openssl_spki_export example from <keygen>
  • Example#948 - openssl_spki_new 范例：
  • Example#949 - openssl_spki_verify 范例：
  • Example#950 - openssl_spki_verify example from <keygen>
  • Example#951 - openssl_verify 范例：
  • Example#952 - openssl_verify 范例：
  • Example#953 - openssl_x509_verify example
  • Example#954 - Basic password usage
  • Example#955 - password_hash 例子
  • Example#956 - password_hash 手动设置 cost 的例子
  • Example#957 - 寻找最佳 cost 的 password_hash 例子
  • Example#958 - 使用 Argon2i 的password_hash例子
  • Example#959 - password_needs_rehash用法
  • Example#960 - password_verify 例子
  • Example#961 - sodium_crypto_kx_keypair usage
  • Example#962 - password_hash example
  • Example#963 - password_hash example
  • Example#964 - DBA example
  • Example#965 - Traversing a database
  • Example#966 - dba_handlers Example
  • Example#967 - List Privileges for a Column
  • Example#968 - List Columns of a Table
  • Example#969 - DSN-less connections
  • Example#970 - List available DSNs
  • Example#971 - odbc_execute and odbc_prepare example
  • Example#972 - odbc_fetch_into examples
  • Example#973 - odbc_next_result
  • Example#974 - odbc_execute and odbc_prepare example
  • Example#975 - List primary Keys of a Column
  • Example#976 - List Columns of a stored Procedure
  • Example#977 - List stored Procedures of a Database
  • Example#978 - odbc_result examples
  • Example#979 - odbc_setoption examples
  • Example#980 - List Statistics of a Table
  • Example#981 - List Privileges of a Table
  • Example#982 - List Tables in a Catalog
  • Example#983 - 使用 PDO::ATTR_DRIVER_NAME 的例子
  • Example#984 - 连接到 MySQL
  • Example#985 - 处理连接错误
  • Example#986 - 关闭一个连接
  • Example#987 - 持久化连接
  • Example#988 - 在事务中执行批处理
  • Example#989 - 用预处理语句进行重复插入
  • Example#990 - 用预处理语句进行重复插入
  • Example#991 - 使用预处理语句获取数据
  • Example#992 - 带输出参数调用存储过程
  • Example#993 - 带输入/输出参数调用存储过程
  • Example#994 - 占位符的无效使用
  • Example#995 - 创建 PDO 实例并设置错误模式
  • Example#996 - 创建 PDO 实例并在构造函数中设置错误模式
  • Example#997 - 从数据库中显示一张图片
  • Example#998 - 插入一张图片到数据库
  • Example#999 - 插入一张图片到数据库：Oracle
  • Example#1000 - 回滚一个事务
  • Example#1001 - 提交一个基础事务
  • Example#1002 - 提交一个DDL事务
  • Example#1003 - Create a PDO instance via driver invocation
  • Example#1004 - Create a PDO instance via URI invocation
  • Example#1005 - 使用别名创建一个PDO实例
  • Example#1006 - 取得一个 SQLSTATE 码
  • Example#1007 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1008 - 发出一条 DELETE 语句
  • Example#1009 - 取回数据库连接属性
  • Example#1010 - 一个 PDO::getAvailableDrivers 的例子
  • Example#1011 - 用命名参数形式准备 SQL 语句参数
  • Example#1012 - 用问号形式准备 SQL 语句参数
  • Example#1013 - 展示 PDO::query 的使用
  • Example#1014 - 普通字符串加引号
  • Example#1015 - 危险字符串加引号
  • Example#1016 - 复杂字符串加引号
  • Example#1017 - 回滚一个事务
  • Example#1018 - 把结果集输出绑定到 PHP 变量
  • Example#1019 - 执行一条使用命名占位符的预处理语句
  • Example#1020 - 执行一条使用问号占位符的预处理语句
  • Example#1021 - 使用 INOUT 参数调用一个存储过程
  • Example#1022 - 执行一条使用命名占位符的预处理语句
  • Example#1023 - 执行一条使用问号占位符的预处理语句
  • Example#1024 - 一个 PDOStatement::closeCursor 的例子
  • Example#1025 - 计算列数
  • Example#1026 - PDOStatement::debugDumpParams 使用命名参数的例子
  • Example#1027 - PDOStatement::debugDumpParams 使用未命名参数的例子
  • Example#1028 - 取回一个 SQLSTATE 码
  • Example#1029 - 显示连接到DB2数据库的 PDO_ODBC 连接的 errorInfo() 的字段
  • Example#1030 - 执行一条绑定变量的预处理语句
  • Example#1031 - 使用一个含有插入值的数组执行一条预处理语句（命名参数）
  • Example#1032 - 使用一个含有插入值的数组执行一条预处理语句（占位符）
  • Example#1033 - 执行一条问号占位符的预处理语句
  • Example#1034 - 使用数组执行一条含有 IN 子句的预处理语句
  • Example#1035 - 使用不同的提取方式获取行
  • Example#1036 - 使用一个可滚动游标获取行
  • Example#1037 - 获取结果集中所有剩余的行
  • Example#1038 - 获取结果集中单独一列的所有值
  • Example#1039 - 根据单独的一列把所有值分组
  • Example#1040 - 每行结果实例化一个类
  • Example#1041 - 每行调用一次函数
  • Example#1042 - 返回下一行的第一列
  • Example#1043 - 检索列的元数据
  • Example#1044 - 获取由一个存储过程返回的多个行集
  • Example#1045 - 返回删除的行数
  • Example#1046 - 计算由一个 SELECT 语句返回的行数
  • Example#1047 - 设置获取模式
  • Example#1048 - Insert LOBs in CUBRID PDO
  • Example#1049 - Fetch LOBs in CUBRID PDO
  • Example#1050 - Insert set in CUBRID PDO with default data type.
  • Example#1051 - Specify data type when insert set in CUBRID PDO
  • Example#1052 - PDO_CUBRID DSN examples
  • Example#1053 - A PDO::cubrid_schema example
  • Example#1054 - PDO_DBLIB DSN examples
  • Example#1055 - PDO_FIREBIRD DSN example with path
  • Example#1056 - PDO_FIREBIRD DSN example with port and path
  • Example#1057 - PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system
  • Example#1058 - PDO_FIREBIRD DSN to connect to a dialect 1 database
  • Example#1059 - PDO_IBM DSN example using db2cli.ini
  • Example#1060 - PDO_IBM DSN example using a connection string
  • Example#1061 - PDO_INFORMIX DSN example using odbc.ini
  • Example#1062 - PDO_INFORMIX DSN example using a connection string
  • Example#1063 - Forcing queries to be buffered in mysql
  • Example#1064 - PDO_MYSQL DSN examples
  • Example#1065 - PDO_SQLSRV DSN examples
  • Example#1066 - PDO_OCI DSN examples
  • Example#1067 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#1068 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#1069 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#1070 - PDO_PGSQL DSN examples
  • Example#1071 - A PDO::pgsqlLOBCreate example
  • Example#1072 - A PDO::pgsqlLOBOpen example
  • Example#1073 - A PDO::pgsqlLOBUnlink example
  • Example#1074 - PDO_SQLITE DSN examples
  • Example#1075 - max_length aggregation function example
  • Example#1076 - PDO::sqliteCreateCollation example
  • Example#1077 - PDO::sqliteCreateFunction example
  • Example#1078 - 数据查询的例子
  • Example#1079 - 数据插入的例子
  • Example#1080 - cubrid_bind example
  • Example#1081 - cubrid_bind BLOB/CLOB example
  • Example#1082 - cubrid_bind BLOB/CLOB example
  • Example#1083 - cubrid_close_prepare example
  • Example#1084 - cubrid_close_request example
  • Example#1085 - cubrid_col_get example
  • Example#1086 - cubrid_col_size example
  • Example#1087 - cubrid_column_names example
  • Example#1088 - cubrid_column_types example
  • Example#1089 - cubrid_commit example
  • Example#1090 - cubrid_connect_with_url url without properties example
  • Example#1091 - cubrid_connect_with_url url with properties example
  • Example#1092 - cubrid_connect example
  • Example#1093 - cubrid_current_oid example
  • Example#1094 - cubrid_disconnect example
  • Example#1095 - cubrid_drop example
  • Example#1096 - cubrid_error_code_facility example
  • Example#1097 - cubrid_error_code example
  • Example#1098 - cubrid_error_msg example
  • Example#1099 - cubrid_execute example
  • Example#1100 - cubrid_fetch example
  • Example#1101 - cubrid_free_result example
  • Example#1102 - cubrid_get_charset example
  • Example#1103 - cubrid_get_class_name example
  • Example#1104 - cubrid_get_client_info example
  • Example#1105 - cubrid_get_db_parameter example
  • Example#1106 - cubrid_get_query_timeout example
  • Example#1107 - cubrid_get_server_info example
  • Example#1108 - cubrid_get example
  • Example#1109 - cubrid_insert_id example
  • Example#1110 - cubrid_is_instance example
  • Example#1111 - cubrid_lob_close example
  • Example#1112 - cubrid_lob_export example
  • Example#1113 - cubrid_lob_get example
  • Example#1114 - cubrid_lob_send example
  • Example#1115 - cubrid_lob_size example
  • Example#1116 - cubrid_lob2_bind example
  • Example#1117 - cubrid_lob2_export example
  • Example#1118 - cubrid_lob2_export example
  • Example#1119 - cubrid_lob2_read example 1
  • Example#1120 - cubrid_lob2_read example 2
  • Example#1121 - cubrid_lob2_seek64 example
  • Example#1122 - cubrid_lob2_seek example
  • Example#1123 - cubrid_lob2_write example 1
  • Example#1124 - cubrid_lob2_write example 2
  • Example#1125 - cubrid_lock_read example
  • Example#1126 - cubrid_lock_write example
  • Example#1127 - cubrid_move_cursor example
  • Example#1128 - cubrid_next_result example
  • Example#1129 - cubrid_num_cols example
  • Example#1130 - cubrid_num_rows example
  • Example#1131 - cubrid_pconnect_with_url url without properties example
  • Example#1132 - cubrid_pconnect_with_url url with properties example
  • Example#1133 - cubrid_connect example
  • Example#1134 - cubrid_prepare example
  • Example#1135 - cubrid_put example
  • Example#1136 - cubrid_rollback example
  • Example#1137 - cubrid_schema example
  • Example#1138 - cubrid_seq_drop example
  • Example#1139 - cubrid_seq_insert example
  • Example#1140 - cubrid_seq_put example
  • Example#1141 - cubrid_set_add example
  • Example#1142 - cubrid_get_db_parameter example
  • Example#1143 - cubrid_set_drop example
  • Example#1144 - cubrid_version example
  • Example#1145 - cubrid_affected_rows example
  • Example#1146 - cubrid_client_encoding example
  • Example#1147 - cubrid_close example
  • Example#1148 - cubrid_data_seek example
  • Example#1149 - cubrid_db_name example
  • Example#1150 - cubrid_errno example
  • Example#1151 - cubrid_error example
  • Example#1152 - cubrid_fetch_array example
  • Example#1153 - cubrid_fetch_assoc example
  • Example#1154 - cubrid_fetch_field example
  • Example#1155 - cubrid_fetch_lengths example
  • Example#1156 - cubrid_fetch_object example
  • Example#1157 - cubrid_fetch_row example
  • Example#1158 - cubrid_field_flags example
  • Example#1159 - cubrid_field_len example
  • Example#1160 - cubrid_field_name example
  • Example#1161 - cubrid_field_seek example
  • Example#1162 - cubrid_field_table example
  • Example#1163 - cubrid_field_type example
  • Example#1164 - cubrid_list_dbs example
  • Example#1165 - cubrid_num_fields example
  • Example#1166 - cubrid_ping example
  • Example#1167 - Invalid Query
  • Example#1168 - Valid Query
  • Example#1169 - cubrid_real_escape_string example
  • Example#1170 - cubrid_result example
  • Example#1171 - cubrid_unbuffered_query example
  • Example#1172 - cubrid_load_from_glo example
  • Example#1173 - cubrid_new_glo example
  • Example#1174 - cubrid_save_to_glo example
  • Example#1175 - cubrid_send_glo example
  • Example#1176 - Inserting a record in a dBase database
  • Example#1177 - Closing a dBase database file
  • Example#1178 - Creating a dBase database file
  • Example#1179 - Showing header information for a dBase database file
  • Example#1180 - Listing all the registered members in the database
  • Example#1181 - dbase_numfields Example
  • Example#1182 - Looping over all the records of the database
  • Example#1183 - Opening a dBase database file
  • Example#1184 - Emptying a dBase database
  • Example#1185 - Updating a record in the database
  • Example#1186 - ibase_backup example
  • Example#1187 - ibase_backup example with arguments
  • Example#1188 - ibase_blob_get example
  • Example#1189 - ibase_blob_import example
  • Example#1190 - ibase_connect example
  • Example#1191 - ibase_execute example
  • Example#1192 - ibase_fetch_object example
  • Example#1193 - ibase_field_info example
  • Example#1194 - ibase_name_result example
  • Example#1195 - ibase_num_fields example
  • Example#1196 - ibase_query example
  • Example#1197 - ibase_restore example
  • Example#1198 - ibase_restore example with arguments
  • Example#1199 - ibase_service_attach example
  • Example#1200 - ibase_service_attach example
  • Example#1201 - ibase_service_attach example using hostname/port syntax
  • Example#1202 - ibase_service_detach example
  • Example#1203 - ibase_set_event_handler example
  • Example#1204 - fbsql_close example
  • Example#1205 - fbsql_connect example
  • Example#1206 - fbsql_create_blob example
  • Example#1207 - fbsql_create_clob example
  • Example#1208 - fbsql_create_db example
  • Example#1209 - fbsql_data_seek example
  • Example#1210 - fbsql_create_clob example
  • Example#1211 - fbsql_errno Example
  • Example#1212 - fbsql_error Example
  • Example#1213 - fbsql_fetch_array example
  • Example#1214 - fbsql_fetch_assoc example
  • Example#1215 - fbsql_fetch_field example
  • Example#1216 - fbsql_fetch_object example
  • Example#1217 - fbsql_field_name example
  • Example#1218 - fbsql_field_type example
  • Example#1219 - fbsql_list_dbs example
  • Example#1220 - fbsql_list_fields example
  • Example#1221 - fbsql_next_result example
  • Example#1222 - fbsql_num_rows example
  • Example#1223 - fbsql_query example
  • Example#1224 - fbsql_query example
  • Example#1225 - fbsql_read_blob example
  • Example#1226 - fbsql_read_clob example
  • Example#1227 - fbsql_table_name example
  • Example#1228 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1229 - Setting the AUTOCOMMIT value for a connection
  • Example#1230 - Binding PHP variables to a prepared statement
  • Example#1231 - Calling stored procedures with IN and OUT parameters
  • Example#1232 - Inserting a binary large object (BLOB) directly from a file
  • Example#1233 - A db2_client_info example
  • Example#1234 - Closing a connection
  • Example#1235 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1236 - Retrieving the error message returned by a failed connection attempt
  • Example#1237 - Creating a cataloged connection
  • Example#1238 - Creating an uncataloged connection
  • Example#1239 - Creating a connection with autocommit off by default
  • Example#1240 - i5/OS best performance
  • Example#1241 - Using trusted context
  • Example#1242 - A db2_escape_string example
  • Example#1243 - Creating a table with db2_exec
  • Example#1244 - Executing a SELECT statement with a scrollable cursor
  • Example#1245 - Returning XML data as an SQL ResultSet
  • Example#1246 - Performing a "JOIN" with XML data
  • Example#1247 - Returning SQL data as part of a larger XML document
  • Example#1248 - Preparing and executing an SQL statement with parameter markers
  • Example#1249 - Calling a stored procedure with an OUT parameter
  • Example#1250 - Returning XML data as an SQL ResultSet
  • Example#1251 - Performing a "JOIN" with XML data
  • Example#1252 - Returning SQL data as part of a larger XML document
  • Example#1253 - Iterating through a forward-only cursor
  • Example#1254 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1255 - Iterating through a forward-only cursor
  • Example#1256 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1257 - Iterating through a forward-only cursor
  • Example#1258 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1259 - A db2_fetch_object example
  • Example#1260 - Iterating through a result set
  • Example#1261 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1262 - Setting and retrieving parameters through a connection resource
  • Example#1263 - A db2_last_insert_id example
  • Example#1264 - Iterating through different types of data
  • Example#1265 - Calling a stored procedure that returns multiple result sets
  • Example#1266 - Retrieving the number of fields in a result set
  • Example#1267 - Closing a persistent connection
  • Example#1268 - A db2_pconnect example
  • Example#1269 - Using trusted context
  • Example#1270 - Preparing and executing an SQL statement with parameter markers
  • Example#1271 - A db2_result example
  • Example#1272 - Rolling back a DELETE statement
  • Example#1273 - A db2_server_info example
  • Example#1274 - Setting one parameter with a connection resource
  • Example#1275 - Setting multiple parameters with a connection resource
  • Example#1276 - Setting multiple parameters with an invalid key
  • Example#1277 - Setting multiple parameters with an invalid value
  • Example#1278 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1279 - Setting multiple parameters with the wrong resource
  • Example#1280 - Putting it all together
  • Example#1281 - i5/OS cursors are read-only
  • Example#1282 - Example usage of PassEnv for Ingres
  • Example#1283 - Simple Ingres Example
  • Example#1284 - ingres_charset - Get the installation character set
  • Example#1285 - Open a connection to an Ingres database
  • Example#1286 - Get cursor name for a query resource
  • Example#1287 - Get the last Ingres error number generated
  • Example#1288 - Get a message for the last error generated
  • Example#1289 - Get the last SQLSTATE error code generated
  • Example#1290 - Escape special characters for use in a query
  • Example#1291 - Fetch a row of result into an array
  • Example#1292 - Fetch a row into an associative array
  • Example#1293 - Fetch a row into an object
  • Example#1294 - Get the return value from a procedure call
  • Example#1295 - Fetch a row of result into an enumerated array
  • Example#1296 - Free a result resource
  • Example#1297 - Send a simple select
  • Example#1298 - Passing query parameters to ingres_query
  • Example#1299 - Inserting a BLOB with parameter types
  • Example#1300 - Position the cursor on the 3rd row
  • Example#1301 - Set date_format to ISO4
  • Example#1302 - Set timezone to HONG-KONG
  • Example#1303 - Issue a simple un-buffered select
  • Example#1304 - Passing query parameters to ingres_unbuffered_query
  • Example#1305 - Inserting a BLOB with parameter types
  • Example#1306 -
  • Example#1307 -
  • Example#1308 -
  • Example#1309 -
  • Example#1310 -
  • Example#1311 -
  • Example#1312 -
  • Example#1313 -
  • Example#1314 -
  • Example#1315 -
  • Example#1316 -
  • Example#1317 -
  • Example#1318 -
  • Example#1319 -
  • Example#1320 -
  • Example#1321 - 查询串语法的读取首选项URI链接
  • Example#1322 - Setting read preferences with array syntax for tag sets
  • Example#1323 - Passing a WriteConcern to a write operation
  • Example#1324 - Connection string WriteConcerns
  • Example#1325 - MongoDB::setWriteConcern and MongoCollection::setWriteConcern
  • Example#1326 - Unacknowledged WriteConcern, followed with Acknowledged Write
  • Example#1327 - Acknowledged Writes
  • Example#1328 - Majority Acknowledged Write
  • Example#1329 - Acknowledged and Journaled Write
  • Example#1330 - 针对“admin”数据库的认证
  • Example#1331 - 针对一般数据库的认证
  • Example#1332 - 链接到一个复制
  • Example#1333 -
  • Example#1334 -
  • Example#1335 -
  • Example#1336 -
  • Example#1337 -
  • Example#1338 - Inheriting read preferences from the database level down to the cursor
  • Example#1339 -
  • Example#1340 -
  • Example#1341 -
  • Example#1342 -
  • Example#1343 -
  • Example#1344 -
  • Example#1345 -
  • Example#1346 - MongoClient 基本用法
  • Example#1347 - MongoClient::close 例子
  • Example#1348 - MongoClient::__construct 集群例子
  • Example#1349 - 连接到一个域套接字（domain socket）
  • Example#1350 - MongoClient::__construct 验证的例子
  • Example#1351 - MongoClient::__construct 读取选项例子
  • Example#1352 - MongoClient::getConnections 例子
  • Example#1353 - MongoClient::getReadPreference 返回值例子
  • Example#1354 - MongoClient::getWriteConcern return value example
  • Example#1355 - MongoClient::killCursor example
  • Example#1356 - MongoClient::listDBs 例子
  • Example#1357 - MongoClient::selectCollection 例子
  • Example#1358 - MongoClient::setReadPreference 标签集数组语法的例子
  • Example#1359 - MongoClient::setWriteConcern example
  • Example#1360 - 选择一个数据库
  • Example#1361 - MongoDB::command "distinct"实例
  • Example#1362 - MongoDB::command "distinct"实例
  • Example#1363 - MongoDB::command MapReduce实例
  • Example#1364 - MongoDB::command "textSearch"实例
  • Example#1365 - MongoDB::command "geoNear"实例
  • Example#1366 - MongoDB::createCollection 固定大小集合 实例
  • Example#1367 - MongoDB::createDBRef实例
  • Example#1368 - MongoDB::createDBRef实例
  • Example#1369 - MongoDB::drop 例子
  • Example#1370 - 简单的 MongoDB::execute 实例
  • Example#1371 - 带参数的 MongoDB::execute 实例
  • Example#1372 - 作用域实例
  • Example#1373 - MongoDB::getCollectionInfo example
  • Example#1374 - MongoDB::getCollectionNames example
  • Example#1375 - MongoDB::getDBRef example
  • Example#1376 - MongoDB::getGridFS example
  • Example#1377 - MongoDB::getReadPreference return value example
  • Example#1378 - MongoDB::getWriteConcern return value example
  • Example#1379 - MongoDB::lastError null error example
  • Example#1380 - MongoDB::lastError duplicate key example
  • Example#1381 - MongoDB::listCollections example
  • Example#1382 - MongoDB::repair example
  • Example#1383 - MongoDB::setReadPreference tag set array syntax example
  • Example#1384 - MongoDB::setWriteConcern example
  • Example#1385 - MongoCollection::aggregate example
  • Example#1386 - MongoCollection::aggregate example
  • Example#1387 - MongoCollection::aggregate example
  • Example#1388 - MongoCollection::aggregate with command options
  • Example#1389 - MongoCollection::aggregateCursor example
  • Example#1390 - MongoCollection::aggregateCursor example with different initial batch size
  • Example#1391 - MongoCollection::batchInsert example
  • Example#1392 - MongoCollection::batchInsert example with ignoring errors
  • Example#1393 - MongoCollection::count 例子
  • Example#1394 - MongoCollection::createDBRef 例子
  • Example#1395 - MongoCollection::createIndex example
  • Example#1396 - Geospatial Indexing
  • Example#1397 - Drop duplicates example
  • Example#1398 - MongoCollection::deleteIndex example
  • Example#1399 - MongoCollection::deleteIndexes 例子
  • Example#1400 - MongoCollection::distinct 例子
  • Example#1401 - 内嵌文档的 MongoCollection::distinct 例子
  • Example#1402 - MongoCollection::drop 例子
  • Example#1403 - MongoCollection::ensureIndex example
  • Example#1404 - Geospatial Indexing
  • Example#1405 - Drop duplicates example
  • Example#1406 - MongoCollection::find 例子
  • Example#1407 - MongoCollection::find 例子
  • Example#1408 - 使用 $where 的 MongoCollection::find 例子
  • Example#1409 - 使用 $in 的 MongoCollection::find 例子
  • Example#1410 - 以数组形式获取结果集
  • Example#1411 - MongoCollection::findAndModify example
  • Example#1412 - MongoCollection::findAndModify error handling
  • Example#1413 - MongoCollection::findOne document by its id.
  • Example#1414 - MongoCollection::findOne document by some condition.
  • Example#1415 - MongoCollection::getDBRef example
  • Example#1416 - MongoCollection::getIndexInfo example
  • Example#1417 - MongoCollection::getName 例子
  • Example#1418 - MongoCollection::getReadPreference return value example
  • Example#1419 - MongoCollection::getWriteConcern return value example
  • Example#1420 - MongoCollection::group example
  • Example#1421 - MongoCollection::group example
  • Example#1422 - Passing a keys function
  • Example#1423 - MongoCollection::insert _id 例子
  • Example#1424 - MongoCollection::insert 确认写入的例子
  • Example#1425 - MongoCollection::parallelCollectionScan example
  • Example#1426 - MongoCollection::remove 的 justOne 例子
  • Example#1427 - MongoCollection::save 例子
  • Example#1428 - MongoCollection::setReadPreference tag set array syntax example
  • Example#1429 - MongoDB::setWriteConcern example
  • Example#1430 - MongoCollection::toIndexString example
  • Example#1431 - MongoCollection::__toString example
  • Example#1432 - MongoCollection::update
  • Example#1433 - MongoCollection::update upsert examples
  • Example#1434 - MongoCollection::update multiple example
  • Example#1435 - MongoCursor basic usage
  • Example#1436 - Iterating over MongoCursor
  • Example#1437 - Adding options to MongoCursor
  • Example#1438 - Adding a comment with MongoCursor::addOption example
  • Example#1439 - MongoCursor::addOption example
  • Example#1440 - MongoCursor::awaitData example
  • Example#1441 - MongoCursor::batchSize and combinations with MongoCursor::limit
  • Example#1442 - MongoCursor::count example
  • Example#1443 - MongoCursor::doQuery example
  • Example#1444 - MongoCursor::explain example
  • Example#1445 - MongoCursor::getReadPreference return value example
  • Example#1446 - MongoCursor::info example
  • Example#1447 - MongoCursor::maxTimeMS example
  • Example#1448 - MongoCursor::setFlag example
  • Example#1449 - MongoCursor::setReadPreference tag set array syntax example
  • Example#1450 - MongoCursor::slaveOkay example
  • Example#1451 - MongoCursor::sort example
  • Example#1452 - MongoCursor::tailable example
  • Example#1453 - MongoCursor::timeout example
  • Example#1454 - Adding options to MongoCommandCursor
  • Example#1455 - MongoCommandCursor::batchSize
  • Example#1456 - MongoCommandCursor example
  • Example#1457 - MongoCommandCursor::createFromDocument
  • Example#1458 - MongoCommandCursor::getReadPreference return value example
  • Example#1459 - MongoCommandCursor::info example
  • Example#1460 - MongoCommandCursor::rewind
  • Example#1461 - MongoCommandCursor::setReadPreference tag set array syntax example
  • Example#1462 - MongoCommandCursor::timeout example
  • Example#1463 - MongoId::__construct 例子
  • Example#1464 - 参数的例子
  • Example#1465 - MongoId::__toString 例子
  • Example#1466 - MongoCode::__construct 例子
  • Example#1467 - 使用具有 $where 的 MongoCode
  • Example#1468 - MongoCode::__toString 例子
  • Example#1469 - Storing dates with MongoDate
  • Example#1470 - MongoDate::__construct 例子
  • Example#1471 - MongoDate::toDateTime example
  • Example#1472 - 正则表达式
  • Example#1473 - MongoRegex::__construct 例子
  • Example#1474 - MongoRegex::__toString 例子
  • Example#1475 -
  • Example#1476 - 链接文档
  • Example#1477 - Creating MongoDBRef links
  • Example#1478 - MongoDBRef::create 例子
  • Example#1479 - MongoCollection::createDBRef 例子
  • Example#1480 - MongoGridFS::findOne example
  • Example#1481 - MongoGridFS::storeBytes with additional metadata
  • Example#1482 - MongoGridFS::storeFile with additional metadata
  • Example#1483 - MongoGridFS::storeUpload HTML form example
  • Example#1484 - MongoGridFSFile::getBytes example
  • Example#1485 - MongoGridFSFile::getResource example
  • Example#1486 - MongoGridFSFile::write example
  • Example#1487 - MongoLog::setCallback example
  • Example#1488 - Changing pool size
  • Example#1489 - Mongo::setPoolSize example
  • Example#1490 - Changing pool size
  • Example#1491 - Mongo::setPoolSize example
  • Example#1492 - MongoResultException::getDocument 例子
  • Example#1493 - Catching MongoDuplicateKeyException
  • Example#1494 - Catching MongoProtocolException
  • Example#1495 - MongoDB\Driver\Manager::__construct basic example
  • Example#1496 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1497 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1498 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1499 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1500 - Limiting execution time for a command
  • Example#1501 - MongoDB\Driver\Manager::executeQuery example
  • Example#1502 - Limiting execution time for a query
  • Example#1503 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1504 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1505 - MongoDB\Driver\Manager::getServers example
  • Example#1506 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1507 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1508 - MongoDB\Driver\Command::__construct example
  • Example#1509 - MongoDB\Driver\Command::__construct example
  • Example#1510 - MongoDB\Driver\Query::__construct example
  • Example#1511 - Mixed write operations are grouped by type
  • Example#1512 - Ordered write operations causing an error
  • Example#1513 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1514 - MongoDB\Driver\BulkWrite::count example
  • Example#1515 - MongoDB\Driver\BulkWrite::delete example
  • Example#1516 - MongoDB\Driver\BulkWrite::insert example
  • Example#1517 - MongoDB\Driver\BulkWrite::update example
  • Example#1518 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1519 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1520 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1521 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1522 - MongoDB\Driver\WriteConcern::getW example
  • Example#1523 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1524 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1525 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1526 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1527 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1528 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1529 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1530 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1531 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1532 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1533 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1534 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1535 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1536 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1537 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1538 - Reading a result set
  • Example#1539 - Reading a result set for a tailable cursor
  • Example#1540 - MongoDB\Driver\Cursor::getId example
  • Example#1541 - MongoDB\Driver\Cursor::getServer example
  • Example#1542 - MongoDB\Driver\Cursor::isDead example
  • Example#1543 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1544 - MongoDB\Driver\Cursor::toArray example
  • Example#1545 - MongoDB\Driver\CursorId::__toString example
  • Example#1546 - MongoDB\Driver\Server::getHost example
  • Example#1547 - MongoDB\Driver\Server::getInfo example
  • Example#1548 - MongoDB\Driver\Server::getLatency example
  • Example#1549 - MongoDB\Driver\Server::getPort example
  • Example#1550 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1551 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1552 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1553 - MongoDB\Driver\WriteError::getCode example
  • Example#1554 - MongoDB\Driver\WriteError::getIndex example
  • Example#1555 - MongoDB\Driver\WriteError::getMessage example
  • Example#1556 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1557 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1558 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1559 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1560 - MongoDB\Driver\WriteResult::getServer example
  • Example#1561 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1562 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1563 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1564 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1565 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1566 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1567 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1568 - MongoDB\BSON\fromJSON example
  • Example#1569 - MongoDB\BSON\fromPHP example
  • Example#1570 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1571 - MongoDB\BSON\toJSON example
  • Example#1572 - MongoDB\BSON\toPHP example
  • Example#1573 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1574 - MongoDB\BSON\Binary::__construct example
  • Example#1575 - MongoDB\BSON\Binary::getData example
  • Example#1576 - MongoDB\BSON\Binary::getType example
  • Example#1577 - MongoDB\BSON\Binary::__toString example
  • Example#1578 - MongoDB\BSON\Decimal128::__construct example
  • Example#1579 - MongoDB\BSON\Decimal128::__toString example
  • Example#1580 - MongoDB\BSON\Javascript::__construct example
  • Example#1581 - MongoDB\BSON\Javascript::getCode example
  • Example#1582 - MongoDB\BSON\Javascript::getScope example
  • Example#1583 - MongoDB\BSON\Javascript::__toString example
  • Example#1584 - MongoDB\BSON\MaxKey::__construct example
  • Example#1585 - MongoDB\BSON\MinKey::__construct example
  • Example#1586 - MongoDB\BSON\ObjectId::__construct example
  • Example#1587 - MongoDB\BSON\ObjectId::getTimestamp example
  • Example#1588 - MongoDB\BSON\ObjectId::__toString example
  • Example#1589 - MongoDB\BSON\Regex::__construct example
  • Example#1590 - MongoDB\BSON\Regex::getFlags example
  • Example#1591 - MongoDB\BSON\Regex::getPattern example
  • Example#1592 - MongoDB\BSON\Regex::__toString example
  • Example#1593 - MongoDB\BSON\Timestamp::__construct example
  • Example#1594 - MongoDB\BSON\Timestamp::__toString example
  • Example#1595 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1596 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1597 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1598 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1599 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1600 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1601 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1602 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1603 - MongoDB\BSON\Int64::__toString example
  • Example#1604 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1605 - Comparing the MySQL APIs
  • Example#1606 - Configure commands for using mysqlnd or libmysqlclient
  • Example#1607 - Unbuffered query example: mysqli
  • Example#1608 - Unbuffered query example: pdo_mysql
  • Example#1609 - Problems with setting the character set with SQL
  • Example#1610 - Setting the character set example: mysqli
  • Example#1611 - Setting the character set example: pdo_mysql
  • Example#1612 - Easy migration from the old mysql extension
  • Example#1613 - Object-oriented and procedural interface
  • Example#1614 - Bad coding style
  • Example#1615 - Special meaning of localhost
  • Example#1616 - Setting defaults
  • Example#1617 - Connecting to MySQL
  • Example#1618 - Navigation through buffered results
  • Example#1619 - Navigation through unbuffered results
  • Example#1620 - Text protocol returns strings by default
  • Example#1621 - Native data types with mysqlnd and connection option
  • Example#1622 - First stage: prepare
  • Example#1623 - Second stage: bind and execute
  • Example#1624 - INSERT prepared once, executed multiple times
  • Example#1625 - Less round trips using multi-INSERT SQL
  • Example#1626 - Native datatypes
  • Example#1627 - Output variable binding
  • Example#1628 - Using mysqli_result to fetch results
  • Example#1629 - Buffered result set for flexible read out
  • Example#1630 - Calling a stored procedure
  • Example#1631 - Using session variables
  • Example#1632 - Fetching results from stored procedures
  • Example#1633 - Stored Procedures and Prepared Statements
  • Example#1634 - Stored Procedures and Prepared Statements using bind API
  • Example#1635 - Multiple Statements
  • Example#1636 - SQL Injection
  • Example#1637 - Setting autocommit mode with SQL and through the API
  • Example#1638 - Commit and rollback
  • Example#1639 - Accessing result set meta data
  • Example#1640 - Prepared statements metadata
  • Example#1641 - $mysqli->affected_rows example
  • Example#1642 - mysqli::autocommit example
  • Example#1643 - mysqli::begin_transaction example
  • Example#1644 - mysqli::change_user example
  • Example#1645 - mysqli::character_set_name example
  • Example#1646 - mysqli::commit example
  • Example#1647 - $mysqli->connect_errno example
  • Example#1648 - $mysqli->connect_error example
  • Example#1649 - mysqli::__construct example
  • Example#1650 - Extending mysqli class
  • Example#1651 - Manual error handling
  • Example#1652 - Generating a Trace File
  • Example#1653 - mysqli->errno example
  • Example#1654 - $mysqli->error_list example
  • Example#1655 - $mysqli->error example
  • Example#1656 - $mysqli->field_count example
  • Example#1657 - mysqli::get_charset example
  • Example#1658 - mysqli_get_client_info
  • Example#1659 - mysqli_get_client_version
  • Example#1660 - A mysqli_get_connection_stats 例程
  • Example#1661 - $mysqli->host_info example
  • Example#1662 - $mysqli->protocol_version example
  • Example#1663 - $mysqli->server_info example
  • Example#1664 - $mysqli->server_version example
  • Example#1665 - $mysqli->info 例程
  • Example#1666 - $mysqli->insert_id 例程
  • Example#1667 - mysqli::kill 例程
  • Example#1668 - mysqli::multi_query 例程
  • Example#1669 - mysqli::ping 例程
  • Example#1670 - A mysqli_poll 例程
  • Example#1671 - mysqli::prepare 例程
  • Example#1672 - mysqli::query example
  • Example#1673 - mysqli::real_connect 例子
  • Example#1674 - mysqli::real_escape_string 例程
  • Example#1675 - mysqli::rollback example
  • Example#1676 - mysqli::select_db example
  • Example#1677 - mysqli::set_charset example
  • Example#1678 - $mysqli->sqlstate 例程
  • Example#1679 - mysqli::stat 例程
  • Example#1680 - $mysqli->thread_id 例程
  • Example#1681 - mysqli::use_result example
  • Example#1682 - $mysqli->warning_count example
  • Example#1683 - 面向对象风格
  • Example#1684 - 过程化风格
  • Example#1685 - 面向对象风格
  • Example#1686 - 过程化风格
  • Example#1687 - 面向对象风格
  • Example#1688 - 过程化风格
  • Example#1689 - 面向对象风格
  • Example#1690 - 过程化风格
  • Example#1691 - 面向对象风格
  • Example#1692 - 过程化风格
  • Example#1693 - 面向对象风格
  • Example#1694 - 过程化风格
  • Example#1695 - 面向对象风格
  • Example#1696 - 过程化风格
  • Example#1697 - 面向对象风格
  • Example#1698 - 过程化风格
  • Example#1699 - 面向对象风格
  • Example#1700 - 过程化风格
  • Example#1701 - 面向对象风格
  • Example#1702 - 过程化风格
  • Example#1703 - 面向对象风格
  • Example#1704 - 过程化风格
  • Example#1705 - 面向对象风格
  • Example#1706 - 过程化风格
  • Example#1707 - 面向对象风格
  • Example#1708 - 过程化风格
  • Example#1709 - 面向对象风格
  • Example#1710 - 过程化风格
  • Example#1711 - 面向对象风格
  • Example#1712 - 过程化风格
  • Example#1713 - 面向对象风格
  • Example#1714 - 面向对象风格
  • Example#1715 - 过程化风格
  • Example#1716 - 面向对象风格
  • Example#1717 - 过程化风格
  • Example#1718 - 面向对象风格
  • Example#1719 - 过程化风格
  • Example#1720 - 面向对象风格
  • Example#1721 - 过程化风格
  • Example#1722 - mysqli_result::fetch_array example
  • Example#1723 - mysqli_result::fetch_assoc example
  • Example#1724 - Comparison of mysqli_result iterator and mysqli_result::fetch_assoc usage
  • Example#1725 - 面向对象风格
  • Example#1726 - 过程化风格
  • Example#1727 - 面向对象风格
  • Example#1728 - 过程化风格
  • Example#1729 - 面向对象风格
  • Example#1730 - 过程化风格
  • Example#1731 - mysqli_result::fetch_object example
  • Example#1732 - mysqli_result::fetch_row example
  • Example#1733 - 面向对象风格
  • Example#1734 - 过程化风格
  • Example#1735 - 面向对象风格
  • Example#1736 - 过程化风格
  • Example#1737 - 面向对象风格
  • Example#1738 - 过程化风格
  • Example#1739 - 面向对象风格
  • Example#1740 - 过程化风格
  • Example#1741 - 面向对象风格
  • Example#1742 - 过程化风格
  • Example#1743 - Error reporting except bad index errors
  • Example#1744 - mysqli_connect 例程
  • Example#1745 - A mysqli_get_client_stats 例程
  • Example#1746 - Connecting to a MySQL Server
  • Example#1747 - Creating a Schema and Collection on the MySQL Server
  • Example#1748 - Storing and Retrieving Data
  • Example#1749 - Fetching and Iterating Multiple Documents
  • Example#1750 - mysql_xdevapi\Expression example
  • Example#1751 - URI examples
  • Example#1752 - mysql_xdevapi\getSession example
  • Example#1753 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1754 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1755 - mysql_xdevapi\Client::__construct example
  • Example#1756 - mysql_xdevapi\Collection::add example
  • Example#1757 - mysql_xdevapi\Collection::addOrReplaceOne example
  • Example#1758 - mysql_xdevapi\Collection::getOne example
  • Example#1759 - mysql_xdevapi\Collection::count example
  • Example#1760 - mysql_xdevapi\Collection::createIndex example
  • Example#1761 - mysql_xdevapi\Collection::dropIndex example
  • Example#1762 - mysql_xdevapi\Collection::existsInDatabase example
  • Example#1763 - mysql_xdevapi\Collection::find example
  • Example#1764 - mysql_xdevapi\Collection::getName example
  • Example#1765 - mysql_xdevapi\Collection::getOne example
  • Example#1766 - mysql_xdevapi\Collection::getSchema example
  • Example#1767 - mysql_xdevapi\Collection::getSession example
  • Example#1768 - mysql_xdevapi\Collection::modify example
  • Example#1769 - mysql_xdevapi\Collection::remove example
  • Example#1770 - mysql_xdevapi\Collection::removeOne example
  • Example#1771 - mysql_xdevapi\Collection::replaceOne example
  • Example#1772 - mysql_xdevapi\CollectionAdd::__construct example
  • Example#1773 - mysql_xdevapi\CollectionAdd::execute example
  • Example#1774 - mysql_xdevapi\CollectionFind::bind example
  • Example#1775 - CollectionFind example
  • Example#1776 - CollectionFind example
  • Example#1777 - mysql_xdevapi\CollectionFind::fields example
  • Example#1778 - mysql_xdevapi\CollectionFind::groupBy example
  • Example#1779 - mysql_xdevapi\CollectionFind::having example
  • Example#1780 - mysql_xdevapi\CollectionFind::limit example
  • Example#1781 - mysql_xdevapi\CollectionFind::lockExclusive example
  • Example#1782 - mysql_xdevapi\CollectionFind::lockShared example
  • Example#1783 - mysql_xdevapi\CollectionFind::offset example
  • Example#1784 - mysql_xdevapi\CollectionFind::sort example
  • Example#1785 - mysql_xdevapi\CollectionModify::arrayAppend example
  • Example#1786 - mysql_xdevapi\CollectionModify::arrayInsert example
  • Example#1787 - mysql_xdevapi\CollectionModify::bind example
  • Example#1788 - mysql_xdevapi\CollectionModify::__construct example
  • Example#1789 - mysql_xdevapi\CollectionModify::execute example
  • Example#1790 - mysql_xdevapi\CollectionModify::limit example
  • Example#1791 - mysql_xdevapi\CollectionModify::patch example
  • Example#1792 - mysql_xdevapi\CollectionModify::replace example
  • Example#1793 - mysql_xdevapi\CollectionModify::set example
  • Example#1794 - mysql_xdevapi\CollectionModify::skip example
  • Example#1795 - mysql_xdevapi\CollectionModify::sort example
  • Example#1796 - mysql_xdevapi\CollectionModify::unset example
  • Example#1797 - mysql_xdevapi\CollectionRemove::bind example
  • Example#1798 - mysql_xdevapi\Collection::remove example
  • Example#1799 - mysql_xdevapi\CollectionRemove::execute example
  • Example#1800 - mysql_xdevapi\CollectionRemove::limit example
  • Example#1801 - mysql_xdevapi\CollectionRemove::sort example
  • Example#1802 - mysql_xdevapi\ColumnResult::__construct example
  • Example#1803 - mysql_xdevapi\ColumnResult::getCharacterSetName example
  • Example#1804 - mysql_xdevapi\ColumnResult::getCollationName example
  • Example#1805 - mysql_xdevapi\ColumnResult::getColumnLabel example
  • Example#1806 - mysql_xdevapi\ColumnResult::getColumnName example
  • Example#1807 - mysql_xdevapi\ColumnResult::getFractionalDigits example
  • Example#1808 - mysql_xdevapi\ColumnResult::getLength example
  • Example#1809 - mysql_xdevapi\ColumnResult::getSchemaName example
  • Example#1810 - mysql_xdevapi\ColumnResult::getTableLabel example
  • Example#1811 - mysql_xdevapi\ColumnResult::getTableName example
  • Example#1812 - mysql_xdevapi\ColumnResult::getType example
  • Example#1813 - mysql_xdevapi\ColumnResult::isNumberSigned example
  • Example#1814 - mysql_xdevapi\ColumnResult::isPadded example
  • Example#1815 - mysql_xdevapi\CrudOperationBindable::bind example
  • Example#1816 - mysql_xdevapi\CrudOperationLimitable::limit example
  • Example#1817 - mysql_xdevapi\CrudOperationSkippable::skip example
  • Example#1818 - mysql_xdevapi\CrudOperationSortable::sort example
  • Example#1819 - mysql_xdevapi\DatabaseObject::existsInDatabase example
  • Example#1820 - mysql_xdevapi\DatabaseObject::getName example
  • Example#1821 - mysql_xdevapi\DatabaseObject::getSession example
  • Example#1822 - A DocResult example
  • Example#1823 - mysql_xdevapi\DocResult::fetchAll example
  • Example#1824 - mysql_xdevapi\DocResult::fetchOne example
  • Example#1825 - mysql_xdevapi\DocResult::getWarnings example
  • Example#1826 - mysql_xdevapi\DocResult::getWarningsCount example
  • Example#1827 - execute() examples
  • Example#1828 - mysql_xdevapi\ExecutionStatus::__construct example
  • Example#1829 - mysql_xdevapi\Expression::__construct example
  • Example#1830 - mysql_xdevapi\Result::__construct example
  • Example#1831 - mysql_xdevapi\Result::getAffectedItemsCount example
  • Example#1832 - mysql_xdevapi\Result::getAutoIncrementValue example
  • Example#1833 - mysql_xdevapi\Result::getGeneratedIds example
  • Example#1834 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1835 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1836 - mysql_xdevapi\RowResult::__construct example
  • Example#1837 - mysql_xdevapi\RowResult::fetchAll example
  • Example#1838 - mysql_xdevapi\RowResult::fetchOne example
  • Example#1839 - mysql_xdevapi\RowResult::getColumnsCount example
  • Example#1840 - mysql_xdevapi\RowResult::getColumnNames example
  • Example#1841 - mysql_xdevapi\RowResult::getColumns example
  • Example#1842 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1843 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1844 - Schema::__construct example
  • Example#1845 - Schema::createCollection example
  • Example#1846 - Schema::dropCollection example
  • Example#1847 - Schema::existsInDatabase example
  • Example#1848 - Schema::getCollection example
  • Example#1849 - Schema::getCollectionAsTable example
  • Example#1850 - mysql_xdevapi\Schema::getCollections example
  • Example#1851 - mysql_xdevapi\Schema::getName example
  • Example#1852 - mysql_xdevapi\Schema::getSession example
  • Example#1853 - mysql_xdevapi\Schema::getTable example
  • Example#1854 - mysql_xdevapi\Schema::getTables example
  • Example#1855 - mysql_xdevapi\Session::getSchema example
  • Example#1856 - mysql_xdevapi\Session::close example
  • Example#1857 - mysql_xdevapi\Session::commit example
  • Example#1858 - mysql_xdevapi\Session::__construct example
  • Example#1859 - mysql_xdevapi\Session::createSchema example
  • Example#1860 - mysql_xdevapi\Session::dropSchema example
  • Example#1861 - mysql_xdevapi\Session::generateUuid example
  • Example#1862 - mysql_xdevapi\Session::getSchema example
  • Example#1863 - mysql_xdevapi\Session::getSchema example
  • Example#1864 - mysql_xdevapi\Session::getSchemas example
  • Example#1865 - mysql_xdevapi\Session::getServerVersion example
  • Example#1866 - mysql_xdevapi\Session::listClients example
  • Example#1867 - mysql_xdevapi\Session::quoteName example
  • Example#1868 - mysql_xdevapi\Session::releaseSavepoint example
  • Example#1869 - mysql_xdevapi\Session::rollback example
  • Example#1870 - mysql_xdevapi\Session::rollbackTo example
  • Example#1871 - mysql_xdevapi\Session::setSavepoint example
  • Example#1872 - mysql_xdevapi\Session::sql example
  • Example#1873 - mysql_xdevapi\Session::startTransaction example
  • Example#1874 - mysql_xdevapi\SqlStatement::bind example
  • Example#1875 - mysql_xdevapi\SqlStatement::__construct example
  • Example#1876 - mysql_xdevapi\SqlStatement::execute example
  • Example#1877 - mysql_xdevapi\SqlStatement::getNextResult example
  • Example#1878 - mysql_xdevapi\SqlStatement::getResult example
  • Example#1879 - mysql_xdevapi\SqlStatement::hasMoreResults example
  • Example#1880 - mysql_xdevapi\SqlStatementResult::__construct example
  • Example#1881 - mysql_xdevapi\SqlStatementResult::fetchAll example
  • Example#1882 - mysql_xdevapi\SqlStatementResult::fetchOne example
  • Example#1883 - mysql_xdevapi\SqlStatementResult::getAffectedItemsCount example
  • Example#1884 - mysql_xdevapi\SqlStatementResult::getColumnsCount example
  • Example#1885 - mysql_xdevapi\SqlStatementResult::getColumnNames example
  • Example#1886 - mysql_xdevapi\SqlStatementResult::getColumns example
  • Example#1887 - mysql_xdevapi\SqlStatementResult::getGeneratedIds example
  • Example#1888 - mysql_xdevapi\SqlStatementResult::getLastInsertId example
  • Example#1889 - mysql_xdevapi\SqlStatementResult::getWarnings example
  • Example#1890 - mysql_xdevapi\SqlStatementResult::getWarningsCount example
  • Example#1891 - mysql_xdevapi\SqlStatementResult::hasData example
  • Example#1892 - mysql_xdevapi\SqlStatementResult::nextResult example
  • Example#1893 - mysql_xdevapi\Statement::__construct example
  • Example#1894 - mysql_xdevapi\Statement::getNextResult example
  • Example#1895 - mysql_xdevapi\Statement::getResult example
  • Example#1896 - mysql_xdevapi\Statement::hasMoreResults example
  • Example#1897 - mysql_xdevapi\Table::__construct example
  • Example#1898 - mysql_xdevapi\Table::count example
  • Example#1899 - mysql_xdevapi\Table::delete example
  • Example#1900 - mysql_xdevapi\Table::existsInDatabase example
  • Example#1901 - mysql_xdevapi\Table::getName example
  • Example#1902 - mysql_xdevapi\Table::getSchema example
  • Example#1903 - mysql_xdevapi\Table::getSession example
  • Example#1904 - mysql_xdevapi\Table::insert example
  • Example#1905 - mysql_xdevapi\Table::isView example
  • Example#1906 - mysql_xdevapi\Table::count example
  • Example#1907 - mysql_xdevapi\Table::update example
  • Example#1908 - mysql_xdevapi\TableDelete::bind example
  • Example#1909 - mysql_xdevapi\TableDelete::__construct example
  • Example#1910 - mysql_xdevapi\TableDelete::execute example
  • Example#1911 - mysql_xdevapi\TableDelete::limit example
  • Example#1912 - mysql_xdevapi\TableDelete::orderBy example
  • Example#1913 - mysql_xdevapi\TableDelete::where example
  • Example#1914 - mysql_xdevapi\TableInsert::__construct example
  • Example#1915 - mysql_xdevapi\TableInsert::execute example
  • Example#1916 - mysql_xdevapi\TableInsert::values example
  • Example#1917 - mysql_xdevapi\TableSelect::bind example
  • Example#1918 - mysql_xdevapi\TableSelect::__construct example
  • Example#1919 - mysql_xdevapi\TableSelect::execute example
  • Example#1920 - mysql_xdevapi\TableSelect::groupBy example
  • Example#1921 - mysql_xdevapi\TableSelect::having example
  • Example#1922 - mysql_xdevapi\TableSelect::limit example
  • Example#1923 - mysql_xdevapi\TableSelect::lockExclusive example
  • Example#1924 - mysql_xdevapi\TableSelect::lockShared example
  • Example#1925 - mysql_xdevapi\TableSelect::offset example
  • Example#1926 - mysql_xdevapi\TableSelect::orderBy example
  • Example#1927 - mysql_xdevapi\TableSelect::where example
  • Example#1928 - mysql_xdevapi\TableUpdate::bind example
  • Example#1929 - mysql_xdevapi\TableUpdate::__construct example
  • Example#1930 - mysql_xdevapi\TableUpdate::execute example
  • Example#1931 - mysql_xdevapi\TableUpdate::limit example
  • Example#1932 - mysql_xdevapi\TableUpdate::orderby example
  • Example#1933 - mysql_xdevapi\TableUpdate::set example
  • Example#1934 - mysql_xdevapi\TableUpdate::where example
  • Example#1935 - mysql_xdevapi\Warning::__construct example
  • Example#1936 - MySQL 扩展概述范例
  • Example#1937 - mysql_affected_rows 例子
  • Example#1938 - 使用事务处理的 mysql_affected_rows 例子
  • Example#1939 - mysql_client_encoding 例子
  • Example#1940 - mysql_close 例子
  • Example#1941 - mysql_connect 例子
  • Example#1942 - mysql_connect 例子：使用 hostname:port 语法
  • Example#1943 - mysql_connect 例子：使用 ":/path/to/socket" 语法
  • Example#1944 - 替代 mysql_create_db 的例子
  • Example#1945 - mysql_data_seek 例子
  • Example#1946 - mysql_db_name 例子
  • Example#1947 - mysql_drop_db alternative example
  • Example#1948 - mysql_errno 例子
  • Example#1949 - mysql_error 例子
  • Example#1950 - mysql_escape_string 例子
  • Example#1951 - msql_fetch_array 示例
  • Example#1952 - 扩展的 mysql_fetch_assoc 例子
  • Example#1953 - mysql_fetch_field
  • Example#1954 - mysql_fetch_field example
  • Example#1955 - mysql_fetch_object example
  • Example#1956 - mysql_fetch_object example
  • Example#1957 - Fetching one row with mysql_fetch_row
  • Example#1958 - mysql_field_name 例子
  • Example#1959 - mysql_field_name example
  • Example#1960 - mysql_field_type 例子
  • Example#1961 - mysql_field_type example
  • Example#1962 - A mysql_free_result example
  • Example#1963 - mysql_get_client_info 例子
  • Example#1964 - mysql_get_host_info 例子
  • Example#1965 - mysql_get_proto_info 例子
  • Example#1966 - mysql_get_server_info 例子
  • Example#1967 - 相关的 MySQL 语句
  • Example#1968 - mysql_insert_id 例子
  • Example#1969 - mysql_list_dbs 例子
  • Example#1970 - mysql_list_fields 例子
  • Example#1971 - mysql_list_processes 例子
  • Example#1972 - mysql_list_tables 例子
  • Example#1973 - mysql_num_rows 例子
  • Example#1974 - 无效的查询
  • Example#1975 - 有效的查询
  • Example#1976 - mysql_real_escape_string 例子
  • Example#1977 - mysql_real_escape_string requires a connection example
  • Example#1978 - An example SQL Injection Attack
  • Example#1979 - mysql_result 例子
  • Example#1980 - mysql_select_db 例子
  • Example#1981 - mysql_select_db example
  • Example#1982 - mysql_stat 例子
  • Example#1983 - mysql_tablename example
  • Example#1984 - mysql_thread_id 例子
  • Example#1985 - 启用插件(php.ini)
  • Example#1986 - 最基本的插件配置文件 (mysqlnd_ms_plugin.ini)
  • Example#1987 - 建议最基本的插件配置文件 (mysqlnd_ms_plugin.ini)
  • Example#1988 - 使用一个服务器同时作为 master 和 slave（仅用于测试！）
  • Example#1989 - 插件指定的配置文件 (mysqlnd_ms_plugin.ini)
  • Example#1990 - 开启一个负载均衡链接
  • Example#1991 - Executing statements
  • Example#1992 - 配置了一个 master 和一个 slave 的插件
  • Example#1993 - 陷阱：连接状态和 SQL 用户变量
  • Example#1994 - 配置一个 master 和一个 slave 的插件
  • Example#1995 - SQL hints 禁止连接切换
  • Example#1996 - 与同步延迟斗争
  • Example#1997 - Table creation on a slave
  • Example#1998 - 配置一个 master 和一个 slave 的插件
  • Example#1999 - 在事务中使用 SQL hints
  • Example#2000 - 事务相关负载均衡下的 trx_stickiness 设置
  • Example#2001 - Transaction aware
  • Example#2002 - General pattern for XA transactions
  • Example#2003 - Local and global transactions are mutually exclusive
  • Example#2004 - Transaction coordinator state store
  • Example#2005 - session 一致性：读取写入内容
  • Example#2006 - Requesting session consistency
  • Example#2007 - Maximum age/slave lag
  • Example#2008 - 限制 slave 延迟
  • Example#2009 - 不设置故障处理
  • Example#2010 - No slave within time limit
  • Example#2011 - 在 master 创建计数器表
  • Example#2012 - Plugin config: SQL for client-side GTID injection
  • Example#2013 - Transparent global transaction ID injection
  • Example#2014 - Plugin config: SQL for fetching GTID
  • Example#2015 - Obtaining GTID after injection
  • Example#2016 - Plugin config: Checking for a certain GTID
  • Example#2017 - Session consistency service level and GTID combined
  • Example#2018 - 使用 MySQL 5.6.5-m8 内置 GTID
  • Example#2019 - Recap: quality of service to request read your writes
  • Example#2020 - Plugin config: no special entries for caching
  • Example#2021 - Caching a slave request
  • Example#2022 - Read your writes and caching combined
  • Example#2023 - 手动故障转移，可选自动
  • Example#2024 - 手动故障转移
  • Example#2025 - Cluster node groups
  • Example#2026 - 通过 SQL hints 完成手动分区
  • Example#2027 - Plugin config: Fabric hosts instead of MySQL servers
  • Example#2028 - Manual partitioning using SQL hints
  • Example#2029 - Provoking a connection error
  • Example#2030 - 在查询执行时产生连接错误
  • Example#2031 - 产生一个连接错误
  • Example#2032 - 非常基础的错误处理
  • Example#2033 - Provoking a transient error
  • Example#2034 - 短错误尝试循环
  • Example#2035 - Enabling the plugin (php.ini)
  • Example#2036 - Basic plugin configuration (mysqlnd_ms_plugin.ini) for MySQL Replication
  • Example#2037 - Multiple primaries - multi master (php.ini)
  • Example#2038 - Primary copy with multiple primaries and paritioning
  • Example#2039 - Multiple primaries - multi master (php.ini)
  • Example#2040 - Synchronous update anywhere cluster
  • Example#2041 - General pattern for XA transactions
  • Example#2042 - Converting a PHP array (hash) into JSON format
  • Example#2043 - Using section names example
  • Example#2044 - List of anonymous slaves
  • Example#2045 - Master list using symbolic names
  • Example#2046 - Keywords to configure a server
  • Example#2047 - New roundrobin filter, old functionality
  • Example#2048 - The user filter replaces mysqlnd_ms_set_user_pick_server
  • Example#2049 - Common error message in case of configuration file issues (upto version 1.5.0)
  • Example#2050 - Improved configuration file validation since 1.5.0
  • Example#2051 - Possibly more precise error due to mysqlnd_ms.force_config_usage=1
  • Example#2052 - Minimum pluging configuration for use with MySQL Fabric
  • Example#2053 - Optional timeout for communication with Fabric
  • Example#2054 - Warnings about the violation of transaction boundaries
  • Example#2055 - Invalid filter sequence
  • Example#2056 - Random load balancing with random filter
  • Example#2057 - Random once load balancing with random filter
  • Example#2058 - Referencing error
  • Example#2059 - Assigning a weight for load balancing
  • Example#2060 - roundrobin filter
  • Example#2061 - Setting a callback
  • Example#2062 - Using a callback
  • Example#2063 - Returning random masters and slaves
  • Example#2064 - Manual partitioning
  • Example#2065 - Global limit on slave lag
  • Example#2066 - Optional master failover when failing to connect to slave (PECL/mysqlnd_ms < 1.4.0)
  • Example#2067 - New syntax since 1.4.0
  • Example#2068 - Disabling lazy connection
  • Example#2069 - String escaping on a lazy connection handle
  • Example#2070 - Master on write for consistent reads
  • Example#2071 - Using master to execute transactions
  • Example#2072 - No automatic failover, error handling pitfall
  • Example#2073 - Retry loop for transient errors
  • Example#2074 - SQL definition for the MySQL state store transaction table
  • Example#2075 - SQL definition for the MySQL state store transaction table
  • Example#2076 - SQL definition for the MySQL state store garbage collection table
  • Example#2077 - Using section names example
  • Example#2078 - List-like syntax
  • Example#2079 - Verify plugin activity in a non-threaded deployment model
  • Example#2080 - Recording statistics during shutdown
  • Example#2081 - Example demonstrating the usage of mysqlnd_ms constants
  • Example#2082 - mysqlnd_ms_dump_servers example
  • Example#2083 - mysqlnd_ms_get_last_gtid example
  • Example#2084 - mysqlnd_ms_get_last_used_connection example
  • Example#2085 - mysqlnd_ms_get_stats example
  • Example#2086 - mysqlnd_ms_match_wild example
  • Example#2087 - mysqlnd_ms_query_is_select example
  • Example#2088 - mysqlnd_ms_set_qos example
  • Example#2089 - mysqlnd_ms_set_user_pick_server example
  • Example#2090 - Enabling the plugin (php.ini)
  • Example#2091 - Using the MYSQLND_QC_ENABLE_SWITCH SQL hint
  • Example#2092 - Using the MYSQLND_QC_DISABLE_SWITCH SQL hint
  • Example#2093 - Example showing which type of statements are not cached
  • Example#2094 - Enabling caching for all statements using the mysqlnd_qc.cache_no_table ini setting
  • Example#2095 - Setting the TTL with the mysqlnd_qc.ttl ini setting
  • Example#2096 - Setting TTL with SQL hints
  • Example#2097 - Setting a callback with mysqlnd_qc_set_is_select
  • Example#2098 - Enabling the slam defense mechanism
  • Example#2099 - Collecting a query trace
  • Example#2100 - Setting the backtrace depth with the mysqlnd_qc.query_trace_bt_depth ini setting
  • Example#2101 - Collecting statistics data with the mysqlnd_qc.time_statistics ini setting
  • Example#2102 - Example mysqlnd_qc_get_cache_info usage
  • Example#2103 - Example mysqlnd_qc_get_normalized_query_trace_log usage
  • Example#2104 - Using a user-defined storage handler
  • Example#2105 - Using SQL hint constants
  • Example#2106 - Example mysqlnd_qc_set_cache_condition usage
  • Example#2107 - mysqlnd_qc_get_available_handlers example
  • Example#2108 - mysqlnd_qc_get_cache_info example
  • Example#2109 - mysqlnd_qc_get_core_stats example
  • Example#2110 - mysqlnd_qc_get_normalized_query_trace_log example
  • Example#2111 - mysqlnd_qc_get_query_trace_log example
  • Example#2112 - mysqlnd_qc_set_cache_condition example
  • Example#2113 - mysqlnd_qc_set_is_select example
  • Example#2114 - mysqlnd_qc_set_storage_handler example
  • Example#2115 - Enabling the plugin (php.ini)
  • Example#2116 - Pseudo-code: what a built-in class does
  • Example#2117 - Installing a proxy
  • Example#2118 - Proxy registration, mysqlnd_uh.enable=1
  • Example#2119 - Proxy installation disabled
  • Example#2120 - Connection proxy
  • Example#2121 - Prepared statement proxy
  • Example#2122 - Basic Monitoring
  • Example#2123 - MysqlndUhConnection::changeUser example
  • Example#2124 - MysqlndUhConnection::charsetName example
  • Example#2125 - MysqlndUhConnection::close example
  • Example#2126 - MysqlndUhConnection::connect example
  • Example#2127 - MysqlndUhConnection::endPSession example
  • Example#2128 - MysqlndUhConnection::escapeString example
  • Example#2129 - MysqlndUhConnection::getAffectedRows example
  • Example#2130 - MysqlndUhConnection::getErrorNumber example
  • Example#2131 - MysqlndUhConnection::getErrorString example
  • Example#2132 - MysqlndUhConnection::getFieldCount example
  • Example#2133 - MysqlndUhConnection::getHostInformation example
  • Example#2134 - MysqlndUhConnection::getLastInsertId example
  • Example#2135 - MysqlndUhConnection::getLastMessage example
  • Example#2136 - MysqlndUhConnection::getProtocolInformation example
  • Example#2137 - MysqlndUhConnection::getServerInformation example
  • Example#2138 - MysqlndUhConnection::getServerStatistics example
  • Example#2139 - MysqlndUhConnection::getServerVersion example
  • Example#2140 - MysqlndUhConnection::getSqlstate example
  • Example#2141 - MysqlndUhConnection::getStatistics example
  • Example#2142 - MysqlndUhConnection::getThreadId example
  • Example#2143 - MysqlndUhConnection::getWarningCount example
  • Example#2144 - MysqlndUhConnection::init example
  • Example#2145 - MysqlndUhConnection::kill example
  • Example#2146 - MysqlndUhConnection::listFields example
  • Example#2147 - MysqlndUhConnection::listMethod example
  • Example#2148 - MysqlndUhConnection::moreResults example
  • Example#2149 - MysqlndUhConnection::nextResult example
  • Example#2150 - MysqlndUhConnection::ping example
  • Example#2151 - MysqlndUhConnection::query example
  • Example#2152 - MysqlndUhConnection::queryReadResultsetHeader example
  • Example#2153 - MysqlndUhConnection::reapQuery example
  • Example#2154 - MysqlndUhConnection::refreshServer example
  • Example#2155 - MysqlndUhConnection::restartPSession example
  • Example#2156 - MysqlndUhConnection::selectDb example
  • Example#2157 - MysqlndUhConnection::sendClose example
  • Example#2158 - MysqlndUhConnection::sendQuery example
  • Example#2159 - MysqlndUhConnection::serverDumpDebugInformation example
  • Example#2160 - MysqlndUhConnection::setAutocommit example
  • Example#2161 - MysqlndUhConnection::setCharset example
  • Example#2162 - MysqlndUhConnection::setClientOption example
  • Example#2163 - MysqlndUhConnection::setServerOption example
  • Example#2164 - MysqlndUhConnection::simpleCommand example
  • Example#2165 - MysqlndUhConnection::simpleCommandHandleResponse example
  • Example#2166 - MysqlndUhConnection::sslSet example
  • Example#2167 - MysqlndUhConnection::stmtInit example
  • Example#2168 - MysqlndUhConnection::storeResult example
  • Example#2169 - MysqlndUhConnection::txCommit example
  • Example#2170 - MysqlndUhConnection::txRollback example
  • Example#2171 - MysqlndUhConnection::useResult example
  • Example#2172 - MysqlndUhPreparedStatement::execute example
  • Example#2173 - MysqlndUhPreparedStatement::prepare example
  • Example#2174 - mysqlnd_uh_convert_to_mysqlnd example
  • Example#2175 - mysqlnd_uh_set_connection_proxy example
  • Example#2176 - Enabling the plugin (php.ini)
  • Example#2177 - SQL table used for the Quickstart
  • Example#2178 - Basic example.
  • Example#2179 - mysqlnd_memcache_get_config example
  • Example#2180 - mysqlnd_memcache_set example with var_dump as a simple debugging callback.
  • Example#2181 - Basic query
  • Example#2182 - Inserting with bind variables
  • Example#2183 - Binding in the WHERE clause of a query
  • Example#2184 - Inserting and fetching a CLOB
  • Example#2185 - Using a PL/SQL stored function
  • Example#2186 - Using a PL/SQL stored procedure
  • Example#2187 - Calling a PL/SQL function that returns a REF CURSOR
  • Example#2188 -
  • Example#2189 - user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace
  • Example#2190 - oci_bind_array_by_name example
  • Example#2191 - oci_bind_by_name 例子
  • Example#2192 - oci_bind_by_name 例子
  • Example#2193 - oci_bind_by_name 例子
  • Example#2194 - Inserting data with oci_bind_by_name
  • Example#2195 - Binding once for multiple executions
  • Example#2196 - Binding with a foreach loop
  • Example#2197 - Binding in a WHERE clause
  • Example#2198 - Binding with a LIKE clause
  • Example#2199 - Binding with REGEXP_LIKE
  • Example#2200 - Binding Multiple Values in an IN Clause
  • Example#2201 - Binding a ROWID returned by a query
  • Example#2202 - Binding a ROWID on INSERT
  • Example#2203 - Binding for a PL/SQL stored function
  • Example#2204 - Binding parameters for a PL/SQL stored procedure
  • Example#2205 - Binding a CLOB column
  • Example#2206 - Binding a PL/SQL BOOLEAN
  • Example#2207 - oci_client_version example
  • Example#2208 - Closing a connection
  • Example#2209 - Database connections are not closed until all references are closed
  • Example#2210 - Closing a connection opened more than once
  • Example#2211 - Connections are closed when variables go out of scope
  • Example#2212 - oci_commit 例子
  • Example#2213 - oci_commit example
  • Example#2214 - oci_connect 例子
  • Example#2215 - Basic oci_connect using Easy Connect syntax
  • Example#2216 - Basic oci_connect using a Network Connect name
  • Example#2217 - oci_connect with an explicit character set
  • Example#2218 - Using multiple calls to oci_connect
  • Example#2219 - oci_define_by_name 例子
  • Example#2220 - 连接错误后显示 Oracle 错误信息
  • Example#2221 - 语法解析错误后显示 Oracle 错误信息
  • Example#2222 - 执行错误后显示 Oracle 错误信息和出错的语句
  • Example#2223 - oci_execute for queries
  • Example#2224 - oci_execute without specifying a mode example
  • Example#2225 - oci_execute with OCI_NO_AUTO_COMMIT example
  • Example#2226 - oci_execute with different commit modes example
  • Example#2227 - oci_execute with OCI_DESCRIBE_ONLY example
  • Example#2228 - oci_fetch_all 例子
  • Example#2229 - oci_fetch_all example
  • Example#2230 - oci_fetch_all example with OCI_FETCHSTATEMENT_BY_ROW
  • Example#2231 - oci_fetch_all with OCI_NUM
  • Example#2232 - oci_fetch_array with OCI_BOTH
  • Example#2233 - oci_fetch_array with OCI_NUM
  • Example#2234 - oci_fetch_array with OCI_ASSOC
  • Example#2235 - oci_fetch_array with OCI_RETURN_NULLS
  • Example#2236 - oci_fetch_array with OCI_RETURN_LOBS
  • Example#2237 - oci_fetch_array with case sensitive column names
  • Example#2238 - oci_fetch_array with columns having duplicate names
  • Example#2239 - oci_fetch_array with DATE columns
  • Example#2240 - oci_fetch_array with REF CURSOR
  • Example#2241 - Pagination with oci_fetch_array using a LIMIT-like query
  • Example#2242 - oci_fetch_array with Oracle Database Implicit Result Sets
  • Example#2243 - oci_fetch_assoc Example
  • Example#2244 - oci_fetch_object example
  • Example#2245 - oci_fetch_object with case sensitive column names
  • Example#2246 - oci_fetch_object with LOBs
  • Example#2247 - oci_fetch_row Example
  • Example#2248 - oci_fetch with defined variables
  • Example#2249 - oci_fetch with oci_result
  • Example#2250 - oci_field_name 例子
  • Example#2251 - oci_field_size例子
  • Example#2252 - oci_field_type 例子
  • Example#2253 - Fetching Implicit Result Sets in a loop
  • Example#2254 - Getting child statement handles individually
  • Example#2255 - Explicitly setting the Prefetch Count
  • Example#2256 - Implicit Result Set example without using oci_get_implicit_resultset
  • Example#2257 - oci_new_connect 例子
  • Example#2258 - oci_new_connect example
  • Example#2259 - 在 Oracle 的存储过程中使用 REF CURSOR
  • Example#2260 - 在 Oracle 的 select 语句中使用 REF CURSOR
  • Example#2261 - oci_new_descriptor 例子
  • Example#2262 - oci_new_descriptor 例子
  • Example#2263 - oci_num_fields 例子
  • Example#2264 - oci_num_rows 例子
  • Example#2265 - oci_rollback example
  • Example#2266 - Rolling back to a SAVEPOINT example
  • Example#2267 - oci_server_version 例子
  • Example#2268 - Setting the action
  • Example#2269 - Setting the timeout
  • Example#2270 - Setting the client identifier to the application user
  • Example#2271 - Setting the client information
  • Example#2272 - Setting the DBOP
  • Example#2273 - Two scripts can use different versions of myfunc() at the same time
  • Example#2274 - Setting the module name
  • Example#2275 - Changing the default prefetch value for a query
  • Example#2276 - Changing the default prefetch for a REF CURSOR fetch
  • Example#2277 - Setting the prefetch value when passing a REF CURSOR back to Oracle
  • Example#2278 - oci_statement_type 例子
  • Example#2279 - Creating a Paradox database with two fields
  • Example#2280 - Turn a paradox date into a human readable form
  • Example#2281 - Set the date/time fields in a paradox database to the current date/time
  • Example#2282 - Opening a Paradox database
  • Example#2283 - Opening a Paradox database
  • Example#2284 - Turn a paradox timestamp into a human readable form
  • Example#2285 - PostgreSQL extension overview example
  • Example#2286 - PostgreSQL user defined functions example
  • Example#2287 - pg_affected_rows 例子
  • Example#2288 - pg_close 例子
  • Example#2289 - 使用 pg_connect
  • Example#2290 - pg_connection_busy 例子
  • Example#2291 - pg_connection_reset 例子
  • Example#2292 - pg_connection_status 例子
  • Example#2293 - pg_connection_status 例子
  • Example#2294 - pg_convert example
  • Example#2295 - pg_copy_from example
  • Example#2296 - pg_dbname 例子
  • Example#2297 - pg_delete 例子
  • Example#2298 - pg_end_copy 例子
  • Example#2299 - pg_escape_identifier example
  • Example#2300 - pg_escape_literal example
  • Example#2301 - Using pg_execute
  • Example#2302 - pg_fetch_all_columns example
  • Example#2303 - pg_fetch_all 例子
  • Example#2304 - pg_fetch_array
  • Example#2305 - pg_fetch_assoc 例子
  • Example#2306 - pg_fetch_object
  • Example#2307 - pg_fetch_row 例子
  • Example#2308 - pg_field_is_null 例子
  • Example#2309 - 获取字段信息
  • Example#2310 - Getting table information about a field
  • Example#2311 - Getting information about fields
  • Example#2312 - pg_free_result example
  • Example#2313 - PostgreSQL NOTIFY 消息
  • Example#2314 - PostgreSQL 后端 PID
  • Example#2315 - pg_insert example
  • Example#2316 - pg_last_notice example
  • Example#2317 - pg_lo_export example
  • Example#2318 - pg_lo_import 例子
  • Example#2319 - pg_lo_truncate example
  • Example#2320 - pg_lo_unlink example
  • Example#2321 - 取得表的元数据
  • Example#2322 - pg_parameter_status example
  • Example#2323 - Using pg_pconnect
  • Example#2324 - pg_ping
  • Example#2325 - Using pg_prepare
  • Example#2326 - pg_put_line 例子
  • Example#2327 - Using pg_query_params
  • Example#2328 - pg_result_error_field example
  • Example#2329 - pg_select example
  • Example#2330 - Using pg_send_execute
  • Example#2331 - Using pg_send_prepare
  • Example#2332 - Using pg_send_query_params
  • Example#2333 - 异步查询
  • Example#2334 - pg_set_error_verbosity example
  • Example#2335 - pg_transaction_status example
  • Example#2336 - pg_update example
  • Example#2337 - pg_version example
  • Example#2338 - Backup an existing database
  • Example#2339 - SQLite3::changes example
  • Example#2340 - SQLite3::close example
  • Example#2341 - SQLite3::__construct example
  • Example#2342 - max_length aggregation function example
  • Example#2343 - SQLite3::createCollation example
  • Example#2344 - SQLite3::createFunction example
  • Example#2345 - SQLite3::enableExceptions example
  • Example#2346 - SQLite3::exec example
  • Example#2347 - SQLite3::loadExtension example
  • Example#2348 - SQLite3::open example
  • Example#2349 - SQLite3::openBlob example
  • Example#2350 - Incrementally writing a BLOB
  • Example#2351 - SQLite3::prepare example
  • Example#2352 - SQLite3::query example
  • Example#2353 - SQLite3::querySingle example
  • Example#2354 - SQLite3::setAuthorizer example
  • Example#2355 - SQLite3::version example
  • Example#2356 - SQLite3Stmt::bindParam Usage
  • Example#2357 - SQLite3Stmt::bindValue example
  • Example#2358 - Inspecting the expanded SQL
  • Example#2359 - sqlsrv_begin_transaction example
  • Example#2360 - sqlsrv_cancel example
  • Example#2361 - sqlsrv_client_info example
  • Example#2362 - sqlsrv_close example
  • Example#2363 - sqlsrv_commit example
  • Example#2364 - Connect using Windows Authentication.
  • Example#2365 - Connect by specifying a user name and password.
  • Example#2366 - Connect on a specified port.
  • Example#2367 - functionname example
  • Example#2368 - sqlsrv_execute example
  • Example#2369 - Retrieving an associative array.
  • Example#2370 - Retrieving a numeric array.
  • Example#2371 - sqlsrv_fetch_object example
  • Example#2372 - sqlsrv_fetch example
  • Example#2373 - sqlsrv_field_metadata example
  • Example#2374 - sqlsrv_free_stmt example
  • Example#2375 - sqlsrv_get_field example
  • Example#2376 - sqlsrv_has_rows example
  • Example#2377 - sqlsrv_next_result example
  • Example#2378 - sqlsrv_num_fields example
  • Example#2379 - sqlsrv_num_rows example
  • Example#2380 - sqlsrv_prepare example
  • Example#2381 - sqlsrv_query example
  • Example#2382 - sqlsrv_rollback example
  • Example#2383 - sqlsrv_rows_affected example
  • Example#2384 - sqlsrv_send_stream_data example
  • Example#2385 - sqlsrv_server_info example
  • Example#2386 - Putting and getting a key-value pair
  • Example#2387 - TokyoTyrant::add example
  • Example#2388 - TokyoTyrant::connect example
  • Example#2389 - TokyoTyrant::connectUri example
  • Example#2390 - TokyoTyrant::copy example
  • Example#2391 - TokyoTyrant::ext example
  • Example#2392 - TokyoTyrant::fwmKeys example
  • Example#2393 - TokyoTyrant::get example
  • Example#2394 - TokyoTyrant::getIterator example
  • Example#2395 - TokyoTyrant::num example
  • Example#2396 - TokyoTyrant::out example
  • Example#2397 - TokyoTyrant::put example
  • Example#2398 - TokyoTyrant::putCat example
  • Example#2399 - tokyotyrant::putKeep example
  • Example#2400 - TokyoTyrant::putNr example
  • Example#2401 - TokyoTyrant::putShl example
  • Example#2402 - TokyoTyrant::setMaster example
  • Example#2403 - TokyoTyrant::size example
  • Example#2404 - TokyoTyrant::stat example
  • Example#2405 - TokyoTyrant::vanish example
  • Example#2406 - TokyoTyrantTable::genUid example
  • Example#2407 - TokyoTyrantTable::get example
  • Example#2408 - TokyoTyrantTable::getIterator example
  • Example#2409 - TokyoTyrantTable::getQuery example
  • Example#2410 - TokyoTyrantTable::out example
  • Example#2411 - TokyoTyrantTable::put example
  • Example#2412 - TokyoTyrantTable::putCat example
  • Example#2413 - TokyoTyrantTable::putKeep example
  • Example#2414 - TokyoTyrantQuery::addCond example
  • Example#2415 - TokyoTyrantQuery::__construct example
  • Example#2416 - TokyoTyrantQuery::count example
  • Example#2417 - TokyoTyrantQuery iterator example
  • Example#2418 - TokyoTyrantQuery::hint example
  • Example#2419 - TokyoTyrantQuery iterator example
  • Example#2420 - TokyoTyrantQuery::metaSearch example
  • Example#2421 - TokyoTyrantQuery iterator example
  • Example#2422 - TokyoTyrantQuery::out example
  • Example#2423 - TokyoTyrantQuery iterator example
  • Example#2424 - TokyoTyrantQuery::search example
  • Example#2425 - TokyoTyrantQuery iterator example
  • Example#2426 - TokyoTyrantIterator::__construct example
  • Example#2427 - cal_days_in_month example
  • Example#2428 - cal_from_jd example
  • Example#2429 - cal_info example
  • Example#2430 - easter_date example
  • Example#2431 - easter_days example
  • Example#2432 - Calendar functions
  • Example#2433 - jdtojewish Example
  • Example#2434 - DateTimeImmutable::add/sub add intervals which cover elapsed time
  • Example#2435 - DateTimeImmutable::modify and strtotime increment or decrement individual component values
  • Example#2436 - Adding or subtracting times can over- or underflow dates
  • Example#2437 - DateTime::add 例程
  • Example#2438 - Further DateTime::add 例程
  • Example#2439 - 当在 DateTime 上加月的时候要注意
  • Example#2440 - DateTime::__construct 例程
  • Example#2441 - DateTime::__construct 的复杂用法
  • Example#2442 - DateTime::createFromFormat 例程
  • Example#2443 - DateTime::createFromFormat 的复杂用法
  • Example#2444 - 格式化字符串中包含了需要进行转义的字符
  • Example#2445 - Creating a mutable date time object
  • Example#2446 - Creating a mutable date time object
  • Example#2447 - DateTime::getLastErrors 例程
  • Example#2448 - DateTime::modify 例程
  • Example#2449 - 增加或者减少月份的时候需要注意
  • Example#2450 - DateTime::setDate 例程
  • Example#2451 - 超出范围的部分会向上一级增加
  • Example#2452 - DateTime::setISODate 例程
  • Example#2453 - 超出有效范围的部分，会加到上一级
  • Example#2454 - 找出来某个周所属的月份
  • Example#2455 - DateTime::setTime 例程
  • Example#2456 - 超出有效范围的部分会增加到上一级
  • Example#2457 - DateTime::setTimestamp 例程
  • Example#2458 - PHP 5.2 之后的版本中，DateTime::setTimestamp 替代方案
  • Example#2459 - DateTime::setTimeZone 例程
  • Example#2460 - DateTime::sub 例程
  • Example#2461 - Further DateTime::sub 例程
  • Example#2462 - 减去一定量的月份的时候需要注意
  • Example#2463 - Creating an immutable date time object
  • Example#2464 - Creating an immutable date time object
  • Example#2465 - DateTime::diff example
  • Example#2466 - DateTime object comparison
  • Example#2467 - DateTime::format example
  • Example#2468 - DateTime::getOffset example
  • Example#2469 - DateTime::getTimestamp example
  • Example#2470 - DateTime::getTimezone example
  • Example#2471 - Catching errors when instantiating DateTimeZone
  • Example#2472 - DateTimeZone::getLocation 函数的范例：
  • Example#2473 - DateTimeZone::getOffset 例子
  • Example#2474 - A timezone_transitions_get example
  • Example#2475 - timezone_abbreviations_list 函数的范例：
  • Example#2476 - timezone_identifiers_list 函数的范例：
  • Example#2477 - DateInterval example
  • Example#2478 - Parsing valid date intervals
  • Example#2479 - DateInterval example
  • Example#2480 - DateInterval and carry over points
  • Example#2481 - DateInterval and DateTime::diff with the %a and %d modifiers
  • Example#2482 - DatePeriod example
  • Example#2483 - DatePeriod example with DatePeriod::EXCLUDE_START_DATE
  • Example#2484 - DatePeriod::getDateInterval example
  • Example#2485 - DatePeriod::getEndDate example
  • Example#2486 - DatePeriod::getEndDate without an end date
  • Example#2487 - DatePeriod::getStartDate example
  • Example#2488 - checkdate 例子
  • Example#2489 - 获取默认时区
  • Example#2490 - 获取一个时区的简写
  • Example#2491 - 获取默认时区
  • Example#2492 - date_parse_from_format example
  • Example#2493 - date_parse 示例
  • Example#2494 - date_parse 使用相对格式
  • Example#2495 - A date_sun_info example
  • Example#2496 - Polar night
  • Example#2497 - Midnight sun
  • Example#2498 - date_sunrise 例子
  • Example#2499 - date_sunset 例子
  • Example#2500 - date 例子
  • Example#2501 - 在 date 中转义字符
  • Example#2502 - date 和 mktime 例子
  • Example#2503 - date 格式举例
  • Example#2504 - date 函数示例
  • Example#2505 - 对 date 函数中的格式字符串进行转义
  • Example#2506 - date 和 mktime 联合使用示例
  • Example#2507 - date 函数格式化
  • Example#2508 - getdate 例子
  • Example#2509 - gettimeofday 例子
  • Example#2510 - gmdate 例子
  • Example#2511 - gmmktime 在 Windows 中的边界
  • Example#2512 - gmstrftime 例子
  • Example#2513 - localtime 例子
  • Example#2514 - 用 microtime 对脚本的运行计时
  • Example#2515 - 基本例子
  • Example#2516 - mktime 例子
  • Example#2517 - 下个月的最后一天
  • Example#2518 - strftime 区域的例子
  • Example#2519 - ISO 8601:1988 week number example
  • Example#2520 - %e 修改器跨平台兼容的例子
  • Example#2521 - 显示所有已知和未知的格式
  • Example#2522 - strptime 例子
  • Example#2523 - strtotime 例子
  • Example#2524 - 失败检查
  • Example#2525 - time 例子
  • Example#2526 - A timezone_name_from_abbr example
  • Example#2527 - 获取 timezonedb 版本
  • Example#2528 - Measure several code blocks execution and get the total
  • Example#2529 - Closing an open file descriptor
  • Example#2530 - Setting and clearing a lock
  • Example#2531 - Opening a file descriptor
  • Example#2532 - Positioning in a file
  • Example#2533 - Setting the baud rate on a serial port
  • Example#2534 - chdir 例子
  • Example#2535 - chroot example
  • Example#2536 - closedir 例子
  • Example#2537 - dir 示例
  • Example#2538 - getcwd 例子
  • Example#2539 - opendir 例子
  • Example#2540 - 列出目录中的所有文件
  • Example#2541 - 列出当前目录的所有文件并去掉 . 和 ..
  • Example#2542 - 一个简单的 scandir 例子
  • Example#2543 - scandir 在 PHP 4 中的实现
  • Example#2544 - finfo_buffer 函数例程
  • Example#2545 - finfo_file 例程
  • Example#2546 - 面向对象风格
  • Example#2547 - 过程化风格
  • Example#2548 - mime_content_type 示例
  • Example#2549 - basename 例子
  • Example#2550 - 改变文件所属的组
  • Example#2551 - 简单的 chown 用法
  • Example#2552 - clearstatcache 例子
  • Example#2553 - copy 例子
  • Example#2554 - dirname 例子
  • Example#2555 - disk_free_space 例子
  • Example#2556 - disk_total_space 例子
  • Example#2557 - 一个简单 fclose 例子
  • Example#2558 - 处理 feof 的超时
  • Example#2559 - 使用无效文件指针的 feof 例子
  • Example#2560 - File write example using fflush
  • Example#2561 - 一个 fgetc 例子
  • Example#2562 - 读取并显示 CSV 文件的整个内容
  • Example#2563 - 逐行读取文件
  • Example#2564 - 一行行读取一个 PHP 文件
  • Example#2565 - 测试一个文件是否存在
  • Example#2566 - Get and output the source of the homepage of a website
  • Example#2567 - Searching within the include_path
  • Example#2568 - Reading a section of a file
  • Example#2569 - Using stream contexts
  • Example#2570 - Simple usage example
  • Example#2571 - Using flags
  • Example#2572 - file 例子
  • Example#2573 - fileatime 例子
  • Example#2574 - filectime 例子
  • Example#2575 - 查找文件所在的组
  • Example#2576 - 将某个文件和当前文件的 inode 进行对比
  • Example#2577 - filemtime 例子
  • Example#2578 - 找到文件的所有者
  • Example#2579 - 以八进制的形式显示文件的权限
  • Example#2580 - 输出全部权限
  • Example#2581 - filesize 例子
  • Example#2582 - filetype 例子
  • Example#2583 - flock 例子
  • Example#2584 - flock 使用 LOCK_NB 选项
  • Example#2585 - 用 shell 中的通配符模式匹配来检查颜色名称
  • Example#2586 - fopen 例子
  • Example#2587 - 对二进制文件使用 fpassthru
  • Example#2588 - fputcsv 例子
  • Example#2589 - 一个简单的 fread 例子
  • Example#2590 - Binary fread example
  • Example#2591 - Remote fread examples
  • Example#2592 - fscanf 例子
  • Example#2593 - users.txt 的内容
  • Example#2594 - fseek 例子
  • Example#2595 - fstat 例子
  • Example#2596 - ftell 例子
  • Example#2597 - File truncation example
  • Example#2598 - 一个简单的 fwrite 例子
  • Example#2599 - 怎样用 glob 方便地替代 opendir 和相关函数
  • Example#2600 - is_dir 例子
  • Example#2601 - is_executable 例子
  • Example#2602 - is_file 例子
  • Example#2603 - 创建并确认一个文件是否为符号连接
  • Example#2604 - is_readable 例子
  • Example#2605 - is_uploaded_file 例子
  • Example#2606 - is_writable 例子
  • Example#2607 - 更改符号链接的所有组
  • Example#2608 - Changing the owner of a symbolic link
  • Example#2609 - Creating a simple hard link
  • Example#2610 - linkinfo 例子
  • Example#2611 - stat 和 lstat 的对照
  • Example#2612 - mkdir 例子
  • Example#2613 - 通过 recursive 参数使用 mkdir
  • Example#2614 - Uploading multiple files
  • Example#2615 - sample.ini 的内容
  • Example#2616 - parse_ini_file 例子
  • Example#2617 - parse_ini_file parsing a php.ini file
  • Example#2618 - pathinfo 例子
  • Example#2619 - pathinfo example showing difference between null and no extension
  • Example#2620 - pclose 例子
  • Example#2621 - popen 例子
  • Example#2622 - popen 例子
  • Example#2623 - 使用 readfile 强制下载
  • Example#2624 - readlink 例
  • Example#2625 - realpath_cache_get example
  • Example#2626 - realpath_cache_size example
  • Example#2627 - realpath 例子
  • Example#2628 - Windows 上的 realpath
  • Example#2629 - rename 例子
  • Example#2630 - rewind overwriting example
  • Example#2631 - rmdir 例子
  • Example#2632 - stat 例子
  • Example#2633 - Using stat information together with touch
  • Example#2634 - 创建一个符号连接
  • Example#2635 - tempnam 例子
  • Example#2636 - tmpfile 例子
  • Example#2637 - touch 例子
  • Example#2638 - 使用 time 参数的 touch
  • Example#2639 - umask 例子
  • Example#2640 - 基本的 unlink 用法
  • Example#2641 - Example usage of inotify
  • Example#2642 - setproctitle example
  • Example#2643 - setthreadtitle example
  • Example#2644 - Checks if system administrator has signed the file
  • Example#2645 - Prints names of all extended attributes of file
  • Example#2646 - Removes all extended attributes of a file
  • Example#2647 - Sets extended attributes on .wav file
  • Example#2648 - xattr_supported example
  • Example#2649 - xdiff_file_bdiff_size example
  • Example#2650 - xdiff_file_bdiff example
  • Example#2651 - xdiff_file_bpatch example
  • Example#2652 - xdiff_file_diff_binary example
  • Example#2653 - xdiff_file_diff example
  • Example#2654 - xdiff_file_merge3 example
  • Example#2655 - xdiff_file_patch_binary example
  • Example#2656 - xdiff_file_patch example
  • Example#2657 - Patch reversing example
  • Example#2658 - xdiff_file_rabdiff example
  • Example#2659 - xdiff_string_bdiff_size example
  • Example#2660 - xdiff_string_diff example
  • Example#2661 - xdiff_string_patch example
  • Example#2662 - Enchant Usage Example
  • Example#2663 - List the backends provided by the given broker
  • Example#2664 - A enchant_broker_dict_exists example
  • Example#2665 - List all available dictionaries for one broker
  • Example#2666 - A enchant_broker_request_dict example
  • Example#2667 - Adding a word to a PWL
  • Example#2668 - A enchant_dict_describe example
  • Example#2669 - A enchant_dict_quick_check example
  • Example#2670 - A enchant_dict_suggest example
  • Example#2671 - Usage example.
  • Example#2672 - Using Gender\Gender::country
  • Example#2673 - bindtextdomain example
  • Example#2674 - gettext-check
  • Example#2675 - ngettext example
  • Example#2676 - iconv_get_encoding 例子
  • Example#2677 - iconv_mime_decode_headers 例子
  • Example#2678 - iconv_mime_decode实例
  • Example#2679 - iconv_mime_encode example
  • Example#2680 - iconv_set_encoding 例子
  • Example#2681 - iconv 例子
  • Example#2682 - ob_iconv_handler 例子：
  • Example#2683 - Example of using the procedural API
  • Example#2684 - Example of using the object-oriented API
  • Example#2685 - FRENCH_COLLATION rules
  • Example#2686 - ALTERNATE_HANDLING rules
  • Example#2687 - CASE_FIRST rules
  • Example#2688 - CASE_LEVEL rules
  • Example#2689 - collator_asortexample
  • Example#2690 - collator_compareexample
  • Example#2691 - Collator::__construct example
  • Example#2692 - collator_create example
  • Example#2693 - collator_get_attribute example
  • Example#2694 - collator_get_error_code example
  • Example#2695 - collator_get_error_message example
  • Example#2696 - collator_get_locale example
  • Example#2697 - collator_get_sort_keyexample
  • Example#2698 - collator_get_strength example
  • Example#2699 - collator_set_attribute example
  • Example#2700 - collator_set_strength example
  • Example#2701 - collator_sort_with_sort_keys example
  • Example#2702 - collator_sort example
  • Example#2703 - numfmt_create example
  • Example#2704 - NumberFormatter::create example
  • Example#2705 - numfmt_format_currency example
  • Example#2706 - OO example
  • Example#2707 - numfmt_format example
  • Example#2708 - OO example
  • Example#2709 - numfmt_get_attribute example
  • Example#2710 - OO example
  • Example#2711 - numfmt_get_error_code example
  • Example#2712 - OO example
  • Example#2713 - numfmt_get_error_message example
  • Example#2714 - OO example
  • Example#2715 - numfmt_get_locale example
  • Example#2716 - numfmt_get_pattern example
  • Example#2717 - OO example
  • Example#2718 - numfmt_get_symbol example
  • Example#2719 - OO example
  • Example#2720 - numfmt_get_text_attribute example
  • Example#2721 - OO example
  • Example#2722 - numfmt_parse_currency example
  • Example#2723 - OO example
  • Example#2724 - numfmt_parse example
  • Example#2725 - OO example
  • Example#2726 - numfmt_set_attribute example
  • Example#2727 - OO example
  • Example#2728 - numfmt_set_pattern example
  • Example#2729 - OO example
  • Example#2730 - numfmt_set_symbol example
  • Example#2731 - OO example
  • Example#2732 - numfmt_set_text_attribute example
  • Example#2733 - OO example
  • Example#2734 - locale_accept_from_http example
  • Example#2735 - OO example
  • Example#2736 - locale_compose example
  • Example#2737 - OO example
  • Example#2738 - locale_filter_matches example
  • Example#2739 - OO example
  • Example#2740 - locale_get_all_variants example
  • Example#2741 - OO example
  • Example#2742 - locale_get_default example
  • Example#2743 - OO example
  • Example#2744 - locale_get_display_language example
  • Example#2745 - OO example
  • Example#2746 - locale_get_display_name example
  • Example#2747 - OO example
  • Example#2748 - locale_get_display_region example
  • Example#2749 - OO example
  • Example#2750 - locale_get_display_script example
  • Example#2751 - OO example
  • Example#2752 - locale_get_display_variant example
  • Example#2753 - OO example
  • Example#2754 - locale_get_keywords example
  • Example#2755 - OO example
  • Example#2756 - locale_get_primary_language example
  • Example#2757 - OO example
  • Example#2758 - locale_get_region example
  • Example#2759 - OO example
  • Example#2760 - locale_get_script example
  • Example#2761 - OO example
  • Example#2762 - locale_lookup example
  • Example#2763 - OO example
  • Example#2764 - locale_parse example
  • Example#2765 - OO example
  • Example#2766 - locale_set_default example
  • Example#2767 - OO example
  • Example#2768 - Normalizer::getRawDecomposition example
  • Example#2769 - normalizer_is_normalized example
  • Example#2770 - OO example
  • Example#2771 - normalizer_normalize example
  • Example#2772 - OO example
  • Example#2773 - msgfmt_create example
  • Example#2774 - OO example
  • Example#2775 - msgfmt_format_message example
  • Example#2776 - OO example
  • Example#2777 - msgfmt_format example
  • Example#2778 - OO example
  • Example#2779 - msgfmt_get_error_message example
  • Example#2780 - OO example
  • Example#2781 - msgfmt_get_locale example
  • Example#2782 - OO example
  • Example#2783 - msgfmt_get_pattern example
  • Example#2784 - OO example
  • Example#2785 - msgfmt_parse_message example
  • Example#2786 - OO example
  • Example#2787 - msgfmt_parse example
  • Example#2788 - OO example
  • Example#2789 - msgfmt_set_pattern example
  • Example#2790 - OO example
  • Example#2791 - IntlCalendar::add
  • Example#2792 - IntlCalendar::after
  • Example#2793 - IntlCalendar::clear examples
  • Example#2794 - IntlCalendar::createInstance
  • Example#2795 - IntlCalendar::equals
  • Example#2796 - IntlCalendar::fieldDifference
  • Example#2797 - IntlCalendar::fromDateTime
  • Example#2798 - IntlCalendar::get
  • Example#2799 - IntlCalendar::getActualMaximum
  • Example#2800 - IntlCalendar::getAvailableLocales
  • Example#2801 - IntlCalendar::getDayOfWeekType
  • Example#2802 - IntlCalendar::getErrorCode and IntlCalendar::getErrorMessage
  • Example#2803 - IntlCalendar::getErrorMessage
  • Example#2804 - IntlCalendar::getFirstDayOfWeek
  • Example#2805 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2806 - Maxima examples
  • Example#2807 - IntlCalendar::getLocale
  • Example#2808 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2809 - IntlCalendar::getNow
  • Example#2810 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2811 - IntlCalendar::getSkippedWallTimeOption
  • Example#2812 - IntlCalendar::getTime
  • Example#2813 - IntlCalendar::getTimeZone
  • Example#2814 - IntlCalendar::getType
  • Example#2815 - IntlCalendar::inDaylightTime
  • Example#2816 - IntlCalendar::isEquivalentTo
  • Example#2817 - IntlCalendar::isLenient
  • Example#2818 - IntlCalendar::isWeekend
  • Example#2819 - IntlCalendar::roll
  • Example#2820 - IntlCalendar::set
  • Example#2821 - IntlCalendar::setFirstDayOfWeek
  • Example#2822 - IntlCalendar::setTime
  • Example#2823 - IntlCalendar::setTimeZone
  • Example#2824 - IntlCalendar::toDateTime
  • Example#2825 - datefmt_create example
  • Example#2826 - OO example
  • Example#2827 - datefmt_format example
  • Example#2828 - OO example
  • Example#2829 - With IntlCalendar object
  • Example#2830 - IntlDateFormatter::formatObject examples
  • Example#2831 - datefmt_get_calendar example
  • Example#2832 - OO example
  • Example#2833 - datefmt_get_datetype example
  • Example#2834 - OO example
  • Example#2835 - datefmt_get_error_code example
  • Example#2836 - OO example
  • Example#2837 - datefmt_get_error_message example
  • Example#2838 - OO example
  • Example#2839 - datefmt_get_locale example
  • Example#2840 - OO example
  • Example#2841 - datefmt_get_pattern example
  • Example#2842 - OO example
  • Example#2843 - datefmt_get_timetype example
  • Example#2844 - OO example
  • Example#2845 - datefmt_get_timezone_id example
  • Example#2846 - OO example
  • Example#2847 - IntlDateFormatter::getCalendarObject example
  • Example#2848 - IntlDateFormatter::getTimeZone examples
  • Example#2849 - datefmt_is_lenient example
  • Example#2850 - OO example
  • Example#2851 - datefmt_localtime example
  • Example#2852 - OO example
  • Example#2853 - OO example
  • Example#2854 - datefmt_parse example
  • Example#2855 - datefmt_set_calendar example
  • Example#2856 - OO example
  • Example#2857 - Example with IntlCalendar argument
  • Example#2858 - datefmt_set_lenient example
  • Example#2859 - OO example
  • Example#2860 - datefmt_set_pattern example
  • Example#2861 - OO example
  • Example#2862 - IntlDateFormatter::setTimeZone examples
  • Example#2863 - resourcebundle_count example
  • Example#2864 - OO example
  • Example#2865 - resourcebundle_create example
  • Example#2866 - ResourceBundle::create example
  • Example#2867 - resourcebundle_get_error_code example
  • Example#2868 - OO example
  • Example#2869 - resourcebundle_get_error_message example
  • Example#2870 - OO example
  • Example#2871 - resourcebundle_get example
  • Example#2872 - OO example
  • Example#2873 - resourcebundle_locales example
  • Example#2874 - OO example
  • Example#2875 - Spoofchecker::areConfusable example
  • Example#2876 - Spoofchecker::isSuspicious example
  • Example#2877 - Retrieving the registered transliterator IDs
  • Example#2878 - Converting escaped UTF-16 code units
  • Example#2879 - grapheme_extract example
  • Example#2880 - grapheme_stripos example
  • Example#2881 - grapheme_stristr example
  • Example#2882 - grapheme_strlen example
  • Example#2883 - grapheme_strpos example
  • Example#2884 - grapheme_strripos example
  • Example#2885 - grapheme_strrpos example
  • Example#2886 - grapheme_strstr example
  • Example#2887 - grapheme_substr example
  • Example#2888 - idn_to_ascii 示例
  • Example#2889 - idn_to_utf8 示例
  • Example#2890 - Testing different code points
  • Example#2891 - Testing different code points
  • Example#2892 - Testing different code points
  • Example#2893 - Testing different code points
  • Example#2894 - Testing different code points
  • Example#2895 - Testing different code points
  • Example#2896 - Testing different code points
  • Example#2897 - Testing different code points
  • Example#2898 - Testing different code points
  • Example#2899 - Enumerating over a sample range of code points
  • Example#2900 - Enumerating over a sample range of code points
  • Example#2901 - Testing different code points
  • Example#2902 - Testing different code points
  • Example#2903 - Testing different code points
  • Example#2904 - Testing different code points
  • Example#2905 - Testing different code points
  • Example#2906 - Testing different properties
  • Example#2907 - Testing different properties
  • Example#2908 - Testing different properties
  • Example#2909 - Testing different code points
  • Example#2910 - Testing different properties
  • Example#2911 - Testing different properties
  • Example#2912 - Testing different properties
  • Example#2913 - Testing different properties
  • Example#2914 - Testing different properties
  • Example#2915 - Testing different properties
  • Example#2916 - Testing different code points
  • Example#2917 - Testing different code points
  • Example#2918 - Testing different code points
  • Example#2919 - Testing different code points
  • Example#2920 - Testing different code points
  • Example#2921 - Testing different code points
  • Example#2922 - Testing different code points
  • Example#2923 - Testing different code points
  • Example#2924 - Testing different code points
  • Example#2925 - Testing different code points
  • Example#2926 - Testing different code points
  • Example#2927 - Testing different code points
  • Example#2928 - Testing different code points
  • Example#2929 - Testing different code points
  • Example#2930 - Testing different code points
  • Example#2931 - Testing different code points
  • Example#2932 - Testing different code points
  • Example#2933 - Testing different code points
  • Example#2934 - Testing different code points
  • Example#2935 - Testing different code points
  • Example#2936 - Testing different code points
  • Example#2937 - Testing different code points
  • Example#2938 - Testing different code points
  • Example#2939 - Testing different code points
  • Example#2940 - Testing different code points
  • Example#2941 - Testing different code points
  • Example#2942 - Testing different code points
  • Example#2943 - Testing different code points
  • Example#2944 - Testing different code points
  • Example#2945 - Testing different code points
  • Example#2946 - Testing different code points
  • Example#2947 - Testing different code points
  • Example#2948 - intl_error_name example
  • Example#2949 - intl_get_error_code example
  • Example#2950 - intl_get_error_message example
  • Example#2951 - intl_is_failure example
  • Example#2952 - php.ini 设置例子
  • Example#2953 - php.ini 里 EUC-JP 用户的设置
  • Example#2954 - php.ini 里 SJIS 用户的设置
  • Example#2955 - 在 php.ini 中禁用 HTTP 输入转换
  • Example#2956 - php.ini 设置例子
  • Example#2957 - 脚本例子
  • Example#2958 - mb_convert_case 例子
  • Example#2959 - 非拉丁 UTF-8 文本的mb_convert_case 例子
  • Example#2960 - mb_convert_encoding 例子
  • Example#2961 - mb_convert_kana example
  • Example#2962 - mb_convert_variables 例子
  • Example#2963 - convmap 例子
  • Example#2964 - convmap 的例子： 编码(escape) JavaScript 字符串
  • Example#2965 - mb_detect_encoding 例子
  • Example#2966 - mb_detect_order 例子
  • Example#2967 - 案例展示了无效的检测顺序
  • Example#2968 - mb_encode_mimeheader 例子
  • Example#2969 - map example
  • Example#2970 - mb_encode_numericentity example
  • Example#2971 - mb_encoding_aliases example
  • Example#2972 - mb_ereg_replace_callback example
  • Example#2973 - mb_ereg_replace_callback using anonymous function supported in PHP 5.3.0 or later
  • Example#2974 - mb_internal_encoding 例子
  • Example#2975 - mb_list_encodings 例子
  • Example#2976 - mb_output_handler 例子
  • Example#2977 - mb_preferred_mime_name 例子
  • Example#2978 - mb_strimwidth 例子
  • Example#2979 - mb_strtolower 例子
  • Example#2980 - 非拉丁 UTF-8 文本的 mb_strtolower 例子
  • Example#2981 - mb_strtoupper 例子
  • Example#2982 - 非拉丁 UTF-8 文本的 mb_strtoupper 例子
  • Example#2983 - mb_substitute_character 例子
  • Example#2984 - mb_substr_count 例子
  • Example#2985 - pspell_add_to_personal
  • Example#2986 - pspell_check Example
  • Example#2987 - pspell_add_to_personal Example
  • Example#2988 - pspell_config_create
  • Example#2989 - pspell_config_ignore
  • Example#2990 - pspell_config_mode Example
  • Example#2991 - pspell_config_personal
  • Example#2992 - pspell_config_repl
  • Example#2993 - pspell_config_runtogether
  • Example#2994 - pspell_new_config
  • Example#2995 - pspell_new_personal
  • Example#2996 - pspell_new
  • Example#2997 - pspell_add_to_personal
  • Example#2998 - pspell_store_replacement
  • Example#2999 - pspell_suggest example
  • Example#3000 - Basic recode_file example
  • Example#3001 - Basic recode_string example
  • Example#3002 - exif_imagetype 例子
  • Example#3003 - exif_read_data 例子
  • Example#3004 - exif_tagname 函数例程
  • Example#3005 - exif_thumbnail 例子
  • Example#3006 - 使用 PHP 创建 PNG 图像
  • Example#3007 - 使用 Alpha 通道为图像加水印
  • Example#3008 - 使用 imagecopymerge 函数创建半透明水印
  • Example#3009 - 使用 gd_info
  • Example#3010 - getimagesize（文件）
  • Example#3011 - getimagesize（URL）
  • Example#3012 - getimagesize() 和 MIME 类型
  • Example#3013 - getimagesize() 返回 IPTC
  • Example#3014 - getimagesize and MIME types
  • Example#3015 - getimagesize example
  • Example#3016 - getimagesize (URL)
  • Example#3017 - getimagesize() returning IPTC
  • Example#3018 - getimagesizefromstring 函数例程
  • Example#3019 - image_type_to_extension 例子
  • Example#3020 - image_type_to_mime_type (file)
  • Example#3021 - image2wbmp 例子
  • Example#3022 - imageaffinematrixconcat example
  • Example#3023 - imageaffinematrixget example
  • Example#3024 - imagealphablending usage example
  • Example#3025 - A comparison of two lines, one with anti-aliasing switched on
  • Example#3026 - 用 imagearc 画一个圆
  • Example#3027 - Saving a BMP file
  • Example#3028 - imagechar 例子
  • Example#3029 - imagecharup 例子
  • Example#3030 - imagecolorallocate 例子
  • Example#3031 - 使用 imagecolorallocatealpha 的例子
  • Example#3032 - Example of using imagecolorallocatealpha
  • Example#3033 - 取得各自的 RGB 值
  • Example#3034 - Search for a set of colors in an image
  • Example#3035 - 使用 imagecolorclosesthwb 的例子
  • Example#3036 - Get colors from the GD logo
  • Example#3037 - imagecolormatch 例子
  • Example#3038 - Using imagecoloresolvealpha to get colors from an image
  • Example#3039 - imagecolorsforindex 例子
  • Example#3040 - Embossing the PHP.net logo
  • Example#3041 - Gaussian blur
  • Example#3042 - 简单的例子
  • Example#3043 - 按比例对图像重新采样
  • Example#3044 - Resizing an image
  • Example#3045 - 新建一个新的 GD 图像流并输出图像
  • Example#3046 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#3047 - imagecreatefromgd2 例子
  • Example#3048 - imagecreatefromgd2part example
  • Example#3049 - imagecreatefromgd 例子
  • Example#3050 - 处理创建过程中的错误
  • Example#3051 - 处理创建过程中的错误
  • Example#3052 - 处理创建 PNG 过程中的错误
  • Example#3053 - imagecreatefromstring example
  • Example#3054 - 处理创建 WBMP 过程中的错误
  • Example#3055 - Convert an WebP image to a jpeg image using imagecreatefromwebp
  • Example#3056 - Convert an XBM image to a png image using imagecreatefromxbm
  • Example#3057 - Creating an image instance using imagecreatefromxpm
  • Example#3058 - 新建一个新的 GD 图像流并输出图像
  • Example#3059 - imagecrop example
  • Example#3060 - Proper handling of auto-cropping
  • Example#3061 - imageellipse 例子
  • Example#3062 - imagefill 例子
  • Example#3063 - 创建一 3D 效果的饼状图
  • Example#3064 - imagefilledellipse 例子
  • Example#3065 - imagefilledpolygon 例子
  • Example#3066 - imagefilter 灰度例子
  • Example#3067 - imagefilter 亮度例子
  • Example#3068 - imagefilter 上彩例子
  • Example#3069 - imagefilter grayscale example
  • Example#3070 - imagefilter brightness example
  • Example#3071 - imagefilter colorize example
  • Example#3072 - imagefilter negate example
  • Example#3073 - imagefilter pixelate example
  • Example#3074 - Flips an image vertically
  • Example#3075 - Flips the image horizontally
  • Example#3076 - imageftbbox example
  • Example#3077 - imagefttext example
  • Example#3078 - 输出一个 GD2 图像
  • Example#3079 - 保存 GD2 图像
  • Example#3080 - imagegetclip example
  • Example#3081 - 使用 imagegif 输出一个图像
  • Example#3082 - 使用 imagegif 将一个 PNG 转换成 GIF
  • Example#3083 - imagegrabscreen example
  • Example#3084 - imagegrabwindow example
  • Example#3085 - 使用 imageinterlace 打开隔行扫描
  • Example#3086 - Simple detection of true color image instances using imageistruecolor
  • Example#3087 - 输出 JPEG 图像
  • Example#3088 - 保存一副 JPEG 图像
  • Example#3089 - 以 75% 的图像质量输出图像
  • Example#3090 - imagelayereffect example
  • Example#3091 - 画一条粗线
  • Example#3092 - 使用 imageloadfont
  • Example#3093 - imageopenpolygon example
  • Example#3094 - Converts any image resource to true color
  • Example#3095 - imagepolygon 例子
  • Example#3096 - Setting and getting the resolution of an image
  • Example#3097 - 将图像旋转 180 度
  • Example#3098 - imagesavealpha 例子
  • Example#3099 - imagesetinterpolation example
  • Example#3100 - imagesetstyle 例子
  • Example#3101 - imagesetthickness example
  • Example#3102 - imagestring 例子
  • Example#3103 - 使用 imagesx
  • Example#3104 - 使用 imagesy
  • Example#3105 - Converting a true color image to a palette-based image
  • Example#3106 - imagettftext 例子
  • Example#3107 - imagetypes 例子
  • Example#3108 - 保存为 WebP 图像文件
  • Example#3109 - 保存一个 XBM 文件
  • Example#3110 - 以不同前景色保存一个 XBM 文件
  • Example#3111 - Embedding IPTC data into a JPEG
  • Example#3112 - iptcparse() used together with getimagesize
  • Example#3113 - jpeg2wbmp 例子
  • Example#3114 - png2wbmp 例子
  • Example#3115 - Gmagick Example
  • Example#3116 - Gmagick::despeckleimage example
  • Example#3117 - Gmagick::setCompressionQuality
  • Example#3118 - Creating a thumbnail in Imagick
  • Example#3119 - Make a thumbnail of all JPG files in a directory
  • Example#3120 - Creating a reflection of an image
  • Example#3121 - Filling text with gradient
  • Example#3122 - Read in GIF image and resize all frames
  • Example#3123 - Create a PHP logo
  • Example#3124 - Using Imagick::adaptiveBlurImage:
  • Example#3125 - Using Imagick::adaptiveResizeImage
  • Example#3126 - A Imagick::adaptiveSharpenImage example
  • Example#3127 - Imagick::adaptiveThresholdImage
  • Example#3128 - Imagick::addNoiseImage
  • Example#3129 - Imagick::affineTransformImage
  • Example#3130 - Using Imagick::annotateImage:
  • Example#3131 - Imagick::appendImages example
  • Example#3132 - Imagick::autoLevelImage
  • Example#3133 - Imagick::blackThresholdImage
  • Example#3134 - Imagick::blueShiftImage
  • Example#3135 - Using Imagick::blurImage:
  • Example#3136 - Imagick::borderImage
  • Example#3137 - Imagick::brightnessContrastImage
  • Example#3138 - Imagick::charcoalImage
  • Example#3139 - Using Imagick::chopImage:
  • Example#3140 - Imagick object cloning in different versions of imagick
  • Example#3141 - Using Imagick::clutImage:
  • Example#3142 - Imagick::colorizeImage
  • Example#3143 - Imagick::colorMatrixImage
  • Example#3144 - Using Imagick::commentImage:
  • Example#3145 - Using Imagick::compareImageLayers
  • Example#3146 - Using Imagick::compareImages:
  • Example#3147 - Imagick::contrastImage
  • Example#3148 - Imagick::convolveImage
  • Example#3149 - Imagick::cropImage
  • Example#3150 - Imagick::deskewImage
  • Example#3151 - Imagick::despeckleImage
  • Example#3152 - Using Imagick::distortImage:
  • Example#3153 - Imagick::edgeImage
  • Example#3154 - Imagick::embossImage
  • Example#3155 - Imagick::enhanceImage
  • Example#3156 - Imagick::equalizeImage
  • Example#3157 - Using Imagick::evaluateImage
  • Example#3158 - Using Imagick::exportImagePixels
  • Example#3159 - Imagick::filter
  • Example#3160 - Imagick::flipImage
  • Example#3161 - Imagick::floodfillPaintImage example
  • Example#3162 - Imagick::flopImage
  • Example#3163 - Imagick::forwardFourierTransformImage
  • Example#3164 - Imagick::frameImage
  • Example#3165 - Create a sinusoidal gradient
  • Example#3166 - Create a gradient from the polynomial (4x^2 - 4x + 1)
  • Example#3167 - Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient
  • Example#3168 - Imagick::fxImage
  • Example#3169 - Imagick::gammaImage
  • Example#3170 - Imagick::gaussianBlurImage
  • Example#3171 - Imagick::getImageGeometry
  • Example#3172 - Generates Imagick::getImageHistogram
  • Example#3173 - Using Imagick::getImageLength:
  • Example#3174 - Using Imagick::getImageProperties:
  • Example#3175 - Using Imagick::getImageProperty:
  • Example#3176 - Using Imagick::getIteratorIndex:
  • Example#3177 - Imagick::getPixelIterator
  • Example#3178 - Imagick::getPixelRegionIterator example
  • Example#3179 - Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)
  • Example#3180 - Imagick::haldClutImage
  • Example#3181 - Imagick::identifyFormat
  • Example#3182 - Example Result Format
  • Example#3183 - Imagick::implodeImage
  • Example#3184 - Imagick::importImagePixels example
  • Example#3185 - Imagick::levelImage
  • Example#3186 - Imagick::linearStretchImage
  • Example#3187 - Imagick::magnifyImage
  • Example#3188 - Imagick::medianFilterImage
  • Example#3189 - Imagick::mergeImageLayers
  • Example#3190 - Imagick::modulateImage
  • Example#3191 - Convolve Imagick::morphology
  • Example#3192 - Correlate Imagick::morphology
  • Example#3193 - Erode Imagick::morphology
  • Example#3194 - Erode Intensity Imagick::morphology
  • Example#3195 - Dilate Imagick::morphology
  • Example#3196 - Dilate intensity Imagick::morphology
  • Example#3197 - Distance with Chebyshev kernel Imagick::morphology
  • Example#3198 - Distance with Manhattan kernel Imagick::morphology
  • Example#3199 - Distance with ocatagonal kernel Imagick::morphology
  • Example#3200 - Distance with Euclidean kernel Imagick::morphology
  • Example#3201 - Edge Imagick::morphology
  • Example#3202 - Open Imagick::morphology
  • Example#3203 - Open intensity Imagick::morphology
  • Example#3204 - Close Imagick::morphology
  • Example#3205 - Close Intensity Imagick::morphology
  • Example#3206 - Smooth Imagick::morphology
  • Example#3207 - Edge in Imagick::morphology
  • Example#3208 - Edge out Imagick::morphology
  • Example#3209 - The 'TopHat' method, or more specifically 'White Top Hat', returns the pixels that were removed by a Opening of the shape, that is the pixels that were removed to round off the points, and the connecting bridged between shapes. Imagick::morphology
  • Example#3210 - The 'BottomHat' method, also known as 'Black TopHat' is the pixels that a Closing of the shape adds to the image. That is the pixels that were used to fill in the 'holes', 'gaps', and 'bridges'. Imagick::morphology
  • Example#3211 - Hit and Miss Imagick::morphology
  • Example#3212 - Thinning Imagick::morphology
  • Example#3213 - Thicken Imagick::morphology
  • Example#3214 - Thick to generate a convex hull Imagick::morphology
  • Example#3215 - Iterative morphology Imagick::morphology
  • Example#3216 - Helper functon to get an image silhouette Imagick::morphology
  • Example#3217 - Imagick::motionBlurImage
  • Example#3218 - Imagick::negateImage
  • Example#3219 - Using Imagick::newImage:
  • Example#3220 - Imagick::newPseudoImage
  • Example#3221 - Imagick::normalizeImage
  • Example#3222 - Imagick::oilPaintImage
  • Example#3223 - Using Imagick::optimizeImageLayers
  • Example#3224 - Imagick::orderedPosterizeImage
  • Example#3225 - Using Imagick::pingImageBlob
  • Example#3226 - Using Imagick::pingImageFile
  • Example#3227 - A Imagick::polaroidImage example
  • Example#3228 - Imagick::posterizeImage
  • Example#3229 - Imagick::quantizeImage
  • Example#3230 - Using Imagick::queryFontMetrics:
  • Example#3231 - Imagick::queryFonts
  • Example#3232 - Imagick::queryFormats
  • Example#3233 - Imagick::radialBlurImage
  • Example#3234 - Imagick::raiseImage
  • Example#3235 - Imagick::randomThresholdImage
  • Example#3236 - Imagick::readImageBlob
  • Example#3237 - Imagick::recolorImage
  • Example#3238 - Imagick::reduceNoiseImage
  • Example#3239 - Imagick::resampleImage
  • Example#3240 - Imagick::resizeImage
  • Example#3241 - Imagick::rollImage
  • Example#3242 - Imagick::rotateImage
  • Example#3243 - Imagick::rotationalBlurImage
  • Example#3244 - Using Imagick::roundCorners:
  • Example#3245 - Imagick::scaleImage
  • Example#3246 - Imagick::segmentImage
  • Example#3247 - Imagick::selectiveBlurImage
  • Example#3248 - Imagick::separateImageChannel
  • Example#3249 - Imagick::sepiaToneImage
  • Example#3250 - Imagick::setCompressionQuality
  • Example#3251 - A Imagick::setFont example
  • Example#3252 - A Imagick::setImage example
  • Example#3253 - Imagick::setImageArtifact
  • Example#3254 - Imagick::setImageBias
  • Example#3255 - Imagick::setImageClipMask
  • Example#3256 - Modify animated Gif with Imagick::setImageDelay
  • Example#3257 - Basic Imagick::setImageIterations usage
  • Example#3258 - A Imagick::setImageOpacity example
  • Example#3259 - Imagick::setImageOrientation
  • Example#3260 - Using Imagick::setImageProperty:
  • Example#3261 - Imagick::setImageResolution
  • Example#3262 - Modify animated Gif with Imagick::setImageTicksPerSecond
  • Example#3263 - Using Imagick::setIteratorIndex:
  • Example#3264 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#3265 - Imagick::setOption
  • Example#3266 - Imagick::setOption
  • Example#3267 - A Imagick::setPointSize example
  • Example#3268 - Imagick::setProgressMonitor
  • Example#3269 - Imagick::setSamplingFactors
  • Example#3270 - Imagick::shadeImage
  • Example#3271 - Imagick::shadowImage
  • Example#3272 - Imagick::sharpenImage
  • Example#3273 - Imagick::shaveImage
  • Example#3274 - Imagick::shearImage
  • Example#3275 - Create a gradient image using Imagick::sigmoidalContrastImage suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint
  • Example#3276 - Imagick::sketchImage
  • Example#3277 - Imagick::smushImages
  • Example#3278 - Imagick::solarizeImage
  • Example#3279 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#3280 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#3281 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#3282 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#3283 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#3284 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#3285 - Imagick::spliceImage
  • Example#3286 - Imagick::spreadImage
  • Example#3287 - Imagick::statisticImage
  • Example#3288 - Imagick::subImageMatch
  • Example#3289 - Imagick::swirlImage
  • Example#3290 - Imagick::textureImage
  • Example#3291 - Imagick::thresholdImage
  • Example#3292 - Imagick::thumbnailImage
  • Example#3293 - Imagick::tintImage
  • Example#3294 - Using Imagick::transformImage:
  • Example#3295 - Imagick::transformImageColorspace example
  • Example#3296 - Imagick::transformImageColorspace
  • Example#3297 - Imagick::transparentPaintImage
  • Example#3298 - Imagick::transposeImage
  • Example#3299 - Imagick::transverseImage
  • Example#3300 - Using Imagick::trimImage:
  • Example#3301 - Imagick::uniqueImageColors
  • Example#3302 - Imagick::unsharpMaskImage
  • Example#3303 - Imagick::vignetteImage
  • Example#3304 - WaveImage can be quite slow Imagick::waveImage
  • Example#3305 - Imagick::whiteThresholdImage
  • Example#3306 - ImagickDraw::affine
  • Example#3307 - ImagickDraw::arc
  • Example#3308 - ImagickDraw::bezier
  • Example#3309 - ImagickDraw::circle
  • Example#3310 - ImagickDraw::composite
  • Example#3311 - ImagickDraw::ellipse
  • Example#3312 - ImagickDraw::line
  • Example#3313 - ImagickDraw::matte
  • Example#3314 - ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • Example#3315 - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • Example#3316 - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • Example#3317 - ImagickDraw::pathStart
  • Example#3318 - ImagickDraw::point
  • Example#3319 - ImagickDraw::polygon
  • Example#3320 - ImagickDraw::polyline
  • Example#3321 - ImagickDraw::popDefs
  • Example#3322 - ImagickDraw::push
  • Example#3323 - ImagickDraw::pushPattern
  • Example#3324 - ImagickDraw::rectangle
  • Example#3325 - ImagickDraw::rotate
  • Example#3326 - ImagickDraw::roundRectangle
  • Example#3327 - ImagickDraw::scale
  • Example#3328 - ImagickDraw::setClipPath
  • Example#3329 - ImagickDraw::setClipRule
  • Example#3330 - ImagickDraw::setClipUnits
  • Example#3331 - ImagickDraw::setFillAlpha
  • Example#3332 - ImagickDraw::setFillColor
  • Example#3333 - ImagickDraw::setFillOpacity
  • Example#3334 - ImagickDraw::setFillRule
  • Example#3335 - ImagickDraw::setFont
  • Example#3336 - ImagickDraw::setFontFamily
  • Example#3337 - ImagickDraw::setFontSize
  • Example#3338 - ImagickDraw::setFontStretch
  • Example#3339 - ImagickDraw::setFontStyle
  • Example#3340 - ImagickDraw::setFontWeight
  • Example#3341 - ImagickDraw::setGravity
  • Example#3342 - ImagickDraw::setStrokeAlpha
  • Example#3343 - ImagickDraw::setStrokeAntialias
  • Example#3344 - ImagickDraw::setStrokeColor
  • Example#3345 - ImagickDraw::setStrokeDashArray
  • Example#3346 - ImagickDraw::setStrokeDashOffset
  • Example#3347 - ImagickDraw::setStrokeLineCap
  • Example#3348 - ImagickDraw::setStrokeLineJoin
  • Example#3349 - ImagickDraw::setStrokeMiterLimit
  • Example#3350 - ImagickDraw::setStrokeOpacity
  • Example#3351 - ImagickDraw::setStrokeWidth
  • Example#3352 - ImagickDraw::setTextAlignment
  • Example#3353 - ImagickDraw::setTextAntialias
  • Example#3354 - ImagickDraw::setTextDecoration
  • Example#3355 - ImagickDraw::setTextUnderColor
  • Example#3356 - ImagickDraw::setVectorGraphics
  • Example#3357 - ImagickDraw::setViewBox
  • Example#3358 - ImagickDraw::skewX
  • Example#3359 - ImagickDraw::skewY
  • Example#3360 - ImagickDraw::translate
  • Example#3361 - ImagickPixel::construct
  • Example#3362 - Basic Imagick::getColor usage
  • Example#3363 - Basic Imagick::getColorAsString usage
  • Example#3364 - ImagickPixel getColorCount
  • Example#3365 - Basic Imagick::getColorValue usage
  • Example#3366 - ImagickPixel::getColorValueQuantum
  • Example#3367 - Basic Imagick::getHSL example
  • Example#3368 - ImagickPixel::isSimilar
  • Example#3369 - ImagickPixel::setColor
  • Example#3370 - Basic Imagick::setColorValue usage
  • Example#3371 - ImagickPixel::setColorValueQuantum
  • Example#3372 - Use ImagickPixel::setHSL to modify a color
  • Example#3373 - ImagickPixelIterator::clear
  • Example#3374 - ImagickPixelIterator::construct
  • Example#3375 - ImagickPixelIterator::getNextIteratorRow
  • Example#3376 - ImagickPixelIterator::resetIterator
  • Example#3377 - ImagickPixelIterator::setIteratorRow
  • Example#3378 - imap_append example
  • Example#3379 - imap_check example
  • Example#3380 - imap_createmailbox example
  • Example#3381 - imap_delete example
  • Example#3382 - imap_fetch_overview example
  • Example#3383 - imap_gc example
  • Example#3384 - imap_get_quota example
  • Example#3385 - imap_get_quota 4.3 or greater example
  • Example#3386 - imap_get_quotaroot example
  • Example#3387 - imap_getacl example
  • Example#3388 - imap_getmailboxes example
  • Example#3389 - imap_list example
  • Example#3390 - imap_mail_compose example
  • Example#3391 - imap_mailboxmsginfo example
  • Example#3392 - imap_mime_header_decode example
  • Example#3393 - Different use of imap_open
  • Example#3394 - imap_open example
  • Example#3395 - imap_ping Example
  • Example#3396 - imap_reopen example
  • Example#3397 - imap_rfc822_parse_adrlist example
  • Example#3398 - imap_rfc822_write_address example
  • Example#3399 - imap_search example
  • Example#3400 - imap_set_quota example
  • Example#3401 - imap_setflag_full example
  • Example#3402 - imap_status example
  • Example#3403 - imap_thread Example
  • Example#3404 - imap_timeout example
  • Example#3405 - Basic imap_utf8 Usage
  • Example#3406 - 计算散列值并订阅一个用户
  • Example#3407 - Sending mail.
  • Example#3408 - Sending mail with extra headers.
  • Example#3409 - Sending mail with an additional command line parameter.
  • Example#3410 - Sending HTML email
  • Example#3411 - mailparse_determine_best_xfer_encoding example
  • Example#3412 - mailparse_rfc822_parse_addresses example
  • Example#3413 - mailparse_stream_encode example
  • Example#3414 - mailparse_uudecode_all example
  • Example#3415 - bcadd 示例
  • Example#3416 - bccomp example
  • Example#3417 - bcdiv 示例
  • Example#3418 - bcmod example
  • Example#3419 - bcmul 示例
  • Example#3420 - bcpow 示例
  • Example#3421 - bcpow scale example
  • Example#3422 - bcscale example
  • Example#3423 - bcsqrt 示例
  • Example#3424 - bcsub example
  • Example#3425 - Factorial function using GMP
  • Example#3426 - gmp_abs example
  • Example#3427 - gmp_add example
  • Example#3428 - gmp_and example
  • Example#3429 - gmp_clrbit example
  • Example#3430 - gmp_cmp example
  • Example#3431 - gmp_com example
  • Example#3432 - gmp_div_q example
  • Example#3433 - Division of GMP numbers
  • Example#3434 - gmp_div_r example
  • Example#3435 - gmp_divexact example
  • Example#3436 - gmp_export example
  • Example#3437 - gmp_fact example
  • Example#3438 - gmp_gcd example
  • Example#3439 - Solving a linear Diophantine equation
  • Example#3440 - gmp_hamdist example
  • Example#3441 - gmp_import example
  • Example#3442 - Creating GMP number
  • Example#3443 - gmp_intval example
  • Example#3444 - gmp_invert example
  • Example#3445 - gmp_jacobi example
  • Example#3446 - gmp_legendre example
  • Example#3447 - gmp_mod example
  • Example#3448 - gmp_mul example
  • Example#3449 - gmp_neg example
  • Example#3450 - gmp_nextprime example
  • Example#3451 - gmp_or example
  • Example#3452 - gmp_perfect_square example
  • Example#3453 - gmp_popcount example
  • Example#3454 - gmp_pow example
  • Example#3455 - gmp_powm example
  • Example#3456 - gmp_prob_prime example
  • Example#3457 - gmp_random_bits example
  • Example#3458 - gmp_random_range example
  • Example#3459 - gmp_random_seed example
  • Example#3460 - gmp_random example
  • Example#3461 - gmp_scan0 example
  • Example#3462 - gmp_scan1 example
  • Example#3463 - gmp_setbit example - 0 index
  • Example#3464 - gmp_setbit example - 1 index
  • Example#3465 - gmp_setbit example - clearing a bit
  • Example#3466 - gmp_sign example
  • Example#3467 - gmp_sqrt example
  • Example#3468 - gmp_sqrtrem example
  • Example#3469 - Converting a GMP number to a string
  • Example#3470 - gmp_sub example
  • Example#3471 - gmp_testbit example
  • Example#3472 - gmp_xor example
  • Example#3473 - abs 例子
  • Example#3474 - base_convert 例子
  • Example#3475 - bindec 例子
  • Example#3476 - bindec 将输入解读为无符号整数
  • Example#3477 - ceil 例子
  • Example#3478 - cos 例子
  • Example#3479 - decbin 例子
  • Example#3480 - dechex 例子
  • Example#3481 - 大整数的 dechex 例子
  • Example#3482 - decoct 范例
  • Example#3483 - deg2rad 例子
  • Example#3484 - exp 例子
  • Example#3485 - Using fdiv
  • Example#3486 - floor 例子
  • Example#3487 - fmod 的使用
  • Example#3488 - hexdec 例子
  • Example#3489 - intdiv 的一些例子
  • Example#3490 - is_nan 例子
  • Example#3491 - 使用 max 的例子
  • Example#3492 - min 用法的例子
  • Example#3493 - 计算一个随机浮点数
  • Example#3494 - mt_rand 例子
  • Example#3495 - mt_srand 例子
  • Example#3496 - octdec 例子
  • Example#3497 - pi 例子
  • Example#3498 - pow 的一些例子
  • Example#3499 - rad2deg 例子
  • Example#3500 - rand 例子
  • Example#3501 - round 例子
  • Example#3502 - mode 例子
  • Example#3503 - sin 例子
  • Example#3504 - sqrt 例子
  • Example#3505 - srand 例子
  • Example#3506 - tan 例子
  • Example#3507 - Evaluating a FDF document
  • Example#3508 - Adding JavaScript code to a FDF
  • Example#3509 - Populating a PDF document
  • Example#3510 - Storing an uploaded file
  • Example#3511 - Detecting all fieldnames in a FDF
  • Example#3512 - Accessing the form data
  • Example#3513 - Accessing the form data
  • Example#3514 - Retrieving FDF as a string
  • Example#3515 - Passing FDF data to a second form
  • Example#3516 - gnupg clearsign example (procedural)
  • Example#3517 - gnupg clearsign example (OO)
  • Example#3518 - keylistiterator
  • Example#3519 - Procedural gnupg_adddecryptkey example
  • Example#3520 - OO gnupg_adddecryptkey example
  • Example#3521 - Procedural gnupg_addencryptkey example
  • Example#3522 - OO gnupg_addencryptkey example
  • Example#3523 - Procedural gnupg_addsignkey example
  • Example#3524 - OO gnupg_addsignkey example
  • Example#3525 - Procedural gnupg_cleardecryptkeys example
  • Example#3526 - OO gnupg_cleardecryptkeys example
  • Example#3527 - Procedural gnupg_clearencryptkeys example
  • Example#3528 - OO gnupg_clearencryptkeys example
  • Example#3529 - Procedural gnupg_clearsignkeys example
  • Example#3530 - OO gnupg_clearsignkeys example
  • Example#3531 - Procedural gnupg_decrypt example
  • Example#3532 - OO gnupg_decrypt example
  • Example#3533 - Procedural gnupg_decryptverify example
  • Example#3534 - OO gnupg_decryptverify example
  • Example#3535 - Procedural gnupg_encrypt example
  • Example#3536 - OO gnupg_encrypt example
  • Example#3537 - Procedural gnupg_encryptsign example
  • Example#3538 - OO gnupg_encryptsign example
  • Example#3539 - Procedural gnupg_export example
  • Example#3540 - OO gnupg_export example
  • Example#3541 - Procedural gnupg_geterror example
  • Example#3542 - OO gnupg_geterror example
  • Example#3543 - Procedural gnupg_getprotocol example
  • Example#3544 - OO gnupg_getprotocol example
  • Example#3545 - Procedural gnupg_import example
  • Example#3546 - OO gnupg_import example
  • Example#3547 - Procedural gnupg_init example
  • Example#3548 - OO gnupg initializer example
  • Example#3549 - Procedural gnupg_keyinfo example
  • Example#3550 - OO gnupg_keyinfo example
  • Example#3551 - Procedural gnupg_setarmor example
  • Example#3552 - OO gnupg_setarmor example
  • Example#3553 - Procedural gnupg_seterrormode example
  • Example#3554 - OO gnupg_seterrormode example
  • Example#3555 - Procedural gnupg_setsignmode example
  • Example#3556 - OO gnupg_setsignmode example
  • Example#3557 - Procedural gnupg_sign example
  • Example#3558 - OO gnupg_sign example
  • Example#3559 - Procedural gnupg_verify example
  • Example#3560 - OO gnupg_verify example
  • Example#3561 - Creating and using a pattern
  • Example#3562 - Creating and using a template
  • Example#3563 - Hyphennate a text
  • Example#3564 - Drawing a rectangle
  • Example#3565 - Creating and using a spot color
  • Example#3566 - Rotation of the coordinate system
  • Example#3567 - Placing text at a given position
  • Example#3568 - Drawing a dashed line
  • Example#3569 - Translation of the coordinate system
  • Example#3570 - A rpmdbinfo example
  • Example#3571 - Searching for the package owning a file
  • Example#3572 - A rpminfo example
  • Example#3573 - example
  • Example#3574 - example
  • Example#3575 - example
  • Example#3576 - example
  • Example#3577 - example
  • Example#3578 - example
  • Example#3579 - example
  • Example#3580 - example
  • Example#3581 - example
  • Example#3582 - example
  • Example#3583 - example
  • Example#3584 - example
  • Example#3585 - example
  • Example#3586 - example
  • Example#3587 - example
  • Example#3588 - example
  • Example#3589 - example
  • Example#3590 - example
  • Example#3591 - example
  • Example#3592 - Incorrect requests
  • Example#3593 - Calling request from a request callback
  • Example#3594 - Calling request from a request callback
  • Example#3595 - Using eio with libevent
  • Example#3596 - Cancelling a request
  • Example#3597 - Calling eio_chmod
  • Example#3598 - Making a custom request
  • Example#3599 - Grouping requests
  • Example#3600 - Using eio with libevent extension
  • Example#3601 - Using eio with event extension
  • Example#3602 - eio_cancel example
  • Example#3603 - eio_custom example
  • Example#3604 - eio_event_loop example
  • Example#3605 - eio_lstat example
  • Example#3606 - Using eio with libevent
  • Example#3607 - Grouping requests
  • Example#3608 - eio_grp example
  • Example#3609 - eio_link example
  • Example#3610 - eio_lstat example
  • Example#3611 - eio_mkdir example
  • Example#3612 - eio_mknod example
  • Example#3613 - eio_nreqs example
  • Example#3614 - eio_open example
  • Example#3615 - eio_poll example
  • Example#3616 - eio_read example
  • Example#3617 - eio_readdir example
  • Example#3618 - eio_readlink example
  • Example#3619 - eio_realpath example
  • Example#3620 - eio_rename example
  • Example#3621 - eio_rmdir example
  • Example#3622 - eio_stat example
  • Example#3623 - eio_statvfs example
  • Example#3624 - eio_symlink example
  • Example#3625 - Simple timers
  • Example#3626 - Periodic timer. Tick each 10.5 seconds
  • Example#3627 - Periodic timer. Use reschedule callback
  • Example#3628 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3629 - Wait until STDIN is readable
  • Example#3630 - Use some async I/O to access a socket
  • Example#3631 - Embedding one loop into another
  • Example#3632 - Embedding loop created with kqueue backend into the default loop
  • Example#3633 - Handle SIGTERM signal
  • Example#3634 - Monitor changes of /var/log/messages
  • Example#3635 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3636 - Process status changes
  • Example#3637 - Using reschedule callback
  • Example#3638 - Embedding loop created with kqueue backend into the default loop
  • Example#3639 - Embedding one loop into another
  • Example#3640 - Embedding loop created with kqueue backend into the default loop
  • Example#3641 - Embedding loop created with kqueue backend into the default loop
  • Example#3642 - Periodic timer. Use reschedule callback
  • Example#3643 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3644 - Hourly watcher
  • Example#3645 - Handle SIGTERM signal
  • Example#3646 - Monitor changes of /var/log/messages
  • Example#3647 - Monitor changes of /var/log/messages
  • Example#3648 - Simple timers
  • Example#3649 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3650 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#3651 - Expect Usage Example
  • Example#3652 - Another Expect Usage Example
  • Example#3653 - expect_expectl example
  • Example#3654 - expect_popen example
  • Example#3655 - 进程控制示例
  • Example#3656 - pcntl_fork 示例
  • Example#3657 - pcntl_signal_dispatch 示例
  • Example#3658 - pcntl_signal_get_handler example
  • Example#3659 - pcntl_signal示例
  • Example#3660 - pcntl_sigprocmask 示例
  • Example#3661 - pcntl_sigwaitinfo example
  • Example#3662 - posix_access example
  • Example#3663 - posix_ctermid example
  • Example#3664 - posix_get_last_error example
  • Example#3665 - posix_getcwd example
  • Example#3666 - posix_getegid example
  • Example#3667 - posix_geteuid example
  • Example#3668 - posix_getgid example
  • Example#3669 - Example use of posix_getgrgid
  • Example#3670 - Example use of posix_getgrnam
  • Example#3671 - Example use of posix_getgroups
  • Example#3672 - Example use of posix_getlogin
  • Example#3673 - Example use of posix_getpgid
  • Example#3674 - posix_getpid 的使用例子
  • Example#3675 - Example use of posix_getppid
  • Example#3676 - Example use of posix_getpwnam
  • Example#3677 - Example use of posix_getpwuid
  • Example#3678 - Example use of posix_getrlimit
  • Example#3679 - Example use of posix_getsid
  • Example#3680 - Example use of posix_getuid
  • Example#3681 - A posix_mknod example
  • Example#3682 - posix_setegid example
  • Example#3683 - posix_setgid example
  • Example#3684 - posix_setuid example
  • Example#3685 - posix_strerror example
  • Example#3686 - Example use of posix_times
  • Example#3687 - Example use of posix_uname
  • Example#3688 - escapeshellarg 的例子
  • Example#3689 - escapeshellcmd example
  • Example#3690 - exec 例程
  • Example#3691 - 使用 proc_open 函数将进程设置为高优先级
  • Example#3692 - proc_open 例程
  • Example#3693 - shell_exec 例程
  • Example#3694 - system 例程
  • Example#3695 - Example showing Future as return value
  • Example#3696 - Example showing Future as synchronization point
  • Example#3697 - 获取对象属性表中的部分条目
  • Example#3698 - 计算对象中的属性数量
  • Example#3699 - Runtime inheritance
  • Example#3700 - Thread safe objects from closures
  • Example#3701 - 检测线程运行时的致命错误
  • Example#3702 - 检测对象状态
  • Example#3703 - 检测对象状态
  • Example#3704 - 检测对象状态
  • Example#3705 - 给对象属性加锁
  • Example#3706 - 合并数据到对象的属性表
  • Example#3707 - 等待和唤醒
  • Example#3708 - Notifications and Waiting
  • Example#3709 - 弹出对象属性表中的最后一项数据
  • Example#3710 - 弹出对象属性表中第一项数据
  • Example#3711 - 同步
  • Example#3712 - 给对象属性表加锁
  • Example#3713 - 等待和唤醒
  • Example#3714 - 返回创建线程的线程或进程ID
  • Example#3715 - 获取当前执行线程
  • Example#3716 - 返回当前执行线程的ID
  • Example#3717 - 返回引用线程的ID
  • Example#3718 - 在全局范围执行代码块
  • Example#3719 - 检测线程状态
  • Example#3720 - 监测线程是否开始执行
  • Example#3721 - 加入线程
  • Example#3722 - 杀除线程
  • Example#3723 - 开始线程
  • Example#3724 - A basic example of Worker::collect
  • Example#3725 - Worker::getStacked 基本示例
  • Example#3726 - 检测 Worker 对象状态
  • Example#3727 - 检测 Worker 对象状态
  • Example#3728 - 关闭 Worker
  • Example#3729 - 向 Worker 中入栈任务并执行
  • Example#3730 - 从 Worker 栈中移除对象
  • Example#3731 - protected 方法示例： 标记为 protected 的方法在同一时间仅允许一个线程访问
  • Example#3732 - private 方法示例：标记为 private 的方法只能由创建该对象的线程调用
  • Example#3733 - Pool::collect 基本用法示例
  • Example#3734 - 创建 Pool 对象
  • Example#3735 - 完全停止一个 Pool
  • Example#3736 - 提交任务
  • Example#3737 - 提交任务到特定的 Worker
  • Example#3738 - 互斥量的创建与销毁
  • Example#3739 - 互斥量的创建与销毁
  • Example#3740 - 互斥量加锁与解锁
  • Example#3741 - 互斥量的加锁与解锁
  • Example#3742 - 互斥量的加锁与解锁
  • Example#3743 - 广播条件变量
  • Example#3744 - 条件变量的创建与销毁
  • Example#3745 - 条件变量的创建与销毁
  • Example#3746 - 发送唤醒信号
  • Example#3747 - 等待条件变量
  • Example#3748 - New immutability semantics of Threaded
  • Example#3749 - Volatile use-case
  • Example#3750 - Adding a new class task to a thread
  • Example#3751 - Adding a new file task to a thread
  • Example#3752 - Adding a new function task to a thread
  • Example#3753 - Joining a thread
  • Example#3754 - Starting a new thread
  • Example#3755 - Getting the task count of a thread
  • Example#3756 - Locking a hash table's mutex lock
  • Example#3757 - Getting a hash table's size
  • Example#3758 - Locking a hash table's mutex lock
  • Example#3759 - Creating a new vector
  • Example#3760 - Deleting values in a vector
  • Example#3761 - Inserting a value into a vector
  • Example#3762 - Locking a vector's mutex lock
  • Example#3763 - Popping a value from a vector
  • Example#3764 - Pushing values to a vector
  • Example#3765 - Resizing a vector
  • Example#3766 - Shifting a value from a vector
  • Example#3767 - Getting a vector's size
  • Example#3768 - Locking a vector's mutex lock
  • Example#3769 - Unshifting a value to the front of a vector
  • Example#3770 - Updating a value in a vector
  • Example#3771 - Retrieving the front value of a queue
  • Example#3772 - Retrieving the front value in a loop (bad example - don't do this)
  • Example#3773 - Retrieving the front value in a loop (good example)
  • Example#3774 - Locking a queue's mutex lock
  • Example#3775 - Popping a value from a queue
  • Example#3776 - Pushing a value to a queue
  • Example#3777 - Getting a queue's size
  • Example#3778 - Locking a queue's mutex lock
  • Example#3779 - Creating a new atomic integer
  • Example#3780 - Decrementing an atomic integer's value
  • Example#3781 - Getting an atomic integer's value
  • Example#3782 - Incrementing an atomic integer's value
  • Example#3783 - Grouping together an atomic integer's operations (requiring a mutex lock)
  • Example#3784 - Setting an atomic integer's value
  • Example#3785 - Grouping together an atomic integer's operations (requiring a mutex lock)
  • Example#3786 - Shared Memory Operations Overview
  • Example#3787 - Closing shared memory block
  • Example#3788 - Deleting shared memory block
  • Example#3789 - Create a new shared memory block
  • Example#3790 - Reading shared memory block
  • Example#3791 - Getting the size of the shared memory block
  • Example#3792 - Writing to shared memory block
  • Example#3793 - SyncMutex::__construct named mutex with lock timeout example
  • Example#3794 - SyncMutex::__construct unnamed mutex example
  • Example#3795 - SyncMutex::lock example
  • Example#3796 - SyncMutex::unlock example
  • Example#3797 - SyncSemaphore::__construct example
  • Example#3798 - SyncSemaphore::lock example
  • Example#3799 - SyncSemaphore::unlock example
  • Example#3800 - SyncEvent::__construct example
  • Example#3801 - SyncEvent::fire example
  • Example#3802 - SyncEvent::reset example
  • Example#3803 - SyncEvent::wait example
  • Example#3804 - SyncReaderWriter::__construct example
  • Example#3805 - SyncReaderWriter::readlock example
  • Example#3806 - SyncReaderWriter::readunlock example
  • Example#3807 - SyncReaderWriter::writelock example
  • Example#3808 - SyncReaderWriter::writeunlock example
  • Example#3809 - SyncSharedMemory::__construct example
  • Example#3810 - SyncSharedMemory::first example
  • Example#3811 - SyncSharedMemory::__construct example
  • Example#3812 - SyncSharedMemory::size example
  • Example#3813 - SyncSharedMemory::write example
  • Example#3814 - geoip_asnum_by_name函数的范例：
  • Example#3815 - geoip_continent_code_by_name 函数的使用范例：
  • Example#3816 - geoip_country_code_by_name 函数的范例：
  • Example#3817 - geoip_country_code3_by_name 函数的使用范例：
  • Example#3818 - geoip_country_name_by_name 函数的使用范例：
  • Example#3819 - geoip_database_info 函数的使用范例：
  • Example#3820 - geoip_db_avail 函数的使用范例：
  • Example#3821 - geoip_db_filename函数的使用范例：
  • Example#3822 - geoip_db_get_all_info 使用范例：
  • Example#3823 - geoip_db_get_all_info 使用范例：
  • Example#3824 - 一个 geoip_domain_by_name 使用范例：
  • Example#3825 - 一个 geoip_id_by_name 使用范例：
  • Example#3826 - 一个 geoip_isp_by_name 使用范例：
  • Example#3827 - 一个 geoip_netspeedcell_by_name 使用范例：
  • Example#3828 - 一个 geoip_org_by_name 使用范例：
  • Example#3829 - geoip_record_by_name 例子：
  • Example#3830 - geoip_region_by_name 例子：
  • Example#3831 - geoip_region_name_by_code 使用美国和加拿大地区的范例。
  • Example#3832 - geoip_region_name_by_code 使用 FIPS 代码的范例：
  • Example#3833 - geoip_setup_custom_directory 例子：
  • Example#3834 - geoip_time_zone_by_country_and_region 使用美国和加拿大地区的范例：
  • Example#3835 - geoip_time_zone_by_country_and_region 使用 FIPS 代码的范例：
  • Example#3836 - xor.data file
  • Example#3837 - 一般训练
  • Example#3838 - 一般测试
  • Example#3839 - fann_create_train_from_callback example
  • Example#3840 - fann_read_train_from_file 函数的使用范例：
  • Example#3841 - JsonSerializable::jsonSerialize 例子 returning an array
  • Example#3842 - JsonSerializable::jsonSerialize 例子 返回了一个关联数组 array
  • Example#3843 - JsonSerializable::jsonSerialize 例子 返回一个 integer
  • Example#3844 - JsonSerializable::jsonSerialize 例子 返回一个 string
  • Example#3845 - json_decode 的例子
  • Example#3846 - Accessing invalid object properties
  • Example#3847 - common mistakes using json_decode
  • Example#3848 - depth errors
  • Example#3849 - json_decode of large integers
  • Example#3850 - json_encode 例子
  • Example#3851 - json_encode 函数中 options 参数的用法
  • Example#3852 - 选项 JSON_NUMERIC_CHECK 例子
  • Example#3853 - 连续与非连续数组示例
  • Example#3854 - 选项 JSON_PRESERVE_ZERO_FRACTION 的例子
  • Example#3855 - json_last_error 例子
  • Example#3856 - json_encode 的 json_last_error
  • Example#3857 - Lua::assign示例
  • Example#3858 - Lua::call示例
  • Example#3859 - Lua::eval示例
  • Example#3860 - Lua::registerCallback示例
  • Example#3861 - LuaClosure::__invoke示例
  • Example#3862 - Execute some Lua code
  • Example#3863 - Calling a Lua function
  • Example#3864 - Profiling Lua code
  • Example#3865 - Loading code into Lua
  • Example#3866 - Manipulating the usage timer
  • Example#3867 - Registering PHP functions to call from Lua
  • Example#3868 - Calling a Lua function
  • Example#3869 - Calling a Lua function
  • Example#3870 - constant 的例子
  • Example#3871 - 定义常量
  • Example#3872 - 以保留名称定义常量
  • Example#3873 - 检查常量
  • Example#3874 - eval 例子 - 简单的文本合并
  • Example#3875 - exit 例子
  • Example#3876 - exit 状态码例子
  • Example#3877 - 无论如何，Shutdown函数与析构函数都会被执行
  • Example#3878 - 列出所有用户浏览器的信息
  • Example#3879 - __halt_compiler 例子
  • Example#3880 - highlight_string 例子
  • Example#3881 - hrtime 的用法
  • Example#3882 - ignore_user_abort例子
  • Example#3883 - pack 范例
  • Example#3884 - php_strip_whitespace 的例子
  • Example#3885 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#3886 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#3887 - sapi_windows_vt100_support default state
  • Example#3888 - sapi_windows_vt100_support changing state
  • Example#3889 - Example usage of VT100 support enabled
  • Example#3890 - sleep 的例子
  • Example#3891 - sys_getloadavg 的例子
  • Example#3892 - time_nanosleep 的例子
  • Example#3893 - time_sleep_until 的一个例子
  • Example#3894 - uniqid 例子
  • Example#3895 - unpack example
  • Example#3896 - unpack example with a repeater
  • Example#3897 - unpack example with unnamed keys
  • Example#3898 - usleep例子
  • Example#3899 - 获取与设置根目录
  • Example#3900 - 获取与设置 Logger
  • Example#3901 - 快速写入日志
  • Example#3902 - 快速获取某级别下日志的数量
  • Example#3903 - 获取某级别下日志的详情
  • Example#3904 - seaslog_get_author example
  • Example#3905 - seaslog_get_version example
  • Example#3906 - SeasLog::alert例子
  • Example#3907 - SeasLog::analyzerCount example
  • Example#3908 - SeasLog::analyzerDetail example
  • Example#3909 - SeasLog::closeLoggerStream example
  • Example#3910 - SeasLog::__construct example
  • Example#3911 - SeasLog::critical example
  • Example#3912 - SeasLog::debug example
  • Example#3913 - SeasLog::__destruct example
  • Example#3914 - SeasLog::emergency example
  • Example#3915 - SeasLog::error example
  • Example#3916 - SeasLog::flushBuffer example
  • Example#3917 - SeasLog::getBasePath example
  • Example#3918 - SeasLog::getBuffer example
  • Example#3919 - SeasLog::getBufferEnabled example
  • Example#3920 - SeasLog::getDatetimeFormat example
  • Example#3921 - SeasLog::getLastLogger example
  • Example#3922 - SeasLog::getRequestID example
  • Example#3923 - SeasLog::getRequestVariable example
  • Example#3924 - SeasLog::info example
  • Example#3925 - SeasLog::log example
  • Example#3926 - SeasLog::notice example
  • Example#3927 - SeasLog::setBasePath example
  • Example#3928 - SeasLog::setDatetimeFormat example
  • Example#3929 - SeasLog::setLogger example
  • Example#3930 - SeasLog::setRequestID example
  • Example#3931 - SeasLog::setRequestVariable example
  • Example#3932 - SeasLog::warning example
  • Example#3933 - SplDoublyLinkedList::__construct example
  • Example#3934 - SplStack::__construct example
  • Example#3935 - SplQueue::__construct example
  • Example#3936 - Efficiently handling tasks with SplQueue
  • Example#3937 - SplFixedArray usage example
  • Example#3938 - SplFixedArray::__construct example
  • Example#3939 - SplFixedArray::count example
  • Example#3940 - SplFixedArray::fromArray example
  • Example#3941 - SplFixedArray::getSize example
  • Example#3942 - SplFixedArray::setSize example
  • Example#3943 - SplFixedArray::toArray example
  • Example#3944 - SplObjectStorage as a set
  • Example#3945 - SplObjectStorage as a map
  • Example#3946 - SplObjectStorage::addAll example
  • Example#3947 - SplObjectStorage::attach example
  • Example#3948 - SplObjectStorage::contains example
  • Example#3949 - SplObjectStorage::count example
  • Example#3950 - SplObjectStorage::current example
  • Example#3951 - SplObjectStorage::detach example
  • Example#3952 - SplObjectStorage::getHash example
  • Example#3953 - SplObjectStorage::getInfo example
  • Example#3954 - SplObjectStorage::key example
  • Example#3955 - SplObjectStorage::next example
  • Example#3956 - SplObjectStorage::offsetExists example
  • Example#3957 - SplObjectStorage::offsetGet example
  • Example#3958 - SplObjectStorage::offsetSet example
  • Example#3959 - SplObjectStorage::offsetUnset example
  • Example#3960 - SplObjectStorage::removeAll example
  • Example#3961 - SplObjectStorage::removeAllExcept example
  • Example#3962 - SplObjectStorage::rewind example
  • Example#3963 - SplObjectStorage::serialize example
  • Example#3964 - SplObjectStorage::setInfo example
  • Example#3965 - SplObjectStorage::unserialize example
  • Example#3966 - SplObjectStorage::valid example
  • Example#3967 - AppendIterator::append example
  • Example#3968 - Iterating AppendIterator with foreach
  • Example#3969 - Iterating AppendIterator with the AppendIterator API
  • Example#3970 - AppendIterator::getInnerIterator example
  • Example#3971 - AppendIterator.getIteratorIndex basic example
  • Example#3972 - AppendIterator::key basic example
  • Example#3973 - ArrayIterator::current example
  • Example#3974 - ArrayIterator::key example
  • Example#3975 - ArrayIterator::next example
  • Example#3976 - ArrayIterator::rewind example
  • Example#3977 - ArrayIterator::valid example
  • Example#3978 - CachingIterator::getCache example
  • Example#3979 - Available callback arguments
  • Example#3980 - Callback basic examples
  • Example#3981 - A DirectoryIterator::__construct example
  • Example#3982 - A DirectoryIterator::current example
  • Example#3983 - A DirectoryIterator::getATime example
  • Example#3984 - A DirectoryIterator::getBasename example
  • Example#3985 - DirectoryIterator::getCTime example
  • Example#3986 - DirectoryIterator::getExtension example
  • Example#3987 -
  • Example#3988 - A DirectoryIterator::getFilename example
  • Example#3989 - DirectoryIterator::getGroup example
  • Example#3990 - DirectoryIterator::getInode example
  • Example#3991 - A DirectoryIterator::getMTime example
  • Example#3992 - DirectoryIterator::getOwner example
  • Example#3993 - DirectoryIterator::getPath example
  • Example#3994 - DirectoryIterator::getPathname example
  • Example#3995 - DirectoryIterator::getPerms example
  • Example#3996 - DirectoryIterator::getSize example
  • Example#3997 - DirectoryIterator::getType example
  • Example#3998 - DirectoryIterator::isDir example
  • Example#3999 - A DirectoryIterator::isDot example
  • Example#4000 - DirectoryIterator::isExecutable example
  • Example#4001 - DirectoryIterator::isFile example
  • Example#4002 - A DirectoryIterator::isLink example
  • Example#4003 - DirectoryIterator::isReadable example
  • Example#4004 - DirectoryIterator::isWritable example
  • Example#4005 - A DirectoryIterator::key example
  • Example#4006 - DirectoryIterator::next example
  • Example#4007 - DirectoryIterator::rewind example
  • Example#4008 - DirectoryIterator::seek example
  • Example#4009 - A DirectoryIterator::__toString example
  • Example#4010 - A DirectoryIterator::valid example
  • Example#4011 - FilesystemIterator::__construct example
  • Example#4012 - FilesystemIterator::current example
  • Example#4013 - FilesystemIterator::key example
  • Example#4014 - FilesystemIterator::next example
  • Example#4015 - FilesystemIterator::rewind example
  • Example#4016 - FilesystemIterator::key example
  • Example#4017 - FilterIterator::accept example
  • Example#4018 - GlobIterator example
  • Example#4019 - GlobIterator::count example
  • Example#4020 - InfiniteIterator::__construct example
  • Example#4021 - LimitIterator usage example
  • Example#4022 - LimitIterator::__construct example
  • Example#4023 - LimitIterator::getPosition example
  • Example#4024 - Iterating a MultipleIterator
  • Example#4025 - NoRewindIterator::__construct example
  • Example#4026 - NoRewindIterator::rewind example
  • Example#4027 - RecursiveArrayIterator::getChildren example
  • Example#4028 - RecursiveArrayIterator::hasChildren example
  • Example#4029 - Available callback arguments
  • Example#4030 - Recursive callback basic example
  • Example#4031 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#4032 - RecursiveDirectoryIterator example
  • Example#4033 - getSubPath example
  • Example#4034 - getSubPathname example
  • Example#4035 - Basic RecursiveFilterIterator example
  • Example#4036 - RecursiveFilterIterator example
  • Example#4037 - Iterating a RecursiveIteratorIterator
  • Example#4038 - RecursiveRegexIterator::__construct example
  • Example#4039 - RecursiveRegexIterator::getChildren example
  • Example#4040 - RecursiveRegexIterator::hasChildren example
  • Example#4041 - RegexIterator::accept example
  • Example#4042 - RegexIterator::__construct example
  • Example#4043 - RegexIterator::getFlags example
  • Example#4044 - RegexIterator::getMode example
  • Example#4045 - RegexIterator::getPregFlags example
  • Example#4046 - RegexIterator::setFlags example
  • Example#4047 - RegexIterator::setMode example
  • Example#4048 - RegexIterator::setPregFlags example
  • Example#4049 - Countable::count example
  • Example#4050 - Basic usage
  • Example#4051 - SeekableIterator::seek example
  • Example#4052 - class_implements example
  • Example#4053 - class_parents example
  • Example#4054 - class_uses example
  • Example#4055 - iterator_apply example
  • Example#4056 - iterator_count example
  • Example#4057 - iterator_to_array example
  • Example#4058 - spl_autoload_extensions 示例
  • Example#4059 - spl_autoload_register 作为 __autoload 函数的替代
  • Example#4060 - class 未能加载的 spl_autoload_register 例子
  • Example#4061 - spl_classes example
  • Example#4062 - A spl_object_hash example
  • Example#4063 - A spl_object_id example
  • Example#4064 - SplFileInfo::__construct 示例
  • Example#4065 - SplFileInfo::getBasename example
  • Example#4066 - SplFileInfo::getCTime 例子
  • Example#4067 - SplFileInfo::getExtension example
  • Example#4068 -
  • Example#4069 - SplFileInfo::getFilename example
  • Example#4070 - SplFileInfo::getGroup example
  • Example#4071 - SplFileInfo::getLinkTarget example
  • Example#4072 - SplFileInfo::getOwner example
  • Example#4073 - SplFileInfo::getPath example
  • Example#4074 - SplFileInfo::getPathInfo example
  • Example#4075 - SplFileInfo::getPathname example
  • Example#4076 - SplFileInfo::getPerms example
  • Example#4077 - SplFileInfo::getRealPath example
  • Example#4078 - SplFileInfo::getType example
  • Example#4079 - SplFileInfo::isDir example
  • Example#4080 - SplFileInfo::isExecutable example
  • Example#4081 - SplFileInfo::isFile example
  • Example#4082 - SplFileInfo::isLink example
  • Example#4083 - SplFileInfo::isReadable example
  • Example#4084 - SplFileInfo::openFile example
  • Example#4085 - SplFileInfo::setFileClass example
  • Example#4086 - SplFileInfo::setFileClass example
  • Example#4087 - SplFileInfo::__toString example
  • Example#4088 - SplFileObject::__construct example
  • Example#4089 - SplFileObject::current example
  • Example#4090 - SplFileObject::eof example
  • Example#4091 - SplFileObject::fflush example
  • Example#4092 - SplFileObject::fgetc example
  • Example#4093 - SplFileObject::fgetcsv example
  • Example#4094 - SplFileObject::READ_CSV example
  • Example#4095 - SplFileObject::fgets example
  • Example#4096 - SplFileObject::fgetss example
  • Example#4097 - SplFileObject::flock example
  • Example#4098 - SplFileObject::fpassthru example
  • Example#4099 - SplFileObject::fputcsv example
  • Example#4100 - SplFileObject::fread example
  • Example#4101 - SplFileObject::fscanf example
  • Example#4102 - SplFileObject::fseek example
  • Example#4103 - SplFileObject::fstat example
  • Example#4104 - SplFileObject::ftell example
  • Example#4105 - SplFileObject::ftruncate example
  • Example#4106 - SplFileObject::fwrite example
  • Example#4107 - SplFileObject::getCsvControl example
  • Example#4108 - SplFileObject::getFlags example
  • Example#4109 - SplFileObject::getMaxLineLen example
  • Example#4110 - SplFileObject::key example
  • Example#4111 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#4112 - SplFileObject::next example
  • Example#4113 - SplFileObject::rewind example
  • Example#4114 - SplFileObject::seek example
  • Example#4115 - SplFileObject::setCsvControl example
  • Example#4116 - SplFileObject::setFlags example
  • Example#4117 - SplFileObject::setMaxLineLen example
  • Example#4118 - SplFileObject::valid example
  • Example#4119 - SplTempFileObject example
  • Example#4120 - ArrayObject::append 例子
  • Example#4121 - ArrayObject::asort example
  • Example#4122 - ArrayObject::__construct example
  • Example#4123 - ArrayObject::count 例子
  • Example#4124 - ArrayObject::exchangeArray example
  • Example#4125 - ArrayObject::getArrayCopy example
  • Example#4126 - ArrayObject::getFlags example
  • Example#4127 - ArrayObject::getIterator example
  • Example#4128 - ArrayObject::getIteratorClass example
  • Example#4129 - ArrayObject::ksort example
  • Example#4130 - ArrayObject::natcasesort example
  • Example#4131 - ArrayObject::natsort example
  • Example#4132 - ArrayObject::offsetExists example
  • Example#4133 - ArrayObject::offsetGet example
  • Example#4134 - ArrayObject::offsetSet 例子
  • Example#4135 - ArrayObject::offsetUnset example
  • Example#4136 - ArrayObject::serialize example
  • Example#4137 - ArrayObject::setFlags example
  • Example#4138 - ArrayObject::setIteratorClass example
  • Example#4139 - ArrayObject::uasort example
  • Example#4140 - ArrayObject::uksort example
  • Example#4141 - Using file_get_contents to retrieve data from multiple sources
  • Example#4142 - Making a POST request to an https server
  • Example#4143 - Writing data to a compressed file
  • Example#4144 - A Stream for reading/writing global variables
  • Example#4145 - Listing files from tar archives
  • Example#4146 - stream_bucket_prepend examples
  • Example#4147 - 使用 stream_context_create
  • Example#4148 - Using stream_context_get_default
  • Example#4149 - stream_context_get_options 的例子
  • Example#4150 - stream_context_get_params example
  • Example#4151 - stream_context_set_default example
  • Example#4152 - A stream_copy_to_stream example
  • Example#4153 - Controlling where filters are applied
  • Example#4154 - Filter for capitalizing characters on foo-bar.txt stream
  • Example#4155 - Registering a generic filter class to match multiple filter names.
  • Example#4156 - 动态地重新过滤一个资源流
  • Example#4157 - stream_get_contents 例子
  • Example#4158 - 使用 stream_get_filters
  • Example#4159 - 使用 stream_get_transports
  • Example#4160 - stream_get_wrappers 例子
  • Example#4161 - 检查一个流类型是否存在
  • Example#4162 - stream_is_local example
  • Example#4163 - stream_isatty example
  • Example#4164 - stream_notification_callback example
  • Example#4165 - Simple progressbar for commandline download client
  • Example#4166 - stream_resolve_include_path example
  • Example#4167 - stream_select Example
  • Example#4168 - stream_set_timeout example
  • Example#4169 - stream_set_write_buffer example
  • Example#4170 - stream_socket_client example
  • Example#4171 - Using UDP connection
  • Example#4172 - stream_socket_enable_crypto example
  • Example#4173 - A stream_socket_pair example
  • Example#4174 - stream_socket_recvfrom example
  • Example#4175 - stream_socket_sendto Example
  • Example#4176 - Using TCP server sockets
  • Example#4177 - Using UDP server sockets
  • Example#4178 - A stream_socket_shutdown example
  • Example#4179 - 如何注册一个 stream wrapper
  • Example#4180 - Basic Tidy usage
  • Example#4181 - tidy::getBody example
  • Example#4182 - tidy::cleanrepair example
  • Example#4183 - tidy::__construct example
  • Example#4184 - tidy::diagnose example
  • Example#4185 - tidy_get_error_buffer example
  • Example#4186 - tidy::getConfig example
  • Example#4187 - tidy_getopt example
  • Example#4188 - Print all options along with their documentation and default value
  • Example#4189 - tidy::getStatus example
  • Example#4190 - tidy::head example
  • Example#4191 - tidy::html example
  • Example#4192 - tidy::parseFile example
  • Example#4193 - tidy::parseString example
  • Example#4194 - tidy::repairFile example
  • Example#4195 - tidy::repairString example
  • Example#4196 - tidy::root example
  • Example#4197 - tidyNode::hasChildren example
  • Example#4198 - tidyNode::hasChildren example
  • Example#4199 - tidyNode::hasSiblings example
  • Example#4200 - Extract ASP code from a mixed HTML document
  • Example#4201 - Extract comments from a mixed HTML document
  • Example#4202 - Extract HTML code from a mixed HTML document
  • Example#4203 - Extract JSTE code from a mixed HTML document
  • Example#4204 - Extract PHP code from a mixed HTML document
  • Example#4205 - Extract text from a mixed HTML document
  • Example#4206 - ob_tidyhandler example
  • Example#4207 - tidy_access_count example
  • Example#4208 - tidy_config_count example
  • Example#4209 - tidy_error_count example
  • Example#4210 - tidy_get_output example
  • Example#4211 - tidy_warning_count example
  • Example#4212 - Strip comments with the tokenizer
  • Example#4213 - PhpToken::getTokenName example
  • Example#4214 - PhpToken::is example
  • Example#4215 - Usage with array
  • Example#4216 - PhpToken::isIgnorable example
  • Example#4217 - PhpToken::__toString example
  • Example#4218 - PhpToken::tokenize example
  • Example#4219 - Extending PhpToken
  • Example#4220 - token_get_all examples
  • Example#4221 - token_name example
  • Example#4222 - base64_decode 示例
  • Example#4223 - base64_encode 示例
  • Example#4224 - get_headers 例子
  • Example#4225 - get_headers using HEAD example
  • Example#4226 - get_meta_tags 解析了什么
  • Example#4227 - get_meta_tags 返回什么些
  • Example#4228 - http_build_query 使用示例
  • Example#4229 - http_build_query 使用数字下标的元素
  • Example#4230 - http_build_query 使用复杂的数组
  • Example#4231 - http_build_query 使用对象
  • Example#4232 - parse_url 例子
  • Example#4233 - parse_url 解析丢失协议的例子
  • Example#4234 - rawurldecode 示例
  • Example#4235 - 在 FTP URL 里包含一个密码
  • Example#4236 - rawurlencode 示例 2
  • Example#4237 - urldecode 示例
  • Example#4238 - urlencode 例子
  • Example#4239 - urlencode 与 htmlentities 例子
  • Example#4240 - Basic Javascript execution
  • Example#4241 - Yaml 范例
  • Example#4242 - Parse callback example
  • Example#4243 - Emit callback example
  • Example#4244 - yaml_emit example
  • Example#4245 - yaml_parse example
  • Example#4246 - 一个典型的应用目录结构
  • Example#4247 - 入口文件
  • Example#4248 - 重写规则
  • Example#4249 - 应用配置文件
  • Example#4250 - 默认控制器
  • Example#4251 - 默认视图文件
  • Example#4252 - 运行应用
  • Example#4253 - config为数组的例子
  • Example#4254 - config为ini文件的例子
  • Example#4255 - A Bootstrapexample
  • Example#4256 - Yaf_Application::bootstrapexample
  • Example#4257 - Yaf_Application::clearLastErrorexample
  • Example#4258 - A ini config file example
  • Example#4259 - Yaf_Application::__constructexample
  • Example#4260 - Yaf_Application::__constructexample
  • Example#4261 - Yaf_Application::environexample
  • Example#4262 - Yaf_Application::executeexample
  • Example#4263 - Yaf_Application::getConfigexample
  • Example#4264 - Yaf_Application::getDispatcherexample
  • Example#4265 - Yaf_Application::getLastErrorMsgexample
  • Example#4266 - Yaf_Application::getLastErrorNoexample
  • Example#4267 - Yaf_Application::getModulesexample
  • Example#4268 - Bootstrap example
  • Example#4269 - Yaf_Dispatcher::autoRenderexample
  • Example#4270 - Yaf_Dispatcher::catchExceptionexample
  • Example#4271 - Yaf_Dispatcher::registerPluginexample
  • Example#4272 - A custom View engineexample
  • Example#4273 - Yaf_Dispatcher::setViewexample
  • Example#4274 - Yaf_Dispatcher::throwexceptionexample
  • Example#4275 - Yaf_Dispatcher::throwexceptionexample
  • Example#4276 - Yaf_Config_Iniexample
  • Example#4277 - 在一个独立的文件中定义action
  • Example#4278 - Dummy_action.php
  • Example#4279 - Yaf_Controller_Abstract::forward例子
  • Example#4280 - Yaf_Action_Abstract::executeexample
  • Example#4281 - Yaf_Action_Abstract::executeexample
  • Example#4282 - Yaf_View_Simple::assignexample
  • Example#4283 - templateexample
  • Example#4284 - Yaf_View_Simple::assignRefexample
  • Example#4285 - templateexample
  • Example#4286 - Yaf_View_Simple::clearexample
  • Example#4287 - Yaf_View_Simple::__constructorexample
  • Example#4288 - Yaf_View_Simple::__setexample
  • Example#4289 - Config example
  • Example#4290 - 注册本地命名空间
  • Example#4291 - 加载类
  • Example#4292 - 加载命名空间类
  • Example#4293 - MVC类加载例子
  • Example#4294 - MVC 类区别
  • Example#4295 - MVC loading example
  • Example#4296 - Yaf_Loader::registerNamespaceexample
  • Example#4297 - Yaf_Loader::registerLocalNamespaceexample
  • Example#4298 - Yaf_Loader::registerNamespaceexample
  • Example#4299 - Plugin example
  • Example#4300 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#4301 - Yaf_Response_Abstract::appendBodyexample
  • Example#4302 - Yaf_Response_Abstract::getBodyexample
  • Example#4303 - Yaf_Response_Abstract::prependBodyexample
  • Example#4304 - Yaf_Response_Abstract::responseexample
  • Example#4305 - Yaf_Response_Abstract::setBodyexample
  • Example#4306 - Yaf_Route_Map::assembleexample
  • Example#4307 - Yaf_Route_Mapexample
  • Example#4308 - Yaf_Route_Mapexample
  • Example#4309 - Yaf_Route_Mapexample
  • Example#4310 - Yaf_Route_Regex::assembleexample
  • Example#4311 - Yaf_Route_Regexexample
  • Example#4312 - Yaf_Route_Regex(as of 2.3.0)example
  • Example#4313 - Yaf_Route_Regexexample
  • Example#4314 - Yaf_Route_Rewrite::assembleexample
  • Example#4315 - Yaf_Route_Rewriteexample
  • Example#4316 - Yaf_Route_Rewriteexample
  • Example#4317 - Yaf_Route_Rewrite(as of 2.3.0)example
  • Example#4318 - Apache的跳转规则
  • Example#4319 - Apache的跳转规则
  • Example#4320 - Lighttpd的跳转规则
  • Example#4321 - Nginx的跳转规则
  • Example#4322 - Yaf_Route_Static(default route)example
  • Example#4323 - application.iniexample
  • Example#4324 - Yaf_Dispatcher::autoConfigexample
  • Example#4325 - Yaf_Dispatcher::autoRenderexample
  • Example#4326 - 注册一些路由到Bootstrap
  • Example#4327 - plugin Dummy.php (under application.directory/plugins)
  • Example#4328 - Yaf_Route_Simple::assembleexample
  • Example#4329 - Yaf_Route_Simple::routeexample
  • Example#4330 - Yaf_Route_Simple::routeexample
  • Example#4331 - Yaf_Route_Static::assembleexample
  • Example#4332 - Yaf_Route_Static::routeexample
  • Example#4333 - Yaf_Route_Supervar::assembleexample
  • Example#4334 - Yaf_Route_Supervarexample
  • Example#4335 - INI example
  • Example#4336 - INI sections example
  • Example#4337 - INIexample
  • Example#4338 - Taintexample
  • Example#4339 - Vector
  • Example#4340 - Map
  • Example#4341 - Ds\Collection::clear example
  • Example#4342 - Ds\Collection::copy example
  • Example#4343 - Ds\Collection::isEmpty example
  • Example#4344 - Ds\Collection::toArray example
  • Example#4345 - Ds\Hashable::hash example
  • Example#4346 - Ds\Sequence::allocate example
  • Example#4347 - Ds\Sequence::apply example
  • Example#4348 - Ds\Sequence::capacity example
  • Example#4349 - Ds\Sequence::contains example
  • Example#4350 - Ds\Sequence::filter example using callback function
  • Example#4351 - Ds\Sequence::filter example without a callback function
  • Example#4352 - Ds\Sequence::find example
  • Example#4353 - Ds\Sequence::first example
  • Example#4354 - Ds\Sequence::get example
  • Example#4355 - Ds\Sequence::get example using array syntax
  • Example#4356 - Ds\Sequence::insert example
  • Example#4357 - Ds\Sequence::join example using a separator string
  • Example#4358 - Ds\Sequence::join example without a separator string
  • Example#4359 - Ds\Sequence::last example
  • Example#4360 - Ds\Sequence::map example
  • Example#4361 - Ds\Sequence::merge example
  • Example#4362 - Ds\Sequence::pop example
  • Example#4363 - Ds\Sequence::push example
  • Example#4364 - Ds\Sequence::reduce with initial value example
  • Example#4365 - Ds\Sequence::reduce without an initial value example
  • Example#4366 - Ds\Sequence::remove example
  • Example#4367 - Ds\Sequence::reverse example
  • Example#4368 - Ds\Sequence::reversed example
  • Example#4369 - Ds\Sequence::rotate example
  • Example#4370 - Ds\Sequence::set example
  • Example#4371 - Ds\Sequence::set example using array syntax
  • Example#4372 - Ds\Sequence::shift example
  • Example#4373 - Ds\Sequence::slice example
  • Example#4374 - Ds\Sequence::sort example
  • Example#4375 - Ds\Sequence::sort example using a comparator
  • Example#4376 - Ds\Sequence::sorted example
  • Example#4377 - Ds\Sequence::sorted example using a comparator
  • Example#4378 - Ds\Sequence::sum integer example
  • Example#4379 - Ds\Sequence::sum float example
  • Example#4380 - Ds\Sequence::unshift example
  • Example#4381 - Ds\Vector::allocate example
  • Example#4382 - Ds\Vector::apply example
  • Example#4383 - Ds\Vector::capacity example
  • Example#4384 - Ds\Vector::clear example
  • Example#4385 - Ds\Vector::__construct example
  • Example#4386 - Ds\Vector::contains example
  • Example#4387 - Ds\Vector::copy example
  • Example#4388 - Ds\Vector::filter example using callback function
  • Example#4389 - Ds\Vector::filter example without a callback function
  • Example#4390 - Ds\Vector::find example
  • Example#4391 - Ds\Vector::first example
  • Example#4392 - Ds\Vector::get example
  • Example#4393 - Ds\Vector::get example using array syntax
  • Example#4394 - Ds\Vector::insert example
  • Example#4395 - Ds\Vector::isEmpty example
  • Example#4396 - Ds\Vector::join example using a separator string
  • Example#4397 - Ds\Vector::join example without a separator string
  • Example#4398 - Ds\Vector::last example
  • Example#4399 - Ds\Vector::map example
  • Example#4400 - Ds\Vector::merge example
  • Example#4401 - Ds\Vector::pop example
  • Example#4402 - Ds\Vector::push example
  • Example#4403 - Ds\Vector::reduce with initial value example
  • Example#4404 - Ds\Vector::reduce without an initial value example
  • Example#4405 - Ds\Vector::remove example
  • Example#4406 - Ds\Vector::reverse example
  • Example#4407 - Ds\Vector::reversed example
  • Example#4408 - Ds\Vector::rotate example
  • Example#4409 - Ds\Vector::set example
  • Example#4410 - Ds\Vector::set example using array syntax
  • Example#4411 - Ds\Vector::shift example
  • Example#4412 - Ds\Vector::slice example
  • Example#4413 - Ds\Vector::sort example
  • Example#4414 - Ds\Vector::sort example using a comparator
  • Example#4415 - Ds\Vector::sorted example
  • Example#4416 - Ds\Vector::sorted example using a comparator
  • Example#4417 - Ds\Vector::sum integer example
  • Example#4418 - Ds\Vector::sum float example
  • Example#4419 - Ds\Vector::toArray example
  • Example#4420 - Ds\Vector::unshift example
  • Example#4421 - Ds\Deque::allocate example
  • Example#4422 - Ds\Deque::apply example
  • Example#4423 - Ds\Deque::capacity example
  • Example#4424 - Ds\Deque::clear example
  • Example#4425 - Ds\Deque::__construct example
  • Example#4426 - Ds\Deque::contains example
  • Example#4427 - Ds\Deque::copy example
  • Example#4428 - Ds\Deque::filter example using callback function
  • Example#4429 - Ds\Deque::filter example without a callback function
  • Example#4430 - Ds\Deque::find example
  • Example#4431 - Ds\Deque::first example
  • Example#4432 - Ds\Deque::get example
  • Example#4433 - Ds\Deque::get example using array syntax
  • Example#4434 - Ds\Deque::insert example
  • Example#4435 - Ds\Deque::isEmpty example
  • Example#4436 - Ds\Deque::join example using a separator string
  • Example#4437 - Ds\Deque::join example without a separator string
  • Example#4438 - Ds\Deque::last example
  • Example#4439 - Ds\Deque::map example
  • Example#4440 - Ds\Deque::merge example
  • Example#4441 - Ds\Deque::pop example
  • Example#4442 - Ds\Deque::push example
  • Example#4443 - Ds\Deque::reduce with initial value example
  • Example#4444 - Ds\Deque::reduce without an initial value example
  • Example#4445 - Ds\Deque::remove example
  • Example#4446 - Ds\Deque::reverse example
  • Example#4447 - Ds\Deque::reversed example
  • Example#4448 - Ds\Deque::rotate example
  • Example#4449 - Ds\Deque::set example
  • Example#4450 - Ds\Deque::set example using array syntax
  • Example#4451 - Ds\Deque::shift example
  • Example#4452 - Ds\Deque::slice example
  • Example#4453 - Ds\Deque::sort example
  • Example#4454 - Ds\Deque::sort example using a comparator
  • Example#4455 - Ds\Deque::sorted example
  • Example#4456 - Ds\Deque::sorted example using a comparator
  • Example#4457 - Ds\Deque::sum integer example
  • Example#4458 - Ds\Deque::sum float example
  • Example#4459 - Ds\Deque::toArray example
  • Example#4460 - Ds\Deque::unshift example
  • Example#4461 - Ds\Map::allocate example
  • Example#4462 - Ds\Map::apply example
  • Example#4463 - Ds\Map::capacity example
  • Example#4464 - Ds\Map::clear example
  • Example#4465 - Ds\Map::__construct example
  • Example#4466 - Ds\Map::copy example
  • Example#4467 - Ds\Map::diff example
  • Example#4468 - Ds\Map::filter example using callback function
  • Example#4469 - Ds\Map::filter example without a callback function
  • Example#4470 - Ds\Map::first example
  • Example#4471 - Ds\Map::get example
  • Example#4472 - Ds\Map::get example using array syntax
  • Example#4473 - Ds\Map::hasKey example
  • Example#4474 - Ds\Map::hasValue example
  • Example#4475 - Ds\Map::intersect example
  • Example#4476 - Ds\Map::isEmpty example
  • Example#4477 - Ds\Map::keys example
  • Example#4478 - Ds\Map::ksort example
  • Example#4479 - Ds\Map::ksort example using a comparator
  • Example#4480 - Ds\Map::ksorted example
  • Example#4481 - Ds\Map::ksorted example using a comparator
  • Example#4482 - Ds\Map::last example
  • Example#4483 - Ds\Map::map example
  • Example#4484 - Ds\Map::merge example
  • Example#4485 - Ds\Map::pairs example
  • Example#4486 - Ds\Map::put example
  • Example#4487 - Ds\Map::put example using objects as keys
  • Example#4488 - Ds\Map::putAll example
  • Example#4489 - Ds\Map::reduce with initial value example
  • Example#4490 - Ds\Map::reduce without an initial value example
  • Example#4491 - Ds\Map::remove example
  • Example#4492 - Ds\Map::reverse example
  • Example#4493 - Ds\Map::reversed example
  • Example#4494 - Ds\Map::skip example
  • Example#4495 - Ds\Map::slice example
  • Example#4496 - Ds\Map::sort example
  • Example#4497 - Ds\Map::sort example using a comparator
  • Example#4498 - Ds\Map::sort example
  • Example#4499 - Ds\Map::sort example using a comparator
  • Example#4500 - Ds\Map::sum integer example
  • Example#4501 - Ds\Map::sum float example
  • Example#4502 - Ds\Map::toArray example
  • Example#4503 - Ds\Map::union example
  • Example#4504 - Ds\Map::values example
  • Example#4505 - Ds\Map::xor example
  • Example#4506 - Ds\Pair::clear example
  • Example#4507 - Ds\Pair::copy example
  • Example#4508 - Ds\Pair::isEmpty example
  • Example#4509 - Ds\Pair::toArray example
  • Example#4510 - Ds\Set::add example using integers
  • Example#4511 - Ds\Set::add example using objects
  • Example#4512 - Ds\Set::allocate example
  • Example#4513 - Ds\Set::capacity example
  • Example#4514 - Ds\Set::clear example
  • Example#4515 - Ds\Set::__construct example
  • Example#4516 - Ds\Set::contains example
  • Example#4517 - Ds\Set::copy example
  • Example#4518 - Ds\Set::diff example
  • Example#4519 - Ds\Set::filter example using callback function
  • Example#4520 - Ds\Set::filter example without a callback function
  • Example#4521 - Ds\Set::first example
  • Example#4522 - Ds\Set::get example
  • Example#4523 - Ds\Set::get example using array syntax
  • Example#4524 - Ds\Set::intersect example
  • Example#4525 - Ds\Set::isEmpty example
  • Example#4526 - Ds\Set::join example using a separator string
  • Example#4527 - Ds\Set::join example without a separator string
  • Example#4528 - Ds\Set::last example
  • Example#4529 - Ds\Set::merge example
  • Example#4530 - Ds\Set::reduce with initial value example
  • Example#4531 - Ds\Set::reduce without an initial value example
  • Example#4532 - Ds\Set::remove example
  • Example#4533 - Ds\Set::reverse example
  • Example#4534 - Ds\Set::reversed example
  • Example#4535 - Ds\Set::slice example
  • Example#4536 - Ds\Set::sort example
  • Example#4537 - Ds\Set::sort example using a comparator
  • Example#4538 - Ds\Set::sorted example
  • Example#4539 - Ds\Set::sorted example using a comparator
  • Example#4540 - Ds\Set::sum integer example
  • Example#4541 - Ds\Set::sum float example
  • Example#4542 - Ds\Set::toArray example
  • Example#4543 - Ds\Set::union example
  • Example#4544 - Ds\Set::xor example
  • Example#4545 - Ds\Stack::clear example
  • Example#4546 - Ds\Stack::__construct example
  • Example#4547 - Ds\Stack::copy example
  • Example#4548 - Ds\Stack::isEmpty example
  • Example#4549 - Ds\Stack::peek example
  • Example#4550 - Ds\Stack::pop example
  • Example#4551 - Ds\Stack::push example
  • Example#4552 - Ds\Stack::toArray example
  • Example#4553 - Ds\Queue::allocate example
  • Example#4554 - Ds\Queue::capacity example
  • Example#4555 - Ds\Queue::clear example
  • Example#4556 - Ds\Queue::__construct example
  • Example#4557 - Ds\Queue::copy example
  • Example#4558 - Ds\Queue::isEmpty example
  • Example#4559 - Ds\Queue::peek example
  • Example#4560 - Ds\Queue::pop example
  • Example#4561 - Ds\Queue::push example
  • Example#4562 - Ds\Queue::toArray example
  • Example#4563 - Ds\PriorityQueue::allocate example
  • Example#4564 - Ds\PriorityQueue::capacity example
  • Example#4565 - Ds\PriorityQueue::clear example
  • Example#4566 - Ds\PriorityQueue::__construct example
  • Example#4567 - Ds\PriorityQueue::copy example
  • Example#4568 - Ds\PriorityQueue::isEmpty example
  • Example#4569 - Ds\PriorityQueue::peek example
  • Example#4570 - Ds\PriorityQueue::pop example
  • Example#4571 - Ds\PriorityQueue::push example
  • Example#4572 - Ds\PriorityQueue::toArray example
  • Example#4573 - 使用 PHP cURL 模块获取 example.com 的主页
  • Example#4574 - 初始化新的 cURL 会话，并获取一张网页
  • Example#4575 - 复制一个cURL句柄
  • Example#4576 - curl_errno 例子
  • Example#4577 - curl_error 例子
  • Example#4578 - curl_escape 示例
  • Example#4579 - 获取网页
  • Example#4580 - curl_getinfo example
  • Example#4581 - 初始化新的 cURL 会话并获取一个网页
  • Example#4582 - curl_multi_add_handle example
  • Example#4583 - curl_multi_close example
  • Example#4584 - curl_multi_exec example
  • Example#4585 - 一个curl_multi_info_read范例
  • Example#4586 - curl_multi_init example
  • Example#4587 - curl_multi_strerror 函数的范例：
  • Example#4588 - curl_reset 示例
  • Example#4589 - 初始化新的 cURL 会话并抓取 web 页面
  • Example#4590 - 我们对curl_setopt_array的等价实现
  • Example#4591 - 初始化一个新的cURL会话并获取一个网页
  • Example#4592 - 上传文件 (PHP 5.5.0 后被废弃)
  • Example#4593 - curl_share_setopt 函数范例：
  • Example#4594 - curl_share_init 函数的范例：
  • Example#4595 - curl_share_setopt 函数的范例：
  • Example#4596 - curl_errno 函数的范例：
  • Example#4597 - curl_escape 示例
  • Example#4598 - curl_version 例子
  • Example#4599 - CURLFile::__construct 示例
  • Example#4600 - Simple HTTP client
  • Example#4601 - HTTP client using asynchronous DNS resolver
  • Example#4602 - Echo server
  • Example#4603 - SSL echo server
  • Example#4604 - Signal handler
  • Example#4605 - Use libevent's loop to process requests of `eio' extension
  • Example#4606 - Miscellaneous
  • Example#4607 - Simple HTTP server
  • Example#4608 - Simple HTTPS server
  • Example#4609 - OpenSSL connection
  • Example#4610 - EventHttpConnection::makeRequest example
  • Example#4611 - Connection listener based on a UNIX domain socket
  • Example#4612 - Simple SMTP server
  • Example#4613 - Handling SIGTERM signal
  • Example#4614 - Event::addSignal example
  • Example#4615 - Event::addTimer example
  • Example#4616 - EventBase::getFeatures example
  • Example#4617 - EventBase::getMethod example
  • Example#4618 - EventBuffer::search example
  • Example#4619 - EventBufferEvent::connect example
  • Example#4620 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#4621 - EventBufferEvent::connectHost example
  • Example#4622 - Buffer event's read callback
  • Example#4623 - EventBufferEvent::getOutput example
  • Example#4624 - EventBufferEvent::sslError example
  • Example#4625 - Simple SMTP server
  • Example#4626 - EventConfig::avoidMethod example
  • Example#4627 - EventConfig::__construct example
  • Example#4628 - EventConfig::requireFeatures example
  • Example#4629 - EventHttp::accept example
  • Example#4630 - EventHttp::addServerAlias example
  • Example#4631 - EventHttp::bind example
  • Example#4632 - Simple HTTP server
  • Example#4633 - EventHttp::setCallback example
  • Example#4634 - EventHttp::setDefaultCallback example
  • Example#4635 - EventHttpConnection::makeRequest example
  • Example#4636 - EventHttpConnection::setCloseCallback example
  • Example#4637 - EventHttpRequest::__construct example
  • Example#4638 - EventHttpRequest::sendError example
  • Example#4639 - EventListener::__construct example
  • Example#4640 - EventSslContext::__construct example
  • Example#4641 - FTP 例程
  • Example#4642 - ftp_alloc 函数例程
  • Example#4643 - ftp_cdup 例子
  • Example#4644 - ftp_chdir 例子
  • Example#4645 - ftp_chmod 函数例程
  • Example#4646 - ftp_close 例子
  • Example#4647 - ftp_connect 示例
  • Example#4648 - ftp_delete 例子
  • Example#4649 - ftp_exec 示例
  • Example#4650 - ftp_fget 例子
  • Example#4651 - ftp_fput 例子
  • Example#4652 - ftp_get_option 示例
  • Example#4653 - ftp_get 例子
  • Example#4654 - ftp_login 例子
  • Example#4655 - ftp_mdtm 示例
  • Example#4656 - ftp_mkdir example
  • Example#4657 - ftp_mlsd 示例
  • Example#4658 - ftp_nb_continue 示例
  • Example#4659 - ftp_nb_fget 函数例程
  • Example#4660 - ftp_nb_fput 函数例程
  • Example#4661 - ftp_nb_get 示例
  • Example#4662 - 通过 ftp_nb_get 恢复下载一个文件
  • Example#4663 - 使用 ftp_nb_get 从指定位置恢复下载文件
  • Example#4664 - ftp_nb_put 示例
  • Example#4665 - 使用 ftp_nb_put 来续传文件
  • Example#4666 - ftp_nlist 例子
  • Example#4667 - ftp_pasv 实例
  • Example#4668 - ftp_put 实例
  • Example#4669 - ftp_pwd 例子
  • Example#4670 - 使用 ftp_raw 登录远程 FTP 服务器
  • Example#4671 - ftp_rawlist 示例
  • Example#4672 - ftp_rename 例子
  • Example#4673 - ftp_rmdir 示例
  • Example#4674 - ftp_set_option 例子
  • Example#4675 - 向一个 FTP 服务器发送一条 SITE 命令
  • Example#4676 - ftp_size 示例
  • Example#4677 - ftp_ssl_connect 函数例程
  • Example#4678 - ftp_systype 示例
  • Example#4679 - Basic Gearman client and worker
  • Example#4680 - Basic Gearman client and worker, background
  • Example#4681 - Basic Gearman client and worker, submitting tasks
  • Example#4682 - Adding two job servers
  • Example#4683 - Add two job servers
  • Example#4684 - Basic submission of two tasks
  • Example#4685 - Basic submission of two tasks with passing application context
  • Example#4686 - Two tasks, one background and one not
  • Example#4687 - A high priority task along with two normal tasks
  • Example#4688 - A low priority task along with two normal tasks
  • Example#4689 - Monitor completion of multiple background tasks
  • Example#4690 - Simple job submission with immediate return
  • Example#4691 - Submitting a job and retrieving incremental status
  • Example#4692 - Submit and monitor a background job
  • Example#4693 - Simple job submission with immediate return
  • Example#4694 - Submitting a job and retrieving incremental status
  • Example#4695 - Get the status of a long running job
  • Example#4696 - Monitor the status of a long running background job
  • Example#4697 - Simple worker making use of extra application context data
  • Example#4698 - Add alternate Gearman servers
  • Example#4699 - Add two job servers
  • Example#4700 - GearmanWorker::setId example
  • Example#4701 - A simple worker with a 5 second timeout
  • Example#4702 - Running worker in non-blocking mode
  • Example#4703 - GearmanWorker::work example
  • Example#4704 - Testing support for paged result control
  • Example#4705 - LDAP search example
  • Example#4706 - Bind with ppolicy information
  • Example#4707 - Modify description only if it's not empty
  • Example#4708 - Read some values before deletion
  • Example#4709 - Delete a reference
  • Example#4710 - Use pagination for a search
  • Example#4711 - Complete example with authenticated bind
  • Example#4712 - 使用 LDAP Bind
  • Example#4713 - Using LDAP Bind Anonymously
  • Example#4714 - Complete example of password check
  • Example#4715 - Example of connecting to LDAP server.
  • Example#4716 - Example of connecting securely to LDAP server.
  • Example#4717 - LDAP pagination
  • Example#4718 - LDAP pagination
  • Example#4719 - ldap-count-entries example
  • Example#4720 - Enumerating all LDAP error messages
  • Example#4721 - Generating and catching an error
  • Example#4722 - Searching for an email address
  • Example#4723 - PASSWD extended operation
  • Example#4724 - Whoami extended operation
  • Example#4725 - Show the list of attributes held for a particular directory entry
  • Example#4726 - Check protocol version
  • Example#4727 - List all values of the "mail" attribute for a directory entry
  • Example#4728 - Produce a list of all organizational units of an organization
  • Example#4729 - Add a telephone number to a contact
  • Example#4730 - Rename a user
  • Example#4731 - Add two e-mail addresses to a user
  • Example#4732 - Change a user's password
  • Example#4733 - Change a user's password (Active Directory)
  • Example#4734 - ldap_parse_result example
  • Example#4735 - LDAP search
  • Example#4736 - Set protocol version
  • Example#4737 - Set server controls
  • Example#4738 - LDAP sort
  • Example#4739 - memcache扩展概览示例
  • Example#4740 - 使用memcache的session处理器
  • Example#4741 - Memcache::add示例
  • Example#4742 - Memcache::addServer 示例
  • Example#4743 - Memcache::close示例
  • Example#4744 - Memcache::connect example
  • Example#4745 - Memcache::decrement example
  • Example#4746 - Memcache::delete example
  • Example#4747 - Memcache::flush示例
  • Example#4748 - Memcache::get 示例
  • Example#4749 - Memcache::getExtendedStats 示例
  • Example#4750 - Memcache::getServerStatus 示例
  • Example#4751 - Memcache::getVersion 示例
  • Example#4752 - Memcache::increment示例
  • Example#4753 - Memcache::pconnect示例
  • Example#4754 - Memcache::replace示例
  • Example#4755 - Memcache::set 示例
  • Example#4756 - Memcache::set 示例
  • Example#4757 - Memcache::setCompressThreshold 示例
  • Example#4758 - Memcache::setServerParams 示例
  • Example#4759 - 结果回调示例
  • Example#4760 - 通读回调示例
  • Example#4761 - Memcached::addServer example
  • Example#4762 - Memcached::addServers示例
  • Example#4763 - Memcached::append示例
  • Example#4764 - Memcached::cas 示例
  • Example#4765 - 创建一个Memcached对象
  • Example#4766 - Memcached::decrement 示例
  • Example#4767 - Memcached::delete 示例
  • Example#4768 - Memcached::fetch 示例
  • Example#4769 - Memcached::getDelayed 示例
  • Example#4770 - Memcached::flush 示例
  • Example#4771 - Memcached::get 示例 #1
  • Example#4772 - Memcached::get 示例 #2
  • Example#4773 - Memcached::getDelayed 示例
  • Example#4774 - Memcached::getMulti 的 Memcached v3 示例
  • Example#4775 - Memcached::getMulti 的 Memcached v1 和 v2 示例
  • Example#4776 - Memcached::GET_PRESERVE_ORDER 的 Memcached v3 示例
  • Example#4777 - Memcached::GET_PRESERVE_ORDER 的 Memcached v1 和 v2 示例
  • Example#4778 - 获取Memcached选项
  • Example#4779 - Memcached::getResultCode 示例
  • Example#4780 - Memcached::getResultMessage 示例
  • Example#4781 - Memcached::getServerByKey 示例
  • Example#4782 - Memcached::getServerList 示例
  • Example#4783 - Memcached::getStats 示例
  • Example#4784 - Memcached::getVersion 示例
  • Example#4785 - Memcached::increment 示例
  • Example#4786 - Memcached::prepend 示例
  • Example#4787 - Memcached::set 示例
  • Example#4788 - Memcached::setByKey 示例
  • Example#4789 - Memcached::setMulti 示例
  • Example#4790 - 设置一个memcached选项值
  • Example#4791 - Setting Memcached options
  • Example#4792 - mqseries_back example
  • Example#4793 - mqseries_begin example
  • Example#4794 - mqseries_close example
  • Example#4795 - mqseries_cmit example
  • Example#4796 - mqseries_conn example
  • Example#4797 - mqseries_connx example
  • Example#4798 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#4799 - mqseries_disc example
  • Example#4800 - mqseries_get example
  • Example#4801 - mqseries_inq example
  • Example#4802 - mqseries_open example
  • Example#4803 - mqseries_put example
  • Example#4804 - mqseries_strerror example
  • Example#4805 - 使用 dns_get_record函数
  • Example#4806 - 使用dns_get_record配合DNS_ANY的例子
  • Example#4807 - fsockopen的例子
  • Example#4808 - 使用UDP连接
  • Example#4809 - 一个使用 gethostbyaddr 的简单例子
  • Example#4810 - 简单的 gethostbyname 例子
  • Example#4811 - gethostbynamel 例子
  • Example#4812 - 简单的 gethostname 例子
  • Example#4813 - getprotobyname example
  • Example#4814 - getservbyname 例子
  • Example#4815 - header_register_callback 例子
  • Example#4816 - 取消指定的头
  • Example#4817 - 取消之前全部指定的头
  • Example#4818 - 下载对话框
  • Example#4819 - 缓存指令
  • Example#4820 - 使用 headers_list 的例子
  • Example#4821 - 使用 headers_sent 的例子
  • Example#4822 - Web 服务器环境内使用 http_response_code
  • Example#4823 - 在 CLI 环境内使用 http_response_code
  • Example#4824 - inet_ntop Example
  • Example#4825 - inet_pton Example
  • Example#4826 - ip2long 例子
  • Example#4827 - 显示IP地址
  • Example#4828 - setcookie 发送例子
  • Example#4829 - setcookie 删除例子
  • Example#4830 - setcookie 和数组
  • Example#4831 - Using syslog
  • Example#4832 - Procedural usage of rrd
  • Example#4833 - OO usage of rrd
  • Example#4834 - RRDGraph::setOptions example
  • Example#4835 - Set multiple color options
  • Example#4836 - RRDUpdater::update examples
  • Example#4837 - Fetch instrumented calls
  • Example#4838 - Fetch the list of functions scoutapm will instrument
  • Example#4839 - snmp_get_quick_print 示例
  • Example#4840 - Using snmp_get_valueretrieval
  • Example#4841 - Using snmp_read_mib
  • Example#4842 - Using snmp_set_enum_print
  • Example#4843 - Using snmprealwalk
  • Example#4844 - Using snmp_set_valueretrieval
  • Example#4845 - Using snmp2_get
  • Example#4846 - Using snmp2_get_next
  • Example#4847 - Using snmp2_real_walk
  • Example#4848 - Using snmp2_set
  • Example#4849 - Using snmp2_set for setting BITS SNMP object id
  • Example#4850 - snmp2_walk Example
  • Example#4851 - Using snmp3_get
  • Example#4852 - Using snmp3_getnext
  • Example#4853 - Using snmp3_real_walk
  • Example#4854 - Using snmp3_set
  • Example#4855 - Using snmp3_set for setting BITS SNMP object id
  • Example#4856 - snmp3_walk Example
  • Example#4857 - Using snmpgetnext
  • Example#4858 - Using snmprealwalk
  • Example#4859 - SNMP::close example
  • Example#4860 - Fetching sysLocation
  • Example#4861 - Single SNMP object
  • Example#4862 - Multiple SNMP objects
  • Example#4863 - SNMP::getErrno example
  • Example#4864 - SNMP::getError example
  • Example#4865 - Single SNMP object
  • Example#4866 - Miltiple SNMP objects
  • Example#4867 - Set single SNMP object id
  • Example#4868 - Set multiple values using single SNMP::set call
  • Example#4869 - Using SNMP::set for setting BITS SNMP object id
  • Example#4870 - SNMP::setSecurity example
  • Example#4871 - SNMP::walk example
  • Example#4872 - suffixAsKey example
  • Example#4873 - Socket举例：简单的TCP/IP服务器
  • Example#4874 - Socket举例：简单的TCP/IP客户端
  • Example#4875 - 使用 socket_bind 来设置套接字资源地址
  • Example#4876 - socket_create_pair example
  • Example#4877 - socket_create_pair IPC example
  • Example#4878 - socket_get_option example
  • Example#4879 - socket_import_stream example
  • Example#4880 - socket_last_error example
  • Example#4881 - socket_recv 范例
  • Example#4882 - socket_recvfrom example
  • Example#4883 - Using null with socket_select
  • Example#4884 - Understanding socket_select's result
  • Example#4885 - socket_select example
  • Example#4886 - socket_sendto Example
  • Example#4887 - socket_set_block example
  • Example#4888 - socket_set_nonblock example
  • Example#4889 - socket_set_option example
  • Example#4890 - socket_strerror example
  • Example#4891 - Authenticating with a ssh agent
  • Example#4892 - Authentication using a public hostkey
  • Example#4893 - Retrieving a list of authentication methods
  • Example#4894 - Authenticating with a password
  • Example#4895 - Authentication using a public key
  • Example#4896 - ssh2_connect example
  • Example#4897 - Executing a command
  • Example#4898 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4899 - Checking the fingerprint against a known value
  • Example#4900 - Determining what methods were negotiated
  • Example#4901 - Adding a publickey with ssh2_publickey_add
  • Example#4902 - Listing authorized keys with ssh2_publickey_list
  • Example#4903 - Downloading a file via SCP
  • Example#4904 - Uploading a file via SCP
  • Example#4905 - Changing the mode of a file on a remote server
  • Example#4906 - Stating a symbolic link via SFTP
  • Example#4907 - Creating a directory on a remote server
  • Example#4908 - Reading a symbolic link
  • Example#4909 - Resolving a pathname
  • Example#4910 - Renaming a file via sftp
  • Example#4911 - Removing a directory on a remote server
  • Example#4912 - Stating a file via SFTP
  • Example#4913 - Creating a symbolic link
  • Example#4914 - Deleting a file
  • Example#4915 - Opening a file via SFTP
  • Example#4916 - Requesting an interactive shell
  • Example#4917 - Opening a tunnel to an arbitrary host
  • Example#4918 - 面向对象风格
  • Example#4919 - 过程化风格
  • Example#4920 - stomp_connect_error example
  • Example#4921 - stomp_version example
  • Example#4922 - 面向对象风格
  • Example#4923 - 过程化风格
  • Example#4924 - 面向对象风格
  • Example#4925 - 过程化风格
  • Example#4926 - 面向对象风格
  • Example#4927 - 过程化风格
  • Example#4928 - 面向对象风格
  • Example#4929 - 过程化风格
  • Example#4930 - 面向对象风格
  • Example#4931 - 过程化风格
  • Example#4932 - 面向对象风格
  • Example#4933 - 过程化风格
  • Example#4934 - 面向对象风格
  • Example#4935 - 过程化风格
  • Example#4936 - 面向对象风格
  • Example#4937 - 过程化风格
  • Example#4938 - 面向对象风格
  • Example#4939 - 过程化风格
  • Example#4940 - Train from array
  • Example#4941 - Train from a file
  • Example#4942 - svn_add 例子
  • Example#4943 - Default authentication example
  • Example#4944 - svn_blame example
  • Example#4945 - Basic example
  • Example#4946 - Basic example
  • Example#4947 - Basic example
  • Example#4948 - Basic example
  • Example#4949 - 基本示例
  • Example#4950 - Basic example
  • Example#4951 - Diffing two revisions of a repository path
  • Example#4952 - Portably diffing two local files
  • Example#4953 - svn_export example
  • Example#4954 - Basic example
  • Example#4955 - svn_log example
  • Example#4956 - svn_ls example
  • Example#4957 - Basic example
  • Example#4958 - Basic example
  • Example#4959 - Deny all connections from localhost
  • Example#4960 - Ban an URL
  • Example#4961 - Get statistic snapshot
  • Example#4962 - Read varnish shared memory log
  • Example#4963 - VarnishAdmin::__construct example
  • Example#4964 - Parallel searching using Yaz
  • Example#4965 - CCL configuration
  • Example#4966 - CCL Parsing
  • Example#4967 - Record Update
  • Example#4968 - Array for GRS-1 record
  • Example#4969 - Working with MARCXML
  • Example#4970 - PHP function that scans titles
  • Example#4971 - Query Examples
  • Example#4972 - Sort Criterias
  • Example#4973 - A ZMQContext example
  • Example#4974 - A ZMQContext example
  • Example#4975 - A ZMQContext example
  • Example#4976 - A ZMQSocket example
  • Example#4977 - A send/recv example
  • Example#4978 - A ZMQPoll example
  • Example#4979 - zookeeper_dispatch example #1
  • Example#4980 - zookeeper_dispatch example #2
  • Example#4981 - Zookeeper::addAuth example
  • Example#4982 - Zookeeper::create example
  • Example#4983 - Zookeeper::delete example
  • Example#4984 - Zookeeper::exists example
  • Example#4985 - Zookeeper::get example
  • Example#4986 - Zookeeper::get stat example
  • Example#4987 - Zookeeper::getAcl example
  • Example#4988 - Zookeeper::getChildren example
  • Example#4989 - Zookeeper::set example
  • Example#4990 - Zookeeper::setAcl example
  • Example#4991 - Zookeeper::setDebugLevel example
  • Example#4992 - ZookeeperConfig::add example
  • Example#4993 - ZookeeperConfig::get example
  • Example#4994 - ZookeeperConfig::remove example
  • Example#4995 - ZookeeperConfig::set example
  • Example#4996 - solr_get_version example
  • Example#4997 - Contents of the BootStrap file
  • Example#4998 - Adding a document to the index
  • Example#4999 - Merging one document into another document
  • Example#5000 - Searching for documents - SolrObject responses
  • Example#5001 - Searching for documents - SolrDocument responses
  • Example#5002 - Simple TermsComponent example - basic
  • Example#5003 - Simple TermsComponent example - using a prefix
  • Example#5004 - Simple TermsComponent example - specifying a minimum frequency
  • Example#5005 - Simple Facet Example
  • Example#5006 - Simple Facet Example - with optional field override for mincount
  • Example#5007 - Facet Date Example
  • Example#5008 - Connecting to SSL-Enabled Server
  • Example#5009 - Collapsing a SolrQuery
  • Example#5010 - Solr Real Time Get (RTG) example SolrClient::getById
  • Example#5011 - SolrInputDocument::addChildDocument example
  • Example#5012 - SolrInputDocument::addChildDocuments example
  • Example#5013 - SolrDocument::toArray example
  • Example#5014 - SolrObject::__construct example
  • Example#5015 - SolrObject::offsetUnset example
  • Example#5016 - SolrClient::addDocument example
  • Example#5017 - SolrClient::addDocument example 2
  • Example#5018 - SolrClient::addDocuments example
  • Example#5019 - SolrClient::__construct example
  • Example#5020 - SolrQuery::deleteByQuery example
  • Example#5021 - SolrClient::getById example
  • Example#5022 - SolrClient::getByIds example
  • Example#5023 - SolrClient::ping example
  • Example#5024 - SolrClient::query example
  • Example#5025 - SolrClient::request example
  • Example#5026 - SolrClient::setResponseWriter example
  • Example#5027 - SolrParams::setParam example
  • Example#5028 - SolrQuery::addFacetField example
  • Example#5029 - SolrQuery::addFacetField example
  • Example#5030 - SolrQuery::addFilterQuery example
  • Example#5031 - SolrQuery::addGroupSortField example
  • Example#5032 - SolrQuery::collapse example
  • Example#5033 - SolrQuery::setExpand example
  • Example#5034 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#5035 - SolrDisMaxQuery::addBoostQuery example
  • Example#5036 - SolrDisMaxQuery::addPhraseField example
  • Example#5037 - SolrDisMaxQuery::addQueryField example
  • Example#5038 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#5039 - SolrDisMaxQuery::addUserField example
  • Example#5040 - SolrDisMaxQuery::__construct example
  • Example#5041 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#5042 - SolrDisMaxQuery::removeBoostQuery example
  • Example#5043 - SolrDisMaxQuery::removePhraseField example
  • Example#5044 - SolrDisMaxQuery::removeQueryField example
  • Example#5045 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#5046 - SolrDisMaxQuery::removeUserField example
  • Example#5047 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#5048 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#5049 - SolrDisMaxQuery::setBoostFunction example
  • Example#5050 - SolrDisMaxQuery::setBoostQuery example
  • Example#5051 - SolrDisMaxQuery::setMinimumMatch example
  • Example#5052 - SolrDisMaxQuery::setPhraseFields example
  • Example#5053 - SolrDisMaxQuery::setPhraseSlop example
  • Example#5054 - SolrDisMaxQuery::setQueryAlt example
  • Example#5055 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#5056 - SolrDisMaxQuery::setTieBreaker example
  • Example#5057 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#5058 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#5059 - SolrDisMaxQuery::setUserFields example
  • Example#5060 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#5061 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#5062 - SolrCollapseFunction::__construct example
  • Example#5063 - SolrCollapseFunction::setHint example
  • Example#5064 - SolrCollapseFunction::setMax example
  • Example#5065 - 基本使用范例
  • Example#5066 - 用 .htaccess 禁用一个目录的 PHP 解析
  • Example#5067 - apache_get_modules 示例
  • Example#5068 - apache_get_version example
  • Example#5069 - apache_getenv example
  • Example#5070 - apache_lookup_uri 例子
  • Example#5071 - Passing information between PHP and Perl
  • Example#5072 - Logging values in access.log
  • Example#5073 - apache_request_headers 示例
  • Example#5074 - apache_response_headers 示例
  • Example#5075 - 使用 apache_setenv 设置一个 Apache 环境变量
  • Example#5076 - getallheaders 示例
  • Example#5077 - 在 $_SESSION 中注册变量。
  • Example#5078 - 从 $_SESSION 中反注册变量。
  • Example#5079 - 某单一用户的点击数
  • Example#5080 - 样例信息
  • Example#5081 - session_cache_expire 示例
  • Example#5082 - session_cache_limiter 示例
  • Example#5083 - session_create_id example with session_regenerate_id
  • Example#5084 - 销毁会话数据以及 $_SESSION
  • Example#5085 - session_gc example for task managers like cron
  • Example#5086 - session_gc example for user accessible script
  • Example#5087 - session_name 示例
  • Example#5088 - A session_regenerate_id 示例
  • Example#5089 - Avoiding lost session by session_regenerate_id
  • Example#5090 - 自定义会话管理器： 完整代码请参见 SessionHandlerInterface。
  • Example#5091 - 使用对象自定义会话保存管理器
  • Example#5092 - page1.php
  • Example#5093 - page2.php
  • Example#5094 - 覆盖 Cookie 超时时间设定
  • Example#5095 - 读取会话之后立即关闭会话存储文件
  • Example#5096 - Using SessionHandler to add encryption to internal PHP save handlers.
  • Example#5097 - Example using SessionHandlerInterface
  • Example#5098 - Tokenize comma separated integer list
  • Example#5099 - Tokenize assign statement
  • Example#5100 - Simple calculator
  • Example#5101 - Parse words out from a sentence
  • Example#5102 - 合法模式示例
  • Example#5103 - 非法模式示例
  • Example#5104 - 比较preg_filter 和preg_replace的示例
  • Example#5105 - preg_grep 示例
  • Example#5106 - preg_last_error_msg example
  • Example#5107 - preg_last_error 示例
  • Example#5108 - 查找所有文本中的电话号码。
  • Example#5109 - 查找匹配的HTML标签（贪婪）
  • Example#5110 - 使用子命名组
  • Example#5111 - 查找文本字符串"php"
  • Example#5112 - 查找单词"word"
  • Example#5113 - 获取URL中的域名
  • Example#5114 - 使用命名子组
  • Example#5115 - preg_quote示例
  • Example#5116 - 将文本中的单词替换为斜体
  • Example#5117 - preg_replace_callback_array example
  • Example#5118 - preg_replace_callback 和 匿名函数
  • Example#5119 - preg_replace_callback示例
  • Example#5120 - preg_replace_callback 使用递归构造处理 BB 码的封装
  • Example#5121 - 使用后向引用紧跟数值原文
  • Example#5122 - preg_replace 中使用基于索引的数组
  • Example#5123 - 替换一些值
  • Example#5124 - 剥离空白字符
  • Example#5125 - 使用参数 count
  • Example#5126 - preg_split示例：获取搜索字符串的部分
  • Example#5127 - 将一个字符串分隔为组成它的字符
  • Example#5128 - 分隔一个字符串并获取每部分的偏移量
  • Example#5129 - 正则表达式例子
  • Example#5130 - ereg_replace 例子
  • Example#5131 - ereg_replace 例子
  • Example#5132 - 将 URL 替换为超连接
  • Example#5133 - ereg 例子
  • Example#5134 - 高亮搜索结果
  • Example#5135 - eregi 例子
  • Example#5136 - split 例子
  • Example#5137 - split 例子
  • Example#5138 - spliti 例子
  • Example#5139 - sql_regcase 例子
  • Example#5140 - addcslashes 例子
  • Example#5141 - 一个 addslashes 例子
  • Example#5142 - chr 例子
  • Example#5143 - chunk_split 例子
  • Example#5144 - convert_uudecode 例子
  • Example#5145 - convert_uuencode 例子
  • Example#5146 - count_chars 示例
  • Example#5147 - 显示一个 crc32 校验码
  • Example#5148 - crypt 范例
  • Example#5149 - 利用 htpasswd 进行 crypt 加密
  • Example#5150 - 以不同散列类型使用 crypt
  • Example#5151 - echo 例子
  • Example#5152 - explode 例子
  • Example#5153 - explode return examples
  • Example#5154 - limit 参数的例子
  • Example#5155 - fprintf: zero-padded integers
  • Example#5156 - fprintf: formatting currency
  • Example#5157 - Translation Table Example
  • Example#5158 - hex2bin 例子
  • Example#5159 - Decoding HTML entities
  • Example#5160 - htmlentities 例子
  • Example#5161 - ENT_IGNORE 用法示例
  • Example#5162 - 一个 htmlspecialchars_decode 的例子
  • Example#5163 - htmlspecialchars 例子
  • Example#5164 - implode 例子
  • Example#5165 - lcfirst 例子：
  • Example#5166 - levenshtein 例子：
  • Example#5167 - localeconv example
  • Example#5168 - ltrim的使用范例
  • Example#5169 - md5_file 使用范例
  • Example#5170 - md5 范例
  • Example#5171 - metaphone basic example
  • Example#5172 - Using the max_phonemes parameter
  • Example#5173 - Using the max_phonemes parameter
  • Example#5174 - money_format 例子
  • Example#5175 - nl2br 使用范例
  • Example#5176 - 使用 is_xhtml 生成合法的 HTML 标记
  • Example#5177 - 各种换行分隔符
  • Example#5178 - number_format Example
  • Example#5179 - ord 范例
  • Example#5180 - 检查 UTF-8 字符串的每一个字节
  • Example#5181 - parse_str 的使用
  • Example#5182 - parse_str 名称改写
  • Example#5183 - print 范例
  • Example#5184 - rtrim 使用范例
  • Example#5185 - setlocale Examples
  • Example#5186 - setlocale Examples for Windows
  • Example#5187 - sha1_file 范例
  • Example#5188 - sha1 范例
  • Example#5189 - Soundex Examples
  • Example#5190 - Argument swapping
  • Example#5191 - Specifying padding character
  • Example#5192 - Position specifier with other specifiers
  • Example#5193 - sprintf: zero-padded integers
  • Example#5194 - sprintf: formatting currency
  • Example#5195 - sprintf: scientific notation
  • Example#5196 - sscanf 例子
  • Example#5197 - sscanf - using optional parameters
  • Example#5198 - Using the empty string ''
  • Example#5199 - Showing case-sensitivity
  • Example#5200 - Using the empty string ''
  • Example#5201 - Showing case-sensitivity
  • Example#5202 - str_ireplace 范例
  • Example#5203 - str_pad 范例
  • Example#5204 - str_repeat 范例
  • Example#5205 - str_replace 基本范例
  • Example#5206 - 可能的 str_replace 替换范例
  • Example#5207 - str_rot13 范例
  • Example#5208 - str_shuffle 范例
  • Example#5209 - str_split 使用范例
  • Example#5210 - Using the empty string ''
  • Example#5211 - Showing case-sensitivity
  • Example#5212 - str_word_count 范例
  • Example#5213 - strcasecmp 范例
  • Example#5214 - strcmp 例子
  • Example#5215 - strcspn example
  • Example#5216 - strip_tags 范例
  • Example#5217 - stripos 范例
  • Example#5218 - stripslashes 范例
  • Example#5219 - 对数组使用 stripslashes
  • Example#5220 - stristr 范例
  • Example#5221 - 测试字符串的存在与否
  • Example#5222 - 使用非字符串 needle
  • Example#5223 - strlen 范例
  • Example#5224 - strpbrk 范例
  • Example#5225 - 使用 ===
  • Example#5226 - 使用 !==
  • Example#5227 - 使用位置偏移量
  • Example#5228 - strrchr 范例
  • Example#5229 - 使用 strrev 反转字符串
  • Example#5230 - strripos 简单范例
  • Example#5231 - 检查字串是否存在
  • Example#5232 - 使用偏移位置进行查找
  • Example#5233 - strspn 范例
  • Example#5234 - strstr 范例
  • Example#5235 - strtok 示例
  • Example#5236 - 当 strtok 找不到标记时的反应
  • Example#5237 - strtolower 范例
  • Example#5238 - strtoupper 范例
  • Example#5239 - strtr 范例
  • Example#5240 - 使用两个参数的 strtr 范例
  • Example#5241 - strtr behavior comparison
  • Example#5242 - substr_compare 范例
  • Example#5243 - substr_count 范例
  • Example#5244 - substr_replace 范例
  • Example#5245 - Using substr_replace to replace multiple strings at once
  • Example#5246 - 使用负数 start
  • Example#5247 - 使用负数 length
  • Example#5248 - substr 基本用法
  • Example#5249 - substr casting behaviour
  • Example#5250 -
  • Example#5251 - trim 使用范例
  • Example#5252 - 使用 trim 清理数组值
  • Example#5253 - ucfirst 范例
  • Example#5254 - ucwords 范例
  • Example#5255 - ucwords 自定义 delimiters 的例子
  • Example#5256 - vfprintf: 前导 0 的整数
  • Example#5257 - vprintf: 前导 0 的整数
  • Example#5258 - vsprintf: 前导 0 的整数
  • Example#5259 - wordwrap 范例
  • Example#5260 - wordwrap 范例
  • Example#5261 - wordwrap 例子
  • Example#5262 - array_change_key_case例一
  • Example#5263 - array_chunk 例子
  • Example#5264 - 从结果集中取出first names列
  • Example#5265 - 从结果集中总取出last names列，用相应的id作为键值
  • Example#5266 - username 列是从对象获取 public 的 "username" 属性
  • Example#5267 - 获取 username 列，从对象通过魔术方法 __get 获取 private 的 "username" 属性。
  • Example#5268 - 一个 array_combine 简单的例子
  • Example#5269 - array_count_values 例子
  • Example#5270 - array_diff_assoc 例子
  • Example#5271 - array_diff_assoc example
  • Example#5272 - array_diff_key 例
  • Example#5273 - array_diff_uassoc 例子
  • Example#5274 - array_diff_ukey 例子
  • Example#5275 - array_diff 例子
  • Example#5276 - array_diff example with non-matching types
  • Example#5277 - array_fill_keys 范例
  • Example#5278 - array_fill 例子
  • Example#5279 - array_filter 示例
  • Example#5280 - array_filter 不使用 callback 参数时
  • Example#5281 - array_filter 不使用 mode 参数时
  • Example#5282 - array_flip 例子
  • Example#5283 - array_flip 例子 : 冲突
  • Example#5284 - array_intersect_assoc 例子
  • Example#5285 - array_intersect_key 例子
  • Example#5286 - array_intersect_uassoc 例子
  • Example#5287 - array_intersect_ukey 例子
  • Example#5288 - array_intersect 例子
  • Example#5289 - array_key_exists 例子
  • Example#5290 - array_key_exists 与 isset 的对比
  • Example#5291 - array_key_first 基本用法
  • Example#5292 - array_keys 例子
  • Example#5293 - array_map 例子
  • Example#5294 - array_map 使用匿名函数 (PHP 5.3.0 起)
  • Example#5295 - array_map：使用更多的数组
  • Example#5296 - 多个数组的合并操作
  • Example#5297 - 仅有 array1 时，callback 设置为 null
  • Example#5298 - array_map 键（key）是 string
  • Example#5299 - array_merge_recursive 例子
  • Example#5300 - array_merge 示例
  • Example#5301 - Simple array_merge 示例
  • Example#5302 - array_merge 合并非数组的类型
  • Example#5303 - 多个数组排序
  • Example#5304 - 排序多维数组
  • Example#5305 - 对数据库结果进行排序
  • Example#5306 - 不区分大小写字母排序
  • Example#5307 - array_pad 例子
  • Example#5308 - array_pop 例子
  • Example#5309 - array_product 例子
  • Example#5310 - array_push 例子
  • Example#5311 - array_rand 例子
  • Example#5312 - array_reduce 例子
  • Example#5313 - array_replace_recursive 范例
  • Example#5314 - array_replace_recursive 及其递归表现
  • Example#5315 - array_replace 范例
  • Example#5316 - array_reverse 例子
  • Example#5317 - array_search 例子
  • Example#5318 - array_shift 例子
  • Example#5319 - array_slice 例子
  • Example#5320 - array_slice 于索引从 1 开始的 array
  • Example#5321 - array_slice 与混合类型键的 array
  • Example#5322 - array_splice 例子
  • Example#5323 - 几个以不同表达式实现相同效果的 array_splice 例子
  • Example#5324 - array_sum 例子
  • Example#5325 - array_udiff_assoc 例子
  • Example#5326 - array_udiff_uassoc 例子
  • Example#5327 - array_udiff 使用 stdClass 对象的例子
  • Example#5328 - array_udiff 使用 DateTime 对象的例子
  • Example#5329 - array_uintersect_assoc 例子
  • Example#5330 - array_uintersect_uassoc 例子
  • Example#5331 - array_uintersect 例子
  • Example#5332 - array_unique 例子
  • Example#5333 - array_unique 和类型
  • Example#5334 - array_unshift 例子
  • Example#5335 - array_values 例子
  • Example#5336 - array_walk_recursive 例子
  • Example#5337 - array_walk 例子
  • Example#5338 - array 例子
  • Example#5339 - array 的自动索引
  • Example#5340 - 从 1 开始索引的 array
  • Example#5341 - 访问双引号内的数组
  • Example#5342 - arsort 例子
  • Example#5343 - asort 例子
  • Example#5344 - compact 例子
  • Example#5345 - count 例子
  • Example#5346 - 递归 count 例子
  • Example#5347 - current 函数使用示例
  • Example#5348 - each 例子
  • Example#5349 - 用 each 遍历数组
  • Example#5350 - end 例子
  • Example#5351 - extract 例子
  • Example#5352 - in_array 例子
  • Example#5353 - in_array 严格类型检查例子
  • Example#5354 - in_array 中用数组作为 needle
  • Example#5355 - key 例子
  • Example#5356 - krsort 例子
  • Example#5357 - ksort 例子
  • Example#5358 - list 例子
  • Example#5359 - list 用法的一个例子
  • Example#5360 - 使用嵌套的 list
  • Example#5361 - 在 list 中使用数组索引
  • Example#5362 - list 和索引顺序定义
  • Example#5363 - 带键的 list
  • Example#5364 - natcasesort 例子
  • Example#5365 - natsort 基本用法的操作示例
  • Example#5366 - natsort examples demonstrating potential gotchas
  • Example#5367 - next 及相关函数的用法示例
  • Example#5368 - prev 及相关函数用法示例
  • Example#5369 - range 例子
  • Example#5370 - reset 例子
  • Example#5371 - rsort 例
  • Example#5372 - shuffle 例子
  • Example#5373 - sort 例子
  • Example#5374 - 使用 sort 不区分大小写自然排序的例子
  • Example#5375 - uasort 的基本例子
  • Example#5376 - uksort 例子
  • Example#5377 - usort 例子
  • Example#5378 - 使用多维数组的 usort 例子
  • Example#5379 - usort example using a member function of an object
  • Example#5380 - usort example using a closure to sort a multi-dimensional array
  • Example#5381 - classes.inc
  • Example#5382 - test_script.php
  • Example#5383 - class_alias 例子
  • Example#5384 - class_exists 例子
  • Example#5385 - autoload parameter 例子
  • Example#5386 - get_called_class 的使用
  • Example#5387 - get_class_methods 示例
  • Example#5388 - get_class_vars example
  • Example#5389 - get_class_vars and scoping behaviour
  • Example#5390 - 使用 get_class
  • Example#5391 - 超类中使用 get_class
  • Example#5392 - 命名空间中的类使用 get_class
  • Example#5393 - get_declared_classes 例子
  • Example#5394 - get_declared_interfaces 例子
  • Example#5395 - 使用 get_object_vars
  • Example#5396 - Use of get_object_vars
  • Example#5397 - 使用 get_parent_class
  • Example#5398 - Using get_parent_class
  • Example#5399 - interface_exists 例子
  • Example#5400 - is_a 例子
  • Example#5401 - 在 PHP 5 中使用 instanceof 运算符
  • Example#5402 - is_subclass_of 例子
  • Example#5403 - is_subclass_of example
  • Example#5404 - method_exists 例子
  • Example#5405 - Static method_exists 例子
  • Example#5406 - A property_exists example
  • Example#5407 - classkit_import example
  • Example#5408 - classkit_method_add example
  • Example#5409 - classkit_method_copy example
  • Example#5410 - classkit_method_redefine example
  • Example#5411 - classkit_method_remove example
  • Example#5412 - classkit_method_rename example
  • Example#5413 - A ctype_alnum 示例 (使用默认的区域设置)
  • Example#5414 - 一个 ctype_alpha 例子（使用默认的语言环境）
  • Example#5415 - 一个 ctype_cntrl 例子
  • Example#5416 - 一个 ctype_digit 例子
  • Example#5417 - 一个通过 ctype_digit 来比对字符和整数的例子。
  • Example#5418 - 一个 ctype_graph 例子
  • Example#5419 - 一个 ctype_lower 例子 (使用默认的语言环境)
  • Example#5420 - 一个 ctype_print 例子
  • Example#5421 - 一个 ctype_punct 的例子
  • Example#5422 - 一个 ctype_space 例子
  • Example#5423 - 一个 ctype_upper 例子 （使用当前默认语言环境）
  • Example#5424 - 一个 ctype_xdigit 的例子
  • Example#5425 - Configuring the default filter to act like htmlspecialchars
  • Example#5426 - Configuring the default filter to act like htmlspecialchars
  • Example#5427 - Validating email addresses with filter_var
  • Example#5428 - Validating IP addresses with filter_var
  • Example#5429 - Passing options to filter_var
  • Example#5430 - Sanitizing and validating email addresses
  • Example#5431 - Configuring a default filter
  • Example#5432 - 一个 filter_input_array 的例子
  • Example#5433 - 一个 filter_input 的例子
  • Example#5434 - 一个 filter_list 的例子
  • Example#5435 - 一个 filter_var_array 的例子
  • Example#5436 - 一个 filter_var 的示例
  • Example#5437 - call_user_func_array例子
  • Example#5438 - call_user_func_array使用命名空间的情况
  • Example#5439 - 把完整的函数作为回调传入call_user_func_array
  • Example#5440 - 传引用
  • Example#5441 - call_user_func 的参考例子
  • Example#5442 - call_user_func 的例子
  • Example#5443 - call_user_func 命名空间的使用
  • Example#5444 - 用call_user_func来调用一个类里面的方法
  • Example#5445 - 把完整的函数作为回调传入call_user_func
  • Example#5446 - Creating an anonymous function with create_function
  • Example#5447 - Making a general processing function with create_function
  • Example#5448 - Using anonymous functions as callback functions
  • Example#5449 - forward_static_call_array example
  • Example#5450 - forward_static_call example
  • Example#5451 - func_get_arg 例子
  • Example#5452 - func_get_arg PHP 5.3 前后对比的例子
  • Example#5453 - func_get_arg example of byref and byval arguments
  • Example#5454 - func_get_args 例子
  • Example#5455 - PHP 5.3 前后使用 func_get_args 在的对比
  • Example#5456 - func_get_args example of byref and byval arguments
  • Example#5457 - func_num_args example
  • Example#5458 - func_num_args example before and after PHP 5.3
  • Example#5459 - function_exists 的例子
  • Example#5460 - get_defined_functions 例子
  • Example#5461 - register_shutdown_function 例子
  • Example#5462 - register_tick_function example
  • Example#5463 - Quickhash Example
  • Example#5464 - Quickhash ArrayAccess Example
  • Example#5465 - Quickhash Iterator Example
  • Example#5466 - Quickhash String Values Example
  • Example#5467 - QuickHashIntSet::add example
  • Example#5468 - QuickHashIntSet::__construct example
  • Example#5469 - QuickHashIntSet::delete example
  • Example#5470 - QuickHashIntSet::exists example
  • Example#5471 - QuickHashIntSet::getSize example
  • Example#5472 - QuickHashIntSet::loadFromFile example
  • Example#5473 - QuickHashIntSet::loadFromString example
  • Example#5474 - QuickHashIntSet::saveToFile example
  • Example#5475 - QuickHashIntSet::saveToString example
  • Example#5476 - QuickHashIntHash::add example
  • Example#5477 - QuickHashIntHash::__construct example
  • Example#5478 - QuickHashIntHash::delete example
  • Example#5479 - QuickHashIntHash::exists example
  • Example#5480 - QuickHashIntHash::get example
  • Example#5481 - QuickHashIntHash::getSize example
  • Example#5482 - QuickHash IntHash file format
  • Example#5483 - QuickHash IntHash file format
  • Example#5484 - QuickHashIntHash::loadFromFile example
  • Example#5485 - QuickHashIntHash::loadFromString example
  • Example#5486 - QuickHashIntHash::saveToFile example
  • Example#5487 - QuickHashIntHash::saveToString example
  • Example#5488 - QuickHashIntHash::set example
  • Example#5489 - QuickHashIntHash::update example
  • Example#5490 - QuickHashStringIntHash::add example
  • Example#5491 - QuickHashStringIntHash::__construct example
  • Example#5492 - QuickHashStringIntHash::delete example
  • Example#5493 - QuickHashStringIntHash::get example
  • Example#5494 - QuickHashStringIntHash::getSize example
  • Example#5495 - QuickHash StringIntHash file format
  • Example#5496 - QuickHash IntHash file format
  • Example#5497 - QuickHashStringIntHash::loadFromFile example
  • Example#5498 - QuickHashStringIntHash::loadFromString example
  • Example#5499 - QuickHashStringIntHash::saveToFile example
  • Example#5500 - QuickHashStringIntHash::saveToString example
  • Example#5501 - QuickHashStringIntHash::set example
  • Example#5502 - QuickHashStringIntHash::update example
  • Example#5503 - QuickHashIntStringHash::add example
  • Example#5504 - QuickHashIntStringHash::__construct example
  • Example#5505 - QuickHashIntStringHash::delete example
  • Example#5506 - QuickHashIntStringHash::get example
  • Example#5507 - QuickHashIntStringHash::getSize example
  • Example#5508 - QuickHash IntString file format
  • Example#5509 - QuickHash IntString file format
  • Example#5510 - QuickHashIntStringHash::loadFromFile example
  • Example#5511 - QuickHashIntStringHash::loadFromString example
  • Example#5512 - QuickHashIntStringHash::saveToFile example
  • Example#5513 - QuickHashIntStringHash::saveToString example
  • Example#5514 - QuickHashIntStringHash::set example
  • Example#5515 - QuickHashIntStringHash::update example
  • Example#5516 - Shell 里的一个反射例子（一个终端）
  • Example#5517 - 扩展内置的类
  • Example#5518 - Reflection::getModifierNames 例子
  • Example#5519 - ReflectionClass 的基本用法
  • Example#5520 - ReflectionClass::export 的基本用法
  • Example#5521 - ReflectionClass::getConstructor 的基本用法
  • Example#5522 - ReflectionClass::getDefaultProperties 例子
  • Example#5523 - ReflectionClass::getDocComment 例子
  • Example#5524 - ReflectionClass::getEndLine 例子
  • Example#5525 - ReflectionClass::getExtension 的基本用法
  • Example#5526 - ReflectionClass::getExtensionName 的基本用法
  • Example#5527 - ReflectionClass::getInterfaceNames 例子
  • Example#5528 - ReflectionClass::getInterfaces 例子
  • Example#5529 - ReflectionClass::getMethod 的基本用法
  • Example#5530 - ReflectionClass::getMethods 的基本用法
  • Example#5531 - 从 ReflectionClass::getMethods 中过滤结果
  • Example#5532 - ReflectionClass::getName 例子
  • Example#5533 - ReflectionClass::getNamespaceName 例子
  • Example#5534 - ReflectionClass::getProperties 过滤例子
  • Example#5535 - ReflectionClass::getProperty 的基本用法
  • Example#5536 - Basic ReflectionClass::getReflectionConstants example
  • Example#5537 - ReflectionClass::getShortName 例子
  • Example#5538 - ReflectionClass::getStaticPropertyValue 的基本用法
  • Example#5539 - ReflectionClass::hasConstant 例子
  • Example#5540 - ReflectionClass::hasMethod 例子
  • Example#5541 - ReflectionClass::hasProperty 例子
  • Example#5542 - ReflectionClass::inNamespace 例子
  • Example#5543 - ReflectionClass::isAbstract 例子
  • Example#5544 - ReflectionClass::isAnonymous example
  • Example#5545 - ReflectionClass::isCloneable 的基本用法
  • Example#5546 - ReflectionClass::isFinal 例子
  • Example#5547 - ReflectionClass::isInstance 相关例子
  • Example#5548 - ReflectionClass::isInstantiable 例子
  • Example#5549 - ReflectionClass::isInterface 基本用法
  • Example#5550 - ReflectionClass::isInternal 的基本用法
  • Example#5551 - Basic ReflectionClass::isIterable Usage
  • Example#5552 - ReflectionClass::isIterateable 例子
  • Example#5553 - ReflectionClass::newInstanceArgs 的基本用法
  • Example#5554 - ReflectionClass::__toString 例子
  • Example#5555 - ReflectionExtension example
  • Example#5556 - ReflectionExtension::getClasses example
  • Example#5557 - ReflectionExtension::getClassNames example
  • Example#5558 - ReflectionExtension::getConstants example
  • Example#5559 - ReflectionExtension::getDependencies example
  • Example#5560 - ReflectionExtension::getFunctions example
  • Example#5561 - ReflectionExtension::getINIEntries example
  • Example#5562 - ReflectionExtension::getName example
  • Example#5563 - ReflectionExtension::getVersion example
  • Example#5564 - ReflectionExtension::info example
  • Example#5565 - ReflectionFunction::__construct example
  • Example#5566 - ReflectionFunction::invoke example
  • Example#5567 - ReflectionFunction::invokeArgs example
  • Example#5568 - ReflectionFunction::invokeArgs with references example
  • Example#5569 - ReflectionFunction::__toString example
  • Example#5570 - ReflectionFunctionAbstract::getReturnType example
  • Example#5571 - Usage on built-in functions
  • Example#5572 - ReflectionFunctionAbstract::hasReturnType example
  • Example#5573 - Usage on built-in functions
  • Example#5574 - ReflectionFunctionAbstract::isDeprecated example
  • Example#5575 - ReflectionMethod::__construct example
  • Example#5576 - ReflectionMethod::getDeclaringClass example
  • Example#5577 - ReflectionMethod::getModifiers example
  • Example#5578 - ReflectionMethod::getPrototype example
  • Example#5579 - ReflectionMethod::invoke example
  • Example#5580 - ReflectionMethod::invokeArgs example
  • Example#5581 - ReflectionMethod::__toString example
  • Example#5582 - Using the ReflectionParameter class
  • Example#5583 - 使用 ReflectionParameter 类
  • Example#5584 - Getting the class that declared the method
  • Example#5585 - Getting default values of function parameters
  • Example#5586 - Getting default values' constant names of function parameters
  • Example#5587 - ReflectionParameter::getType Usage as of PHP 7.1.0
  • Example#5588 - ReflectionParameter::getType Usage before PHP 7.1.0
  • Example#5589 - ReflectionParameter::hasType example
  • Example#5590 - ReflectionProperty::__construct example
  • Example#5591 - Getting value from private and protected properties using ReflectionProperty class
  • Example#5592 - ReflectionClass::getDefaultValue example
  • Example#5593 - ReflectionProperty::getDocComment example
  • Example#5594 - Multiple property declarations
  • Example#5595 - ReflectionProperty::getType example
  • Example#5596 - ReflectionProperty::getValue example
  • Example#5597 - ReflectionClass::hasDefaultValue example
  • Example#5598 - ReflectionProperty::hasType example
  • Example#5599 - ReflectionClass::isDefault example
  • Example#5600 - ReflectionProperty::isInitialized example
  • Example#5601 - Simple Class definition
  • Example#5602 - ReflectionProperty::setValue example
  • Example#5603 - ReflectionType::allowsNull example
  • Example#5604 - ReflectionType::__toString example
  • Example#5605 - ReflectionGenerator::__construct example
  • Example#5606 - ReflectionGenerator::getExecutingFile example
  • Example#5607 - ReflectionGenerator::getExecutingGenerator example
  • Example#5608 - ReflectionGenerator::getExecutingLine example
  • Example#5609 - ReflectionGenerator::getFunction example
  • Example#5610 - ReflectionGenerator::getThis example
  • Example#5611 - ReflectionGenerator::getTrace example
  • Example#5612 - boolval examples
  • Example#5613 - debug_zval_dump example
  • Example#5614 -
  • Example#5615 -
  • Example#5616 - 一个简单的 empty 与 isset 的比较。
  • Example#5617 - 在字符串偏移量上使用empty
  • Example#5618 - get_resource_id example
  • Example#5619 - gettype 示例
  • Example#5620 - intval 例子
  • Example#5621 - is_bool 示例
  • Example#5622 - is_callable 例子
  • Example#5623 - is_countable examples
  • Example#5624 - is_int 示例
  • Example#5625 - is_iterable examples
  • Example#5626 - is_scalar 示例
  • Example#5627 - isset 例子
  • Example#5628 - 在字符串位移中使用 isset
  • Example#5629 - print_r 例子
  • Example#5630 - return 参数的例子
  • Example#5631 - serialize 示例
  • Example#5632 - settype 示例
  • Example#5633 - unserialize 例子
  • Example#5634 - unserialize_callback_func 例子
  • Example#5635 - unset 示例
  • Example#5636 - 使用 (unset) 类型强制转换
  • Example#5637 - var_dump 例子
  • Example#5638 - var_export 示例
  • Example#5639 - 输出类 stdClass (自 PHP 7.3.0 起)
  • Example#5640 - 输出对象 (自 PHP 5.1.0 起)
  • Example#5641 - 使用 __set_state() (自 PHP 5.1.0 起)
  • Example#5642 -
  • Example#5643 - OAuth::fetch example
  • Example#5644 - OAuth::getAccessToken 例子
  • Example#5645 - OAuth::getRequestToken 例子
  • Example#5646 - OAuth::setRequestEngine 例子
  • Example#5647 - 一个 OAuth::setRsaCertificate 例子
  • Example#5648 - OAuth::setToken 例子
  • Example#5649 - OAuthProvider::__construct 例子
  • Example#5650 - OAuthProvider::consumerHandler 回调的例子
  • Example#5651 - OAuthProvider::generateToken 例子
  • Example#5652 - OAuthProvider::is2LeggedEndpoint 例子
  • Example#5653 - OAuthProvider::timestampNonceHandler 回调的例子
  • Example#5654 - OAuthProvider::tokenHandler 回调的例子
  • Example#5655 - is_soap_fault example
  • Example#5656 - SOAP's standard method for error reporting is exceptions
  • Example#5657 - SoapClient::__construct example
  • Example#5658 - SoapClient::__doRequest example
  • Example#5659 - SoapClient::__getFunctions example
  • Example#5660 - SoapClient::__getLastRequest() example
  • Example#5661 - SoapClient::__getLastRequestHeaders() example
  • Example#5662 - SoapClient::__getLastResponse() example
  • Example#5663 - SoapClient::__getLastResponse() example
  • Example#5664 - SoapClient::__getTypes example
  • Example#5665 - SoapClient::__setLocation example
  • Example#5666 - SoapClient::__setSoapHeaders example
  • Example#5667 - Set Multiple Headers
  • Example#5668 - SoapClient::__soapCall example
  • Example#5669 - SoapServer::addFunction example
  • Example#5670 - SoapServer::__construct example
  • Example#5671 - SoapServer::getFunctions example
  • Example#5672 - SoapServer::handle example
  • Example#5673 - SoapServer::setPersistence example
  • Example#5674 - Some examples
  • Example#5675 - Some examples
  • Example#5676 - SoapHeader::__construct example
  • Example#5677 - SoapParam::__construct example
  • Example#5678 - SoapVar::__construct example
  • Example#5679 - Yar Server示例
  • Example#5680 - 通过浏览器访问(GET请求)
  • Example#5681 - Yar Client示例
  • Example#5682 - Yar Concurrent Client示例
  • Example#5683 - Yar_Server::__construct示例
  • Example#5684 - Yar_Server::handle示例
  • Example#5685 - Yar_Client::__call example
  • Example#5686 - Yar_Client::__construct示例
  • Example#5687 - Yar_Client::setOpt示例
  • Example#5688 - Yar_Concurrent_Client::call示例
  • Example#5689 - Yar_Concurrent_Client::loop example
  • Example#5690 - Yar_Server_Exception::getType示例
  • Example#5691 - Yar_Client_Exception::getType example
  • Example#5692 - XMLRPC client functions example
  • Example#5693 - XML-RPC type example
  • Example#5694 - A xmlrpc_set_type example
  • Example#5695 - For Each in ASP
  • Example#5696 - foreach in PHP
  • Example#5697 - com example (1)
  • Example#5698 - com example (2)
  • Example#5699 - dotnet example
  • Example#5700 - variant example
  • Example#5701 - Basic COMPersistHelper::saveToFile Usage
  • Example#5702 - COM event sink example
  • Example#5703 - Registering a PHP script to run as a service
  • Example#5704 - Unregistering a service
  • Example#5705 - Running as a service
  • Example#5706 - A win32_create_service example
  • Example#5707 - A win32_create_service example with dependencies
  • Example#5708 - A win32_create_service example with recovery
  • Example#5709 - A win32_delete_service example
  • Example#5710 - A win32_start_service_ctrl_dispatcher example
  • Example#5711 - book.xml
  • Example#5712 - Creating a new DOMAttr object
  • Example#5713 - DOMAttr::isId() Example
  • Example#5714 - Creating a new DOMCdataSection object
  • Example#5715 - Creating a new DOMComment
  • Example#5716 - Creating a new DOMDocument
  • Example#5717 - Creating a new element and inserting it as root
  • Example#5718 - Passing text containing an unescaped & as value
  • Example#5719 - Creating a new element and inserting it as root
  • Example#5720 - A namespace prefix example
  • Example#5721 - DOMDocument::getElementById() Example
  • Example#5722 - Basic Usage Example
  • Example#5723 - Get all the XInclude elements
  • Example#5724 - DOMDocument::importNode example
  • Example#5725 - Creating a Document
  • Example#5726 - Creating a Document
  • Example#5727 - Creating a Document
  • Example#5728 - Creating a Document
  • Example#5729 - Static invocation of loadXML
  • Example#5730 - Adding a new method to DOMElement to ease our code
  • Example#5731 - Retrieving elements as custom class
  • Example#5732 - Retrieving owner document
  • Example#5733 - Custom objects are transient
  • Example#5734 - Saving a DOM tree into a file
  • Example#5735 - Saving a HTML tree into a string
  • Example#5736 - Saving a HTML tree into a file
  • Example#5737 - Saving a DOM tree into a string
  • Example#5738 - Example of DTD validation
  • Example#5739 - DOMDocument::xinclude() example
  • Example#5740 - Appending XML data to your document
  • Example#5741 - Creating a new DOMElement
  • Example#5742 - Setting an attribute
  • Example#5743 - Creating a new DOMEntityReference
  • Example#5744 - Creating a document with an attached DTD
  • Example#5745 - Testing your DOM Implementation
  • Example#5746 - Adding a child
  • Example#5747 - Nested children
  • Example#5748 - DOMNode::getLineNo example
  • Example#5749 - DOMNode::getNodePath example
  • Example#5750 - Removing a child
  • Example#5751 - Traversing all the entries of the table
  • Example#5752 - Creating a new DOMProcessingInstruction object
  • Example#5753 - Creating a new DOMText
  • Example#5754 - Getting the count of all the english books
  • Example#5755 - Getting all the english books
  • Example#5756 - book.xml
  • Example#5757 - DOMXPath::registerPHPFunctions with php:functionString
  • Example#5758 - DOMXPath::registerPHPFunctions with php:function
  • Example#5759 - Import SimpleXML into DOM with dom_import_simplexml
  • Example#5760 - A libxml_get_errors example
  • Example#5761 - libxml_set_external_entity_loader example
  • Example#5762 - A libxml_set_streams_context example
  • Example#5763 - A libxml_use_internal_errors example
  • Example#5764 - Include file example.php with XML string
  • Example#5765 - Getting <plot>
  • Example#5766 - Getting <line>
  • Example#5767 - Accessing non-unique elements in SimpleXML
  • Example#5768 - Using attributes
  • Example#5769 - Comparing Elements and Attributes with Text
  • Example#5770 - Comparing Two Elements
  • Example#5771 - Using XPath
  • Example#5772 - Setting values
  • Example#5773 - Adding elements and attributes
  • Example#5774 - DOM Interoperability
  • Example#5775 - Loading broken XML string
  • Example#5776 - Add attributes and children to a SimpleXML element
  • Example#5777 - Add attributes and children to a SimpleXML element
  • Example#5778 - Get XML
  • Example#5779 - Using asXML() on SimpleXMLElement::xpath results
  • Example#5780 - Interpret an XML string
  • Example#5781 - Traversing a children() pseudo-array
  • Example#5782 - Using namespaces
  • Example#5783 - Create a SimpleXMLElement object
  • Example#5784 - Create a SimpleXMLElement object from a URL
  • Example#5785 - Counting the number of children
  • Example#5786 - Get document namespaces
  • Example#5787 - Working with multiple namespaces
  • Example#5788 - Get XML element names
  • Example#5789 - Get document namespaces in use
  • Example#5790 - Setting a namespace prefix to use in an XPath query
  • Example#5791 - Get string content
  • Example#5792 - Xpath
  • Example#5793 - Return the current element
  • Example#5794 - Return the sub-elements of the current element
  • Example#5795 - Check whether the current element has sub-elements
  • Example#5796 - Get the current XML tag key
  • Example#5797 - Move to the next element
  • Example#5798 - Rewind to the first element
  • Example#5799 - Check whether the current element is valid
  • Example#5800 - Importing DOM
  • Example#5801 - Interpret an XML document
  • Example#5802 - Interpret an XML string
  • Example#5803 - Serializing a single value with WDDX
  • Example#5804 - Using incremental packets with WDDX
  • Example#5805 - wddx_serialize_vars example
  • Example#5806 - 显示 XML 元素结构
  • Example#5807 - 将 XML 映射为 HTML
  • Example#5808 - 外部实体例程
  • Example#5809 - xmltest.xml
  • Example#5810 - xmltest2.xml
  • Example#5811 - xml_parse_into_struct 示例
  • Example#5812 - moldb.xml - 分子信息的小型数据库
  • Example#5813 - parsemoldb.php - 将 moldb.xml 解析到分子（molecular）对象的数组中
  • Example#5814 - xml_set_object 示例
  • Example#5815 - Validating XML
  • Example#5816 - Creating a simple XML document
  • Example#5817 - Working with XML namespaces
  • Example#5818 - Working with the OO API
  • Example#5819 - Direct output of XML
  • Example#5820 - XMLWriter::setIndent and mixed Content
  • Example#5821 - Basic XMLWriter::startAttribute Usage
  • Example#5822 - Intermixing Sub-elements and Attributes
  • Example#5823 - Basic xmlwriter_write_cdata Usage
  • Example#5824 - collection.xml
  • Example#5825 - collection.xsl
  • Example#5826 - fruits.xml
  • Example#5827 - fruits.xsl
  • Example#5828 - Collating and printing errors
  • Example#5829 - Creating an XSLTProcessor
  • Example#5830 - Testing EXSLT support
  • Example#5831 - Simple PHP Function call from a stylesheet
  • Example#5832 - Changing the owner before the transformation
  • Example#5833 - Example profiling output
  • Example#5834 - Transforming to a DOMDocument
  • Example#5835 - Transforming to a HTML file
  • Example#5836 - Transforming to a string
  • Example#5837 - 隐藏的 HTML 表单单元
  • Example#5838 - 等待用户编辑的数据
  • Example#5839 - URL 中的例子
  • Example#5840 - Activate full on-screen error reporting for dev. domain
  • Example#5841 - Add security script for protected areas
  • Example#5842 - Unix include_path
  • Example#5843 - Windows include_path
  • Example#5844 - Unix include_path using ${USER} env variable
  • Example#5845 - string.rot13
  • Example#5846 - string.toupper
  • Example#5847 - string.tolower
  • Example#5848 - string.strip_tags
  • Example#5849 - convert.base64-encode & convert.base64-decode
  • Example#5850 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5851 - zlib.deflate和 zlib.inflate
  • Example#5852 - zlib.deflate简单参数用法
  • Example#5853 - bzip2.compress和 bzip2.decompress
  • Example#5854 - 用 3DES 将文件加密输出
  • Example#5855 - 读取加密的文件

User Contributed Notes

There are no user contributed notes for this page.


更新日志

对绑定的扩展的函数有以下更新。

Version | Function | Description
Since 5.0.0 | get_parent_class | The object parameter is optional if called from the object's method.
Since 5.0 | cal_info | 参数calendar作为可选项，缺省时默认值为"所有历法"。
Since 4.3.0 | easter_date | year参数可选，缺省的默认值是当年。
easter_days | 参数year 可选，缺省默认值是当年。
easter_days | 引入参数 method。
Since 4.2.0 | srand | seed 成为可选，省略时会默认使用随机值。
Since 4.0.5 | get_parent_class | If object is a string, returns the name of the parent class of the class with that name.
prior to 5.3.0 | get_object_vars | If the object isn't an object, then get_object_vars would return false
Prior to 5.1.3 | imagecolorallocatealpha | Returns -1 if the allocation failed.
prior to 4.2.0 | get_object_vars | If the variables declared in the class of which the object is an instance, have not been assigned a value, those will not be returned in the array
PHP 7.0.15, PHP 7.1.1 | get_defined_functions | 增加 exclude_disabled 参数。
PHP 5.3.2 (PECL OCI8 1.4) | oci_set_prefetch | Before this release, rows must be >= 1.
PHP 5.3 (PECL OCI8 1.3.4) | oci_set_prefetch | Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.
PECL 3.0.0 | IntlDateFormatter::format | Support for providing IntlCalendar objects to the datetime parameter was added.
Before 5.1.0 | get_parent_class | If called without parameter outside object, this function would have returned null with a warning.
8.0.3 | bind_textdomain_codeset | codeset is nullable now. Previously, it was not possible to retrieve the currently set encoding.
bindtextdomain | directory is nullable now. Previously, it was not possible to retrieve the currently set directory.
8.0.0, PECL OCI8 3.0.0 | OCICollection::append | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCICollection::assign | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCICollection::assignElem | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCICollection::free | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCICollection::getElem | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCICollection::max | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCICollection::size | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCICollection::trim | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.
OCILob::append | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::close | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::eof | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::erase | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::export | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::flush | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::free | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::getBuffering | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::import | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::load | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::read | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::rewind | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::save | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::saveFile | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::seek | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::setBuffering | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::size | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::tell | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::truncate | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::write | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::writeTemporary | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
OCILob::writeToFile | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.
8.0.0 | DateTime::format | Prior to this version, false was returned on failure.
DateTime::format | The format character p has been added.
DateTime::getOffset | Prior to this version, false was returned on failure.
DateTime::getTimestamp | These functions no longer return false on failure.
DOMImplementation::createDocument | doctype is now nullable.
array_filter | callback 回调现在可以为空（nullable）。
bcpowmod | scale is now nullable.
com_event_sink | sink_interface is nullable now.
com_get_active_object | codepage is nullable now.
deflate_add | context expects a DeflateContext instance now; previously, a resource was expected.
deflate_init | On success, this function returns a DeflateContext instance now; previously, a resource was returned.
enchant_broker_describe | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_describe | Prior to this version, the function returned false on failure.
enchant_broker_dict_exists | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_free | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_free_dict | dictionary expects a EnchantDictionary now; previoulsy, a 资源(resource) was expected.
enchant_broker_get_dict_path | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_get_error | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_init | On success, this function returns an EnchantBroker instance now; previoulsy, a 资源(resource) was retured.
enchant_broker_list_dicts | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_list_dicts | Prior to this version, the function returned false on failure.
enchant_broker_request_dict | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_request_dict | On success, this function returns an EnchantDictionary instance now; previoulsy, a 资源(resource) was retured.
enchant_broker_request_pwl_dict | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_request_pwl_dict | On success, this function returns an EnchantDictionary instance now; previoulsy, a 资源(resource) was retured.
enchant_broker_set_dict_path | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_broker_set_ordering | broker expects an EnchantBroker instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_add | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_add_to_session | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_check | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_describe | Prior to this version, the function returned false on failure.
enchant_dict_describe | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_get_error | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_is_added | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_quick_check | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_store_replacement | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
enchant_dict_suggest | dictionary expects an EnchantDictionary instance now; previoulsy, a 资源(resource) was expected.
gmp_binomial | This function no longer returns false on failure.
gmp_export | This function no longer returns false on failure.
gmp_import | This function no longer returns false on failure.
gzgets | length is nullable now; previously, the default was 1024.
gzwrite | length is nullable now; previously, the default was 0.
html_entity_decode | encoding is nullable now.
iconv_strpos | encoding is nullable now.
iconv_strrpos | encoding is nullable now.
inflate_add | context expects an InflateContext instance now; previously, a resource was expected.
inflate_get_read_len | context expects an InflateContext instance now; previously, a resource was expected.
inflate_get_status | context expects an InflateContext instance now; previously, a resource was expected.
inflate_init | On success, this function returns an InflateContext instance now; previously, a resource was returned.
ldap_add | controls is nullable now; previously, it defaulted to [].
ldap_add_ext | controls is nullable now; previously, it defaulted to [].
ldap_bind_ext | controls is nullable now; previously, it defaulted to [].
ldap_compare | controls is nullable now; previously, it defaulted to [].
ldap_delete | controls is nullable now; previously, it defaulted to [].
ldap_delete_ext | controls is nullable now; previously, it defaulted to [].
ldap_exop_passwd | controls is nullable now; previously, it defaulted to [].
ldap_list | controls is nullable now; previously, it defaulted to [].
ldap_mod_add | controls is nullable now; previously, it defaulted to [].
ldap_mod_del | controls is nullable now; previously, it defaulted to [].
ldap_mod_replace | controls is nullable now; previously, it defaulted to [].
ldap_modify_batch | controls is nullable now; previously, it defaulted to [].
ldap_mod_add_ext | controls is nullable now; previously, it defaulted to [].
ldap_mod_del_ext | controls is nullable now; previously, it defaulted to [].
ldap_mod_replace_ext | controls is nullable now; previously, it defaulted to [].
ldap_read | controls is nullable now; previously, it defaulted to [].
ldap_rename | controls is nullable now; previously, it defaulted to [].
ldap_rename_ext | controls is nullable now; previously, it defaulted to [].
ldap_sasl_bind | dn, password, mech, realm, authc_id, authz_id and props are nullable now.
ldap_search | controls is nullable now; previously, it defaulted to [].
ldap_set_rebind_proc | callback is nullable now.
libxml_use_internal_errors | use_errors is nullable now. Previously, its default was false.
mb_chr | 现在 encoding 可以为 null。
mb_convert_kana | 现在 encoding 可以为 null。
mb_encode_numericentity | 现在 encoding 可以为 null。
mb_ereg | This function returns true on success now. Previously, it returned the byte length of the matched string if a match for pattern was found in string and matches was passed. If the optional parameter matches was not passed or the length of the matched string was 0, this function returned 1.
mb_ereg_match | options is nullable now.
mb_ereg_replace | options is nullable now.
mb_ereg_replace_callback | options is nullable now.
mb_ereg_search | pattern and options are nullable now.
mb_ereg_search_init | pattern and options are nullable now.
mb_ereg_search_pos | pattern and options are nullable now.
mb_ereg_search_regs | pattern and options are nullable now.
mb_eregi | This function returns true on success now. Previously, it returned the byte length of the matched string if a match for pattern was found in string and matches was passed. If the optional parameter matches was not passed or the length of the matched string was 0, this function returned 1.
mb_eregi_replace | options is nullable now.
mb_get_info | 参数 type 中的 "func_overload" 和 "func_overload_list" 不再被支持。
mb_ord | 现在 encoding 可以为 null。
mb_regex_encoding | 现在 encoding 可以为 null。
mb_regex_set_options | options is nullable now.
mb_regex_set_options | If the parameter options is given and not null, the previous options are returned. Formerly, the current options have been returned.
mb_scrub | 现在 encoding 可以为 null。
mb_str_split | This function no longer returns false on failure.
mb_str_split | 现在 encoding 可以为 null。
metaphone | The function returned false on failure.
mhash | key is now nullable.
msg_get_queue | On success, this function returns a SysvMessageQueue instance now; previously, a resource was returned.
msg_receive | queue expects a SysvMessageQueue instance now; previously, a resource was expected.
msg_remove_queue | queue expects a SysvMessageQueue instance now; previously, a resource was expected.
msg_send | queue expects a SysvMessageQueue instance now; previously, a resource was expected.
msg_set_queue | queue expects a SysvMessageQueue instance now; previously, a resource was expected.
msg_stat_queue | queue expects a SysvMessageQueue instance now; previously, a resource was expected.
odbc_columns | schema, table and column are now nullable.
odbc_error | odbc is nullable now.
odbc_errormsg | odbc is nullable now.
odbc_exec | flags was removed.
odbc_fetch_row | row is nullable now.
odbc_procedurecolumns | Prior to this version, the function could only be called with either one or five arguments.
odbc_procedures | Prior to this version, the function could only be called with either one or four arguments.
odbc_tables | schema, table and types are now nullable.
openssl_pkey_new | 成功时此函数会返回 OpenSSLAsymmetricKey 的实例；在之前版本中，则会返回类似为 OpenSSL key 的 资源(resource)。
openssl_sign | private_key accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a 资源(resource) of type OpenSSL key or OpenSSL X.509 was accepted.
openssl_x509_verify | public_key accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a 资源(resource) of type OpenSSL key or OpenSSL X.509 was accepted.
openssl_x509_verify | certificate accepts an OpenSSLCertificate instance now; previously, a 资源(resource) of type OpenSSL X.509 was accepted.
parse_str | result 是必须项。
sem_acquire | semaphore expects a SysvSemaphore instance now; previously, a resource was expected.
sem_get | On success, this function returns a SysvSemaphore instance now; previously, a resource was returned.
sem_get | The type of auto_release has been changed from int to bool.
sem_release | semaphore expects a SysvSemaphore instance now; previously, a resource was expected.
sem_remove | semaphore expects a SysvSemaphore instance now; previously, a resource was expected.
shm_attach | size is nullable now.
shm_attach | On success, this function returns an SysvSharedMemory instance now; previously, a resource was returned.
shm_detach | shm expects a SysvSharedMemory instance now; previously, a resource was expected.
shm_get_var | shm expects a SysvSharedMemory instance now; previously, a resource was expected.
shm_has_var | shm expects a SysvSharedMemory instance now; previously, a resource was expected.
shm_put_var | shm expects a SysvSharedMemory instance now; previously, a resource was expected.
shm_remove | shm expects a SysvSharedMemory instance now; previously, a resource was expected.
shm_remove_var | shm expects a SysvSharedMemory instance now; previously, a resource was expected.
shmop_close | shmop expects a Shmop instance now; previously, a resource was expected.
shmop_delete | shmop expects a Shmop instance now; previously, a resource was expected.
shmop_open | On success, this function returns an Shmop instance now; previously, a resource was returned.
shmop_read | shmop expects a Shmop instance now; previously, a resource was expected.
shmop_size | shmop expects a Shmop instance now; previously, a resource was expected.
shmop_write | shmop expects a Shmop instance now; previously, a resource was expected.
shmop_write | Prior to PHP 8.0.0, false was returned on failure.
socket_accept | On success, this function returns a Socket instance now; previously, a resource was returned.
socket_addrinfo_bind | address is an AddressInfo instance now; previously, it was a resource.
socket_addrinfo_bind | On success, this function returns a Socket instance now; previously, a resource was returned.
socket_addrinfo_connect | address is an AddressInfo instance now; previously, it was a resource.
socket_addrinfo_connect | On success, this function returns a Socket instance now; previously, a resource was returned.
socket_addrinfo_explain | address is an AddressInfo instance now; previously, it was a resource.
socket_addrinfo_lookup | On success, this function returns a array of AddressInfo instances now; previously, an array of resources was returned.
socket_addrinfo_lookup | service is nullable now.
socket_connect | socket is a Socket instance now; previously, it was a resource.
socket_connect | port 允许为空。
socket_create_listen | On success, this function returns a Socket instance now; previously, a resource was returned.
socket_create_pair | pair is a reference to an array of Socket instances now; previously, it was a reference to an array of resources.
socket_export_stream | socket is a Socket instance now; previously, it was a resource.
socket_get_option | socket is a Socket instance now; previously, it was a resource.
socket_getpeername | socket is a Socket instance now; previously, it was a resource.
socket_getsockname | socket is a Socket instance now; previously, it was a resource.
socket_import_stream | On success, this function returns a Socket instance now; previously, a resource was returned.
socket_last_error | socket is a Socket instance now; previously, it was a resource.
socket_last_error | socket is nullable now.
socket_listen | socket is a Socket instance now; previously, it was a resource.
socket_read | socket is a Socket instance now; previously, it was a resource.
socket_recvfrom | socket is a Socket instance now; previously, it was a resource.
socket_recvmsg | socket is a Socket instance now; previously, it was a resource.
socket_send | socket is a Socket instance now; previously, it was a resource.
socket_sendmsg | socket is a Socket instance now; previously, it was a resource.
socket_sendto | socket is a Socket instance now; previously, it was a resource.
socket_sendto | port is nullable now.
socket_set_block | socket is a Socket instance now; previously, it was a resource.
socket_set_nonblock | socket is a Socket instance now; previously, it was a resource.
socket_set_option | socket is a Socket instance now; previously, it was a resource.
socket_shutdown | socket is a Socket instance now; previously, it was a resource.
socket_write | length is nullable now.
socket_write | socket is a Socket instance now; previously, it was a resource.
socket_wsaprotocol_info_export | socket is a Socket instance now; previously, it was a resource.
socket_wsaprotocol_info_import | On success, this function returns a Socket instance now; previously, a resource was returned.
soundex | Prior to this version, calling the function with an empty string returned false for no particular reason.
sprintf | This function no longer returns false on failure.
ReflectionClass::getReflectionConstants | filter has been added.
ReflectionParameter::getDefaultValue | This method now allows getting the default value of parameters of built-in functions and built-in class methods. Previously, a ReflectionException was thrown.
ReflectionParameter::getDefaultValueConstantName | This method now allows getting the default values' constant names of built-in functions and built-in class methods. Previously, a ReflectionException was thrown.
ReflectionProperty::getValue | object is nullable now.
ReflectionProperty::isInitialized | object is nullable now.
SoapClient::__doRequest | The type of oneWay is bool now; formerly it was int.
SoapClient::__setCookie | value is now nullable.
SoapServer::handle | request is now nullable.
tidy::__construct | filename, config, encoding and useIncludePath are nullable now.
tidy::parseFile | config and encoding are nullable now.
tidy::parseString | config and encoding are nullable now.
tidy::repairFile | config and encoding are nullable now.
tidy::repairFile | tidy::repairFile is a static method now.
tidy::repairString | tidy::repairString is a static method now.
tidy::repairString | This function no longer accepts the useIncludePath parameter.
tidy::repairString | config and encoding are nullable now.
XMLReader::getAttribute | This function can no longer return false.
XMLReader::getAttributeNs | This function can no longer return false.
XMLReader::lookupNamespace | This function can no longer return false.
XMLReader::next | name is nullable now.
XMLReader::open | XMLReader::open is now declared as static method, but can still be called on an XMLReader instance.
XMLReader::XML | XMLReader::XML is now declared as static method, but can still be called on an XMLReader instance.
XMLWriter::endAttribute | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endCdata | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endComment | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endDocument | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endDtd | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endDtdAttlist | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endDtdElement | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endDtdEntity | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endElement | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::endPi | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::flush | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::flush | This function can no longer return false.
XMLWriter::fullEndElement | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::openMemory | This function returns now an XMLWriter instance on success. Previouly, a 资源(resource) has been returned in this case.
XMLWriter::openUri | This function returns now an XMLWriter instance on success. Previouly, a 资源(resource) has been returned in this case.
XMLWriter::outputMemory | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::setIndent | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::setIndentString | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startAttribute | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startAttributeNs | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startAttributeNs | prefix is nullable now.
XMLWriter::startCdata | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startComment | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startDocument | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startDtd | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startDtdAttlist | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startDtdElement | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startDtdEntity | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startElement | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startElementNs | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::startPi | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::text | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeAttribute | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeAttributeNs | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeCdata | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeComment | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeDtd | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeDtdAttlist | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeDtdElement | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeDtdEntity | publicId, systemId and notationData are nullable now.
XMLWriter::writeDtdEntity | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeElement | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeElementNs | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writePi | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
XMLWriter::writeRaw | 现在 writer 需要 XMLWriter 实例， 之前需要的是 resource。
7.4.0 | array_merge | 允许不带参数调用，之前版本至少需要一个参数。
array_merge_recursive | 允许不传递参数调用，之前的版本中至少需要一个参数。
get_magic_quotes_gpc | 该函数已被废弃。
gzread | This functions returns false on failure now; previously 0 was returned.
gzwrite | This functions returns false on failure now; previously 0 was returned.
hash_algos | 支持 crc32c。
idn_to_ascii | 现在 variant 的默认值为 INTL_IDNA_VARIANT_UTS46 ， 而不是已弃用的 INTL_IDNA_VARIANT_2003 。
idn_to_utf8 | 现在 variant 的默认值为 INTL_IDNA_VARIANT_UTS46 ， 而不是已弃用的 INTL_IDNA_VARIANT_2003 。
imagecropauto | The default value of mode has been changed to IMG_CROP_AUTO. Formerly, the default value has been -1 which corresponds to IMG_CROP_DEFAULT, but passing -1 is now deprecated.
imagecropauto | The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd: IMG_CROP_DEFAULT no longer falls back to IMG_CROP_SIDES and threshold-cropping now uses the same algorithm as system libgd.
implode | 把参数 glue 放到 pieces 的后面已被废弃（就是不按文档中的顺序传递参数）。
ldap_control_paged_result | This function has been deprecated.
ldap_control_paged_result_response | This function has been deprecated.
password_hash | 现在 algo 参数可支持 string 类型，但为了向后兼容也支持 int 类型。
password_needs_rehash | 现在 algo 参数可以支持 string 类型，但为了向后兼容性，同时支持 int 类型。
preg_replace_callback | 新增 flags 参数。
preg_replace_callback_array | The flags parameter was added.
SQLite3Stmt::bindParam | param now also supports the @param notation.
SQLite3Stmt::bindValue | param now also supports the @param notation.
7.3.24, 7.4.12 | tidyNode::isHtml | This function has been fixed to have reasonable behavior. Previously, almost any node was reported as being an HTML node.
7.3.14, 7.4.2 | dba_open | The lmdb driver now supports an additional $mapsize parameter.
7.3.0 | apache_request_headers | 此函数可用于 FPM SAPI 模式。
array_push | 可以只用一个参数来调用此函数，之前版本中至少需要两个参数。
array_unshift | 现在可以只用一个参数来调用，之前至少需要两个参数。
compact | 现在，如果字符串指向的变量未定义，compact 会产生 E_NOTICE 级错误。 在此之前，此类问题会静默忽略掉。
define | 废弃了 case_insensitive，并将在 8.0.0 版中移除。
ftp_nb_fget | 参数 mode 变为可选参数。 在之前的版本中，这是一个必填参数。
ftp_nb_fput | 参数 mode 变为可选参数。 在之前的版本中，这是一个必填参数。
ftp_nb_get | mode 参数变为可选，之前是强制性的。
ftp_nb_put | mode 参数为可选，之前版本中为必填。
ftp_put | mode 参数为可选，之前版本中为必选。
is_countable | is_countable has been added.
json_decode | JSON_THROW_ON_ERROR options was added.
json_encode | options 参数新增 JSON_THROW_ON_ERROR 常量。
list | 支持在数组解构时传引用。
password_hash | 增加 PASSWORD_ARGON2ID，支持 Argon2id 密码算法。
preg_quote | 字符 # 被增加为需要转义的。
session_set_cookie_params | 增加 options 参数， 可以通过传入一个关联数组对各个选项进行设置。 同时，通过使用这个参数还可以对 SameSite cookie 进行设置。
setcookie | An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.
unlink | 现在 Windows 也可以用 unlink 删除文件句柄还在使用中的文件了，在此之前是无法删除的。 然而，还是无法重新创建文件，需要等到所有句柄都关闭才可以。
var_export | Now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState. The practical effect is that now stdClass is exportable, and the resulting code will even work on earlier versions of PHP.
7.3 | ldap_add | Support for controls added
ldap_compare | Support for controls added
ldap_delete | Support for controls added
ldap_exop | Support for serverctrls added
ldap_exop_passwd | Support for controls added
ldap_list | Support for controls added
ldap_mod_add | Support for controls added
ldap_mod_del | Support for controls added
ldap_mod_replace | Support for controls added
ldap_modify_batch | Support for controls added
ldap_mod_add_ext | Support for controls added
ldap_mod_del_ext | Support for controls added
ldap_mod_replace_ext | Support for controls added
ldap_parse_result | Support for controls added
ldap_read | Support for controls added
ldap_rename | Support for controls added
ldap_rename_ext | Support for controls added
ldap_search | Support for controls added
7.2.19, 7.3.6, 7.4.0 | DatePeriod::__construct | recurrences must be greater than 0 now.
7.2.18, 7.3.5 | substr_compare | offset 现在可能等于 main_str。
7.2.0 | count | 当无效的 countable 类型传递给 array_or_countable 参数时，count 会产生警告。
date_parse | 返回数组的 zone 键现在代表秒，而不是分钟。 并且正负符号已反转，例如：之前是 -120 现在是 7200。
date_parse_from_format | The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.
gettype | 现在，已关闭的资源报告为 'resource (closed)'。 此前，已关闭的资源报告为 'unknown type'。
hash_copy | 接受的参数以及返回值从资源类型修改为 HashContext 对象类型。
hash_final | 接收参数从资源类型修改为 HashContext 对象类型。
hash_hmac | 不再支持非加密的哈希函数（adler32，crc32，crc32b，fnv132，fnv1a32，fnv164，fnv1a64，joaat）。
hash_hmac_file | 不再支持非加密的哈希函数（adler32，crc32，crc32b，fnv132，fnv1a32，fnv164，fnv1a64，joaat）。
hash_init | 返回 HashContext 对象，不再返回资源类型。
hash_init | 当使用 HASH_HMAC 选项的时候，不再支持非加密的哈希函数（adler32，crc32，crc32b，fnv132，fnv1a32，fnv164，fnv1a64，joaat）。
hash_pbkdf2 | 不再支持非加密的哈希函数（adler32，crc32，crc32b，fnv132，fnv1a32，fnv164，fnv1a64，joaat）。
hash_update | 接收参数从资源类型修改为 HashContext 对象类型。
hash_update_file | 接收参数从资源类型修改为 HashContext 对象类型。
hash_update_stream | 接收参数从资源类型修改为 HashContext 对象类型。
idn_to_ascii | INTL_IDNA_VARIANT_2003 已被弃用； 可以使用 INTL_IDNA_VARIANT_UTS46 代替。
idn_to_utf8 | INTL_IDNA_VARIANT_2003 已被弃用； 可以使用 INTL_IDNA_VARIANT_UTS46 代替。
json_decode | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE options were added.
json_encode | options 参数新增 JSON_INVALID_UTF8_IGNORE 和 JSON_INVALID_UTF8_SUBSTITUTE 常量。
mail | 现在 additional_headers 参数开始支持 array。
number_format | number_format 现在无法返回 -0，之前可能返回 -0，因为 number 可能会是 -0.01。
openssl_pkcs7_verify | 新增 p7bfilename 参数。
pack | float 和 double 类型支持打断和小端。
parse_str | 不带第二个参数的情况下使用 parse_str 会产生 E_DEPRECATED 警告。
password_hash | 增加 PASSWORD_ARGON2I，支持 Argon2i 密码算法。
preg_match | 现在 $flags 参数支持 PREG_UNMATCHED_AS_NULL。
preg_match_all | 现在 $flags 参数可以支持 PREG_UNMATCHED_AS_NULL。
proc_nice | 在 Windows 平台上可用。
session_abort | The return type of this function is bool now. Formerly, it has been void.
session_module_name | 不允许设置模块名称为 "user"。 在之前的版本中，如果设置为 "user"，那么会被静默的忽略到。
session_name | session_name 函数会检查会话状态， 之前的版本仅仅检查 cookie 状态。 所以，旧版本的 PHP 允许你在调用 session_start 函数之后再调用 session_name 函数， 新版本的 PHP 不再允许这样做了。
session_reset | The return type of this function is bool now. Formerly, it has been void.
session_set_cookie_params | 成功时返回 true， 或者在失败时返回 false。 之前版本中是返回 void 的。
session_write_close | The return type of this function is bool now. Formerly, it has been void.
unpack | float and double types supports both Big Endian and Little Endian.
SQLite3::openBlob | The flags parameter has been added, allowing to write BLOBs; formerly only reading was supported.
7.1.5 | IntlDateFormatter::format | Support for providing general DateTimeInterface objects to the datetime parameter was added. Formerly, only proper DateTime objects were supported.
7.1.4 | PDO::sqliteCreateFunction | The flags parameter has been added.
SQLite3::createFunction | The flags parameter has been added.
7.1.0 | DateInterval::format | The F and f format characters were added.
DateTime::setTime | 新增 microsecond 参数。
array_rand | 内部随机化算法已从 libc rand 函数更改为使用 梅森旋转算法（Mersenne Twister） 随机数生成器。
getenv | 现在可以省略 varname 来检索所有环境变量的关联数组 array。
getopt | 添加 optind 参数。
grapheme_extract | Support for negative offsets has been added.
grapheme_stripos | Support for negative offsets has been added.
grapheme_strpos | Support for negative offsets has been added.
hash_algos | 加入 sha512/224，sha512/256，sha3-224，sha3-256，sha3-384 以及 sha3-512 算法的支持。
iconv_strpos | Support for negative offsets has been added.
json_decode | An empty JSON key ("") can be encoded to the empty object property instead of using a key with value _empty_.
json_encode | 对 Double 的值进行编码时，使用 serialize_precision 代替 precision。
json_encode | options 参数新增 JSON_UNESCAPED_LINE_TERMINATORS 常量。
list | 现在可以指定 list 中的键。 这就可以解构非数字键或者无顺序的数组。
long2ip | 参数 proper_address 的类型从 string 改成 integer。
mb_ereg | mb_ereg will now set matches to an empty array, if nothing matched. Formerly, matches was not modified in that case.
mb_ereg_replace | The function checks whether string is valid for the current encoding.
mb_ereg_replace | The e modifier has been deprecated.
mb_ereg_replace_callback | The function checks whether string is valid for the current encoding.
mb_ereg_search_setpos | Support for negative offsets has been added.
mb_eregi | mb_eregi will now set matches to an empty array, if nothing matched. Formerly, matches was not modified in that case.
mb_eregi_replace | The e modifier has been deprecated.
mb_eregi_replace | The function checks whether string is valid for the current encoding.
mb_strimwidth | 支持负数的 start 和 width。
mb_stripos | 支持 offset 使用负数。
mb_strpos | 支持负数的 offset。
openssl_decrypt | 添加了 tag 和 aad 参数。
openssl_encrypt | 增加了 tag、aad、tag_length 参数
openssl_pkey_new | 添加了 curve_name 配置参数使得可以创建 EC 密钥。
session_start | 当 session_start 执行失败， 无法开始一个会话的时候，会返回 false， 并且不会初始化超级变量 $_SESSION。
shuffle | 内置的随机数产生算法从 libc rand 函数改成 梅森旋转伪随机数生成算法。
str_shuffle | 内置的随机算法从 libc rand 函数改成了梅森旋转演伪随机数发生算法。
stripos | 开始支持负数的 offset。
strpos | 开始支持负数的 offset。
substr_count | 开始支持负数的 offset 和 length。
unpack | The optional offset has been added.
ReflectionType::__toString | ReflectionType::__toString has been deprecated.
SessionHandler::gc | Prior to this version, the function returned true on success.
SessionHandlerInterface::gc | Prior to this version, the function returned true on success.
7.1 | DateTime::__construct | 微秒部分不再是 '00000' 了，而是真实的微秒数据。
7.0.15,7.1.1 | pack | 添加了 “e”,“E”,“g” 和 “G” 代码以启用 float 和 double 的字节顺序支持。
7.0.11 | iconv_substr | 如果 str 等长于 offset 个字符， 将返回空字符串。之前的版本里，这种情况是会返回 false 的。
7.0.10 | SQLite3::__construct | The filename can now be empty to use a private, temporary on-disk database.
7.0.7 | curl_setopt | 引入 CURL_HTTP_VERSION_2、 CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE、 CURL_HTTP_VERSION_2TLS、 CURL_REDIR_POST_301、 CURL_REDIR_POST_302、 CURL_REDIR_POST_303、 CURL_REDIR_POST_ALL、 CURL_VERSION_KERBEROS5、 CURL_VERSION_PSL、 CURL_VERSION_UNIX_SOCKETS、 CURLAUTH_NEGOTIATE、 CURLAUTH_NTLM_WB、 CURLFTP_CREATE_DIR、 CURLFTP_CREATE_DIR_NONE、 CURLFTP_CREATE_DIR_RETRY、 CURLHEADER_SEPARATE、 CURLHEADER_UNIFIED、 CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE、 CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE、 CURLMOPT_MAX_HOST_CONNECTIONS、 CURLMOPT_MAX_PIPELINE_LENGTH、 CURLMOPT_MAX_TOTAL_CONNECTIONS、 CURLOPT_CONNECT_TO、 CURLOPT_DEFAULT_PROTOCOL、 CURLOPT_DNS_INTERFACE、 CURLOPT_DNS_LOCAL_IP4、 CURLOPT_DNS_LOCAL_IP6、 CURLOPT_EXPECT_100_TIMEOUT_MS、 CURLOPT_HEADEROPT、 CURLOPT_LOGIN_OPTIONS、 CURLOPT_PATH_AS_IS、 CURLOPT_PINNEDPUBLICKEY、 CURLOPT_PIPEWAIT、 CURLOPT_PROXY_SERVICE_NAME、 CURLOPT_PROXYHEADER、 CURLOPT_SASL_IR、 CURLOPT_SERVICE_NAME、 CURLOPT_SSL_ENABLE_ALPN、 CURLOPT_SSL_ENABLE_NPN、 CURLOPT_SSL_FALSESTART、 CURLOPT_SSL_VERIFYSTATUS、 CURLOPT_STREAM_WEIGHT、 CURLOPT_TCP_FASTOPEN、 CURLOPT_TFTP_NO_OPTIONS、 CURLOPT_UNIX_SOCKET_PATH、 CURLOPT_XOAUTH2_BEARER、 CURLPROTO_SMB、 CURLPROTO_SMBS、 CURLPROXY_HTTP_1_0、 CURLSSH_AUTH_AGENT 和 CURLSSLOPT_NO_REVOKE。
7.0.0 | array_column | input 参数现在可以是包含对象的数组。
assert | assert is now a language construct and not a function. assertion can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
current | array 参数始终通过赋值来传递。之前的版本中，默认通过引用来传值。
define | 允许 array 的值。
dirname | 添加可选的 levels 参数。
getrusage | 此函数现在开始支持 Windows。
json_decode | An empty PHP string or value that after casting to string is an empty string (NULL, FALSE) results in JSON syntax error.
json_decode | Rejected RFC 7159 incompatible number formats - top level (07, 0xff, .1, -.1) and all levels ([1.], [1.e1])
key | array 现在总是会传值。 在此之前，它会尽可能传引用，否则就传值。
list | list 表达式不再可以完全为空。
list | 赋值操作的顺序发生了变化。
list | 字符串无法再被拆包（unpack）。
mktime | is_dst参数已经被移除。
openssl_open | 添加了 iv 参数
openssl_seal | 添加 iv 变量。
session_set_save_handler | 新增可选参数 validate_sid 和 update_timestamp。
session_start | 新加 options 参数。
substr | 如果 string 的字符串长度与 start 相同时将返回一个空字符串。在之前的版本中，这种情况将返回 false 。
5.6.5 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.
5.6.3 | pack | 添加了 “q”、“q”、“J” 和 “P” 代码以支持处理 64 位数字。
5.6.0 | array_fill | count 现在可以是零。 之前 count 必须大于零。
array_filter | 添加可选的 mode 标志和常量（ ARRAY_FILTER_USE_KEY 和 ARRAY_FILTER_USE_BOTH ）
crypt | Raise E_NOTICE security warning if salt is omitted.
htmlentities | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
htmlspecialchars | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
json_decode | Invalid non-lowercased variants of the true, false and null literals are no longer accepted as valid input, and will generate warnings.
mb_regex_encoding | Default encoding is changed to UTF-8. It was EUC-JP Previously.
mcrypt_create_iv | source 参数的默认值是 MCRYPT_DEV_URANDOM。
mcrypt_decrypt | 不再接受无效长度的 key and iv 参数。 如果参数长度无效，则 mcrypt_decrypt 函数会产生警告并且返回 false。 之前版本中，对于长度不足的密钥和初始向量会在其后补齐 '\0' 使其达到有效长度。
mcrypt_encrypt | 不再接受无效长度的 key and iv 参数。 如果参数长度无效，则 mcrypt_decrypt 函数会产生警告并且返回 false。 之前版本中，对于长度不足的密钥和初始向量会在其后补齐 '\0' 使其达到有效长度。
pg_lo_truncate | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
stream_socket_enable_crypto | The crypto_type is now optional.
stream_socket_enable_crypto | Introduce STREAM_CRYPTO_METHOD_ANY_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, STREAM_CRYPTO_METHOD_ANY_SERVER, STREAM_CRYPTO_METHOD_TLSv1_0_SERVER, STREAM_CRYPTO_METHOD_TLSv1_1_SERVER, STREAM_CRYPTO_METHOD_TLSv1_2_SERVER.
ReflectionClass::newInstanceWithoutConstructor | All internal classes can now be instantiated except for those declared final.
XMLReader::getAttributeNo | XMLReader::getAttributeNo now returns null if the attribute doesn't exist.
XMLReader::getAttributeNs | XMLReader::getAttributeNS now returns null if the attribute doesn't exist.
5.5.38, 5.6.24, 7.0.9 | getenv | 添加 local_only 参数。
5.5.21 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.
5.5.7 | getallheaders | 此函数可用于 CLI server。
5.5.2 | DOMDocument::schemaValidate | Added the flags parameter
DOMDocument::schemaValidateSource | Added the flags parameter
5.5.1 | hex2bin | 如果输入的字符串是无效的十六进制字符串则抛出一个警告，
session_set_save_handler | 新增可选参数 create_sid。
5.5.0/PECL 3.0.0 | IntlDateFormatter::create | An IntlCalendar object is allowed for calendar. Objects of type IntlTimeZone and DateTimeZone are allowed for timezone. Invalid timezone identifiers (including empty strings) are no longer allowed for timezone. If null is given for timezone, the timezone identifier given by date_default_timezone_get will be used instead of ICU?s default.
IntlDateFormatter::setCalendar | It became possible to pass an IntlCalendar object.
5.5.0 | empty | empty 现在支持表达式了，而不仅仅是变量。
ip2long | Prior to this version, on Windows ip2long would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.
此函数会生成一个 E_DEPRECATED 错误。
mysql_list_dbs 函数已废弃，调用时会抛出 E_DEPRECATED 级别的错误。
函数会抛出一个 E_DEPRECATED 错误。
mysql_tablename 函数已废弃，调用时会抛出 E_DEPRECATED 级别的错误。
pack | “Z” 代码添加了与 “a” 等效的功能，以实现 Perl 兼容性。
setrawcookie | 发送给客户端的 Set-Cookie 头现在会加上 Max-Age 属性。
unpack | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.
5.4.43, 5.5.27, 5.6.11 | escapeshellcmd | 感叹号会被空格所替换。
5.4.32, 5.5.16 | ucwords | 增加了 delimiters 参数。
5.4.8 | assert | 增加了参数 description。 description 现在也作为第四个参数提供给 ASSERT_CALLBACK 模式里的回调函数。
mb_strcut | Passing NULL as length extracts all bytes to the end of the string. Prior to this version NULL was treated the same as 0.
mb_substr | length 传入 NULL，则从 start 提取到字符串的结尾处。 在之前的版本里， NULL 会被当作 0 来处理。
5.4.7 | parse_url | 修复了 host 在 协议 省略时的识别。
5.4.4 | hex2bin | 如果输入的字符串有多余将抛出异常。 PHP 5.4.0 起字符串将被静默地接受，但是最后的字节会被截断。
5.4.0 | array_combine | （修复）早期版本中如果是空数组就报E_WARNING的错并且返回false。
array_multisort | array1_sort_flags 增加 SORT_NATURAL 和 SORT_FLAG_CASE 选项。
date_default_timezone_get | 不再使用 TZ 来推测时区。
date_default_timezone_get | 不再根据操作系统的信息来推测时区，因为这是不可靠的。
dns_get_record | 增加了参数raw。
empty | 检查非数字的字符串偏移量会返回 true.
filter_input_array | 添加 add_empty 参数.
filter_var_array | 添加 add_empty 参数。
get_html_translation_table | The default value for the encoding parameter was changed to UTF-8.
get_html_translation_table | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
get_magic_quotes_runtime | 总是返回 false，因为魔术引号（magic quotes）功能已经从 PHP 中移除。
getallheaders | 此函数可用于 FastCGI。 此前仅在PHP以 Apache 模块方式运行时支持。
htmlentities | encoding 参数的默认值改成 UTF-8。
htmlentities | 增加常量 ENT_SUBSTITUTE、 ENT_DISALLOWED、 ENT_HTML401、 ENT_XML1、 ENT_XHTML、 ENT_HTML5。
htmlspecialchars | encoding 参数的默认值改成 UTF-8。
htmlspecialchars | 增加常量 ENT_SUBSTITUTE、 ENT_DISALLOWED、 ENT_HTML401、 ENT_XML1、 ENT_XHTML、 ENT_HTML5。
htmlspecialchars_decode | 增加了 ENT_HTML401、ENT_XML1、 ENT_XHTML 和 ENT_HTML5 等常量。
http_build_query | 加入了 enc_type 参数。
iconv | 这个版本起，字符非法时候会返回 false，除非在输出字符里指定了 //IGNORE 。 在之前版本，它会返回一部分字符串。
imagewebp | 支持把 resource 流作为 to 参数传入。
isset | 检查字符的非数字偏移量将会返回 false。
json_decode | JSON_BIGINT_AS_STRING, and JSON_OBJECT_AS_ARRAY options were added.
json_decode | The options parameter was added.
number_format | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.
openssl_decrypt | 将 raw_output 更改至 options。
openssl_encrypt | raw_output 改到 options。
scandir | sorting_order now accepts constants. Any nonzero value caused descending order in previous versions.
session_set_save_handler | 新增用来实现自定义会话处理器的接口 SessionHandlerInterface； 新增 PHP 内部会话处理器类：SessionHandler。
5.3.15, 5.4.5 | Collator::getSortKey | Sort keys do no longer contain any NUL bytes.
5.3.9 | DateTime::createFromFormat | 新增 format 格式字符串中对于 + 格式字符的支持。
5.3.7 | crypt | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
5.3.6 | array_product | 空数组现在会产生 1，而之前此函数处理空数组会产生 0。
5.3.4 | get_html_translation_table | The encoding parameter was added.
rawurlencode | 因为 rawurlencode 使用了 EBCDIC，所以波浪线字符不会再被编码。
strip_tags | strip_tags ignores self-closing XHTML tags in allowable_tags.
5.3.3 | openssl_decrypt | 添加 iv 参数。
openssl_encrypt | 增加 iv 参数。
parse_url | 在 URL 解析失败时将不会产生 E_WARNING 级别的错误。
5.3.2 | crypt | 基于 Ulrich Drepper 的实现，新增基于 SHA-256 算法和 SHA-512 算法的 crypt。
crypt | 修正了 Blowfish 算法由于非法循环导致的问题，返回“失败”字符串（“*0” 或 “*1”）而不是转而使用 DES 算法。
flock | 在文件资源句柄关闭时不再自动解锁。现在要解锁必须手动进行。
5.3.1 | get_defined_constants | 仅作用于 Windows：内核常量归类到 Core，之前是 mhash。
5.3.0 起 | get_class | object 默认参数现在是 null ，所以，现在传入 null 到 object 参数时，和没传参数的结果一样。
5.3.0 | DateTime::__construct | 如果 time 参数不是一个有效的 日期/时间格式， 会抛出异常。 在之前的版本中是会发出一个错误。
DateTimeZone::listIdentifiers | 添加可选的 what 和 country 参数。
acosh | This function is now available on all platforms
array_multisort | array1_sort_flags 增加选项 SORT_LOCALE_STRING。
array_search | As with all internal PHP functions as of 5.3.0, array_search returns null if invalid parameters are passed to it.
asinh | 此函数在所有平台上均可用
atanh | 此函数在所有平台上都可以用了
call_user_func | 对面向对象里面的关键字的解析有所增强。在此之前，使用两个冒号来连接一个类和里面的一个方法，把它作为参数来作为回调函数的话，将会发出一个E_STRICT的警告，因为这个传入的参数被视为静态方法。
call_user_func_array | 对面向对象里面的关键字的解析有所增强。在此之前，使用两个冒号来连接一个类和里面的一个方法，把它作为参数来作为回调函数的话，将会发出一个E_STRICT的警告，因为这个传入的参数被视为静态方法。
checkdnsrr | 这个函数在Windows平台上也可以使用了。
clearstatcache | 增加了可选的 clear_realpath_cache 和 filename 参数.
crypt | PHP 现在包含了它自己的 MD5 Crypt 实现，包括标准 DES 算法，扩展的 DES 算法以及 Blowfish 算法。如果系统缺乏相应的实现，那么 PHP 将使用它自己的实现。
date_default_timezone_set | 现在会抛出 E_WARNING 而不是 E_STRICT。
dns_get_record | 在此版本之前，如果给参数authns传入值，则必须同时传入addtl的值。
dns_get_record | 可以是在windows平台上使用这个函数了。
expm1 | 此函数在所有平台上均可用
fgetcsv | 增加了 escape 参数。
fnmatch | 此函数开始在 Windows 平台上生效。
func_get_arg | 该函数可以在参数列表中使用。
func_get_arg | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns false. （不知道如何翻译跟好，直接参考例2即可明白）
func_get_args | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns false. （不知道如何翻译跟好，直接参考例2即可明白）
func_get_args | 该函数可以在参数列表中使用。
func_num_args | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns -1.
func_num_args | This function can now be used in parameter lists.
get_cfg_var | get_cfg_var 被修复，能够返回 "array" 的 ini 选项。
get_defined_constants | 内核常量归类为 Core，之前是 internal。在 Windows 上，内核常量归类到 mhash。
get_object_vars | This function now returns NULL if the object isn't an object.
getimagesize | Added icon support.
getmxrr | Windows 平台上也能用这个函数了。
htmlentities | 增加常量 ENT_IGNORE。
htmlspecialchars | 增加常量 ENT_IGNORE。
imagecolorclosesthwb | 在 Windows 平台上可用
imagefilter | Pixelation support (IMG_FILTER_PIXELATE) was added.
ini_get | 当配置项不存在，之前会返回空字符串，现在会返回 false。
ini_get_all | 增加参数 details。
json_decode | Added the optional depth. The default recursion depth was increased from 128 to 512
link | 该功能在 Windows 平台下开始有效（Vista、 Server 2008 或更高版本）。
linkinfo | Windows 平台上开始可用（Vista、Server 2008 或更高版本）。
log1p | 此函数在所有平台上均可用
mcrypt_create_iv | 不再需要提前调用 srand 函数， 由本函数自动完成调用。
mcrypt_create_iv | MCRYPT_DEV_RANDOM 和 MCRYPT_DEV_URANDOM 在 Windows 平台也可用了。
mktime | mktime now throws E_DEPRECATED notice if the is_dst parameter is used.
nl2br | 新增可选的 is_xhtml 参数。在此之前，总是插入 '<br />'。
openssl_open | 添加了 method 参数
openssl_seal | 添加 method 变量。
property_exists | This function checks the existence of a property independent of accessibility.
rawurlencode | 现在符合了RFC 3986。
readlink | 此函数在 Windows 平台下可用（Vista、Server 2008 或更高版本）。
register_tick_function | Ticks are now supported on threaded web server modules.
round | 引入了 mode 参数
session_start | 如果函数调用失败返回 false， 之前版本返回了 true。
setlocale | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.
stream_context_create | 增加了可选参数 params 。
stream_socket_pair | 这个函数在windows平台不可用
stristr | 新增可选的 before_needle 参数。
strlen | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.
strstr | 新增可选的 before_needle 参数。
symlink | 此函数在 Windows 平台上可用（Vista、Server 2008 或更高版本）。
time_nanosleep | 至此之后该函数在Windows平台下可用。
time_sleep_until | 自此，函数在Windows平台可用。
5.2.11 | get_defined_constants | categorize 参数现在可以合适得被处理。 在此之前，categorize 被解释为 !is_null($categorize)，导致任何非 null 的值会强制常量分类。
5.2.10 | array_unique | 修改回 sort_flags 的默认值为 SORT_STRING。
ip2long | 再此之前的版本, ip2long 有时会返回即使这不是一个IPV4的标准地址的数字地址。
natsort | 用零填充的数字字符串 (例如 '00005')现在本质上会忽略掉填充的前道零。
5.2.9 | array_unique | 增加可选选项sort_flags，默认值 SORT_REGULAR。 5.2.9 之前，此函数内部使用 SORT_STRING 排序。
5.2.7 | round | round 的内部运作修改符合 C99 的标准。
5.2.6 | fopen | 增加了选项 'c' 和 'c+'
5.2.5 | addcslashes | The escape sequences \v and \f were added.
imagefilter | Alpha support for IMG_FILTER_COLORIZE was added.
5.2.4 | checkdnsrr | 增加了TXT的记录类型。
stream_wrapper_register | 添加 flags 参数.
5.2.3 | getimagesize | Read errors generated by this function downgraded to E_NOTICE from E_WARNING.
htmlentities | 增加参数 double_encode。
htmlspecialchars | 增加参数 double_encode。
json_decode | The nesting limit was increased from 20 to 128
PDOStatement::getColumnMeta | table 字段
5.2.2 - 5.2.6 | substr | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.
5.2.2 | ftp_ssl_connect | 以前版本中，如果无法使用 SSL 连接，将会返回一个非 SSL 的连接， 在 5.2.2 版本中修改为返回 false
phpinfo | 增加了“已加载的配置文件”信息，之前只存在“配置文件路径(php.ini)"。
proc_terminate | 之前的版本被用来销毁进程 resource。
token_get_all | Line numbers are returned in element 2
5.2.1 | json_decode | Added support for JSON decoding of basic types.
memory_get_peak_usage | 使用此函数无需在编译时加上 --enable-memory-limit 选项。
memory_get_usage | 不需要在编译时使用 --enable-memory-limit 选项就能够使用这个函数。
mt_srand | The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.
proc_open | 为 other_options 参数增加 bypass_shell 选项。
5.2.0 | base64_decode | 增加了 strict 。
curl_multi_info_read | msgs_in_queue被加入。
imagettftext | It is now possible to specify an hexadecimal entity in text.
mb_strrpos | 增加了可选参数 offset。
memory_get_peak_usage | 添加参数 real_usage。
memory_get_usage | 增加了参数 real_usage。
openssl_verify | 添加了 signature_alg 参数。
pathinfo | 添加了常量 PATHINFO_FILENAME。
session_get_cookie_params | 在返回数组中加入 “httponly”。
session_set_cookie_params | 加入 httponly 参数。
setrawcookie | 增加了 httponly 参数。
simplexml_load_file | The optional parameter is_prefix was added.
simplexml_load_string | The optional parameter is_prefix was added.
PDOStatement::execute | input_parameters 中的键名必须和 SQL 中声明的相匹配。PHP 5.2.0 之前默认忽略。
SimpleXMLElement::attributes | The optional parameter is_prefix was added.
SimpleXMLElement::__construct | Added the ns and is_prefix parameters.
5.1.3 | curl_getinfo | 引入CURLINFO_HEADER_OUT.
get_headers | 自 PHP 5.1.3 起本函数使用默认的流上下文，其可以用 stream_context_get_default 函数设定和修改。
http_build_query | 方括号也会被转义。
5.1.2 | date_default_timezone_set | 本版本开始验证 timezone_identifier 参数。
http_build_query | 加入了参数 arg_separator。
parse_url | 增加了参数 component。
SimpleXMLElement::__construct | Added the options and data_is_url parameters.
5.1.1 | date | format 参数标准的可用日期/时间格式常量见： 常量
5.1.0 | ctype_digit | 在 PHP 5.1.0 之前，当 text 是一个空字符串的时候，该函数将返回 true 。
date | 现在发布 E_STRICT 和 E_NOTICE 时区错误。
date | 时间戳的有效取值范围为 GMT 时间的 1901 年 12 月 13 日至 GMT 时间的 2038 年 1 月 19 日。 （32 位有符号整数的取值范围）。 但是，在 PHP 5.1.0 之前的版本，在某些系统（例如 Windows）上有效取值范围为 1970 年 1 月 1 日至 2038 年 1 月 19 日。
date_sunrise | 现在发布 E_STRICT 和 E_NOTICE 时区错误。
date_sunset | 现在发布 E_STRICT 和 E_NOTICE 时区错误。
explode | 支持负数的 limit
file_get_contents | Added the offset and maxlen parameters.
file_put_contents | 添加了对 LOCK_EX 的支持和 data 参数处理 stream 资源的功能。
gettimeofday | 增加了参数 return_float。
imagerotate | 新增： ignore_transparent 。
localtime | 现在发布 E_STRICT 和 E_NOTICE 时区错误。
md5_file | 函数改用流 API。这意味着能够配合封装器使用该函数，比如 md5_file('http://example.com/..')。
mktime | 现在发布 E_STRICT 和 E_NOTICE 时区错误。
mktime | When called with no arguments, mktime throws E_STRICT notice. Use the time function instead.
mktime | is_dst 参数被废弃。出错时函数返回 false 而不再是 -1。修正了本函数可以接受年月日参数全为零。
stream_get_contents | 增加参数 offset 。
strftime | 现在发布 E_STRICT 和 E_NOTICE 时区错误。
5.0.0 | apache_get_modules | 可用于Apache 1或PHP Apache 2 filter API。 在此之前, 只可用于 Apache 2 handler API。
apache_get_version | 可用于 Apache 2 filter API.
checkdnsrr | 增加了AAAA的记录类型。
fgetss | 参数 length 从 此开始可选。
file_get_contents | Added context support.
file_put_contents | Added context support
is_executable | is_executable 开始可用以于 Windows。
jdtojewish | 增加了参数 fl。
opendir | path 支持 ftp:// URL wrapper
socket_create | 增加 AF_INET6 支持。
strip_tags | strip_tags 变为二进制安全的。
strrpos | 引入 offset 参数。
strrpos | 参数 needle 可以是一个多字符的字符串。

User Contributed Notes

There are no user contributed notes for this page.


CHM 版本

  • 关于此版本
  • Using PHP Manual CHM Edition
    • The HTML Help Toolbar
    • The Navigation Pane
    • Keyboard Shortcuts
  • The Full Text Search
    • General searching rules
    • Searching for words or phrases
    • Defining search terms
    • Using nested expressions when searching
  • Integrating the PHP Manual

User Contributed Notes

There are no user contributed notes for this page.


关于此版本

PHP 手册的 Windows HTML Help 版本是针对开发人员的，他们希望每时每刻都有手册在手头，并且不需要等待远程页面下载就可以阅读手册以及用户注解。此版本给你完整的手册内容加上用户注解，以及一些很棒的特色。这是由我们用来生成此格式的脚本产生的阅读程序以及其他人在皮肤样式上的贡献所提供的。

PHP 手册的此发行包中由很多文件组成，包括主要的手册文件 php_manual_zh.chm。你可以通过双击此文件查看本手册（你可能已经猜到了）。 你可能也会在目录中看到 php_manual_zh.chw 文件，该文件是在你第一次使用索引标签时生成的，包含了手册页面的索引。

对那些对 Microsoft HTML Help 的技术细节有兴趣的人来说，» http://www.helpware.net/ 是一个很棒的资源。有关 Microsoft 帮助格式和服务历史中的 Windows HTML Help 的更多信息与配置，见 » WinWriters article。

User Contributed Notes

There are no user contributed notes for this page.


Using PHP Manual CHM Edition

Table of Contents

  • The HTML Help Toolbar
  • The Navigation Pane
  • Keyboard Shortcuts

When you double click on a CHM, a HTML Help Viewer window opens with three panes. On the left side of the window is the Navigation pane. It contains four navigational tabs: the Contents, Index, Search and Favorites tabs. On the right side of the window is the Topic pane. It displays the selected help topic, or the default help topic on startup. The help pages are all separate HTML files, your Internet Explorer displays the pages in the Topic pane. The third pane is the toolbar, which is located below the help window title bar. You can adjust the horizontal layout with dragging the vertical border between the Navigation pane and the Topic pane.

Note, that when you open the CHM the first time, it may appear in a strange position and size. From then, Windows remembers the window position, size and the last opened tab. All these including your favorites are stored in a file named hh.dat. If you move your file to another directory, all these remembered settings will be lost (including your favorites listing!). If you replace your CHM file with a new one, with the same name, this is not a problem though. The file names and path values are stored in hh.dat.

User Contributed Notes

There are no user contributed notes for this page.


The HTML Help Toolbar

The HTML Help Toolbar contains the following icons, when you view the PHP Manual:

  • Hide/Show - Hides/shows the navigation pane.
  • Locate - Locates a topic in the contents tab (in case you reached a topic with search, index or favorites, and would like to see where it is in the table of contents tree view).
  • Back - Goes back in the history.
  • Forward - Goes forward in the history.
  • Refresh - Reloads the current page.
  • Home - Opens the startup page of the CHM.
  • Print - Opens the print dialog box.
  • Options - Provides a dropdown with more options.
Using this toolbar is really easy, many of the toolbar icons are strongly related to their Internet Explorer equivalents.

User Contributed Notes

There are no user contributed notes for this page.


The Navigation Pane

The Navigation Pane contains four navigational tabs: the Contents, Index, Search and Favorites tabs. These all provide different methods to access a topic in the help file.

  • The contents tab reveals a tree like table of contents, where you can navigate to the desired topic by opening and closing parts of the tree. You can even access the deepest sections using this TOC. If you right click on an item here and choose "Print...", you'll have the option to print the selected topic or the selected topic and all subtopics. However printing is not the initial goal of this representation of the manual (the PDF version is suitable for printing).
  • The index tab lists a huge number of "keywords" (actually manual page titles). You can pick one, or start to type a keyword, see the list adjusting to your input, and then click on a topic, or press enter if the selected topic is the one you would like to see.
  • The search tab shows one of the most powerful features of the HTML Help Viewer, the full text search (also known as FTS). Here you can type in your search expression, optionally connecting words with AND/OR/NEAR/NOT. Before you click 'List topics', you can also set some options at the bottom. After the search results are displayed, you'll realize that manual text and user note results are separated. To sort out the two types, click on the 'Location' column header. Now from the search results list, you can pick a topic, and see it's page. The keywords you searched for are highlighted on the page.
  • The favorites tab enables you to store your most used topics in a list, easily accessible. Here you can see the list, add the current topic to it, remove one, or display a selected item. You can also specify your own title for the favorite, by typing it into the 'Current topic:' box. The user note page titles are prepended with a 'N:' string so you can distinguish them from normal manual pages in the favorites listing.

User Contributed Notes

There are no user contributed notes for this page.


Keyboard Shortcuts

There are many keyboard shortcuts you can use to increase your productivity. Many users find it more appropriate to use these keyboard shortcuts to access topics, instead of clicking.

General Help Viewer Shortcuts
To | Press
Close the Help Viewer | ALT+F4
Display the Options menu | ALT+O
Hide or show the Navigation pane | ALT+O, and then T
Print a topic | ALT+O, and then P
Move back to the previous topic | ALT+LEFT ARROW
Move forward to the next topic (provided you have viewed it just previously) | ALT+RIGHT ARROW
Turn on or off search highlighting. | ALT+O, and then O
Return to the help file home page | ALT+O, and then H
Switch between the Navigation pane and the Topic pane | F6
Scroll through all the links in a topic or through all the options on a Navigation pane tab | TAB
Display context (right click) menu | SHIFT+F10
Contents Tab Shortcuts
To | Press
Display the Contents tab | ALT+C
Open and close a book or folder | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic | DOWN ARROW and UP ARROW
Display the selected topic | ENTER
Index Tab Shortcuts
To | Press
Display the Index tab | ALT+N
Type a keyword to search for | ALT+W, and then type the word
Select a keyword in the list | UP ARROW and DOWN ARROW
Display the associated topic | ENTER or ALT+D
Search Tab shortcuts
To | Press
Display the Search tab | ALT+S
Type a keyword to search for | ALT+W, and then type the word
Start a search | ALT+L
Select a topic in the results list | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Search for a keyword in the result list of a prior search | ALT+U
Search for words similar to the keyword. For example, to find words like "running" and "runs" for the keyword "run" | ALT+M
Only search through topic titles | ALT+R
Favorites Tab Shortcuts
To | Press
Display the Favorites tab | ALT+I
Add the currently displayed topic to the Favorites list | ALT+A
Select a topic in the Favorites list | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Remove the selected topic from the list | ALT+R
Topic Pane Shortcuts
To | Press
Index Lookup | Select the words you would like to look up and press F1
Find on page | CTRL+F, and then adjust options
Refresh page | F5

User Contributed Notes

There are no user contributed notes for this page.


The Full Text Search

Table of Contents

  • General searching rules
  • Searching for words or phrases
  • Defining search terms
  • Using nested expressions when searching

This edition of the PHP Manual includes an advanced full text search possibility provided by the viewer application. This enables users to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.

User Contributed Notes

There are no user contributed notes for this page.


General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.
  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.
  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.
  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

Note:

If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."

User Contributed Notes

There are no user contributed notes for this page.


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

Word and phrase searches
Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase | "new operator" or new operator | Topics that contain the literal phrase "new operator" and all its grammatical variations. Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.
Wildcard expressions | esc* or HT?? | Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term. Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

Note:

Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".

User Contributed Notes

There are no user contributed notes for this page.


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

Search operators
Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

Note:

The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.

User Contributed Notes

There are no user contributed notes for this page.


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.
  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".
  • You cannot nest expressions more than five levels deep.

User Contributed Notes

There are no user contributed notes for this page.


Integrating the PHP Manual

Note:

The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

Note:

All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name collisions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a » HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

If you would like to integrate the manual into an IDE without direct support for the PHP manual (actually the underscore to hyphen conversion), you can use the included _function.html file to access a function page. This file is simply a redirector, and can be parameterized via the URL, as _function.html#mysql_close. This page will redirect you to the mysql_close function page (function.mysql-close.html) automatically. You can provide the full path of this file if your IDE supports context sensitive help, and provide the IDE specified string as the parameter. An example for this is the UltraEdit 9 intergation (see the edition's website).

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at » http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at » http://www.microsoft.com/download/en/details.aspx?id=21138.

User Contributed Notes

There are no user contributed notes for this page.