Vérifie si la propriété est celle par défaut

  • « ReflectionProperty::hasType
  • ReflectionProperty::isInitialized »
  • PHP Manual
  • ReflectionProperty
  • Vérifie si la propriété est celle par défaut

ReflectionProperty::isDefault

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isDefault — Vérifie si la propriété est celle par défaut

Description

public ReflectionProperty::isDefault(): bool

Vérifie si la propriété a été déclarée au moment de la compilation, ou si la propriété a été déclarée dynamiquement au moment de l'exécution.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true si la propriété a été déclarée lors de la compilation ou false si elle a été déclarée au moment de l'exécution.

Exemples

Exemple #1 Exemple avec ReflectionClass::isDefault()

<?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());
?>

L'exemple ci-dessus va afficher :

bool(true)
bool(false)

Voir aussi

  • ReflectionProperty::getValue() - Récupère la valeur de la propriété

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si une propriété est initialisée

  • « ReflectionProperty::isDefault
  • ReflectionProperty::isPrivate »
  • PHP Manual
  • ReflectionProperty
  • Vérifie si une propriété est initialisée

ReflectionProperty::isInitialized

(PHP 7 >= 7.4.0, PHP 8)

ReflectionProperty::isInitialized — Vérifie si une propriété est initialisée

Description

public ReflectionProperty::isInitialized(?object $object = null): bool

Vérifie si une propriété est initialisée.

Liste de paramètres

object

Si la propriété n'est pas statique un objet doit être fourni pour récupérer la propriété depuis.

Valeurs de retour

Retourne false pour les propriétés typées antérieur à leur initialisation, et pour les propriétés qui ont était explicitement unset(). Pour toutes les autres propriétés true sera retourné.

Erreurs / Exceptions

Lance une ReflectionException si la propriété est inaccessible. Il est possible de rendre une propriété protégée ou privée accessible en utilisant ReflectionProperty::setAccessible().

Historique

Version | Description
8.0.0 | object est désormais nullable.

Exemples

Exemple #1 Exemple de ReflectionProperty::isInitialized()

<?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));
?>

L'exemple ci-dessus va afficher :

bool(false)
bool(true)

Voir aussi

  • ReflectionProperty::hasType() - Vérifie si la propriété à un type

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si la propriété est privée

  • « ReflectionProperty::isInitialized
  • ReflectionProperty::isPromoted »
  • PHP Manual
  • ReflectionProperty
  • Vérifie si la propriété est privée

ReflectionProperty::isPrivate

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isPrivate — Vérifie si la propriété est privée

Description

public ReflectionProperty::isPrivate(): bool

Vérifie si la propriété est privée.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true si la propriété est privée, false sinon.

Voir aussi

  • ReflectionProperty::isPublic() - Vérifie si la propriété est publique
  • ReflectionProperty::isProtected() - Vérifie si la propriété est protégée
  • ReflectionProperty::isReadOnly() - Checks if property is readonly
  • ReflectionProperty::isStatic() - Vérifie si la propriété est statique

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is promoted

  • « ReflectionProperty::isPrivate
  • ReflectionProperty::isProtected »
  • PHP Manual
  • ReflectionProperty
  • Checks if property is promoted

ReflectionProperty::isPromoted

(PHP 8)

ReflectionProperty::isPromoted — Checks if property is promoted

Description

public ReflectionProperty::isPromoted(): bool

Checks whether the property is promoted

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true if the property is promoted, false otherwise.

Exemples

Exemple #1 ReflectionProperty::isPromoted() example

<?php
class Foo {
public $baz;

public function __construct(public $bar) {}
}

$o = new Foo(42);
$o->baz = 42;

$ro = new ReflectionObject($o);
var_dump($ro->getProperty('bar')->isPromoted());
var_dump($ro->getProperty('baz')->isPromoted());
?>

L'exemple ci-dessus va afficher :

bool(true)
bool(false)

Voir aussi

  • ReflectionProperty::isDefault() - Vérifie si la propriété est celle par défaut
  • ReflectionProperty::isInitialized() - Vérifie si une propriété est initialisée
  • ReflectionProperty::getValue() - Récupère la valeur de la propriété

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si la propriété est protégée

  • « ReflectionProperty::isPromoted
  • ReflectionProperty::isPublic »
  • PHP Manual
  • ReflectionProperty
  • Vérifie si la propriété est protégée

ReflectionProperty::isProtected

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isProtected — Vérifie si la propriété est protégée

Description

public ReflectionProperty::isProtected(): bool

Vérifie si la propriété est protégée.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true si la propriété est protégée, false sinon.

Voir aussi

  • ReflectionProperty::isPublic() - Vérifie si la propriété est publique
  • ReflectionProperty::isPrivate() - Vérifie si la propriété est privée
  • ReflectionProperty::isReadOnly() - Checks if property is readonly
  • ReflectionProperty::isStatic() - Vérifie si la propriété est statique

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();
?>


Vérifie si la propriété est publique

  • « ReflectionProperty::isProtected
  • ReflectionProperty::isReadOnly »
  • PHP Manual
  • ReflectionProperty
  • Vérifie si la propriété est publique

ReflectionProperty::isPublic

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isPublic — Vérifie si la propriété est publique

Description

public ReflectionProperty::isPublic(): bool

Vérifie si la propriété est publique.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true si la propriété est publique, false sinon.

Voir aussi

  • ReflectionProperty::isProtected() - Vérifie si la propriété est protégée
  • ReflectionProperty::isPrivate() - Vérifie si la propriété est privée
  • ReflectionProperty::isReadOnly() - Checks if property is readonly
  • ReflectionProperty::isStatic() - Vérifie si la propriété est statique

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is readonly

  • « ReflectionProperty::isPublic
  • ReflectionProperty::isStatic »
  • PHP Manual
  • ReflectionProperty
  • Checks if property is readonly

ReflectionProperty::isReadOnly

(PHP 8 >= 8.1.0)

ReflectionProperty::isReadOnly — Checks if property is readonly

Description

public ReflectionProperty::isReadOnly(): bool

Checks whether the property is readonly.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true if the property is readonly, false otherwise.

Voir aussi

  • ReflectionProperty::isPublic() - Vérifie si la propriété est publique
  • ReflectionProperty::isProtected() - Vérifie si la propriété est protégée
  • ReflectionProperty::isPrivate() - Vérifie si la propriété est privée
  • ReflectionProperty::isStatic() - Vérifie si la propriété est statique

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si la propriété est statique

  • « ReflectionProperty::isReadOnly
  • ReflectionProperty::setAccessible »
  • PHP Manual
  • ReflectionProperty
  • Vérifie si la propriété est statique

ReflectionProperty::isStatic

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isStatic — Vérifie si la propriété est statique

Description

public ReflectionProperty::isStatic(): bool

Vérifie si la propriété est statique.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true si la propriété est statique, false sinon.

Voir aussi

  • ReflectionProperty::isPublic() - Vérifie si la propriété est publique
  • ReflectionProperty::isProtected() - Vérifie si la propriété est protégée
  • ReflectionProperty::isPrivate() - Vérifie si la propriété est privée
  • ReflectionProperty::isReadOnly() - Checks if property is readonly

User Contributed Notes

There are no user contributed notes for this page.


Définit l'accessibilité d'une propriété

  • « ReflectionProperty::isStatic
  • ReflectionProperty::setValue »
  • PHP Manual
  • ReflectionProperty
  • Définit l'accessibilité d'une propriété

ReflectionProperty::setAccessible

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionProperty::setAccessible — Définit l'accessibilité d'une propriété

Description

public ReflectionProperty::setAccessible(bool $accessible): void

Active l'accès à une propriété protégée ou privée via les méthodes ReflectionProperty::getValue() et ReflectionProperty::setValue().

Note: À partir de PHP 8.1.0, l'appel à cette méthode n'a aucun effet; toutes les propriétés sont accessibles par défaut.

Liste de paramètres

accessible

true pour permettre l'accès, ou false.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Définition d'une classe simple

<?php
class MyClass
{
private $foo = 'bar';
}
$property = new ReflectionProperty("MyClass", "foo");
$property->setAccessible(true);
$obj = new MyClass();
echo $property->getValue($obj);
echo $obj->foo;
?>

Résultat de l'exemple ci-dessus est similaire à :

bar
Fatal error: Uncaught Error: Cannot access private property MyClass::$foo in /in/WJqTv:12

Voir aussi

  • ReflectionProperty::isPrivate() - Vérifie si la propriété est privée
  • ReflectionProperty::isProtected() - Vérifie si la propriété est protégée

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);
?>


Définit la valeur de la propriété

  • « ReflectionProperty::setAccessible
  • ReflectionProperty::__toString »
  • PHP Manual
  • ReflectionProperty
  • Définit la valeur de la propriété

ReflectionProperty::setValue

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::setValue — Définit la valeur de la propriété

Description

public ReflectionProperty::setValue(object $object, mixed $value): void
public ReflectionProperty::setValue(mixed $value): void

Définit (modifie) la valeur de la propriété.

Note: À partir de PHP 8.3.0, l'appel de cette méthode avec un seul argument est obsolète. Utilisez plutôt ReflectionClass::setStaticPropertyValue().

Liste de paramètres

object

L'objet à utiliser dans le cas d'une propriété non statique. Si la propriété est statique une valeur de null doit être fournit.

value

La nouvelle valeur.

Valeurs de retour

Aucune valeur n'est retournée.

Historique

Version | Description
8.3.0 | L'appel de cette méthode avec un seul argument est obsolète. Utilisez plutôt ReflectionClass::setStaticPropertyValue() pour modifier les propriétés statiques.
8.1.0 | Les propriétés privées et protégées sont immédiatement accessibles par ReflectionProperty::setValue(). Auparavant, elles devaient être rendues accessibles en appelant ReflectionProperty::setAccessible(), sinon une ReflectionException était déclenchée.

Exemples

Exemple #1 Exemple avec ReflectionProperty::setValue()

<?php
class Foo {
public static $staticProperty;

public $property;
protected $privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

// À partir de PHP 8.3, setValue ne devrait plus être utilisé pour définir la valeur d'une propriété statique, utilisez plutôt setStaticPropertyValue() à la place
$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); // Seulement nécessaire avant PHP 8.1.0.
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

L'exemple ci-dessus va afficher :

string(3) "foo"
string(3) "bar"
string(6) "foobar"

Voir aussi

  • ReflectionProperty::getValue() - Récupère la valeur de la propriété
  • ReflectionProperty::setAccessible() - Définit l'accessibilité d'une propriété
  • ReflectionClass::setStaticPropertyValue() - Définit la valeur d'une propriété statiques

User Contributed Notes

p stewart imperial ac uk 16-Dec-2022 03:18
setValue can be used for readonly properties, but only if the property has not yet been initialised:

<?php

class Person
{
    private readonly int $age;
    public function __construct(array $props = []) {
        if (isset($props['age'])) {
            $this->age = (int)$props['age'];
        }
    }
}

$personWithKnownAge = new Person(['age' => 50]);

$reflection = new ReflectionProperty($personWithKnownAge, 'age');
$reflection->setValue($personWithKnownAge, 10); // Fails - Age is already initialised, value cannot be changed.

$personWithUnknownAge = new Person();

$reflection = new ReflectionProperty($personWithUnknownAge, 'age');
$reflection->setValue($personWithUnknownAge, 10); // Succeeeds - Age is not yet initialised, value can be set.
?>

This can be useful for situations where it is desirable to initialise properties from outside of the defining class, for example an ORM setup where the parent class is responsible for setting properties on a model subclass instance.
temirkhan.nasukhov 10-Oct-2022 05:41
Keep in mind that setValue won't work for readonly properties.

<?php

class Person
{
    public function __construct(private readonly int $age) {}
}

$someOldPerson = new Person(80);

$reflection = new ReflectionProperty($someOldPerson, 'age');
$reflection->setValue($someOldPerson, 10); // Fatal error: Uncaught Error: Cannot modify readonly property Person::$age
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"
?>


Récupère une représentation textuelle

  • « ReflectionProperty::setValue
  • ReflectionType »
  • PHP Manual
  • ReflectionProperty
  • Récupère une représentation textuelle

ReflectionProperty::__toString

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::__toString — Récupère une représentation textuelle

Description

public ReflectionProperty::__toString(): string

Récupère une représentation textuelle de la propriété.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

La châine.

Voir aussi

  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


La classe ReflectionType

(PHP 7, PHP 8)

Introduction

La classe ReflectionType relate les informations à propos du type de retour d'une fonction. L'extension Reflection déclare les sous-types suivants :

  • ReflectionNamedType (à partir de PHP 7.1.0)
  • ReflectionUnionType (à partir de PHP 8.0.0)
  • ReflectionIntersectionType (à partir de PHP 8.1.0)

Synopsis de la classe

abstract class ReflectionType implements Stringable {
/* Méthodes */
public allowsNull(): bool
public __toString(): string
}

Historique

Version | Description
8.0.0 | ReflectionType est devenue abstraite et ReflectionType::isBuiltin() a été déplacée vers ReflectionNamedType::isBuiltin().

Sommaire

  • ReflectionType::allowsNull — Vérifie si null est permit
  • 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.


Vérifie si null est permit

  • « ReflectionType
  • ReflectionType::__toString »
  • PHP Manual
  • ReflectionType
  • Vérifie si null est permit

ReflectionType::allowsNull

(PHP 7, PHP 8)

ReflectionType::allowsNull — Vérifie si null est permit

Description

public ReflectionType::allowsNull(): bool

Vérifie si le paramètre accepte null.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true si null est permit, sinon false

Exemples

Exemple #1 Exemple avec ReflectionType::allowsNull()

<?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());

L'exemple ci-dessus va afficher :

bool(false)
bool(true)

Voir aussi

  • ReflectionNamedType::isBuiltin() - Vérifie si c'est un type intégré
  • ReflectionType::__toString() - To string
  • ReflectionParameter::getType() - Récupère le type du paramètre

User Contributed Notes

There are no user contributed notes for this page.


To string

  • « ReflectionType::allowsNull
  • ReflectionUnionType »
  • PHP Manual
  • ReflectionType
  • To string

ReflectionType::__toString

(PHP 7, PHP 8)

ReflectionType::__toString — To string

Avertissement

Cette fonction est OBSOLÈTE à partir de PHP 7.1.0. Dépendre de cette fonction est fortement déconseillé.

Description

public ReflectionType::__toString(): string

Récupère le nom du type du paramètre.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le type du paramètre.

Historique

Version | Description
7.1.0 | ReflectionType::__toString() a été rendu obsolète.

Exemples

Exemple #1 Exemple avec ReflectionType::__toString()

<?php
function someFunction(string $param) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

echo $reflectionParam->getType();

Résultat de l'exemple ci-dessus est similaire à :

string

Voir aussi

  • ReflectionNamedType::getName() - Récupère le nom du type en tant que chaîne
  • ReflectionNamedType::isBuiltin() - Vérifie si c'est un type intégré
  • ReflectionType::allowsNull() - Vérifie si null est permit
  • ReflectionUnionType::getTypes() - Returns the types included in the union type
  • ReflectionParameter::getType() - Récupère le type du paramètre

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.


The ReflectionUnionType class

(PHP 8)

Introduction

Synopsis de la classe

class ReflectionUnionType extends ReflectionType {
/* Méthodes */
public getTypes(): array
/* Méthodes héritées */
public ReflectionType::allowsNull(): bool
public ReflectionType::__toString(): string
}

Sommaire

  • ReflectionUnionType::getTypes — Returns the types included in the union type

User Contributed Notes

There are no user contributed notes for this page.


Returns the types included in the union type

  • « ReflectionUnionType
  • ReflectionGenerator »
  • PHP Manual
  • ReflectionUnionType
  • Returns the types included in the union type

ReflectionUnionType::getTypes

(PHP 8)

ReflectionUnionType::getTypes — Returns the types included in the union type

Description

public ReflectionUnionType::getTypes(): array

Returns the reflections of types included in the union type.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

An array of ReflectionType objects.

Exemples

Exemple #1 ReflectionUnionType::getTypes() example

<?php
function someFunction(int|float $number) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

var_dump($reflectionParam->getType()->getTypes());

Résultat de l'exemple ci-dessus est similaire à :

array(2) {
    [0] =>
    class ReflectionNamedType#4(0) {
    }
    [1] =>
    class ReflectionNamedType#5(0) {
    }
}

Voir aussi

  • ReflectionType::allowsNull() - Vérifie si null est permit
  • ReflectionParameter::getType() - Récupère le type du paramètre

User Contributed Notes

baptiste at pillot dot fr 08-Sep-2023 12:22
ReflectionUnionType::getTypes can return an array of ReflectionNamedType and/or ReflectionIntersectionType objects only.
baptiste at pillot dot fr 08-Sep-2023 12:12
Sorting :

Contrary to what one might expect, the returned array of ReflectionType objects will not be sorted in the same order than the types declared into the source code.

- Classes, interfaces, traits, iterable (replaced by Traversable), ReflectionIntersectionType objects, parent and self: these types will be returned first, in the order in which they were declared.
- static and all built-in types (iterable replaced by array) will come next. They will always be returned in this order: static, callable, array, string, int, float, bool (or false or true), null.

Notice that when used into an union type, iterable is an alias for Traversable|array. ReflectionUnionType::getTypes will return these both ReflectionNamedType objects, instead of a single one named 'iterable'.

Example :
<?php
class PC {}
class C extends PC {
    function f(): null|bool|float|int|parent|PC|string|iterable|(ReflectionClass&ReflectionProperty)|callable|static|self|C {}
}
echo join(', ', array_map(
    function($t) { return ($t instanceof ReflectionIntersectionType) ? '<intersection>' : $t->getName(); },
    (new ReflectionMethod('C', 'f'))->getReturnType()->getTypes()
)) . "\n";
?>

Will display :
parent, PC, Traversable, <intersection>, self, C, static, callable, array, string, int, float, bool, null

Try it: https://onlinephp.io/c/777c6


La classe ReflectionGenerator

(PHP 7, PHP 8)

Introduction

La classe ReflectionGenerator rapporte des informations à propos d'un générateur.

Synopsis de la classe

final class ReflectionGenerator {
/* Méthodes */
public __construct(Generator $generator)
public getExecutingFile(): string
public getExecutingGenerator(): Generator
public getExecutingLine(): int
public getFunction(): ReflectionFunctionAbstract
public getThis(): ?object
public getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array
}

Historique

Version | Description
8.0.0 | La classe est final maintenant.

Sommaire

  • ReflectionGenerator::__construct — Construit un objet ReflectionGenerator
  • ReflectionGenerator::getExecutingFile — Récupère le nom de fichier du générateur actuellement exécuté
  • ReflectionGenerator::getExecutingGenerator — Récupère l'objet Generator exécuté
  • ReflectionGenerator::getExecutingLine — Récupère la ligne actuellement exécutée du générateur
  • ReflectionGenerator::getFunction — Récupère le nom de fonction du générateur
  • ReflectionGenerator::getThis — Récupère la valeur de $this du générateur
  • ReflectionGenerator::getTrace — Récupère la trace du générateur exécutant

User Contributed Notes

There are no user contributed notes for this page.


Construit un objet ReflectionGenerator

  • « ReflectionGenerator
  • ReflectionGenerator::getExecutingFile »
  • PHP Manual
  • ReflectionGenerator
  • Construit un objet ReflectionGenerator

ReflectionGenerator::__construct

(PHP 7, PHP 8)

ReflectionGenerator::__construct — Construit un objet ReflectionGenerator

Description

public ReflectionGenerator::__construct(Generator $generator)

Construit un objet ReflectionGenerator.

Liste de paramètres

generator

Un objet generator.

Exemples

Exemple #1 Exemple avec ReflectionGenerator::__construct()

<?php

function gen()
{
yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

echo <<< output
{$reflectionGen->getFunction()->name}
Line: {$reflectionGen->getExecutingLine()}
File: {$reflectionGen->getExecutingFile()}
output;

Résultat de l'exemple ci-dessus est similaire à :

gen
Line: 5
File: /path/to/file/example.php

Voir aussi

  • ReflectionGenerator::getFunction() - Récupère le nom de fonction du générateur
  • ReflectionGenerator::getExecutingLine() - Récupère la ligne actuellement exécutée du générateur
  • ReflectionGenerator::getExecutingFile() - Récupère le nom de fichier du générateur actuellement exécuté

User Contributed Notes

There are no user contributed notes for this page.


Récupère le nom de fichier du générateur actuellement exécuté

  • « ReflectionGenerator::__construct
  • ReflectionGenerator::getExecutingGenerator »
  • PHP Manual
  • ReflectionGenerator
  • Récupère le nom de fichier du générateur actuellement exécuté

ReflectionGenerator::getExecutingFile

(PHP 7, PHP 8)

ReflectionGenerator::getExecutingFile — Récupère le nom de fichier du générateur actuellement exécuté

Description

public ReflectionGenerator::getExecutingFile(): string

Récupère le chemin complet et le nom de fichier du générateur actuellement exécuté.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le chemin complet et le nom de fichier du générateur actuellement exécuté.

Exemples

Exemple #1 Exemple avec ReflectionGenerator::getExecutingFile()

<?php

class GenExample
{
public function gen()
{
yield 1;
}
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "File: {$reflectionGen->getExecutingFile()}";

Résultat de l'exemple ci-dessus est similaire à :

File: /path/to/file/example.php

Voir aussi

  • ReflectionGenerator::getExecutingLine() - Récupère la ligne actuellement exécutée du générateur
  • ReflectionGenerator::getExecutingGenerator() - Récupère l'objet Generator exécuté

User Contributed Notes

There are no user contributed notes for this page.


Récupère l'objet Generator exécuté

  • « ReflectionGenerator::getExecutingFile
  • ReflectionGenerator::getExecutingLine »
  • PHP Manual
  • ReflectionGenerator
  • Récupère l'objet Generator exécuté

ReflectionGenerator::getExecutingGenerator

(PHP 7, PHP 8)

ReflectionGenerator::getExecutingGenerator — Récupère l'objet Generator exécuté

Description

public ReflectionGenerator::getExecutingGenerator(): Generator

Récupère l'objet Generator exécuté.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne l'objet Generator actuellement exécuté.

Exemples

Exemple #1 Exemple avec ReflectionGenerator::getExecutingGenerator()

<?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());

Résultat de l'exemple ci-dessus est similaire à :

bool(true)
int(1);

Voir aussi

  • ReflectionGenerator::getExecutingLine() - Récupère la ligne actuellement exécutée du générateur
  • ReflectionGenerator::getExecutingFile() - Récupère le nom de fichier du générateur actuellement exécuté

User Contributed Notes

There are no user contributed notes for this page.


Récupère la ligne actuellement exécutée du générateur

  • « ReflectionGenerator::getExecutingGenerator
  • ReflectionGenerator::getFunction »
  • PHP Manual
  • ReflectionGenerator
  • Récupère la ligne actuellement exécutée du générateur

ReflectionGenerator::getExecutingLine

(PHP 7, PHP 8)

ReflectionGenerator::getExecutingLine — Récupère la ligne actuellement exécutée du générateur

Description

public ReflectionGenerator::getExecutingLine(): int

Récupère la ligne actuellement exécutée du générateur.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le numéro de ligne de la déclaration actuellement exécutée dans le générateur.

Exemples

Exemple #1 Exemple avec ReflectionGenerator::getExecutingLine()

<?php

class GenExample
{
public function gen()
{
yield 1;
}
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "Line: {$reflectionGen->getExecutingLine()}";

Résultat de l'exemple ci-dessus est similaire à :

Line: 7

Voir aussi

  • ReflectionGenerator::getExecutingGenerator() - Récupère l'objet Generator exécuté
  • ReflectionGenerator::getExecutingFile() - Récupère le nom de fichier du générateur actuellement exécuté

User Contributed Notes

There are no user contributed notes for this page.


Récupère le nom de fonction du générateur

  • « ReflectionGenerator::getExecutingLine
  • ReflectionGenerator::getThis »
  • PHP Manual
  • ReflectionGenerator
  • Récupère le nom de fonction du générateur

ReflectionGenerator::getFunction

(PHP 7, PHP 8)

ReflectionGenerator::getFunction — Récupère le nom de fonction du générateur

Description

public ReflectionGenerator::getFunction(): ReflectionFunctionAbstract

Permet l'obtention du nom de fonction du générateur en retournant une classe dérivé depuis ReflectionFunctionAbstract.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne une classe ReflectionFunctionAbstract. Ceci sera ReflectionFunction pour les fonctions, ou ReflectionMethod pour les méthodes.

Exemples

Exemple #1 Exemple avec ReflectionGenerator::getFunction()

<?php

function gen()
{
yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getFunction());

Résultat de l'exemple ci-dessus est similaire à :

object(ReflectionFunction)#3 (1) {
  ["name"]=>
  string(3) "gen"
}

Voir aussi

  • ReflectionGenerator::getThis() - Récupère la valeur de $this du générateur
  • ReflectionGenerator::getTrace() - Récupère la trace du générateur exécutant

User Contributed Notes

There are no user contributed notes for this page.


Récupère la valeur de $this du générateur

  • « ReflectionGenerator::getFunction
  • ReflectionGenerator::getTrace »
  • PHP Manual
  • ReflectionGenerator
  • Récupère la valeur de $this du générateur

ReflectionGenerator::getThis

(PHP 7, PHP 8)

ReflectionGenerator::getThis — Récupère la valeur de $this du générateur

Description

public ReflectionGenerator::getThis(): ?object

Récupère la valeur de $this du générateur auquel il a accès.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne la valeur de $this, ou null si le générateur n'a pas été crée dans un contexte de classe.

Exemples

Exemple #1 Exemple avec ReflectionGenerator::getThis()

<?php

class GenExample
{
public function gen()
{
yield 1;
}
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getThis());

Résultat de l'exemple ci-dessus est similaire à :

object(GenExample)#3 (0) {
}

Voir aussi

  • ReflectionGenerator::getFunction() - Récupère le nom de fonction du générateur
  • ReflectionGenerator::getTrace() - Récupère la trace du générateur exécutant

User Contributed Notes

There are no user contributed notes for this page.


Récupère la trace du générateur exécutant

  • « ReflectionGenerator::getThis
  • ReflectionFiber »
  • PHP Manual
  • ReflectionGenerator
  • Récupère la trace du générateur exécutant

ReflectionGenerator::getTrace

(PHP 7, PHP 8)

ReflectionGenerator::getTrace — Récupère la trace du générateur exécutant

Description

public ReflectionGenerator::getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array

Récupère la trace du générateur actuellement exécuté.

Liste de paramètres

options

La valeur d'options peut être n'importe laquelle des drapeaux suivant.

Options disponible
Option | Description
DEBUG_BACKTRACE_PROVIDE_OBJECT | Par défaut.
DEBUG_BACKTRACE_IGNORE_ARGS | N'inclue pas les informations des arguments pour les fonctions dans la trace d'appels.

Valeurs de retour

Retourne la trace du générateur actuellement exécuté.

Exemples

Exemple #1 Exemple avec ReflectionGenerator::getTrace()

<?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());

Résultat de l'exemple ci-dessus est similaire à :

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) {
    }
  }
}

Voir aussi

  • ReflectionGenerator::getFunction() - Récupère le nom de fonction du générateur
  • ReflectionGenerator::getThis() - Récupère la valeur de $this du générateur

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionFiber class

(PHP 8 >= 8.1.0)

Introduction

Synopsis de la classe

final class ReflectionFiber {
/* Méthodes */
public __construct(Fiber $fiber)
public getCallable(): callable
public getExecutingFile(): string
public getExecutingLine(): int
public getFiber(): Fiber
public getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array
}

Sommaire

  • ReflectionFiber::__construct — Constructs a ReflectionFiber object
  • ReflectionFiber::getCallable — Gets the callable used to create the Fiber
  • ReflectionFiber::getExecutingFile — Get the file name of the current execution point
  • ReflectionFiber::getExecutingLine — Get the line number of the current execution point
  • ReflectionFiber::getFiber — Get the reflected Fiber instance
  • ReflectionFiber::getTrace — Get the backtrace of the current execution point

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionFiber object

  • « ReflectionFiber
  • ReflectionFiber::getCallable »
  • PHP Manual
  • ReflectionFiber
  • Constructs a ReflectionFiber object

ReflectionFiber::__construct

(PHP 8 >= 8.1.0)

ReflectionFiber::__construct — Constructs a ReflectionFiber object

Description

public ReflectionFiber::__construct(Fiber $fiber)

Constructs a ReflectionFiber object.

Liste de paramètres

fiber

The Fiber to reflect.

User Contributed Notes

There are no user contributed notes for this page.


Gets the callable used to create the Fiber

  • « ReflectionFiber::__construct
  • ReflectionFiber::getExecutingFile »
  • PHP Manual
  • ReflectionFiber
  • Gets the callable used to create the Fiber

ReflectionFiber::getCallable

(PHP 8 >= 8.1.0)

ReflectionFiber::getCallable — Gets the callable used to create the Fiber

Description

public ReflectionFiber::getCallable(): callable

Returns the callable used to construct the Fiber. If the fiber has terminated, an Error is thrown.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

The callable used to create the Fiber.

User Contributed Notes

There are no user contributed notes for this page.


Get the file name of the current execution point

  • « ReflectionFiber::getCallable
  • ReflectionFiber::getExecutingLine »
  • PHP Manual
  • ReflectionFiber
  • Get the file name of the current execution point

ReflectionFiber::getExecutingFile

(PHP 8 >= 8.1.0)

ReflectionFiber::getExecutingFile — Get the file name of the current execution point

Description

public ReflectionFiber::getExecutingFile(): string

Returns the full path and file name of the current execution point in the reflected Fiber. If the fiber has not been started or has terminated, an Error is thrown.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

The full path and file name of the reflected fiber.

User Contributed Notes

There are no user contributed notes for this page.


Get the line number of the current execution point

  • « ReflectionFiber::getExecutingFile
  • ReflectionFiber::getFiber »
  • PHP Manual
  • ReflectionFiber
  • Get the line number of the current execution point

ReflectionFiber::getExecutingLine

(PHP 8 >= 8.1.0)

ReflectionFiber::getExecutingLine — Get the line number of the current execution point

Description

public ReflectionFiber::getExecutingLine(): int

Returns the line number of the current execution point in the reflected Fiber. If the fiber has not been started or has terminated, an Error is thrown.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

The line number of the current execution point in the fiber.

User Contributed Notes

There are no user contributed notes for this page.


Get the reflected Fiber instance

  • « ReflectionFiber::getExecutingLine
  • ReflectionFiber::getTrace »
  • PHP Manual
  • ReflectionFiber
  • Get the reflected Fiber instance

ReflectionFiber::getFiber

(PHP 8 >= 8.1.0)

ReflectionFiber::getFiber — Get the reflected Fiber instance

Description

public ReflectionFiber::getFiber(): Fiber

Returns the Fiber instance being reflected.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

The Fiber instance being reflected.

User Contributed Notes

There are no user contributed notes for this page.


Get the backtrace of the current execution point

  • « ReflectionFiber::getFiber
  • ReflectionIntersectionType »
  • PHP Manual
  • ReflectionFiber
  • Get the backtrace of the current execution point

ReflectionFiber::getTrace

(PHP 8 >= 8.1.0)

ReflectionFiber::getTrace — Get the backtrace of the current execution point

Description

public ReflectionFiber::getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array

Get the backtrace of the current execution point in the reflected Fiber.

Liste de paramètres

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.

Valeurs de retour

The backtrace of the current execution point in the fiber.

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionIntersectionType class

(PHP 8 >= 8.1.0)

Introduction

Synopsis de la classe

class ReflectionIntersectionType extends ReflectionType {
/* Méthodes */
public getTypes(): array
/* Méthodes héritées */
public ReflectionType::allowsNull(): bool
public ReflectionType::__toString(): string
}

Sommaire

  • ReflectionIntersectionType::getTypes — Returns the types included in the intersection type

User Contributed Notes

There are no user contributed notes for this page.


Returns the types included in the intersection type

  • « ReflectionIntersectionType
  • ReflectionReference »
  • PHP Manual
  • ReflectionIntersectionType
  • Returns the types included in the intersection type

ReflectionIntersectionType::getTypes

(PHP 8 >= 8.1.0)

ReflectionIntersectionType::getTypes — Returns the types included in the intersection type

Description

public ReflectionIntersectionType::getTypes(): array

Returns the reflections of types included in the intersection type.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

An array of ReflectionType objects.

Exemples

Exemple #1 ReflectionIntersectionType::getTypes() example

<?php

function someFunction(Iterator&Countable $value) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

var_dump($reflectionParam->getType()->getTypes());
?>

Résultat de l'exemple ci-dessus est similaire à :

array(2) {
    [0] =>
    class ReflectionNamedType#4(0) {
    }
    [1] =>
    class ReflectionNamedType#5(0) {
    }
}

Voir aussi

  • ReflectionType::allowsNull() - Vérifie si null est permit
  • ReflectionParameter::getType() - Récupère le type du paramètre

User Contributed Notes

baptiste at pillot dot fr 08-Sep-2023 12:30
php 8.2: ReflectionIntersectionType::getTypes returns an array of ReflectionNamedType. For now, PHP's DNF implementation does not allow union types nested into intersection types.


The ReflectionReference class

(PHP 7 >= 7.4.0, PHP 8)

Introduction

The ReflectionReference class provides information about a reference.

Synopsis de la classe

final class ReflectionReference {
/* Méthodes */
private __construct()
public static fromArrayElement(array $array, int|string $key): ?ReflectionReference
public getId(): string
}

Sommaire

  • ReflectionReference::__construct — Private constructor to disallow direct instantiation
  • ReflectionReference::fromArrayElement — Create a ReflectionReference from an array element
  • ReflectionReference::getId — Get unique ID of a reference

User Contributed Notes

There are no user contributed notes for this page.


Private constructor to disallow direct instantiation

  • « ReflectionReference
  • ReflectionReference::fromArrayElement »
  • PHP Manual
  • ReflectionReference
  • Private constructor to disallow direct instantiation

ReflectionReference::__construct

(No version information available, might only be in Git)

ReflectionReference::__construct — Private constructor to disallow direct instantiation

Description

private ReflectionReference::__construct()

Liste de paramètres

Cette fonction ne contient aucun paramètre.

User Contributed Notes

There are no user contributed notes for this page.


Create a ReflectionReference from an array element

  • « ReflectionReference::__construct
  • ReflectionReference::getId »
  • PHP Manual
  • ReflectionReference
  • Create a ReflectionReference from an array element

ReflectionReference::fromArrayElement

(PHP 7 >= 7.4.0, PHP 8)

ReflectionReference::fromArrayElement — Create a ReflectionReference from an array element

Description

public static ReflectionReference::fromArrayElement(array $array, int|string $key): ?ReflectionReference

Creates a ReflectionReference from an array element.

Liste de paramètres

array

The tableau which contains the potential reference.

key

The key; either an entier or a chaîne de caractères.

Valeurs de retour

Returns a ReflectionReference instance if $array[$key] is a reference, or null otherwise.

Erreurs / Exceptions

If array is not an tableau, or key is not an entier or chaîne de caractères, a TypeError is thrown. If $array[$key] does not exist, a ReflectionException is thrown.

User Contributed Notes

There are no user contributed notes for this page.


Get unique ID of a reference

  • « ReflectionReference::fromArrayElement
  • ReflectionAttribute »
  • PHP Manual
  • ReflectionReference
  • Get unique ID of a reference

ReflectionReference::getId

(PHP 7 >= 7.4.0, PHP 8)

ReflectionReference::getId — Get unique ID of a reference

Description

public ReflectionReference::getId(): string

Returns an ID which is unique for the reference for the lifetime of that reference. This ID can be used to compare references for equality, or to maintain a map of known references.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Returns a chaîne de caractères of unspecified format.

Exemples

Exemple #1 Basic ReflectionReference::getId() usage

<?php
$val1 = 'foo';
$val2 = 'bar';
$arr = [&$val1, &$val2, &$val1];

$rr1 = ReflectionReference::fromArrayElement($arr, 0);
$rr2 = ReflectionReference::fromArrayElement($arr, 1);
$rr3 = ReflectionReference::fromArrayElement($arr, 2);

var_dump($rr1->getId() === $rr2->getId());
var_dump($rr1->getId() === $rr3->getId());
?>

L'exemple ci-dessus va afficher :

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionAttribute class

(PHP 8)

Introduction

The ReflectionAttribute class provides information about an Attribute.

Synopsis de la classe

class ReflectionAttribute implements Reflector {
/* Constantes */
public const int IS_INSTANCEOF;
/* Méthodes */
private __construct()
public getArguments(): array
public getName(): string
public getTarget(): int
public isRepeated(): bool
public newInstance(): object
}

Constantes pré-définies

ReflectionAttribute Flags

ReflectionAttribute::IS_INSTANCEOF

Retrieve attributes using an instanceof check.

Note:

The values of these constants may change between PHP versions. It is recommended to always use the constants and not rely on the values directly.

Sommaire

  • ReflectionAttribute::__construct — Private constructor to disallow direct instantiation
  • ReflectionAttribute::getArguments — Gets arguments passed to attribute
  • ReflectionAttribute::getName — Gets attribute name
  • ReflectionAttribute::getTarget — Returns the target of the attribute as bitmask
  • ReflectionAttribute::isRepeated — Returns whether the attribute of this name has been repeated on a code element
  • ReflectionAttribute::newInstance — Instantiates the attribute class represented by this ReflectionAttribute class and arguments

User Contributed Notes

There are no user contributed notes for this page.


Private constructor to disallow direct instantiation

  • « ReflectionAttribute
  • ReflectionAttribute::getArguments »
  • PHP Manual
  • ReflectionAttribute
  • Private constructor to disallow direct instantiation

ReflectionAttribute::__construct

(PHP 8)

ReflectionAttribute::__construct — Private constructor to disallow direct instantiation

Description

private ReflectionAttribute::__construct()

Liste de paramètres

Cette fonction ne contient aucun paramètre.

User Contributed Notes

There are no user contributed notes for this page.


Gets arguments passed to attribute

  • « ReflectionAttribute::__construct
  • ReflectionAttribute::getName »
  • PHP Manual
  • ReflectionAttribute
  • Gets arguments passed to attribute

ReflectionAttribute::getArguments

(PHP 8)

ReflectionAttribute::getArguments — Gets arguments passed to attribute

Description

public ReflectionAttribute::getArguments(): array

Gets arguments passed to attribute.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

The arguments passed to attribute.

User Contributed Notes

There are no user contributed notes for this page.


Gets attribute name

  • « ReflectionAttribute::getArguments
  • ReflectionAttribute::getTarget »
  • PHP Manual
  • ReflectionAttribute
  • Gets attribute name

ReflectionAttribute::getName

(PHP 8)

ReflectionAttribute::getName — Gets attribute name

Description

public ReflectionAttribute::getName(): string

Gets the attributes name.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

The name of the attribute.

User Contributed Notes

There are no user contributed notes for this page.


Returns the target of the attribute as bitmask

  • « ReflectionAttribute::getName
  • ReflectionAttribute::isRepeated »
  • PHP Manual
  • ReflectionAttribute
  • Returns the target of the attribute as bitmask

ReflectionAttribute::getTarget

(PHP 8)

ReflectionAttribute::getTarget — Returns the target of the attribute as bitmask

Description

public ReflectionAttribute::getTarget(): int

Gets target of the attribute as bitmask.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Gets target of the attribute as bitmask.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the attribute of this name has been repeated on a code element

  • « ReflectionAttribute::getTarget
  • ReflectionAttribute::newInstance »
  • PHP Manual
  • ReflectionAttribute
  • Returns whether the attribute of this name has been repeated on a code element

ReflectionAttribute::isRepeated

(PHP 8)

ReflectionAttribute::isRepeated — Returns whether the attribute of this name has been repeated on a code element

Description

public ReflectionAttribute::isRepeated(): bool

Returns whether the attribute of this name has been repeated on a code element.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Returns true when attribute is used repeatedly, otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


Instantiates the attribute class represented by this ReflectionAttribute class and arguments

  • « ReflectionAttribute::isRepeated
  • Reflector »
  • PHP Manual
  • ReflectionAttribute
  • Instantiates the attribute class represented by this ReflectionAttribute class and arguments

ReflectionAttribute::newInstance

(PHP 8)

ReflectionAttribute::newInstance — Instantiates the attribute class represented by this ReflectionAttribute class and arguments

Description

public ReflectionAttribute::newInstance(): object

Instantiates the attribute class represented by this ReflectionAttribute class and arguments.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

New instance of the attribute.

User Contributed Notes

baptiste at pillot dot fr 30-Jan-2023 11:07
Calling ReflectionAttribute::newInstance() using an attribute name that has a matching class without #[Attribute] will result in an error.

Example :

<?php
class FakeAttribute {}

#[FakeAttribute]
class Test {}

try {
    (new ReflectionClass(Test::class))->getAttributes()[0]->newInstance();
}
catch (Error $error) {
    echo 'Throwed error ' . get_class($error) . ' with message : ' . $error->getMessage();
}
?>

This will output :

Throwed error Error with message : Attempting to use non-attribute class "FakeAttribute" as attribute
baptiste at pillot dot fr 30-Jan-2023 11:06
Calling ReflectionAttribute::newInstance() using an attribute name that does not have a corresponding class will result in an error.

Example :

<?php
#[FakeAttribute]
class Test {}

try {
  (new ReflectionClass(Test::class))->getAttributes()[0]->newInstance();
}
catch (Error $error) {
  echo 'Throwed error ' . get_class($error) . ' with message : ' . $error->getMessage();
}
?>

This will output :

Throwed error Error with message : Attribute class "FakeAttribute" not found


L'interface Reflector

(PHP 5, PHP 7, PHP 8)

Introduction

Reflector est une interface implémentée par toutes les classes exportables Reflection.

Sommaire de l'Interface

interface Reflector extends Stringable {
/* Méthodes héritées */
public Stringable::__toString(): string
}

Historique

Version | Description
8.0.0 | Reflector::export() a été supprimé.
8.0.0 | Reflector étend désormais Stringable. Elle hérite Stringable::__toString(), remplaçant Reflector::__toString().

Voir aussi

  • Reflector::export()

Sommaire

  • Reflector::export — Exporte

User Contributed Notes

There are no user contributed notes for this page.


Exporte

  • « Reflector
  • ReflectionException »
  • PHP Manual
  • Reflector
  • Exporte

Reflector::export

(PHP 5, PHP 7)

Reflector::export — Exporte

Avertissement

Cette fonction est OBSOLÈTE à partir de PHP 7.4.0, et a été SUPPRIMÉE à partir de PHP 8.0.0. Dépendre de cette fonction est fortement déconseillé.

Description

public static Reflector::export(): string

Exporte.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Voir aussi

  • Reflection::__toString()

User Contributed Notes

There are no user contributed notes for this page.


La classe ReflectionException

(PHP 5, PHP 7, PHP 8)

Introduction

La classe ReflectionException.

Synopsis de la classe

class ReflectionException extends Exception {
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes héritées */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
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');
}


Gestion des variables

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Fonctions de gestion des variables
    • boolval — Récupère la valeur booléenne d'une variable
    • debug_zval_dump — Extrait une représentation sous forme de chaîne de la structure interne d'une zval pour affichage
    • doubleval — Alias de floatval
    • empty — Détermine si une variable est vide
    • floatval — Convertit une chaîne en nombre à virgule flottante
    • get_debug_type — Gets the type name of a variable in a way that is suitable for debugging
    • get_defined_vars — Liste toutes les variables définies
    • get_resource_id — Retourne un entier identifiant une ressource
    • get_resource_type — Retourne le type de ressource
    • gettype — Retourne le type de la variable
    • intval — Retourne la valeur numérique entière équivalente d'une variable
    • is_array — Détermine si une variable est un tableau
    • is_bool — Détermine si une variable est un booléen
    • is_callable — Détermine si une valeur peut être appelé comme une fonction dans la portée courante.
    • is_countable — Vérifie si le contenu de la variable est une valeur dénombrable
    • is_double — Alias de is_float
    • is_float — Détermine si une variable est de type nombre décimal
    • is_int — Détermine si une variable est de type nombre entier
    • is_integer — Alias de is_int
    • is_iterable — Détermine si le contenu de la variable est itérable.
    • is_long — Alias de is_int
    • is_null — Indique si une variable vaut null
    • is_numeric — Détermine si une variable est un nombre ou une chaîne numérique
    • is_object — Détermine si une variable est de type objet
    • is_real — Alias de is_float
    • is_resource — Détermine si une variable est une ressource
    • is_scalar — Indique si une variable est un scalaire
    • is_string — Détermine si une variable est de type chaîne de caractères
    • isset — Détermine si une variable est déclarée et est différente de null
    • print_r — Affiche des informations lisibles pour une variable
    • serialize — Génère une représentation stockable d'une valeur
    • settype — Affecte un type à une variable
    • strval — Récupère la valeur d'une variable, au format chaîne
    • unserialize — Crée une variable PHP à partir d'une valeur sérialisée
    • unset — Détruit une variable
    • var_dump — Affiche les informations d'une variable
    • var_export — Retourne le code PHP utilisé pour générer une variable

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Pour plus de détails sur le comportement des variables, reportez-vous à la section Variables du chapitre Référence du langage.

User Contributed Notes

There are no user contributed notes for this page.


Configuration à l'exécution

Le comportement de ces fonctions est affecté par la configuration dans le fichier php.ini.

Options de configuration pour les variables
Nom | Défaut | Modifiable | Historique
unserialize_callback_func | null | PHP_INI_ALL |
unserialize_max_depth | "4096" | PHP_INI_ALL | Disponible à partir de PHP 7.4.0.
Pour plus de détails sur les modes PHP_INI_*, reportez-vous à Où une directive de configuration peut être modifiée.

Voici un éclaircissement sur l'utilisation des directives de configuration.

unserialize_callback_func string

La fonction de rappel spécifié est appelée lorsque la fonction unserialize() tente d'utiliser une classe non définie. Une alerte apparaît si la fonction de rappel n'est pas définie, ou si elle échoue lors de la définition de la classe manquante.

Voir aussi unserialize() et l'autochargement de classes.

unserialize_max_depth int

La profondeur maximale des structures autorisée pendant la désérialisation lors de l'utilisation de unserialize(), et est destinée à empêcher les débordements de pile. Ceci peut être désactivé en définissant unserialize_max_depth=0.

Voir aussi unserialize() et l'autochargement de classes.

User Contributed Notes

There are no user contributed notes for this page.


Fonctions de gestion des variables

Sommaire

  • boolval — Récupère la valeur booléenne d'une variable
  • debug_zval_dump — Extrait une représentation sous forme de chaîne de la structure interne d'une zval pour affichage
  • doubleval — Alias de floatval
  • empty — Détermine si une variable est vide
  • floatval — Convertit une chaîne en nombre à virgule flottante
  • get_debug_type — Gets the type name of a variable in a way that is suitable for debugging
  • get_defined_vars — Liste toutes les variables définies
  • get_resource_id — Retourne un entier identifiant une ressource
  • get_resource_type — Retourne le type de ressource
  • gettype — Retourne le type de la variable
  • intval — Retourne la valeur numérique entière équivalente d'une variable
  • is_array — Détermine si une variable est un tableau
  • is_bool — Détermine si une variable est un booléen
  • is_callable — Détermine si une valeur peut être appelé comme une fonction dans la portée courante.
  • is_countable — Vérifie si le contenu de la variable est une valeur dénombrable
  • is_double — Alias de is_float
  • is_float — Détermine si une variable est de type nombre décimal
  • is_int — Détermine si une variable est de type nombre entier
  • is_integer — Alias de is_int
  • is_iterable — Détermine si le contenu de la variable est itérable.
  • is_long — Alias de is_int
  • is_null — Indique si une variable vaut null
  • is_numeric — Détermine si une variable est un nombre ou une chaîne numérique
  • is_object — Détermine si une variable est de type objet
  • is_real — Alias de is_float
  • is_resource — Détermine si une variable est une ressource
  • is_scalar — Indique si une variable est un scalaire
  • is_string — Détermine si une variable est de type chaîne de caractères
  • isset — Détermine si une variable est déclarée et est différente de null
  • print_r — Affiche des informations lisibles pour une variable
  • serialize — Génère une représentation stockable d'une valeur
  • settype — Affecte un type à une variable
  • strval — Récupère la valeur d'une variable, au format chaîne
  • unserialize — Crée une variable PHP à partir d'une valeur sérialisée
  • unset — Détruit une variable
  • var_dump — Affiche les informations d'une variable
  • var_export — Retourne le code PHP utilisé pour générer une variable

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.


Récupère la valeur booléenne d'une variable

  • « Fonctions de gestion des variables
  • debug_zval_dump »
  • PHP Manual
  • Fonctions de gestion des variables
  • Récupère la valeur booléenne d'une variable

boolval

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

boolval — Récupère la valeur booléenne d'une variable

Description

boolval(mixed $value): bool

Retourne la valeur booléen de la variable fournie dans le paramètre value.

Liste de paramètres

value

La valeur scalaire qui sera convertie en booléen.

Valeurs de retour

La valeur booléen du paramètre value.

Exemples

Exemple #1 Exemple avec boolval()

<?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";
?>

L'exemple ci-dessus va afficher :

0:        false
42:       true
0.0:      false
4.2:      true
"":       false
"string": true
"0":      false
"1":      true
[1, 2]:   true
[]:       false
stdClass: true

Voir aussi

  • floatval() - Convertit une chaîne en nombre à virgule flottante
  • intval() - Retourne la valeur numérique entière équivalente d'une variable
  • strval() - Récupère la valeur d'une variable, au format chaîne
  • settype() - Affecte un type à une variable
  • is_bool() - Détermine si une variable est un booléen
  • Le transtypage

User Contributed Notes

John Doe 16-Aug-2021 07:51
Type casting is the easiet and fastest way:

(bool)$value
Anonymous 18-Mar-2021 11:39
boolval('false') returns true.
boolval('False') return true.
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;
        }
}
?>


Extrait une représentation sous forme de chaîne de la structure interne d'une zval pour affichage

  • « boolval
  • doubleval »
  • PHP Manual
  • Fonctions de gestion des variables
  • Extrait une représentation sous forme de chaîne de la structure interne d'une zval pour affichage

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

debug_zval_dump — Extrait une représentation sous forme de chaîne de la structure interne d'une zval pour affichage

Description

debug_zval_dump(mixed $value, mixed ...$values): void

Extrait une représentation sous forme de chaîne de caractère d'un structure interne d'une zval (Zend value) pour affichage. Ceci est généralement utile pour comprendre ou déboguer les détails d'implémentation du moteur Zend ou d'extensions PHP.

Liste de paramètres

value

La variable où valeur à extraire.

values

Variables ou valeurs supplémentaire à extraire.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec debug_zval_dump()

<?php
$var1 = 'Hello';
$var1 .= ' World';
$var2 = $var1;

debug_zval_dump($var1);
?>

L'exemple ci-dessus va afficher :

string(11) "Hello World" refcount(3)

Note: Comprendre le refcount

La valeur refcount affiché par cette fonction peut être surprenant sans une compréhension détaillé de l'implémentation du moteur.

Le moteur Zend utilise le comptage de référence pour deux raisons différentes :

  • Optimiser l'usage de mémoire en utilisant une technique appelé "copy on write", où plusieurs variables tenant la même valeur pointe à la même copie en mémoire. Quand une de ces variables est modifié, elle pointe à une nouvelle copie en mémoire, et le comptage de référence de l'originale est réduit de 1.
  • Le pistage des variables qui ont été assigné ou passé par référence (voir Références Expliquer). Ce refcount est stocker dans un zval de référence séparé, pointant à la zval pour la valeur actuelle. Cette zval additionnelle n'est actuellement pas montré par debug_zval_dump().

Car debug_zval_dump() prend son entrée comme un paramètre normal, passé par valeur, la technique de copy on write sera utilisé pour la passé: au lieu de copier les données, le refcount sera incrémenté de 1 pour la durée de vie de l'appel de la fonction. Si la fonction modifie le paramètre après l'avoir reçu, alors une copie sera fait ; comme elle n'en fait pas, elle affichera un refcount de 1 plus élevé que dans la portée d'appel.

Le passage de paramètre empêche aussi debug_zval_dump() de montrer les variables qui ont été assigné par référence. Pour illustrer ceci, considérons une version légèrement modifié de l'exemple ci-dessus : showing variables which have been assigned by reference. To illustrate, consider a slightly modified version of the above example:

<?php
$var1 = 'Hello';
$var1 .= ' World';
// Point three variables as references to the same value
$var2 =& $var1;
$var3 =& $var1;

debug_zval_dump($var1);
?>

L'exemple ci-dessus va afficher :

string(11) "Hello World" refcount(2)

Bien que $var1, $var2, et $var3 sont lié en tant que référence, seul la valeur est passé à debug_zval_dump(). Cette valeur est utilisé une seul fois par le jeu de références, et une fois à l'intérieur de debug_zval_dump(), ainsi il affiche un refcount de 2.

Des complications supplémentaire émergent à cause des optimisations effectué par le moteur pour différent types de données. Certains types tel que les entiers n'utilise pas "copy on write", et donc n'affiche aucun refcount. Dans d'autre cas, le refcount montre d'autres copies utilisé en interne, tel que quand une chaîne littérale ou tableau est stocké comme une partie d'une instruction de code

Voir aussi

  • var_dump() - Affiche les informations d'une variable
  • debug_backtrace() - Génère le contexte de débogage
  • Explication sur les références
  • » Explication sur les références (par 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.


Alias de floatval

  • « debug_zval_dump
  • empty »
  • PHP Manual
  • Fonctions de gestion des variables
  • Alias de floatval

doubleval

(PHP 4, PHP 5, PHP 7, PHP 8)

doubleval — Alias de floatval()

Description

Cette fonction est un alias de : floatval().

User Contributed Notes

There are no user contributed notes for this page.


Détermine si une variable est vide

  • « doubleval
  • floatval »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est vide

empty

(PHP 4, PHP 5, PHP 7, PHP 8)

empty — Détermine si une variable est vide

Description

empty(mixed $var): bool

Détermine si une variable est considérée comme vide. Une variable est considérée comme vide si elle n'existe pas, ou si sa valeur équivaut à false. La fonction empty() ne génère pas d'alerte si la variable n'existe pas.

Liste de paramètres

var

Variable à vérifier.

Aucune alerte n'est générée si la variable n'existe pas. Cela signifie que empty() est strictement équivalent à !isset($var) || $var == false.

Valeurs de retour

Retourne true si var n'existe pas ou a une valeur vide ou égale à zéro, c.à.d. qu'elle est considérée "false", voir conversion en booléen. Sinon retourne false.

Exemples

Exemple #1 Une comparaison simple empty() / isset().

<?php
$var = 0;

// Évaluée à vrai car $var est vide
if (empty($var)) {
echo '$var vaut soit 0, vide, ou pas définie du tout';
}

// Évaluée à vrai car $var est définie
if (isset($var)) {
echo '$var est définie même si elle est vide';
}
?>

Exemple #2 empty() sur des positions dans une chaîne

<?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']));
?>

L'exemple ci-dessus va afficher :

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

Notes

Note: Comme ceci est une structure du langage, et non pas une fonction, il n'est pas possible de l'appeler avec les fonctions variables ou arguments nommés.

Note:

Lors de l'utilisation de cette fonction sur des propriétés d'objet inaccessibles, la méthode magique __isset() sera appelée, si elle existe.

Voir aussi

  • isset() - Détermine si une variable est déclarée et est différente de null
  • __isset()
  • unset() - Détruit une variable
  • array_key_exists() - Vérifie si une clé existe dans un tableau
  • count() - Compte tous les éléments d'un tableau ou dans un objet Countable
  • strlen() - Calcule la taille d'une chaîne
  • Les tables de comparaison des types

User Contributed Notes

mmulej at gmail dot com 30-Dec-2022 11:28
Tests on
- Win 11
- Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz   2.21 GHz
- 64Gb RAM,
- PHP 8.1.10 (in Tinkerwell)
repeatedly show `empty` > `count` > `=== []`, but the margin is small and not worth the micro-optimizations.

Note: Same results (with `$n = 10000000`) for PHP v7.4.33 using onlinephp(dot)io sandbox tool.

<?php

$test = range(0, 1000);
$test2 = [];
$n = 1000_000_000;

$t1 = microtime(true); for ($x = 0; $x < $n; $x++) if (count($test)) {}
$t2 = microtime(true); for ($x = 0; $x < $n; $x++) if (count($test2)) {}
$t3 = microtime(true); for ($x = 0; $x < $n; $x++) if ($test === []) {}
$t4 = microtime(true); for ($x = 0; $x < $n; $x++) if ($test2 === []) {}
$t5 = microtime(true); for ($x = 0; $x < $n; $x++) if (empty($test)) {}
$t6 = microtime(true); for ($x = 0; $x < $n; $x++) if (empty($test2)) {}
$t7 = microtime(true);

echo "count(\$test):  " . ($t2 - $t1) . " sec\n";
echo "count(\$test2): " . ($t3 - $t2) . " sec\n";
echo "\$test === []:  " . ($t4 - $t3) . " sec\n";
echo "\$test2 === []: " . ($t5 - $t4) . " sec\n";
echo "empty(\$test):  " . ($t6 - $t5) . " sec\n";
echo "empty(\$test2): " . ($t7 - $t6) . " sec\n";

?>

Results:
<?php
count($test):  18.034885168076 sec
count($test2): 17.133869886398 sec
$test === []:  20.059770107269 sec
$test2 === []: 14.204195022583 sec
empty($test):  13.583840847015 sec
empty($test2): 12.971315145493 sec
?>
Lukas 05-May-2022 02:36
<?php

// Difference of empty() vs. isset()

$testCase = array(
    1 => '',
    2 => ' ',
    3 => null,
    4 => array(),
    5 => false,
    6 => true,
    7 => '0',
    8 => 0,
);

foreach ($testCase as $k => $v) {
    echo "<br> $k => " . strval($v) . " " . (empty($v) ? "is empty" : "is not empty") . " / " . (isset($v) ? "is set" : "is not set");
}

/*
RESULT:
 1 =>  is empty / is set
 2 =>   is not empty / is set
 3 =>  is empty / is not set
 4 => Array is empty / is set
 5 =>  is empty / is set
 6 => 1 is not empty / is set
 7 => 0 is empty / is set
 8 => 0 is empty / is set
*/
info at ensostudio dot ru 22-Jul-2021 09:11
Multiple empty():
<?php
/**
 * Multiple empty().
 *
 * @param mixed[] $vars Variables to test
 * @return bool
 */
function multi_empty(& ...$vars)
{
    // no callback is supplied, all empty values will be removed
    return array_filter($vars) === [];
}
?>
example:
<?php
$notEmptyVar = 1;
$emptyVar = null;
// $undefinedVar - not defined

multi_empty($emptyVar); // true
multi_empty($emptyVar, $undefinedVar); // true
multi_empty($notEmptyVar , $emptyVar); // false
multi_empty($notEmptyVar , $emptyVar, $undefinedVar); // false
?>
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
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
?>


Convertit une chaîne en nombre à virgule flottante

  • « empty
  • get_debug_type »
  • PHP Manual
  • Fonctions de gestion des variables
  • Convertit une chaîne en nombre à virgule flottante

floatval

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

floatval — Convertit une chaîne en nombre à virgule flottante

Description

floatval(mixed $value): float

floatval() retourne la valeur de type float (nombre à virgule flottante), extraite à partir du paramètre value.

Liste de paramètres

value

Peut être de n'importe quel type scalaire. floatval() ne doit pas être utilisé sur les objets ; si tel est le cas, une alerte de niveau E_WARNING sera émise et la fonction retournera 1.

Valeurs de retour

La valeur flottante de la variable donnée. Un tableau vide retourne 0, alors qu'un tableau non-vide retourne 1.

Les chaînes de caractères retourneront la plupart du temps 0, mais cela dépend du caractère le plus à gauche de la chaîne. Les règles classiques de transtypage d'un nombre à virgule flottante sont appliquées.

Historique

Version | Description
8.0.0 | Le niveau d'erreur lors de la conversion d'un objet a été modifié de E_NOTICE à E_WARNING.

Exemples

Exemple #1 Exemple avec floatval()

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

Exemple #2 Exemple avec floatval() avec des caractères à gauche non numériques

<?php
$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0
?>

Voir aussi

  • boolval() - Récupère la valeur booléenne d'une variable
  • intval() - Retourne la valeur numérique entière équivalente d'une variable
  • strval() - Récupère la valeur d'une variable, au format chaîne
  • settype() - Affecte un type à une variable
  • Transtypage

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 m²';
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.


Gets the type name of a variable in a way that is suitable for debugging

  • « floatval
  • get_defined_vars »
  • PHP Manual
  • Fonctions de gestion des variables
  • Gets the type name of a variable in a way that is suitable for debugging

get_debug_type

(PHP 8)

get_debug_type — Gets the type name of a variable in a way that is suitable for debugging

Description

get_debug_type(mixed $value): string

Returns the resolved name of the PHP variable value. This function will resolve objects to their class name, resources to their resource type name, and scalar values to their common name as would be used in type declarations.

This function differs from gettype() in that it returns type names that are more consistent with actual usage, rather than those present for historical reasons.

Liste de paramètres

value

The variable being type checked.

Valeurs de retour

Possible values for the returned string are:

Type + State | Return Value | Notes
null | "null" | -
Booleans (true or false) | "bool" | -
Integers | "int" | -
Floats | "float" | -
Strings | "string" | -
Arrays | "array" | -
Resources | "resource (resourcename)" | -
Resources (Closed) | "resource (closed)" | Example: A file stream after being closed with fclose.
Objects from Named Classes | The full name of the class including its namespace e.g. Foo\Bar | -
Objects from Anonymous Classes | "class@anonymous" | Anonymous classes are those created through the $x = new class { ... } syntax

Exemples

Exemple #1 get_debug_type() example

<?php
echo get_debug_type(null) . PHP_EOL;
echo get_debug_type(true) . PHP_EOL;
echo get_debug_type(1) . PHP_EOL;
echo get_debug_type(0.1) . PHP_EOL;
echo get_debug_type("foo") . PHP_EOL;
echo get_debug_type([]) . PHP_EOL;

$fp = fopen(__FILE__, 'rb');
echo get_debug_type($fp) . PHP_EOL;

fclose($fp);
echo get_debug_type($fp) . PHP_EOL;

echo get_debug_type(new stdClass) . PHP_EOL;
echo get_debug_type(new class {}) . PHP_EOL;
?>

Résultat de l'exemple ci-dessus est similaire à :

null
bool
int
float
string
array
resource (stream)
resource (closed)
stdClass
class@anonymous

Voir aussi

  • gettype() - Retourne le type de la variable
  • get_class() - Retourne le nom de la classe d'un objet

User Contributed Notes

vyacheslav dot belchuk at gmail dot com 02-Nov-2023 05:52
Also, the function returns the correct type of Closure, as opposed to gettype()

<?php

echo get_debug_type(function () {}) . PHP_EOL;
echo get_debug_type(fn () => '') . PHP_EOL . PHP_EOL;

echo gettype(function () {}) . PHP_EOL;
echo gettype(fn () => '');

?>

Output:

Closure
Closure

object
object


Liste toutes les variables définies

  • « get_debug_type
  • get_resource_id »
  • PHP Manual
  • Fonctions de gestion des variables
  • Liste toutes les variables définies

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

get_defined_vars — Liste toutes les variables définies

Description

get_defined_vars(): array

get_defined_vars() retourne un tableau multidimensionnel contenant la liste de toutes les variables définies, qu'elles soient des variables d'environnement, de serveur ou définies par l'utilisateur dans la portée d'appel de la fonction get_defined_vars().

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Un tableau multidimensionnel contenant toutes les variables.

Exemples

Exemple #1 Exemple avec get_defined_vars()

<?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// Affiche $b
print_r($arr["b"]);

/* Affiche le chemin vers l'interpréteur PHP (Si utilisé en tant que CGI)
* e.g. /usr/local/bin/php */
echo $arr["_"];

// Affiche les paramètres de la ligne de commande s'il y en a
print_r($arr["argv"]);

// Affiche toutes les variables serveur
print_r($arr["_SERVER"]);

// Affiche toutes les clés disponibles du tableau de variables
print_r(array_keys(get_defined_vars()));
?>

Voir aussi

  • isset() - Détermine si une variable est déclarée et est différente de null
  • get_defined_functions() - Liste toutes les fonctions définies
  • get_defined_constants() - Retourne la liste des constantes et leurs valeurs

User Contributed Notes

cmswares dot com at gmail dot com 10-Jan-2022 11:27
Be aware of what get_defined_vars() function returns in different contexts:

- In global scope, a list of all defined variables, whether superglobals, command line arguments or user-defined variables
- In function scope, only a list of user-defined variables (both arguments and in-body definitions)
- In class/object method scope, does not return class/object properties;

Also, as of PHP 5.4, does not return $_ENV even where available.

For further details and scope tests/results, see https://github.com/php/doc-en/issues/1317
Qiibow 05-Sep-2021 02:55
get_defined_vars() is very useful for importing many values at once
into another scope (Such as User-defined functions).

Below is an example for showing some of many values and their variable-names in a table.
(useful in debugging)

You can put this user-defined function at many places in your script
to show some values (values to be changed in loops)
to check if they are what they shall be there or not.

<?php
// Set "get_defined_vars()" to 2nd argument.
function get_value_table($name_array, $gdv) {
    $name_value_table = [];
    foreach ($name_array as $name) :
        if (!array_key_exists($name, $gdv)) :
            $value = 'undefined';
        elseif (is_bool($gdv[$name])) :
            $value = $gdv[$name]? 'true' : 'false';
        elseif (is_numeric($gdv[$name]) || is_string($gdv[$name])) :
            $value = $gdv[$name];
        elseif (is_array($gdv[$name])) :
            $value = '<pre>'.print_r($gdv[$name],true).'</pre>';
        else :
            $value = (PHP_VERSION_ID >= 80000)? get_debug_type($gdv[$name]) : get_type($gdv[$name]);
        endif;
        $name_value_table[] = '<tr><td>$'.$name.'<td>'.$value;
    endforeach;
    return '<table border=1>'.implode("\n", $name_value_table).'</table>';
} // (f) get_value_table()

$_1 = 'a';
$_2 = 'b';
$_3 = [1,2];
$_4 = false;
$_5 = null;

$name_array = ['_1','_2','_3','_4','_5','_6'];
$show_id = 1;

if ($show_id === 1) :
    echo get_value_table($name_array, get_defined_vars());
endif;
/*
if $show_id === 1, only shows below.

$_1      a
$_2      b
$_3      Array
      (
          [0] => 1
          [1] => 2
      )
$_4      false
$_5      null
$_6      undefined
*/

$_2 = 'c';
if ($show_id === 2) :
    echo get_value_table($name_array, get_defined_vars()); // $_2   c
endif;
# if $show_id === 2, $_2 turns "c".

?>
nix dot code at 4assistance dot com dot nix 22-Jun-2021 01:27
Insert this at point of interest; add keys of unwanted 1st dim variables to 2nd param of array_diff_key
<?php
echo '<pre>defined_except '; var_dump (array_diff_key (get_defined_vars(), ['GLOBALS'=>0,'_SERVER'=>0])); echo ' '.basename(__FILE__).':'.__LINE__.'</pre>'; #die;
?>
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>


Retourne un entier identifiant une ressource

  • « get_defined_vars
  • get_resource_type »
  • PHP Manual
  • Fonctions de gestion des variables
  • Retourne un entier identifiant une ressource

get_resource_id

(PHP 8)

get_resource_id — Retourne un entier identifiant une ressource

Description

get_resource_id(resource $resource): int

Cette fonction fournit un moyen sûr pour générer un entier identifiant une ressource.

Liste de paramètres

resource

Le gestionnaire de la ressource à identifier.

Valeurs de retour

L'int identifiant la resource passée en paramètre.

Cette fonction est une conversion de type de resource vers un int pour faciliter la récupération de l'ID d'une ressource.

Exemples

Exemple #1 get_resource_id() produit le même résultat qu'un cast int

<?php

$handle = fopen("php://stdout", "w");

echo (int) $handle . "\n";

echo get_resource_id($handle);

?>

Résultat de l'exemple ci-dessus est similaire à :

698
698

Voir aussi

  • get_resource_type() - Retourne le type de ressource

User Contributed Notes

There are no user contributed notes for this page.


Retourne le type de ressource

  • « get_resource_id
  • gettype »
  • PHP Manual
  • Fonctions de gestion des variables
  • Retourne le type de ressource

get_resource_type

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

get_resource_type — Retourne le type de ressource

Description

get_resource_type(resource $resource): string

Cette fonction retourne le type de la ressource donnée.

Liste de paramètres

resource

Le gestionnaire de ressources à évaluer.

Valeurs de retour

Si le paramètre resource est une ressource, cette fonction retournera une chaîne de caractères représentant son type. Si le type n'est pas identifié par cette fonction, la valeur de retour sera la chaîne de caractères Unknown.

Cette fonction retournera null et générera une erreur si resource n'est pas une ressource.

Exemples

Exemple #1 Exemple avec get_resource_type()

<?php

$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// À partir de PHP 8.0.0, ce qui suit ne fonctionne plus. La fonction curl_init returne maintenant un objet CurlHandle.
$c = curl_init();
echo get_resource_type($c) . "\n";
?>

Résultat de l'exemple ci-dessus en PHP 7 :

stream
curl

Voir aussi

  • get_resource_id() - Retourne un entier identifiant une ressource

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


Retourne le type de la variable

  • « get_resource_type
  • intval »
  • PHP Manual
  • Fonctions de gestion des variables
  • Retourne le type de la variable

gettype

(PHP 4, PHP 5, PHP 7, PHP 8)

gettype — Retourne le type de la variable

Description

gettype(mixed $value): string

Retourne le type de la variable value. Pour vérifier le type de la variable, vous pouvez utiliser les fonctions is_*.

Liste de paramètres

value

La variable à analyser.

Valeurs de retour

Les chaînes de caractères que peut retourner la fonction sont les suivantes :

  • "boolean"
  • "integer"
  • "double" (pour des raisons historiques, "double" est retournée lorsqu'une valeur de type float est fournie, et non "float"")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "resource (closed)" à partir de PHP 7.2.0
  • "NULL"
  • "unknown type"

Historique

Version | Description
7.2.0 | Les ressources fermées sont maintenant rapportées en tant que 'resource (closed)'. Précédemment la valeur retournée pour des ressources fermées était 'unknown type'.

Exemples

Exemple #1 Exemple avec gettype()

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
echo gettype($value), "\n";
}

?>

Résultat de l'exemple ci-dessus est similaire à :

integer
double
NULL
object
string

Voir aussi

  • get_debug_type() - Gets the type name of a variable in a way that is suitable for debugging
  • settype() - Affecte un type à une variable
  • get_class() - Retourne le nom de la classe d'un objet
  • is_array() - Détermine si une variable est un tableau
  • is_bool() - Détermine si une variable est un booléen
  • is_callable() - Détermine si une valeur peut être appelé comme une fonction dans la portée courante.
  • is_float() - Détermine si une variable est de type nombre décimal
  • is_int() - Détermine si une variable est de type nombre entier
  • is_null() - Indique si une variable vaut null
  • is_numeric() - Détermine si une variable est un nombre ou une chaîne numérique
  • is_object() - Détermine si une variable est de type objet
  • is_resource() - Détermine si une variable est une ressource
  • is_scalar() - Indique si une variable est un scalaire
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • function_exists() - Indique si une fonction est définie
  • method_exists() - Vérifie si la méthode existe pour une classe

User Contributed Notes

mohammad dot alavi1990 at gmail dot com 11-Jun-2023 12:37
Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.

string - string // OK
int - integer // Type mismatch
bool - boolean // Type mismatch
array - array // OK
Anonymous 20-Jan-2022 06:59
Same as for "boolean" below, happens with integers. gettype() return "integer" yet proper type hint is "int".

If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.


Retourne la valeur numérique entière équivalente d'une variable

  • « gettype
  • is_array »
  • PHP Manual
  • Fonctions de gestion des variables
  • Retourne la valeur numérique entière équivalente d'une variable

intval

(PHP 4, PHP 5, PHP 7, PHP 8)

intval — Retourne la valeur numérique entière équivalente d'une variable

Description

intval(mixed $value, int $base = 10): int

Retourne la valeur entier de value en utilisant la base fourni pour la conversion (par défaut en base 10). intval() ne devrait pas être utilisée sur des objets, dans ces cas, une erreur de niveau E_WARNING sera émise et la fonction retournera 1.

Liste de paramètres

value

La valeur scalaire à être convertie en entier

base

La base pour la conversion

Note:

Si base vaut 0, la base utilisée est déterminée par le format du paramètre value :

  • si la chaîne inclue un préfixe "0x" (ou "0X"), la base prise sera 16 (hex) ; sinon,
  • si la chaîne commence par "0b" (ou "0B"), la base prise sera 2 (binaire); sinon,
  • si la chaîne commence par "0", la base prise sera 8 (octal); sinon,
  • la base prise sera 10 (décimal).

Valeurs de retour

Une valeur de type entier de value en cas de succès ou 0 en cas d'échec. Les tableaux vides retournent 0, les tableaux non vides retournent 1.

La valeur maximale dépend du système. Les systèmes à 32 bits ont une valeur entière signée maximale de -2147483648 à 2147483647. Alors, par exemple, sur un système semblable, intval('1000000000000') retournera 2147483647. La valeur entière signée maximale pour un système à 64 bits est 9223372036854775807.

Les chaînes de caractères retournent la plupart du temps 0, cela dépend des caractères à l'extrême gauche de la chaîne. La règle courante du transtypage d'entier s'applique.

Historique

Version | Description
8.0.0 | Le niveau d'erreur lors de la conversion à partir d'un objet a été modifié de E_NOTICE à E_WARNING.

Exemples

Exemple #1 Exemples avec intval()

Les exemples suivants sont basés sur un système à 64 bits.

<?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); // 10000000000
echo intval('1e10'); // 10000000000
echo intval(0x1A); // 26
echo intval('0x1A'); // 0
echo intval('0x1A', 0); // 26
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // -4275113695319687168
echo intval('420000000000000000000'); // 9223372036854775807
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
?>

Notes

Note:

Le paramètre base n'a aucun effet à moins que le paramètre value soit une chaîne de caractères.

Voir aussi

  • boolval() - Récupère la valeur booléenne d'une variable
  • floatval() - Convertit une chaîne en nombre à virgule flottante
  • strval() - Récupère la valeur d'une variable, au format chaîne
  • settype() - Affecte un type à une variable
  • is_numeric() - Détermine si une variable est un nombre ou une chaîne numérique
  • Définition du type
  • Nombres de grande taille 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


Détermine si une variable est un tableau

  • « intval
  • is_bool »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est un tableau

is_array

(PHP 4, PHP 5, PHP 7, PHP 8)

is_array — Détermine si une variable est un tableau

Description

is_array(mixed $value): bool

is_array() détermine si la variable donnée est un tableau.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un array, false sinon.

Exemples

Exemple #1 Exemple avec is_array()

<?php
$yes = array('ceci', 'est', 'un tableau');

echo is_array($yes) ? 'Tableau' : 'ce n\'est pas un tableau';
echo "\n";

$no = 'ceci est une chaîne';

echo is_array($no) ? 'Tableau' : 'ce n\'est pas un tableau';
?>

L'exemple ci-dessus va afficher :

Tableau
ce n'est pas un tableau

Voir aussi

  • array_is_list() - Vérifie si un array donné est une liste
  • is_float() - Détermine si une variable est de type nombre décimal
  • is_int() - Détermine si une variable est de type nombre entier
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_object() - Détermine si une variable est de type objet

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
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.
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.
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.
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;
}

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


Détermine si une variable est un booléen

  • « is_array
  • is_callable »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est un booléen

is_bool

(PHP 4, PHP 5, PHP 7, PHP 8)

is_bool — Détermine si une variable est un booléen

Description

is_bool(mixed $value): bool

is_bool() détermine si la variable donnée est un booléen.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un booléen, false sinon.

Exemples

Exemple #1 Exemple avec is_bool()

<?php
$a = false;
$b = 0;

// Si $a est un booléen, is_bool retournera true
if (is_bool($a) === true) {
echo "Oui, c'est un booléen.";
}

// Si $b n'est pas un booléen, is_bool retournera false
if (is_bool($b) === false) {
echo "Non, ce n'est pas un booléen.";
}
?>

Voir aussi

  • is_float() - Détermine si une variable est de type nombre décimal
  • is_int() - Détermine si une variable est de type nombre entier
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_object() - Détermine si une variable est de type objet
  • is_array() - Détermine si une variable est un tableau

User Contributed Notes

David Jarry 24-Oct-2023 11:41
Since PHP 8.0.0, it's more flexible to use a match() structure (e.g. for translations into another language), with all benefits of strict comparisons (===):

<?php
function to_bool(int|bool|string|null $value): bool|null {
    return match(is_string($value) ? strtolower(trim($value)) : $value) {
        1, TRUE, '1', 'true', 'on', 'yes', 'y' => TRUE,
        0, FALSE, '0', 'false', 'off', 'no', 'n' => FALSE,
        default => NULL,
    };
}
?>
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;
  }
}


Détermine si une valeur peut être appelé comme une fonction dans la portée courante.

  • « is_bool
  • is_countable »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une valeur peut être appelé comme une fonction dans la portée courante.

is_callable

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

is_callable — Détermine si une valeur peut être appelé comme une fonction dans la portée courante.

Description

is_callable(mixed $value, bool $syntax_only = false, string &$callable_name = null): bool

Vérifie qu'une variable est un callable.

Liste de paramètres

value

La valeur à vérifier.

syntax_only

Si l'argument syntax_only vaut true, la fonction ne va vérifier que si value peut être une fonction ou une méthode. Il va simplement rejeter les variables qui ne sont pas des chaînes, ou des tableaux qui n'ont pas la bonne structure pour être utilisés comme fonction de rappel. Les tableaux valides sont supposés n'avoir que deux entrées, le premier étant un objet ou une chaîne, et le second une chaîne.

callable_name

L'argument callable_name reçoit le nom à utiliser. Dans l'exemple ci-dessous, il vaut "someClass::someMethod". Notez que, bien que someClass::someMethod() puisse être appelée sous forme statique, ce n'est pas le cas.

Valeurs de retour

Retourne true si value peut être appelé comme une fonction, false sinon.

Exemples

Exemple #1 Exemple avec is_callable()

<?php
// Comment vérifier qu'une variable peut être appelée
// comme fonction ?

//
// Variable simple contenant une fonction
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name)); // bool(true)

echo $callable_name, "\n"; // someFunction

//
// Tableau contenant une méthode
//

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

?>

Exemple #2 is_callable() et les constructeurs

is_callable() rapporte les constructeurs comme n'étant pas appelable.

<?php

class Foo
{
public function __construct() {}
public function foo() {}
}

var_dump(
is_callable(array('Foo', '__construct')),
is_callable(array('Foo', 'foo'))
);

L'exemple ci-dessus va afficher :

bool(false)
bool(false)

  • Un object est tout le temps appelable s'il implémente __invoke(), et que la méthode est visible dans le portée courante.
  • Un nom de classe est appelable si elle implémente __callStatic()
  • Si un object implémente __call(), alors cette fonction retournera true pour n'importe quelle méthode sur cet object, même si la méthode n'est pas définie.
  • Cette fonction peut déclancher l'autochargement si appelé avec le nom d'une classe.

Voir aussi

  • function_exists() - Indique si une fonction est définie
  • method_exists() - Vérifie si la méthode existe pour une classe

User Contributed Notes

php dot net at scare dot ca 03-Jul-2022 12:42
Note that is_callable('_') will return true, since there is a built-in function called "_". It is an alias for gettext().

https://www.php.net/manual/en/function.gettext.php

Searching this site for a function named "_" does not return a result, but it's the first result in a search for "_()".
mohamed dot elidrissi at protonmail dot com 28-Jun-2021 12:26
Note that -- as mentioned in the migration guide-- starting from PHP 8.0, is_callable() will not work with non-static methods if you use a class name, instead an object of the class should be provided:

<?php

class Test
{
    public function method1() { }
    public static function method2() { }
}

// Pre PHP 8
var_dump(is_callable(array('Test', 'method1'))); // bool(true)
var_dump(is_callable(array('Test', 'method2'))); // bool(true)

// Post PHP 8
var_dump(is_callable(array('Test', 'method1'))); // bool(false)
var_dump(is_callable(array('Test', 'method2'))); // bool(true)
var_dump(is_callable(array(new Test, 'method1'))); // bool(true)

?>
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
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
?>
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
?>
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


Vérifie si le contenu de la variable est une valeur dénombrable

  • « is_callable
  • is_double »
  • PHP Manual
  • Fonctions de gestion des variables
  • Vérifie si le contenu de la variable est une valeur dénombrable

is_countable

(PHP 7 >= 7.3.0, PHP 8)

is_countable — Vérifie si le contenu de la variable est une valeur dénombrable

Description

is_countable(mixed $value): bool

Vérifie si le contenue de la variable est un tableau array ou un object qui implémente Countable

Liste de paramètres

value

La variable à vérifier

Valeurs de retour

Retourne true si value est dénombrable, false sinon.

Historique

Version | Description
7.3.0 | is_countable() a été ajouté.

Exemples

Exemple #1 Exemples avec is_countable()

<?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)

Voir aussi

  • is_array() - Détermine si une variable est un tableau
  • is_object() - Détermine si une variable est de type objet
  • is_iterable() - Détermine si le contenu de la variable est itérable.
  • is_bool() - Détermine si une variable est un booléen

User Contributed Notes

zhaoyifans at gmail dot com 14-Dec-2022 03:53
polyfill:

function is_countable($value) {
    return is_array($value)
        || $value instanceof Countable
        || $value instanceof ResourceBundle
        || $value instanceof SimpleXmlElement;
}
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);
    }
}
?>


Alias de is_float

  • « is_countable
  • is_float »
  • PHP Manual
  • Fonctions de gestion des variables
  • Alias de is_float

is_double

(PHP 4, PHP 5, PHP 7, PHP 8)

is_double — Alias de is_float()

Description

Cette fonction est un alias de : is_float().

User Contributed Notes

There are no user contributed notes for this page.


Détermine si une variable est de type nombre décimal

  • « is_double
  • is_int »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est de type nombre décimal

is_float

(PHP 4, PHP 5, PHP 7, PHP 8)

is_float — Détermine si une variable est de type nombre décimal

Description

is_float(mixed $value): bool

Détermine si la variable donnée est de type nombre décimal.

Note:

Pour tester si une variable est un nombre ou une chaîne numérique (comme les entrées de formulaire, qui sont toujours des chaînes), vous devez utiliser la fonction is_numeric().

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un nombre décimal, false sinon.

Exemples

Exemple #1 Exemple avec is_float()

<?php
var_dump(is_float(27.25));
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7)); //Notation Scientifique
var_dump(is_float(true));
?>

L'exemple ci-dessus va afficher :

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

Voir aussi

  • is_bool() - Détermine si une variable est un booléen
  • is_int() - Détermine si une variable est de type nombre entier
  • is_numeric() - Détermine si une variable est un nombre ou une chaîne numérique
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_array() - Détermine si une variable est un tableau
  • is_object() - Détermine si une variable est de type objet

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);


Détermine si une variable est de type nombre entier

  • « is_float
  • is_integer »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est de type nombre entier

is_int

(PHP 4, PHP 5, PHP 7, PHP 8)

is_int — Détermine si une variable est de type nombre entier

Description

is_int(mixed $value): bool

Détermine si la variable donnée est de type nombre entier.

Note:

Pour tester si une variable est un nombre ou une chaîne numérique (comme les entrées de formulaire, qui sont toujours des chaînes), vous devez utiliser la fonction is_numeric().

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un entier, false sinon.

Exemples

Exemple #1 Exemple avec 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));
}
?>

L'exemple ci-dessus va afficher :

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)

Voir aussi

  • is_bool() - Détermine si une variable est un booléen
  • is_float() - Détermine si une variable est de type nombre décimal
  • is_numeric() - Détermine si une variable est un nombre ou une chaîne numérique
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_array() - Détermine si une variable est un tableau
  • is_object() - Détermine si une variable est de type objet

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.


Alias de is_int

  • « is_int
  • is_iterable »
  • PHP Manual
  • Fonctions de gestion des variables
  • Alias de is_int

is_integer

(PHP 4, PHP 5, PHP 7, PHP 8)

is_integer — Alias de is_int()

Description

Cette fonction est un alias de : is_int().

User Contributed Notes

There are no user contributed notes for this page.


Détermine si le contenu de la variable est itérable.

  • « is_integer
  • is_long »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si le contenu de la variable est itérable.

is_iterable

(PHP 7 >= 7.1.0, PHP 8)

is_iterable — Détermine si le contenu de la variable est itérable.

Description

is_iterable(mixed $value): bool

Vérifie que le contenu de la variable est accepté par le pseudo-type iterable, c'est-à-dire qu'il s'agit soit d'un array ou un objet qui implémente l'interface Traversable

Liste de paramètres

value

La valeur à vérifier

Valeurs de retour

Retourne true si value est itérable, false sinon.

Exemples

Exemple #1 Exemples avec is_iterable()

<?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)

?>

Voir aussi

  • is_array() - Détermine si une variable est un tableau

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


Alias de is_int

  • « is_iterable
  • is_null »
  • PHP Manual
  • Fonctions de gestion des variables
  • Alias de is_int

is_long

(PHP 4, PHP 5, PHP 7, PHP 8)

is_long — Alias de is_int()

Description

Cette fonction est un alias de : is_int().

User Contributed Notes

There are no user contributed notes for this page.


Indique si une variable vaut null

  • « is_long
  • is_numeric »
  • PHP Manual
  • Fonctions de gestion des variables
  • Indique si une variable vaut null

is_null

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

is_null — Indique si une variable vaut null

Description

is_null(mixed $value): bool

Indique si la variable donnée vaut null.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est null, false sinon.

Exemples

Exemple #1 Exemple avec is_null()

<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>
Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

Voir aussi

  • Le type null
  • isset() - Détermine si une variable est déclarée et est différente de null
  • is_bool() - Détermine si une variable est un booléen
  • is_numeric() - Détermine si une variable est un nombre ou une chaîne numérique
  • is_float() - Détermine si une variable est de type nombre décimal
  • is_int() - Détermine si une variable est de type nombre entier
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_object() - Détermine si une variable est de type objet
  • is_array() - Détermine si une variable est un tableau

User Contributed Notes

ahamilton9 19-Apr-2022 08:28
A quick test in 2022 on PHP 8.1 confirms there is still no need to micro-optimize NULL checks:

<?php

// Comparison Operator
$before = microtime(true);
$var = null;
for ($i=0 ; $i<1000000000 ; $i++) {
    if($var === null) {}
}
$after = microtime(true);
echo '    ===: ' . ($after - $before) . " seconds\n";

// Function
$before = microtime(true);
$var = null;
for ($i=0 ; $i<1000000000 ; $i++) {
    if(is_null($var)) {}
}
$after = microtime(true);
echo 'is_null: ' . ($after - $before) . " seconds\n";

//     ===: 4.1487579345703 seconds
// is_null: 4.1316878795624 seconds
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


Détermine si une variable est un nombre ou une chaîne numérique

  • « is_null
  • is_object »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est un nombre ou une chaîne numérique

is_numeric

(PHP 4, PHP 5, PHP 7, PHP 8)

is_numeric — Détermine si une variable est un nombre ou une chaîne numérique

Description

is_numeric(mixed $value): bool

Détermine si la variable donnée est un nombre ou une chaîne numérique.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un nombre ou une chaîne numérique, false sinon.

Historique

Version | Description
8.0.0 | Les chaînes numériques terminant avec des caractères d'espacement blanc ("42 ") retourneront désormais true. Auparavant, false était retourné à la place.

Exemples

Exemple #1 Exemple avec is_numeric()

<?php
$tests = array(
"42",
1337,
0x539,
02471,
0b10100111001,
1337e0,
"0x539",
"02471",
"0b10100111001",
"1337e0",
"not numeric",
array(),
9.1,
null,
'',
);

foreach ($tests as $element) {
if (is_numeric($element)) {
echo var_export($element, true) . " est numérique", PHP_EOL;
} else {
echo var_export($element, true) . " N'est PAS numérique", PHP_EOL;
}
}
?>

L'exemple ci-dessus va afficher :

'42' est numérique
1337 est numérique
1337 est numérique
1337 est numérique
1337 est numérique
1337.0 est numérique
'0x539' N'est PAS numérique
'02471' est numérique
'0b10100111001' N'est PAS numérique
'1337e0' est numérique
'not numeric' N'est PAS numérique
array (
) N'est PAS numérique
9.1 est numérique
NULL N'est PAS numérique
'' N'est PAS numérique

Exemple #2 is_numeric() avec des caractères d'espacement blanc

<?php
$tests = [
" 42",
"42 ",
"\u{A0}9001", // non-breaking space
"9001\u{A0}", // non-breaking space
];

foreach ($tests as $element) {
if (is_numeric($element)) {
echo var_export($element, true) . " is numeric", PHP_EOL;
} else {
echo var_export($element, true) . " is NOT numeric", PHP_EOL;
}
}
?>

Résultat de l'exemple ci-dessus en PHP 8 :

' 42' is numeric
'42 ' is numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

Résultat de l'exemple ci-dessus en PHP 7 :

' 42' is numeric
'42 ' is NOT numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

Voir aussi

  • Les chaînes numérique
  • ctype_digit() - Vérifie qu'une chaîne est un entier
  • is_bool() - Détermine si une variable est un booléen
  • is_null() - Indique si une variable vaut null
  • is_float() - Détermine si une variable est de type nombre décimal
  • is_int() - Détermine si une variable est de type nombre entier
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_object() - Détermine si une variable est de type objet
  • is_array() - Détermine si une variable est un tableau
  • filter_var() - Filtre une variable avec un filtre spécifique

User Contributed Notes

Katrina Kizenbach 07-Dec-2022 08:44
Note that is_numeric() will evaluate to false for number strings using decimal commas.

is_numeric('0.11');
Output: true

is_numeric('0,11');
Output: false
anantkumarsingh03101988 at gmail dot com 22-Aug-2022 05:16
Example #2

Output:

'9001 ' is NOT numeric

is incorrect for PHP8, it's numeric.

So please correct this.
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
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...
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.
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.
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
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);
}


Détermine si une variable est de type objet

  • « is_numeric
  • is_real »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est de type objet

is_object

(PHP 4, PHP 5, PHP 7, PHP 8)

is_object — Détermine si une variable est de type objet

Description

is_object(mixed $value): bool

Détermine si la variable donnée est de type objet.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un objet, false sinon.

Historique

Version | Description
7.2.0 | is_object() retourne maintenant true pour un objet désérialise sans une définition de classe (classe de __PHP_Incomplete_Class). Précédement false était retourné.

Exemples

Exemple #1 Exemple avec is_object()

<?php
// Déclare une simple fonction pour retourner un tableau
// de notre objet
function get_students($obj)
{
if (!is_object($obj)) {
return false;
}

return $obj->students;
}

// Déclare une nouvelle instance et
// la remplit
$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');

var_dump(get_students(null));
var_dump(get_students($obj));;
?>

Voir aussi

  • is_bool() - Détermine si une variable est un booléen
  • is_int() - Détermine si une variable est de type nombre entier
  • is_float() - Détermine si une variable est de type nombre décimal
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_array() - Détermine si une variable est un tableau

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.


Alias de is_float

  • « is_object
  • is_resource »
  • PHP Manual
  • Fonctions de gestion des variables
  • Alias de is_float

is_real

(PHP 4, PHP 5, PHP 7, PHP 8)

is_real — Alias de is_float()

Description

Cette fonction est un alias de : is_float().

Avertissement

Cet alias est OBSOLÈTE en PHP 7.4.0, et SUPPRIMÉ à partir de PHP 8.0.0.

User Contributed Notes

There are no user contributed notes for this page.


Détermine si une variable est une ressource

  • « is_real
  • is_scalar »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est une ressource

is_resource

(PHP 4, PHP 5, PHP 7, PHP 8)

is_resource — Détermine si une variable est une ressource

Description

is_resource(mixed $value): bool

Détermine si une variable est une ressource.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est une ressource, false autrement.

Exemples

Exemple #1 Exemple avec is_resource()

<?php

$handle = fopen("php://stdout", "w");
if (is_resource($handle)) {
echo '$handle est une ressource';
}
?>

L'exemple ci-dessus va afficher :

$handle est une ressource

Notes

Note:

La fonction is_resource() n'est pas une méthode de vérification stricte de type : elle va retourner false si le paramètre value est une ressource qui a été fermée.

Voir aussi

  • La documentation sur les ressources
  • get_resource_type() - Retourne le type de ressource

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.


Indique si une variable est un scalaire

  • « is_resource
  • is_string »
  • PHP Manual
  • Fonctions de gestion des variables
  • Indique si une variable est un scalaire

is_scalar

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

is_scalar — Indique si une variable est un scalaire

Description

is_scalar(mixed $value): bool

Indique si la variable donnée est un scalaire.

Les variables scalaires sont celles qui contiennent un entier, un nombre décimal, une chaîne de caractères ou un booléen. Les types array, object, resource et null ne sont pas scalaires.

Note:

is_scalar() ne considère pas les valeurs des types ressource comme scalaires, étant donné que les ressources sont des types abstraits, basés sur des entiers. Ceci est susceptible de changer.

Note:

La fonction is_scalar() ne considère pas la valeur NULL comme un scalaire.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un scalaire, false autrement.

Exemples

Exemple #1 Exemple avec is_scalar()

<?php
function show_var($var)
{
if (is_scalar($var)) {
echo $var;
} else {
var_dump($var);
}
}
$pi = 3.1416;
$proteines = array("hémoglobine", "cytochrome c oxidase", "ferredoxine");

show_var($pi);

show_var($proteines)
?>

L'exemple ci-dessus va afficher :

3.1416
array(3) {
  [0]=>
  string(11) "hémoglobine"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(11) "ferredoxine"
}

Voir aussi

  • is_float() - Détermine si une variable est de type nombre décimal
  • is_int() - Détermine si une variable est de type nombre entier
  • is_numeric() - Détermine si une variable est un nombre ou une chaîne numérique
  • is_real() - Alias de is_float
  • is_string() - Détermine si une variable est de type chaîne de caractères
  • is_bool() - Détermine si une variable est un booléen
  • is_object() - Détermine si une variable est de type objet
  • is_array() - Détermine si une variable est un tableau

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


Détermine si une variable est de type chaîne de caractères

  • « is_scalar
  • isset »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est de type chaîne de caractères

is_string

(PHP 4, PHP 5, PHP 7, PHP 8)

is_string — Détermine si une variable est de type chaîne de caractères

Description

is_string(mixed $value): bool

Détermine si la variable donnée est de type chaîne de caractères.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est une chaîne de caractères, false sinon.

Exemples

Exemple #1 Exemple avec is_string()

<?php
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
echo "is_string(";
var_export($value);
echo ") = ";
echo var_dump(is_string($value));
}
?>

L'exemple ci-dessus va afficher :

is_string(false) = bool(false)
is_string(true) = bool(false)
is_string(NULL) = bool(false)
is_string('abc') = bool(true)
is_string('23') = bool(true)
is_string(23) = bool(false)
is_string('23.5') = bool(true)
is_string(23.5) = bool(false)
is_string('') = bool(true)
is_string(' ') = bool(true)
is_string('0') = bool(true)
is_string(0) = bool(false)

Voir aussi

  • is_float() - Détermine si une variable est de type nombre décimal
  • is_int() - Détermine si une variable est de type nombre entier
  • is_bool() - Détermine si une variable est un booléen
  • is_object() - Détermine si une variable est de type objet
  • is_array() - Détermine si une variable est un tableau

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
?>


Détermine si une variable est déclarée et est différente de null

  • « is_string
  • print_r »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détermine si une variable est déclarée et est différente de null

isset

(PHP 4, PHP 5, PHP 7, PHP 8)

isset — Détermine si une variable est déclarée et est différente de null

Description

isset(mixed $var, mixed ...$vars): bool

Détermine si une variable est considérée définie, ceci signifie qu'elle est déclarée et est différente de null.

Si une variable a été détruite avec la fonction unset(), elle n'est plus considéré comme définie.

isset() renverra false lors de la vérification d'une variable de valeur null. Il est à noter que aussi que le caractère nul ("\0") n'est pas équivalent à la constante PHP null.

Si plusieurs paramètres sont fournis, alors isset() retournera true seulement si tous les paramètres sont définis. L'évaluation s'effectue de gauche à droite et s'arrête dès qu'une variable non définie est rencontrée.

Liste de paramètres

var

La variable à analyser.

vars

Variables supplémentaires.

Valeurs de retour

Retourne true si var existe et a une valeur autre que null. false sinon.

Exemples

Exemple #1 Exemple avec isset()

<?php

$var = '';

// Ceci est vrai, alors le texte est affiché
if (isset($var)) {
echo 'Cette variable existe, donc je peux l\'afficher.';
}

// Dans les exemples suivants, nous utilisons var_dump() pour afficher
// le retour de la fonction 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

?>

Fonctionne aussi avec les tableaux :

<?php

$a = array ('test' => 1, 'bonjour' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test'])); // TRUE
var_dump(isset($a['foo'])); // FALSE
var_dump(isset($a['bonjour'])); // FALSE

// La clé 'bonjour' vaut NULL et est considérée comme non existante
// Si vous voulez vérifier l'existence de cette clé, utilisez cette fonction
var_dump(array_key_exists('bonjour', $a) ); // TRUE

// Vérification des valeurs en profondeur
var_dump(isset($a['pie']['a'])); // TRUE
var_dump(isset($a['pie']['b'])); // FALSE
var_dump(isset($a['cake']['a']['b'])); // FALSE
?>

Exemple #2 isset() sur des positions dans une chaîne

<?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']));
?>

L'exemple ci-dessus va afficher :

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

Notes

Avertissement

isset() fonctionne uniquement avec des variables car l'utilisation de toute autre chose aura comme conséquence une erreur d'analyse. Pour vérifier si une constants est définie, utilisez la fonction defined().

Note: Comme ceci est une structure du langage, et non pas une fonction, il n'est pas possible de l'appeler avec les fonctions variables ou arguments nommés.

Note:

Lors de l'utilisation de cette fonction sur des propriétés d'objet inaccessibles, la méthode magique __isset() sera appelée, si elle existe.

Voir aussi

  • empty() - Détermine si une variable est vide
  • __isset()
  • unset() - Détruit une variable
  • defined() - Vérifie l'existence d'une constante
  • le tableau de comparaison de types
  • array_key_exists() - Vérifie si une clé existe dans un tableau
  • is_null() - Indique si une variable vaut null
  • l'opérateur de contrôle de rapport d'erreurs @

User Contributed Notes

eckoson at gmail dot com 01-Aug-2023 02:41
If you are annoyed by the behavior of isset() concerning null values, here is a handy function for you. its similar to array_key_exists but, its a lot more flexible and can check for multiple array keys across multiple arrays.
Not recursive!
Tested on php 8.1.6, linux
<?php
/**
* is_set
* @author DJ Eckoson
* @link @eckosongh Facebook Page
* checks whether variable names are set within the global space or they exists as an key and return if they are set (even if their values are null)
* @param string $var_name
*   name of the first variable to check
* @param array|null|string
*   optional array to check for key (if null, checks from $GLOBALS) OR
*   other variable names to check OR
*   other variable names and their associated arrays to their right (use null for global variables, optional if its the last parameter)
* check examples below
*/
function is_set(string $var_name, array|null|string ... $args): bool {
  $vars[$var_name] = null;
  if (array_key_exists(0, $args)) {
    if (is_array($args[0])) {
      $vars[$var_name] = $args[0];
    } elseif (is_string($args[0])) {
      goto main;
    }
    unset($args[0]);
  }
  main:
  if ($args) {
    $args = array_reverse($args);
    $cur_array = null;
    array_walk($args, function ($value) use (&$cur_array, &$vars): void {
      if (!is_string($value)) {
        $cur_array = $value;
      } else {
        $vars[$value] = $cur_array;
      }
    });
  }
  foreach ($vars as $name => $array) {
    if (!array_key_exists($name, $array??$GLOBALS)) return false;
  }
  return true;
}

// Examples
$arr1 = range(0, 5);
$arr2 = [
  'a' => 1,
  'b' => 2,
  'c' => 'hELLO wORLD!'
];
$gender = 'male';
$age = 12;
var_dump(is_set('age')); // true
var_dump(is_set('age', null)); // true
var_dump(is_set('age', $arr1)); // false
var_dump(is_set('age', array())); // false
var_dump(is_set('age', array('age' => 48))); // true
var_dump(is_set('age', 'arr1', null, 'b', $arr2, 0, 3, 4, $arr1, 'gender')); // true
var_dump(is_set('age', 'arr1', null, 'b', $arr2, 0, 3, 4, $arr1, 'gender', null)); // true

$c=$d=$e=$a=2;
$arr = [1,4];
var_dump(is_set('a', 'c', null, 0, 1, $arr)); // true
var_dump(is_set('a', 'c', null, 0, 4, $arr)); // false
?>
 Note:
 it won't work for variables declared locally inside a function;
 however you can use it for checking if array keys exists inside a function
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 );
?>
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
?>
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.
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.
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.
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.
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
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'.


Affiche des informations lisibles pour une variable

  • « isset
  • serialize »
  • PHP Manual
  • Fonctions de gestion des variables
  • Affiche des informations lisibles pour une variable

print_r

(PHP 4, PHP 5, PHP 7, PHP 8)

print_r — Affiche des informations lisibles pour une variable

Description

print_r(mixed $value, bool $return = false): string|bool

print_r() affiche des informations à propos d'une variable, de manière à ce qu'elle soit lisible.

print_r(), var_dump() et var_export() affiche également les propriétés protégées et privées d'un objet. Les membres des classes statiques ne seront pas affichés.

Liste de paramètres

value

L'expression à afficher.

return

Si vous voulez obtenir le résultat de print_r() dans une chaîne, utilisez le paramètre return. Lorsque ce paramètre vaut true, print_r() retournera l'information plutôt que de l'afficher.

Valeurs de retour

Si une chaîne de caractères, un entier ou un nombre décimal est fournie, sa valeur sera affichée. Si un tableau est fourni, les valeurs seront affichées dans un format permettant de voir les clés et les éléments. Un format similaire sera également utilisé pour les objets.

Lorsque le paramètre return vaut true, cette fonction retournera une chaîne de caractères. Autrement, la valeur de retour sera true.

Exemples

Exemple #1 Exemple avec print_r()

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

L'exemple ci-dessus va afficher :

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Exemple #2 Exemple avec le paramètre return

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results contient l'affichage de print_r
?>

Notes

Note:

Lorsque le paramètre return est utilisé, cette fonction utilisait la mise en tampon (buffer) interne de sortie antérieur à PHP 7.1.0, et donc ne peut pas être utilisé dans la fonction de rappel de ob_start().

Voir aussi

  • ob_start() - Enclenche la temporisation de sortie
  • var_dump() - Affiche les informations d'une variable
  • var_export() - Retourne le code PHP utilisé pour générer une variable

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=Windows-1252');
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


Génère une représentation stockable d'une valeur

  • « print_r
  • settype »
  • PHP Manual
  • Fonctions de gestion des variables
  • Génère une représentation stockable d'une valeur

serialize

(PHP 4, PHP 5, PHP 7, PHP 8)

serialize — Génère une représentation stockable d'une valeur

Description

serialize(mixed $value): string

Retourne un tableau en chaine de caractères.

C'est une technique pratique pour stocker ou passer des valeurs PHP entre scripts, sans perdre leur structure ni leur type.

Pour récupérer une variable sérialisée et retrouver une valeur PHP, utilisez unserialize().

Liste de paramètres

value

La valeur à sérialiser. serialize() accepte tous les types sauf les ressources ressource et certains objets (voir note ci-dessous). Vous pouvez même sérialiser un tableau qui contient des références sur lui-même. Les références cycliques dans des tableaux/objets seront également stockées. Toutes les autres références seront perdues.

Lors de la sérialisation d'un objet, PHP tentera d'appeler les fonctions
membres __serialize() ou
__sleep() avant de sérialiser.
Cela permet à l'objet de faire un dernier nettoyage, etc.
avant d'être sérialisé. De même, lorsque l'objet est restauré en
utilisant unserialize(), la fonction membre
__unserialize() ou
__wakeup() est appelée.

Note:

Les attributs privés d'un objet auront le nom de la classe préfixé au nom de l'attribut ; les attributs protégés seront préfixés avec un astérisque '*'. Ces valeurs préfixées ont des caractères nuls des deux cotés.

Valeurs de retour

Retourne une chaîne de caractères contenant une représentation sous forme de flux d'octets qui peut être stocker partout.

Il est à noter que c'est une chaîne binaire qui peut inclure des octets nuls, et doit donc être stockée et gérée comme telle. Par exemple, la sortie de serialize() doit généralement être stockée dans un champ de type BLOB d'une base de données, plutôt que dans un champ de type CHAR ou TEXT.

Exemples

Exemple #1 Exemple avec serialize()

<?php
// $session_data contient un tableau multidimensionnel , avec les
// informations de session de l'utilisateur courant. On utilise serialize()
// pour les stocker dans une base de données

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
"UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
$stmt = odbc_prepare($conn,
"INSERT INTO sessions (id, data) VALUES(?, ?)");
if (!odbc_execute($stmt, array_reverse($sqldata))) {
/* Un problème est survenu ! */
}
}
?>

Notes

Note:

Il est à noter que de nombreux objets internes de PHP ne peuvent pas être sérialisés. Cependant, ceux qui le peuvent implémentent soit l'interface Serializable soit les méthodes magiques __serialize()/__unserialize() ou __sleep()/__wakeup(). Si une classe interne ne remplit aucune de ces conditions, elle ne peut pas être sérialisée de manière fiable.

Il existe des exceptions historiques à cette règle, où des objets internes peuvent être sérialisés alors qu'ils n'implémentent pas l'interface ou n'exposent pas les méthodes magiques prévues à cet effet.

Avertissement

Lorsque la fonction serialize() sérialise des objets, l'antislash de fin n'est pas inclus dans l'espace de nom du nom de la classe et ce, pour un maximum de compatibilité.

Voir aussi

  • unserialize() - Crée une variable PHP à partir d'une valeur sérialisée
  • var_export() - Retourne le code PHP utilisé pour générer une variable
  • json_encode() - Retourne la représentation JSON d'une valeur
  • Serializing Objects
  • __sleep()
  • __wakeup()
  • __serialize()
  • __unserialize()

User Contributed Notes

mark at bvits dot co dot uk 09-Feb-2023 01:05
There is a type not mentioned in the user notes so far, 'E'.  This is the newer Enum class that can be utilised:

login_security|E:25:"Permission:manageClient"
synnus 11-Nov-2021 07:57
https://stackoverflow.com/questions/22308365/get-string-representation-of-anonymous-function

https://3v4l.org/CEmqV

UPDATE PHP8

    <?php

    function closure_to_str($func)
    {
        $refl = new \ReflectionFunction($func); // get reflection object
        $path = $refl->getFileName();  // absolute path of php file
        $begn = $refl->getStartLine(); // have to `-1` for array index
        $endn = $refl->getEndLine();
        $dlim = PHP_EOL;
        $list = explode($dlim, file_get_contents($path));         // lines of php-file source
        $list = array_slice($list, ($begn-1), ($endn-($begn-1))); // lines of closure definition
        $last = (count($list)-1); // last line number

        if((substr_count($list[0],'function')>1)|| (substr_count($list[0],'{')>1) || (substr_count($list[$last],'}')>1))
        { throw new \Exception("Too complex context definition in: `$path`. Check lines: $begn & $endn."); }

        $list[0] = ('function'.explode('function',$list[0])[1]);
        $list[$last] = (explode('}',$list[$last])[0].'}');

        return implode($dlim,$list);
    }

    $dog2 = function(){
        return 'test';
    };

    echo closure_to_str($dog2)."\n\n";
?>

Return String

    function(){
        return 'test';
    }
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.


Affecte un type à une variable

  • « serialize
  • strval »
  • PHP Manual
  • Fonctions de gestion des variables
  • Affecte un type à une variable

settype

(PHP 4, PHP 5, PHP 7, PHP 8)

settype — Affecte un type à une variable

Description

settype(mixed &$var, string $type): bool

Force le type de la variable var en type.

Liste de paramètres

var

La variable à convertir.

type

Les valeurs possibles pour le paramètre type sont :

  • "boolean" ou "bool"
  • "integer" ou "int"
  • "float" ou "double"
  • "string"
  • "array"
  • "object"
  • "null"

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec settype()

<?php
$foo = "5bar"; // chaîne
$bar = true; // booléen

settype($foo, "integer"); // $foo vaut maintenant 5 (integer)
settype($bar, "string"); // $bar vaut maintenant "1" (string)
?>

Notes

Note:

La valeur maximale des entiers est la valeur contenue dans la variable PHP_INT_MAX.

Voir aussi

  • gettype() - Retourne le type de la variable
  • conversion de type
  • transtypage automatique

User Contributed Notes

DarkMaster 17-Apr-2021 07:08
<?php
/*
This example works 4x faster than settype() function in PHP-CGI 5.4.13 and
8x faster in PHP-CGI 7.1.3(x64) for windows
*/

$v = '12345';

$v = (int)$v;
$v = (string)$v;

?>
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.


Récupère la valeur d'une variable, au format chaîne

  • « settype
  • unserialize »
  • PHP Manual
  • Fonctions de gestion des variables
  • Récupère la valeur d'une variable, au format chaîne

strval

(PHP 4, PHP 5, PHP 7, PHP 8)

strval — Récupère la valeur d'une variable, au format chaîne

Description

strval(mixed $value): string

Récupère la valeur de la variable value, au format chaîne de caractères. Voir la documentation sur les chaînes de caractères pour plus d'informations sur la conversion en chaîne.

Cette fonction n'effectue aucun formatage sur la valeur retournée. Si vous cherchez un moyen de formatter une valeur numérique en chaîne de caractères, reportez-vous à la fonction sprintf() ou la fonction number_format().

Liste de paramètres

value

La variable à convertir en chaîne de caractères.

value peut être un scalaire, null, ou un objet implémentant la méthode magique __toString(). Vous ne pouvez pas utiliser la fonction strval() avec des tableaux ou des objets qui n'implémentent pas la méthode magique __toString().

Valeurs de retour

La valeur de la variable value sous la forme d'une chaîne de caractères.

Exemples

Exemple #1 Exemple pour strval() utilisant la méthode magique PHP __toString().

<?php
class StrValTest
{
public function __toString()
{
return __CLASS__;
}
}

// Affiche 'StrValTest'
echo strval(new StrValTest);
?>

Voir aussi

  • boolval() - Récupère la valeur booléenne d'une variable
  • floatval() - Convertit une chaîne en nombre à virgule flottante
  • intval() - Retourne la valeur numérique entière équivalente d'une variable
  • settype() - Affecte un type à une variable
  • sprintf() - Retourne une chaîne formatée
  • number_format() - Formate un nombre pour l'affichage
  • Le transtypage
  • __toString()

User Contributed Notes

fabrice at vignals dot com 17-Dec-2021 10:01
My logic is stress.

bolean is true OR false;

<?= strval( true); ?> //output: 1

You must use:
<?= var_export( true ) ?> //output: true
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.';
?>


Crée une variable PHP à partir d'une valeur sérialisée

  • « strval
  • unset »
  • PHP Manual
  • Fonctions de gestion des variables
  • Crée une variable PHP à partir d'une valeur sérialisée

unserialize

(PHP 4, PHP 5, PHP 7, PHP 8)

unserialize — Crée une variable PHP à partir d'une valeur sérialisée

Description

unserialize(string $data, array $options = []): mixed

unserialize() prend une variable sérialisée (voir serialize()) et la convertit en variable PHP.

Avertissement

Ne passez pas d'entrée utilisateur non fiable à la fonction unserialize() quelle que soit la valeur de allowed_classes dans options. La désérialisation peut résulter en une exécution de code chargé et exécuté lors de l'instanciation et l'autochargement d'objet, et ainsi, un utilisateur mal intentionné peut être capable d'exploiter ce comportement. Utilisez un standard d'échange sûr, comme JSON (via les fonctions json_decode() et json_encode()) si vous devez passer des données sérialisées à l'utilisateur.

Si vous avez besoin de désérialiser des données sérialisées enregistré à l'extérieur, considérez l'utilisation de hash_hmac() pour valider les données. Assurez-vous que les données n'ont été modifiées par personne d'autre que vous.

Liste de paramètres

data

La chaîne sérialisée.

Si la variable désérialisée est un objet, après avoir réussi à le reconstruire, PHP tentera automatiquement d'appeller les méthodes __unserialize() ou __wakeup (si l'une d'elles existent).

Note: unserialize_callback_func directive

Il est possible de définir une fonction de rappel qui sera appelée si une classe indéfinie est utilisée lors de la désérialisation (ce qui évitera de recevoir un object "__PHP_Incomplete_Class"). Utilisez votre php.ini ou le fichier .htaccess pour définir unserialize_callback_func. Chaque fois qu'une classe non-définie sera instanciée, cette fonction sera appelée. Pour désactiver cette fonctionnalité, laissez simplement la chaîne de caractère vide.

options

Toute option à fournir à unserialize(), sous la forme d'un tableau associatif.

Options valides
Nom | Type | Description
allowed_classes | mixed | Soit un tableau de noms de classes qui doivent être acceptées, false pour accepter aucune classe, ou true pour accepter toutes les classes. Si cette option est définie, et unserialize() rencontre un objet d'une classe qui n'est pas accepté, alors l'objet sera instancié plutôt comme __PHP_Incomplete_Class. Le fait d'ommettre cette option revient à le définir comme true : PHP va tenter d'instancier les objets de n'importe quelle classe.
max_depth | int | La profondeur maximale autorisée des structures lors de la désérialisation, qui est destinée à empêcher les débordements de pile. La limite de profondeur par défaut est de 4096 et peut être désactivée en définissant max_depth à 0.

Valeurs de retour

La valeur convertie est retournée par la fonction, et peut être de type booléen, entier, nombre décimal, chaîne de caractères, tableau ou objet.

Si la chaîne passée ne peut être désérialisée, cette fonction retourne false et une erreur E_NOTICE est émise.

Erreurs / Exceptions

Les objets peuvent lancer Throwables dans leur gestionnaire de désérialisation.

Historique

Version | Description
7.4.0 | Ajout de l'élément max_depth aux options pour définir la profondeur maximale autorisée des structures lors de la désérialisation.
7.1.0 | L'élément allowed_classes de options) est maintenant strictement typé, c'est à dire si quelque chose autre qu'un tableau array ou un bool est donné unserialize() retourne false et émet une E_WARNING.

Exemples

Exemple #1 Exemple avec unserialize()

<?php
// Ici, on utilise <function>unserialize</function> pour charger les données de sessions
// depuis la base de données, dans $session_data. Cet exemple complète
// celui fourni avec <function>serialize</function>.

$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)) {
// si la préparation ou la lecture échouent, on crée un tableau vide
$session_data = array();
} else {
// les données sauvées sont dans $tmp[0].
$session_data = unserialize($tmp[0]);
if (!is_array($session_data)) {
// Erreur... initialisation d'un tableau vide
$session_data = array();
}
}
?>

Exemple #2 Exemple avec la directive unserialize_callback_func

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

ini_set('unserialize_callback_func', 'mycallback');

function mycallback($classname)
{
// Incluez simplement un fichier contenant votre définition de classe
// vous saurez quelle classe grâce à $classname
}
?>

Notes

Avertissement

false est retourné dans les cas où une erreur survient et si vous tentez de désérialiser une valeur sérialisée égale à false. Il est possible d'intercepter ce cas spécial en comparant data avec serialize(false) ou en attrapant l'erreur E_NOTICE émise.

Voir aussi

  • json_encode() - Retourne la représentation JSON d'une valeur
  • json_decode() - Décode une chaîne JSON
  • hash_hmac() - Génère une valeur de clé de hachage en utilisant la méthode HMAC
  • serialize() - Génère une représentation stockable d'une valeur
  • Autoloading Classes
  • unserialize_callback_func
  • unserialize_max_depth
  • __wakeup()
  • __serialize()
  • __unserialize()

User Contributed Notes

OscarZarrus 20-Oct-2022 09:34
For those who are looking for an efficient solution for handling controversial "FALSE", they can use this function which in case of non-unserializable string, instead of a "FALSE", throws an Exception. Vice versa it returns the unserialized variable.
<?php
    /**
     * @param string $serializedString
     * @param array $options
     * @return mixed
     * @throws Exception
     */
    function UnSerialize(string $serializedString, array $options = []) {
        $_unserialized = @unserialize($serializedString, $options);
        if ($serializedString === serialize(false) || $_unserialized !== false){
            return $_unserialized;
        }
        throw new Exception("Non-unserializable string");

    }

?>
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.


Détruit une variable

  • « unserialize
  • var_dump »
  • PHP Manual
  • Fonctions de gestion des variables
  • Détruit une variable

unset

(PHP 4, PHP 5, PHP 7, PHP 8)

unset — Détruit une variable

Description

unset(mixed $var, mixed ...$vars): void

unset() détruit la ou les variables dont le nom a été passé en argument var.

Le comportement de unset() à l'intérieur d'une fonction peut varier suivant le type de variable que vous voulez détruire.

Si une variable globale est détruite avec unset() depuis une fonction, seule la variable locale sera détruite. La variable globale gardera la valeur acquise avant l'appel à unset().

<?php
function destroy_foo()
{
global $foo;
unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

L'exemple ci-dessus va afficher :

bar

Pour détruire une variable globale à l'intérieur d'une fonction, vous pouvez utiliser le tableau $GLOBALS :

<?php
function foo()
{
unset($GLOBALS['bar']);
}

$bar = "truc";
foo();
?>

Si une variable qui est passée par référence est détruite à l'intérieur d'une fonction, seule la variable locale sera détruite. La variable globale conservera la même valeur qu'elle avait avant l'appel de unset().

<?php
function foo(&$bar)
{
unset($bar);
$bar = "blah";
}

$bar = 'truc';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

L'exemple ci-dessus va afficher :

truc
truc

Si une variable statique est détruite à l'intérieur d'une fonction unset() détruira la variable seulement dans le contexte du reste de la fonction. Les appels suivants restaureront la valeur précédente de la variable.

<?php
function foo()
{
static $bar;
$bar++;
echo "Avant unset : $bar, ";
unset($bar);
$bar = 23;
echo "après unset : $bar\n";
}

foo();
foo();
foo();
?>

L'exemple ci-dessus va afficher :

Avant unset : 1, après unset: 23
Avant unset : 2, après unset: 23
Avant unset : 3, après unset: 23

Liste de paramètres

var

La variable à détruire.

vars

Variables supplémentaires.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec unset()

<?php
// Destruction d'une seule variable
unset($foo);

// Destruction d'un élément de tableau
unset($bar['quux']);

// Destruction de plusieurs variables
unset($foo1, $foo2, $foo3);
?>

Exemple #2 Exemple avec un transtypage (unset)

Le transtypage (unset) est souvent confondu avec la fonction unset(). Le transtypage (unset) sert uniquement à transtyper en type NULL. Il n'altère pas la variable transtypée. Le transtypage (unset) est obsolète à partir de PHP 7.2.0 et supprimé à partir de 8.0.0.

<?php
$name = 'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

L'exemple ci-dessus va afficher :

NULL
string(6) "Felipe"

Notes

Note: Comme ceci est une structure du langage, et non pas une fonction, il n'est pas possible de l'appeler avec les fonctions variables ou arguments nommés.

Note:

Il est possible de détruire n'importe quelle propriété visible dans le contexte courant.

Si déclaré, __get() est appelé lors de l'accès à une propriété non définie, et __set() est appelé lors de la définition d'une propriété non définie.

Note:

Il n'est pas possible de détruire la variable spéciale $this à l'intérieur d'une méthode d'un objet.

Note:

Lors de l'utilisation de cette fonction sur des propriétés d'objet inaccessibles, la méthode magique __unset sera appelée, si elle existe.

Voir aussi

  • isset() - Détermine si une variable est déclarée et est différente de null
  • __unset()
  • empty() - Détermine si une variable est vide
  • array_splice() - Efface et remplace une portion de tableau
  • (unset) casting

User Contributed Notes

tecdoc at ukr dot net 28-Apr-2022 09:25
Be careful!, unset() element in array advances the internal array pointer one place forward
ray.paseur sometimes uses gmail 08-Mar-2022 08:55
Perhaps because it is a language construct and not a function, if you try to use the error suppression operator ...

@unset($var);

... you get this: Parse error: syntax error, unexpected 'unset' (T_UNSET) ...
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 )

?>
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


Affiche les informations d'une variable

  • « unset
  • var_export »
  • PHP Manual
  • Fonctions de gestion des variables
  • Affiche les informations d'une variable

var_dump

(PHP 4, PHP 5, PHP 7, PHP 8)

var_dump — Affiche les informations d'une variable

Description

var_dump(mixed $value, mixed ...$values): void

var_dump() affiche les informations structurées d'une variable, y compris son type et sa valeur. Les tableaux et les objets sont explorés récursivement, avec des indentations, pour mettre en valeur leur structure.

Toutes les propriétés publiques, privées et protégées des objets seront retournées dans la sortie à moins que l'objet n'implémente une méthode __debugInfo().

Astuce

Comme pour toutes les fonctions qui affichent directement des résultats au navigateur, les fonctions de gestion des sorties peuvent être utilisées pour capturer la sortie de cette fonction et l'enregistrer dans une chaîne de caractères (par exemple).

Liste de paramètres

value

L'expression afficher.

values

Expression supplémentaire à afficher.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec var_dump()

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

L'exemple ci-dessus va afficher :

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);

?>

L'exemple ci-dessus va afficher :

float(3.1)
bool(true)

Voir aussi

  • print_r() - Affiche des informations lisibles pour une variable
  • debug_zval_dump() - Extrait une représentation sous forme de chaîne de la structure interne d'une zval pour affichage
  • var_export() - Retourne le code PHP utilisé pour générer une variable
  • __debugInfo()

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.


Retourne le code PHP utilisé pour générer une variable

  • « var_dump
  • Services Web »
  • PHP Manual
  • Fonctions de gestion des variables
  • Retourne le code PHP utilisé pour générer une variable

var_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

var_export — Retourne le code PHP utilisé pour générer une variable

Description

var_export(mixed $value, bool $return = false): ?string

var_export() retourne des données structurées sur la variable donnée. C'est le même principe que var_dump() mais avec une exception : le résultat retourné est du code PHP valide.

Liste de paramètres

value

La variable que vous voulez exporter.

return

Si utilisé et mis à true, var_export() retournera la représentation de la variable au lieu de l'afficher.

Valeurs de retour

Retourne la représentation de la variable lorsque le paramètre return est utilisé et évalué à true. Autrement, cette fonction retournera null.

Historique

Version | Description
8.2.0 | Les noms de classe exportés sont désormais pleinement qualifiés. Auparavant, l'antislash principal était omis.
7.3.0 | Exporte désormais les objets stdClass en tant qu'un tableau transtyper vers un objet ((object) array( ... )), au lieu d'utiliser la méthode non existante stdClass::__setState(). L'effet pratique est que désormais stdClass est exportable, et que le code résultant fonctionnera même sur des versions antérieure de PHP.

Exemples

Exemple #1 Exemple avec var_export()

<?php

$a = array (1, 2, array ("a", "b", "c"));
var_export($a);

?>

L'exemple ci-dessus va afficher :

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

?>

L'exemple ci-dessus va afficher :

3.1

Exemple #2 Exporter stdClass (à partir de PHP 7.3.0)

<?php
$person = new stdClass;
$person->name = 'ElePHPant ElePHPantsdotter';
$person->website = 'https://php.net/elephpant.php';

var_export($person);

L'exemple ci-dessus va afficher :

(object) array(
   'name' => 'ElePHPant ElePHPantsdotter',
   'website' => 'https://php.net/elephpant.php',
)

Exemple #3 Exporter des classes

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

L'exemple ci-dessus va afficher :

A::__set_state(array(
   'var' => 5,
))

Exemple #4 Utilisation de __set_state

<?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);
?>

L'exemple ci-dessus va afficher :

object(A)#2 (2) {
    ["var1"]=>
    int(5)
    ["var2"]=>
    string(3) "foo"
}

Notes

Note:

Les variables de type ressource ne peuvent être exportées par cette fonction.

Note:

var_export() ne gère pas les références circulaires car il serait impossible de générer un code PHP analysable pour ce type de données. Si vous voulez faire quelque chose avec la représentation complète d'un tableau ou d'un objet, utilisez la fonction serialize().

Avertissement

Antérieur à PHP 8.2.0, lorsque var_export() exporte des objets, l'antislash initial n'est pas inclus dans l'espace de nom de la classe et ce, pour un maximum de compatibilité.

Note:

Pour être capable d'évaluer le PHP généré par var_export(), tous les objets analysés doivent implémenter la méthode magique __set_state. La seule exception est stdClass; qui est exportée en utilisant un cast d'un tableau à un objet.

Voir aussi

  • print_r() - Affiche des informations lisibles pour une variable
  • serialize() - Génère une représentation stockable d'une valeur
  • var_dump() - Affiche les informations d'une variable

User Contributed Notes

php dot net at rupert-eibauer dot de 08-Oct-2022 01:02
Warning: var_export fails to create distinct property names if you have a private property in your class and one with the same name in a parent class.

<?php
class TestParent {
    private $priv = "Parent Private";
    protected $prot = "Parent Protected";
    public $pub = "Parent Public";
}
class Test extends TestParent {
    private $priv = "Private Info";
    protected $prot = "Protected Info";
    public $pub = "Public Info";
}
$t = new Test;
var_export($t);
Result:
Test::__set_state(array(
   'priv' => 'Private Info',
   'prot' => 'Protected Info',
   'pub' => 'Public Info',
   'priv' => 'Parent Private',
))
?>

To work around that problem, I created my own var_export, which also uses a more compact format, and using [] for arrays:

<?php
function var_export3($var, $indent = '') {
    if (is_array($var)) {
        $indent .= '    ';
        $ret = '';
        $i = 0;
        $is_num = true;
        foreach ($var AS $idx => $value) {
            if ($ret != '')
                $ret .= ",\n";
            if ($is_num && $idx === $i) {
                $i++;
                $ret .= $indent.var_export3($value, $indent);
            } else {
                $is_num = false;
                $ret .= $indent.var_export3($idx).'=>'.var_export3($value, $indent);
            }
        }
        if ($ret == '')
            return "[]";
        return "[\n".$ret."]";
    } else if (is_bool($var)) {
        return $var ? 'true' : 'false';
    } else if (is_int($var) || is_float($var)) {
        return $var;
    } else if (is_string($var)) {
        if ($var === (string)(float)$var)
            return $var;
        return "'".str_replace(["\0", '\\', '\''], ["\\0", '\\', '\\\''], $var)."'";
    } else if (is_object($var)) {
        $class = get_class($var);
        if ($class == 'stdClass') {
            $prefix = ;
            return "(object)".var_export3((array)$var, $indent);
        } else {
            return "$class::__set_state(".var_export3((array)$var, $indent).')';
        }
    }
}

echo var_export3($t)."\n";
Result:
Test::__set_state([
        '\0Test\0priv'=>'Private Info',
        '\0*\0prot'=>'Protected Info',
        'pub'=>'Public Info',
        '\0TestParent\0priv'=>'Parent Private'])
?>
Note that replacement for non-printable characters is not complete.
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...


Services Web

  • OAuth
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Exemples
    • Fonctions OAuth
    • OAuth — La classe OAuth
    • OAuthProvider — La classe OAuthProvider
    • OAuthException — La classe OAuthException
  • SOAP
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Fonctions SOAP
    • SoapClient — La classe SoapClient
    • SoapServer — La classe SoapServer
    • SoapFault — La classe SoapFault
    • SoapHeader — La classe SoapHeader
    • SoapParam — La classe SoapParam
    • SoapVar — La classe SoapVar
  • Yar — Yet Another RPC Framework
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Exemples
    • Yar_Server — La classe Yar_Server
    • Yar_Client — La classe Yar_Client
    • Yar_Concurrent_Client — La classe Yar_Concurrent_Client
    • Yar_Server_Exception — La classe Yar_Server_Exception
    • Yar_Client_Exception — La classe Yar_Client_Exception
  • XML-RPC
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Fonctions XML-RPC

User Contributed Notes

There are no user contributed notes for this page.


OAuth

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Exemples
    • FireEagle
  • Fonctions OAuth
    • oauth_get_sbs — Génère une chaîne de base de signature
    • oauth_urlencode — Encode une URI conformément à RFC 3986
  • OAuth — La classe OAuth
    • OAuth::__construct — Crée un nouvel objet OAuth
    • OAuth::__destruct — Le destructeur
    • OAuth::disableDebug — Désactive les messages de déboguage
    • OAuth::disableRedirects — Désactive les redirections
    • OAuth::disableSSLChecks — Désactive la vérification SSL
    • OAuth::enableDebug — Active les messages de débogage
    • OAuth::enableRedirects — Active les redirections
    • OAuth::enableSSLChecks — Active la vérification SSL
    • OAuth::fetch — Lit une ressource protégée par OAuth
    • OAuth::generateSignature — Génère une signature
    • OAuth::getAccessToken — Récupère un token d'accès
    • OAuth::getCAPath — Récupère l'information CA
    • OAuth::getLastResponse — Lit la dernière réponse
    • OAuth::getLastResponseHeaders — Récupère les en-têtes de la dernière réponse
    • OAuth::getLastResponseInfo — Lit les informations HTTP de la dernière réponse
    • OAuth::getRequestHeader — Génère une signature d'en-tête OAuth
    • OAuth::getRequestToken — Lit le token de requête
    • OAuth::setAuthType — Définit le type d'autorisation
    • OAuth::setCAPath — Définit le chemin et les informations du CA
    • OAuth::setNonce — Configure le nonce OAuth
    • OAuth::setRequestEngine — Le but de setRequestEngine
    • OAuth::setRSACertificate — Définit le certificat RSA
    • OAuth::setSSLChecks — Définit des vérifications spécifiques à SSL pour les requêtes
    • OAuth::setTimestamp — Définit le timestamp
    • OAuth::setToken — Configure le token et le secret
    • OAuth::setVersion — Configure la version OAuth
  • OAuthProvider — La classe OAuthProvider
    • OAuthProvider::addRequiredParameter — Ajoute des paramètres requis
    • OAuthProvider::callconsumerHandler — Appelle la fonction de rappel consumerNonceHandler
    • OAuthProvider::callTimestampNonceHandler — Appelle la fonction de rappel timestampNonceHandler
    • OAuthProvider::calltokenHandler — Appelle la fonction de rappel tokenNonceHandler
    • OAuthProvider::checkOAuthRequest — Vérifie une requête OAuth
    • OAuthProvider::__construct — Construit un nouvel objet OAuthProvider
    • OAuthProvider::consumerHandler — Définit la fonction de rappel consumerHandler
    • OAuthProvider::generateToken — Génère un jeton aléatoire
    • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint — Définit isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter — Supprime un paramètre
    • OAuthProvider::reportProblem — Rapporte un problème
    • OAuthProvider::setParam — Définit un paramètre
    • OAuthProvider::setRequestTokenPath — Définit le chemin du jeton demandé
    • OAuthProvider::timestampNonceHandler — Définit le gestionnaire de rappel timestampNonceHandler
    • OAuthProvider::tokenHandler — Définit le gestionnaire de rappel tokenHandler
  • OAuthException — La classe OAuthException

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Cette extension fournit un client et un prestataire de service OAuth 1.0a. OAuth est un protocole d'autorisation qui est construit sur HTTP, et qui permet aux applications de sécuriser l'accès aux données sans avoir à stocker de noms d'utilisateurs et de mots de passe.

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.


Pré-requis

PECL/oauth requiert PHP 5.1 ou plus récent, les extensions ext/hash et ext/pcre.

PECL/oauth peut aussi nécessiter la bibliothèque libcurl si elle a été sélectionnée au moment de la compilation. Si c'est le cas, PECL/oauth doit aussi être compilé avec le support HTTPS.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Des informations sur l'installation de ces extensions PECL peuvent être trouvées dans le chapitre du manuel intitulé Installation des extensions PECL. D'autres informations comme les notes sur les nouvelles versions, les téléchargements, les sources des fichiers, les informations concernant les mainteneurs ainsi qu'un CHANGELOG, peuvent être trouvées ici : » https://pear.php.net/package/oauth

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

La plupart de ces constantes impliquent des problèmes décrits dans la documentation officiels de » rapport de problèmes d'OAuth. Notez cependant que les noms des constantes sont spécifiques à PHP, malgré le fait que le schéma de nommage est similaire.

OAUTH_SIG_METHOD_RSASHA1 (string)
Méthode de signature OAuth RSA-SHA1.
OAUTH_SIG_METHOD_HMACSHA1 (string)

Méthode de signature OAuth HMAC-SHA1.

OAUTH_SIG_METHOD_HMACSHA256 (string)
Méthode de signature OAuth HMAC-SHA256.
OAUTH_AUTH_TYPE_AUTHORIZATION (string)

Cette constante représente l'entête Authorization.

OAUTH_AUTH_TYPE_NONE (string)

Cette constante indique une requête NoAuth OAuth.

OAUTH_AUTH_TYPE_URI (string)

Cette constante représente les paramètres OAuth dans l'URI de requête.

OAUTH_AUTH_TYPE_FORM (string)

Cette constante représente les paramètres OAuth comme une partie du corps HTTP POST.

OAUTH_HTTP_METHOD_GET (string)

Utilise la méthode GET pour la requête OAuth.

OAUTH_HTTP_METHOD_POST (string)

Utilise la méthode POST pour la requête OAuth.

OAUTH_HTTP_METHOD_PUT (string)

Utilise la méthode PUT pour la requête OAuth.

OAUTH_HTTP_METHOD_HEAD (string)

Utilise la méthode HEAD pour la requête OAuth.

OAUTH_HTTP_METHOD_DELETE (string)
Utilise la méthode DELETE pour la requête OAuth.
OAUTH_REQENGINE_STREAMS (int)
Utilisé par la méthode Oauth::setRequestEngine() pour définir le moteur de flux PHP, à l'opposé de OAUTH_REQENGINE_CURL pour Curl.
OAUTH_REQENGINE_CURL (int)
Utilisé par la méthode Oauth::setReqeustEngine() pour définir le moteur de Curl, à l'opposé de OAUTH_REQENGINE_STREAMS pour les flux PHP.
OAUTH_OK (int)
La vie est belle.
OAUTH_BAD_NONCE (int)
La valeur oauth_nonce a été utilisée pour une précédente requête, et ne peut être utilisée maintenant.
OAUTH_BAD_TIMESTAMP (int)
La valeur oauth_timestamp n'est pas acceptée par le prestataire de service. Dans ce cas, la réponse devra aussi contenir le paramètre oauth_acceptable_timestamps.
OAUTH_CONSUMER_KEY_UNKNOWN (int)
oauth_consumer_key est temporairement innaceptable par le prestataire de service. Par exemple, le prestataire de service surcharge le consommateur.
OAUTH_CONSUMER_KEY_REFUSED (int)
La clé du consommateur a été refusée.
OAUTH_INVALID_SIGNATURE (int)
oauth_signature est invalide car elle ne correspond pas à la signature calculée par le prestataire de service.
OAUTH_TOKEN_USED (int)
oauth_token a été consommé. Elle ne peut plus être utilisée car elle a déjà été utilisée dans une ou plusieurs précédentes requêtes.
OAUTH_TOKEN_EXPIRED (int)
oauth_token a expiré.
OAUTH_TOKEN_REVOKED (int)
oauth_token a été révoquée et ne pourra plus être acceptée.
OAUTH_TOKEN_REJECTED (int)
oauth_token n'a pas été acceptée par le prestataire de service. La raison est inconnue, mais il se peut que le jeton n'a jamais été utilisé, a déjà été consommé, a expiré et/ou a été oublié par le prestataire de service.
OAUTH_VERIFIER_INVALID (int)
oauth_verifier est incorrect.
OAUTH_PARAMETER_ABSENT (int)
Un paramètre requis n'a pas été reçu. Dans ce cas, la réponse devra également contenir le paramètre oauth_parameters_absent.
OAUTH_SIGNATURE_METHOD_REJECTED (int)
oauth_signature_method n'a pas été accepté par le prestataire de service.

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Sommaire

  • 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();

// En état state=1 la prochaine requete doit inclure le oauth_token.
// Si ce n'est pas le cas, retour à 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");


Fonctions OAuth

Sommaire

  • oauth_get_sbs — Génère une chaîne de base de signature
  • oauth_urlencode — Encode une URI conformément à RFC 3986

User Contributed Notes

There are no user contributed notes for this page.


Génère une chaîne de base de signature

  • « Fonctions OAuth
  • oauth_urlencode »
  • PHP Manual
  • Fonctions OAuth
  • Génère une chaîne de base de signature

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — Génère une chaîne de base de signature

Description

oauth_get_sbs(string $http_method, string $uri, array $request_parameters = ?): string

Génère une chaîne de base de signature pour pecl/oauth.

Liste de paramètres

http_method

La méthode HTTP.

uri

L'URI à encoder.

request_parameters

Tableau de paramètres de requêtes.

Valeurs de retour

Retourne une chaîne, la Signature Base String.

User Contributed Notes

There are no user contributed notes for this page.


Encode une URI conformément à RFC 3986

  • « oauth_get_sbs
  • OAuth »
  • PHP Manual
  • Fonctions OAuth
  • Encode une URI conformément à RFC 3986

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — Encode une URI conformément à RFC 3986

Description

oauth_urlencode(string $uri): string

Encodes une URI conformément à » RFC 3986.

Liste de paramètres

uri

l'URI à encoder.

Valeurs de retour

Retourne une chaîne encodée conformément à » 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;
}

?>


La classe OAuth

(PECL OAuth >= 0.99.1)

Introduction

L'extension OAuth fournit une interface simple pour interagir avec des fournisseur de données, en utilisant les spécifications OAuth HTTP pour protéger les ressources.

Synopsis de la classe

class OAuth {
/* Propriétés */
public $debug;
public $sslChecks;
public $debugInfo;
/* Méthodes */
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|false
public getAccessToken(
string $access_token_url,
string $auth_session_handle = ?,
string $verifier_token = ?,
string $http_method = ?
): array
public getCAPath(): array
public getLastResponse(): string
public getLastResponseHeaders(): string|false
public getLastResponseInfo(): array
public getRequestHeader(string $http_method, string $url, mixed $extra_parameters = ?): string|false
public getRequestToken(string $request_token_url, string $callback_url = ?, string $http_method = ?): array
public setAuthType(int $auth_type): bool
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
}

Propriétés

debug

sslChecks

debugInfo

Sommaire

  • OAuth::__construct — Crée un nouvel objet OAuth
  • OAuth::__destruct — Le destructeur
  • OAuth::disableDebug — Désactive les messages de déboguage
  • OAuth::disableRedirects — Désactive les redirections
  • OAuth::disableSSLChecks — Désactive la vérification SSL
  • OAuth::enableDebug — Active les messages de débogage
  • OAuth::enableRedirects — Active les redirections
  • OAuth::enableSSLChecks — Active la vérification SSL
  • OAuth::fetch — Lit une ressource protégée par OAuth
  • OAuth::generateSignature — Génère une signature
  • OAuth::getAccessToken — Récupère un token d'accès
  • OAuth::getCAPath — Récupère l'information CA
  • OAuth::getLastResponse — Lit la dernière réponse
  • OAuth::getLastResponseHeaders — Récupère les en-têtes de la dernière réponse
  • OAuth::getLastResponseInfo — Lit les informations HTTP de la dernière réponse
  • OAuth::getRequestHeader — Génère une signature d'en-tête OAuth
  • OAuth::getRequestToken — Lit le token de requête
  • OAuth::setAuthType — Définit le type d'autorisation
  • OAuth::setCAPath — Définit le chemin et les informations du CA
  • OAuth::setNonce — Configure le nonce OAuth
  • OAuth::setRequestEngine — Le but de setRequestEngine
  • OAuth::setRSACertificate — Définit le certificat RSA
  • OAuth::setSSLChecks — Définit des vérifications spécifiques à SSL pour les requêtes
  • OAuth::setTimestamp — Définit le timestamp
  • OAuth::setToken — Configure le token et le secret
  • OAuth::setVersion — Configure la version OAuth

User Contributed Notes

There are no user contributed notes for this page.


Crée un nouvel objet OAuth

  • « OAuth
  • OAuth::__destruct »
  • PHP Manual
  • OAuth
  • Crée un nouvel objet OAuth

OAuth::__construct

(PECL OAuth >= 0.99.1)

OAuth::__construct — Crée un nouvel objet OAuth

Description

public OAuth::__construct(
string $consumer_key,
string $consumer_secret,
string $signature_method = OAUTH_SIG_METHOD_HMACSHA1,
int $auth_type = 0
)

Crée un nouvel objet OAuth.

Liste de paramètres

consumer_key

La clé de lecture fournie par le fournisseur de services.

consumer_secret

Le secret de lecture fourni par le fournisseur de services.

signature_method

Ce paramètre optionnel définit la méthode de signature utilisée. Par défaut, c'est OAUTH_SIG_METHOD_HMACSHA1 (HMAC-SHA1).

auth_type

Ce paramètre optionnel définit la méthode de passage des paramètres OAuth au fournisseur de services. Par défaut, c'est OAUTH_AUTH_TYPE_AUTHORIZATION (dans l'entête 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


Le destructeur

  • « OAuth::__construct
  • OAuth::disableDebug »
  • PHP Manual
  • OAuth
  • Le destructeur

OAuth::__destruct

(PECL OAuth >= 0.99.9)

OAuth::__destruct — Le destructeur

Description

public OAuth::__destruct(): void

Le destructeur.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • OAuth::__construct() - Crée un nouvel objet OAuth

User Contributed Notes

There are no user contributed notes for this page.


Désactive les messages de déboguage

  • « OAuth::__destruct
  • OAuth::disableRedirects »
  • PHP Manual
  • OAuth
  • Désactive les messages de déboguage

OAuth::disableDebug

(PECL OAuth >= 0.99.3)

OAuth::disableDebug — Désactive les messages de déboguage

Description

public OAuth::disableDebug(): bool

Désactive les messages de déboguage. Il est désactivé par défaut. Vous pouvez définir la propriété debug à false pour désactiver le déboguage.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true

Historique

Version | Description
PECL oauth 0.99.8 | La propriété debug a été ajoutée

Voir aussi

  • OAuth::enableDebug() - Active les messages de débogage

User Contributed Notes

There are no user contributed notes for this page.


Désactive les redirections

  • « OAuth::disableDebug
  • OAuth::disableSSLChecks »
  • PHP Manual
  • OAuth
  • Désactive les redirections

OAuth::disableRedirects

(PECL OAuth >= 0.99.9)

OAuth::disableRedirects — Désactive les redirections

Description

public OAuth::disableRedirects(): bool

Désactive les redirections, permettant ainsi aux requêtes d'être redirigées manuellement.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true

Voir aussi

  • OAuth::enableRedirects() - Active les redirections

User Contributed Notes

There are no user contributed notes for this page.


Désactive la vérification SSL

  • « OAuth::disableRedirects
  • OAuth::enableDebug »
  • PHP Manual
  • OAuth
  • Désactive la vérification SSL

OAuth::disableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::disableSSLChecks — Désactive la vérification SSL

Description

public OAuth::disableSSLChecks(): bool

Désactive les vérifications de certificats et d'hôtes SLL (activé par défaut). Il est recommandé de ne pas utiliser cette fonction en production.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true

Historique

Version | Description
PECL oauth 0.99.8 | La propriété debug a été ajoutée

Voir aussi

  • OAuth::enableSSLChecks() - Active la vérification SSL

User Contributed Notes

There are no user contributed notes for this page.


Active les messages de débogage

  • « OAuth::disableSSLChecks
  • OAuth::enableRedirects »
  • PHP Manual
  • OAuth
  • Active les messages de débogage

OAuth::enableDebug

(PECL OAuth >= 0.99.3)

OAuth::enableDebug — Active les messages de débogage

Description

public OAuth::enableDebug(): bool

Active les messages de débogage, pratiques en développement, mais inutiles en production.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true

Historique

Version | Description
PECL oauth 0.99.8 | La propriété debug a été ajoutée

Voir aussi

  • OAuth::disableDebug() - Désactive les messages de déboguage

User Contributed Notes

There are no user contributed notes for this page.


Active les redirections

  • « OAuth::enableDebug
  • OAuth::enableSSLChecks »
  • PHP Manual
  • OAuth
  • Active les redirections

OAuth::enableRedirects

(PECL OAuth >= 0.99.9)

OAuth::enableRedirects — Active les redirections

Description

public OAuth::enableRedirects(): bool

Suit les redirections automatiquement ; c'est le comportement par défaut.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true

Voir aussi

  • OAuth::disableRedirects() - Désactive les redirections

User Contributed Notes

There are no user contributed notes for this page.


Active la vérification SSL

  • « OAuth::enableRedirects
  • OAuth::fetch »
  • PHP Manual
  • OAuth
  • Active la vérification SSL

OAuth::enableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::enableSSLChecks — Active la vérification SSL

Description

public OAuth::enableSSLChecks(): bool

Active les vérifications de certificats et d'hôtes SLL (activé par défaut).

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true

Historique

Version | Description
PECL oauth 0.99.8 | La propriété debug a été ajoutée

Voir aussi

  • OAuth::disableSSLChecks() - Désactive la vérification SSL

User Contributed Notes

There are no user contributed notes for this page.


Lit une ressource protégée par OAuth

  • « OAuth::enableSSLChecks
  • OAuth::generateSignature »
  • PHP Manual
  • OAuth
  • Lit une ressource protégée par OAuth

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch — Lit une ressource protégée par OAuth

Description

public OAuth::fetch(
string $protected_resource_url,
array $extra_parameters = ?,
string $http_method = ?,
array $http_headers = ?
): mixed

Lit une ressource protégée par OAuth.

Liste de paramètres

protected_resource_url

URL de la ressource protégées par OAuth.

extra_parameters

Paramètres supplémentaires à envoyer avec la requête, à la ressource.

http_method

Une des constantes OAUTH constants OAUTH_HTTP_METHOD_*, incluant GET, POST, PUT, HEAD, ou DELETE.

HEAD (OAUTH_HTTP_METHOD_HEAD) peut être utile pour découvrir des informations avant la demande (si les autorisations OAuth sont dans l'en-tête Authorization header).

http_headers

Les entêtes client HTTP (tels que User-Agent, Accept, etc.)

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.
PECL oauth 0.99.5 | Ajout du paramètre http_method
PECL oauth 0.99.8 | Ajout du paramètre http_headers

Exemples

Exemple #1 Exemple avec OAuth::fetch()

<?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";
}
?>

Voir aussi

  • OAuth::getLastResponse() - Lit la dernière réponse
  • OAuth::getLastResponseInfo() - Lit les informations HTTP de la dernière réponse
  • OAuth::setToken() - Configure le token et le 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.


Génère une signature

  • « OAuth::fetch
  • OAuth::getAccessToken »
  • PHP Manual
  • OAuth
  • Génère une signature

OAuth::generateSignature

(No version information available, might only be in Git)

OAuth::generateSignature — Génère une signature

Description

public OAuth::generateSignature(string $http_method, string $url, mixed $extra_parameters = ?): string|false

Génère une signature basée sur la méthode HTTP finale, l'URL et une chaîne/tableau de paramètres.

Liste de paramètres

http_method

Méthode HTTP pour la requête.

url

URL de la requête.

extra_parameters

Chaîne ou tableau de paramètres additionnels.

Valeurs de retour

Une chaîne contenant la signature générée ou false si une erreur survient

User Contributed Notes

vk221000 at gmail dot com 03-Jan-2022 11:46
<?php
/**
     * Get signature for the request Oauth 1.0
     *
     * @param string      $url url to send request to.
     * @param string      $consumer_key consumer key for the request credential.
     * @param string      $consumer_secret consumer secret for the request credential.
     * @param string      $method GET, POST etc methods.
     * @param array|false $params parameters to send during the request.
     * @since 1.0.0
     * @return string
     */
    public function get_signature( $url, $consumer_key, $consumer_secret, $method = 'GET', $params = false ) {
            $nonce     = mt_rand();
            $timestamp = time();
            $oauth     = new \OAuth( $consumer_key, $consumer_secret );
            $oauth->setTimestamp( $timestamp );
            $oauth->setNonce( $nonce );
            $sig = $oauth->generateSignature( $method, $url, $params );

            $header = 'OAuth ' .
                'oauth_consumer_key=' . $consumer_key .
                ',oauth_signature_method="HMAC-SHA1"' .
                ',oauth_nonce="'. $nonce . '"' .
                ',oauth_timestamp="' . $timestamp . '"'.
                ',oauth_version="1.0"'.
                ',oauth_signature="' . urlencode( $sig ) . '"'
                ;
            return $header;
    }
?>


Récupère un token d'accès

  • « OAuth::generateSignature
  • OAuth::getCAPath »
  • PHP Manual
  • OAuth
  • Récupère un token d'accès

OAuth::getAccessToken

(PECL OAuth >= 0.99.1)

OAuth::getAccessToken — Récupère un token d'accès

Description

public OAuth::getAccessToken(
string $access_token_url,
string $auth_session_handle = ?,
string $verifier_token = ?,
string $http_method = ?
): array

Lit un token d'accès, un secret et toute information supplémentaire chez un fournisseur de services.

Liste de paramètres

access_token_url

L'URL à utiliser.

auth_session_handle

L'identifiant de session. Ce paramètre n'a pas d'existence dans les spécifications OAuth 1.0, mais peut être mis en place par de grosses implémentations. Voyez » ScalableOAuth pour plus de détails.

verifier_token

Pour les fournisseurs de service qui supportent 1.0a, le paramètre verifier_token doit être fourni, lors de l'échange de token de requête pour obtenir le token d'accès. Si verifier_token est présent dans $_GET ou $_POST, il est automatiquement passé et l'appelant n'a pas besoin de préciser de paramètre verifier_token (généralement, le token d'accès est échangé via l'URL de rappel callback_url.). Voyez » ScalableOAuth pour plus d'informations.

http_method

Méthode HTTP a utiliser, par exemple GET ou POST.

Valeurs de retour

Retourne un tableau contenant la réponse OAuth analyse, en cas de succès, et false sinon.

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.
PECL oauth 0.99.9 | Le paramètre verifier_token a été ajouté

Exemples

Exemple #1 Exemple avec 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";
}
?>

Résultat de l'exemple ci-dessus est similaire à :

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Voir aussi

  • OAuth::getLastResponse() - Lit la dernière réponse
  • OAuth::getLastResponseInfo() - Lit les informations HTTP de la dernière réponse
  • OAuth::setToken() - Configure le token et le secret

User Contributed Notes

There are no user contributed notes for this page.


Récupère l'information CA

  • « OAuth::getAccessToken
  • OAuth::getLastResponse »
  • PHP Manual
  • OAuth
  • Récupère l'information CA

OAuth::getCAPath

(PECL OAuth >= 0.99.8)

OAuth::getCAPath — Récupère l'information CA

Description

public OAuth::getCAPath(): array

Récupère les informations du certificat de l'autorité, incluant les valeurs de ca_path et ca_info définit par la méthode OAuth::setCaPath().

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Un tableau d'informations sur le certificat de l'autorité, contenant entre autres, les clés ca_path et ca_info.

Voir aussi

  • OAuth::setCAPath() - Définit le chemin et les informations du CA
  • OAuth::getLastResponseInfo() - Lit les informations HTTP de la dernière réponse

User Contributed Notes

There are no user contributed notes for this page.


Lit la dernière réponse

  • « OAuth::getCAPath
  • OAuth::getLastResponseHeaders »
  • PHP Manual
  • OAuth
  • Lit la dernière réponse

OAuth::getLastResponse

(PECL OAuth >= 0.99.1)

OAuth::getLastResponse — Lit la dernière réponse

Description

public OAuth::getLastResponse(): string

Lit la réponse brute de la dernière requête.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne une chaîne avec la dernière requête.

Voir aussi

  • OAuth::getLastResponseInfo() - Lit les informations HTTP de la dernière réponse
  • OAuth::fetch() - Lit une ressource protégée par OAuth

User Contributed Notes

There are no user contributed notes for this page.


Récupère les en-têtes de la dernière réponse

  • « OAuth::getLastResponse
  • OAuth::getLastResponseInfo »
  • PHP Manual
  • OAuth
  • Récupère les en-têtes de la dernière réponse

OAuth::getLastResponseHeaders

(No version information available, might only be in Git)

OAuth::getLastResponseHeaders — Récupère les en-têtes de la dernière réponse

Description

public OAuth::getLastResponseHeaders(): string|false

Récupère les en-têtes de la dernière réponse.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Une chaîne de caractères contenant les en-têtes de la dernière réponse ou false si une erreur survient

User Contributed Notes

There are no user contributed notes for this page.


Lit les informations HTTP de la dernière réponse

  • « OAuth::getLastResponseHeaders
  • OAuth::getRequestHeader »
  • PHP Manual
  • OAuth
  • Lit les informations HTTP de la dernière réponse

OAuth::getLastResponseInfo

(PECL OAuth >= 0.99.1)

OAuth::getLastResponseInfo — Lit les informations HTTP de la dernière réponse

Description

public OAuth::getLastResponseInfo(): array

Lit les informations HTTP de la dernière réponse.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne un tableau contenant les informations de réponse de la dernière requête. Les constantes de curl_getinfo() sont aussi utilisables.

Voir aussi

  • OAuth::fetch() - Lit une ressource protégée par OAuth
  • OAuth::getLastResponse() - Lit la dernière réponse

User Contributed Notes

There are no user contributed notes for this page.


Génère une signature d'en-tête OAuth

  • « OAuth::getLastResponseInfo
  • OAuth::getRequestToken »
  • PHP Manual
  • OAuth
  • Génère une signature d'en-tête OAuth

OAuth::getRequestHeader

(No version information available, might only be in Git)

OAuth::getRequestHeader — Génère une signature d'en-tête OAuth

Description

public OAuth::getRequestHeader(string $http_method, string $url, mixed $extra_parameters = ?): string|false

Génère une signature d'en-tête OAuth basée sur la méthode HTTP finale, ainsi que sur l'URL et ses paramètres.

Liste de paramètres

http_method

Méthode HTTP pour la demande.

url

URL de la demande.

extra_parameters

Paramètres additionnels (chaîne de caractères ou tableau).

Valeurs de retour

Une chaîne de caractères contenant l'en-tête généré de la demande ou false si une erreur survient

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.


Lit le token de requête

  • « OAuth::getRequestHeader
  • OAuth::setAuthType »
  • PHP Manual
  • OAuth
  • Lit le token de requête

OAuth::getRequestToken

(PECL OAuth >= 0.99.1)

OAuth::getRequestToken — Lit le token de requête

Description

public OAuth::getRequestToken(string $request_token_url, string $callback_url = ?, string $http_method = ?): array

Lit le token de requête, le secret et toute information supplémentaire du fournisseur de services.

Liste de paramètres

request_token_url

l'URL dont il faut obtenir le token.

callback_url

URL de rappel OAuth. Si callback_url est passé et que sa valeur est vide, il prend alors la valeur de "oob" pour satisfaire aux exigences de OAuth 2009.1 advisory.

http_method

Méthode HTTP a utiliser, par exemple GET ou POST.

Valeurs de retour

Retourne un tableau contenant la réponse OAuth analysée, en cas de succès, ou false en cas d'échec.

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.
PECL oauth 0.99.9 | Le paramètre callback_url a été ajouté

Exemples

Exemple #1 Exemple avec 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";
}
?>

Résultat de l'exemple ci-dessus est similaire à :

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Voir aussi

  • OAuth::getLastResponse() - Lit la dernière réponse
  • OAuth::getLastResponseInfo() - Lit les informations HTTP de la dernière réponse

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.


Définit le type d'autorisation

  • « OAuth::getRequestToken
  • OAuth::setCAPath »
  • PHP Manual
  • OAuth
  • Définit le type d'autorisation

OAuth::setAuthType

(PECL OAuth >= 0.99.1)

OAuth::setAuthType — Définit le type d'autorisation

Description

public OAuth::setAuthType(int $auth_type): bool

Configure les paramètres OAuth.

Liste de paramètres

auth_type

auth_type peut être un des options suivantes (elles sont classées par ordre décroissant de préférence, tel que précisé dans OAuth 1.0 section 5.2) :

OAUTH_AUTH_TYPE_AUTHORIZATION
Passe les paramètres OAuth dans l'entête HTTP Authorization.
OAUTH_AUTH_TYPE_FORM
Ajoute les paramètres OAuth au corps de la requête HTTP POST.
OAUTH_AUTH_TYPE_URI
Ajoute les paramètres OAuth à l'URI.
OAUTH_AUTH_TYPE_NONE
Aucun.

Valeurs de retour

Retourne true si un paramètre est correctement défini, false dans les autres cas.

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.

User Contributed Notes

There are no user contributed notes for this page.


Définit le chemin et les informations du CA

  • « OAuth::setAuthType
  • OAuth::setNonce »
  • PHP Manual
  • OAuth
  • Définit le chemin et les informations du CA

OAuth::setCAPath

(PECL OAuth >= 0.99.8)

OAuth::setCAPath — Définit le chemin et les informations du CA

Description

public OAuth::setCAPath(string $ca_path = ?, string $ca_info = ?): mixed

Définit le certificat d'autorité (CA), pour à la fois le chemin et les informations.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

ca_path

Le chemin du CA à définir.

ca_info

Les informations du CA à définir.

Valeurs de retour

Retourne true en cas de succès, ou false si ca_path ou ca_info sont considérés comme invalide.

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.

Voir aussi

  • OAuth::getCaPath() - Récupère l'information CA

User Contributed Notes

There are no user contributed notes for this page.


Configure le nonce OAuth

  • « OAuth::setCAPath
  • OAuth::setRequestEngine »
  • PHP Manual
  • OAuth
  • Configure le nonce OAuth

OAuth::setNonce

(PECL OAuth >= 0.99.1)

OAuth::setNonce — Configure le nonce OAuth

Description

public OAuth::setNonce(string $nonce): mixed

Configure le nonce OAuth pour les appels suivants.

Liste de paramètres

nonce

La valeur de oauth_nonce.

Valeurs de retour

Retourne true en cas de succès, ou false si le paramètre nonce est considéré comme invalide.

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.

Voir aussi

  • OAuth::setToken() - Configure le token et le secret
  • OAuth::setAuthType() - Définit le type d'autorisation
  • OAuth::setVersion() - Configure la version OAuth

User Contributed Notes

There are no user contributed notes for this page.


Le but de setRequestEngine

  • « OAuth::setNonce
  • OAuth::setRSACertificate »
  • PHP Manual
  • OAuth
  • Le but de setRequestEngine

OAuth::setRequestEngine

(PECL OAuth >= 1.0.0)

OAuth::setRequestEngine — Le but de setRequestEngine

Description

public OAuth::setRequestEngine(int $reqengine): void

Définit le moteur de requête, utilisé pour envoyer les requêtes HTTP.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

reqengine

Le moteur de requêtes désiré. Définir à OAUTH_REQENGINE_STREAMS pour utiliser les flux PHP, ou OAUTH_REQENGINE_CURL pour utiliser Curl.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

Émet une exception OAuthException si un moteur de requêtes invalide est choisi.

Exemples

Exemple #1 Exemple avec OAuth::setRequestEngine()

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

Voir aussi

  • Curl
  • Les flux PHP
  • OAuthException

User Contributed Notes

There are no user contributed notes for this page.


Définit le certificat RSA

  • « OAuth::setRequestEngine
  • OAuth::setSSLChecks »
  • PHP Manual
  • OAuth
  • Définit le certificat RSA

OAuth::setRSACertificate

(PECL OAuth >= 1.0.0)

OAuth::setRSACertificate — Définit le certificat RSA

Description

public OAuth::setRSACertificate(string $cert): mixed

Définit le certificat RSA.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

cert

Le certificat RSA.

Valeurs de retour

Retourne true en cas de succès, ou false si une erreur survient (i.e., le certificat RSA ne peut être analysé.)

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.

Exemples

Exemple #1 Exemple avec OAuth::setRsaCertificate()

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

Voir aussi

  • OAuth::setCaPath() - Définit le chemin et les informations du CA

User Contributed Notes

There are no user contributed notes for this page.


Définit des vérifications spécifiques à SSL pour les requêtes

  • « OAuth::setRSACertificate
  • OAuth::setTimestamp »
  • PHP Manual
  • OAuth
  • Définit des vérifications spécifiques à SSL pour les requêtes

OAuth::setSSLChecks

(No version information available, might only be in Git)

OAuth::setSSLChecks — Définit des vérifications spécifiques à SSL pour les requêtes

Description

public OAuth::setSSLChecks(int $sslcheck): bool

Définit des vérifications spécifiques à SSL pour les requêtes.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

sslcheck

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

User Contributed Notes

There are no user contributed notes for this page.


Définit le timestamp

  • « OAuth::setSSLChecks
  • OAuth::setToken »
  • PHP Manual
  • OAuth
  • Définit le timestamp

OAuth::setTimestamp

(PECL OAuth >= 1.0.0)

OAuth::setTimestamp — Définit le timestamp

Description

public OAuth::setTimestamp(string $timestamp): mixed

Définit le timestamp OAuth pour les prochaines requêtes.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

timestamp

Le timestamp.

Valeurs de retour

Retourne true, ou false si timestamp est invalide.

Historique

Version | Description
PECL oauth 1.0.0 | Avant cette version, null était retourné au lieu de false.

Voir aussi

  • OAuth::setNonce() - Configure le nonce OAuth

User Contributed Notes

There are no user contributed notes for this page.


Configure le token et le secret

  • « OAuth::setTimestamp
  • OAuth::setVersion »
  • PHP Manual
  • OAuth
  • Configure le token et le secret

OAuth::setToken

(PECL OAuth >= 0.99.1)

OAuth::setToken — Configure le token et le secret

Description

public OAuth::setToken(string $token, string $token_secret): bool

Configure le token et le secret pour les prochains appels.

Liste de paramètres

token

Le token OAuth.

token_secret

Le secret OAuth.

Valeurs de retour

true

Exemples

Exemple #1 L'exemple 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.


Configure la version OAuth

  • « OAuth::setToken
  • OAuthProvider »
  • PHP Manual
  • OAuth
  • Configure la version OAuth

OAuth::setVersion

(PECL OAuth >= 0.99.1)

OAuth::setVersion — Configure la version OAuth

Description

public OAuth::setVersion(string $version): bool

Configure la version de OAuth pour les prochains appels.

Liste de paramètres

version

La version OAuth, et par défaut, c'est toujours "1.0"

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

User Contributed Notes

There are no user contributed notes for this page.


La classe OAuthProvider

(PECL OAuth >= 1.0.0)

Introduction

Gère une classe OAuthProvider.

Voir aussi un tutoriel externe nommé » Écrire un service OAuth Provider, qui fournit une bonne approche pour proposer ce service. Il y a également des » exemples OAuth provider directement dans les sources de l'extension OAuth.

Synopsis de la classe

class OAuthProvider {
/* Méthodes */
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
}

Sommaire

  • OAuthProvider::addRequiredParameter — Ajoute des paramètres requis
  • OAuthProvider::callconsumerHandler — Appelle la fonction de rappel consumerNonceHandler
  • OAuthProvider::callTimestampNonceHandler — Appelle la fonction de rappel timestampNonceHandler
  • OAuthProvider::calltokenHandler — Appelle la fonction de rappel tokenNonceHandler
  • OAuthProvider::checkOAuthRequest — Vérifie une requête OAuth
  • OAuthProvider::__construct — Construit un nouvel objet OAuthProvider
  • OAuthProvider::consumerHandler — Définit la fonction de rappel consumerHandler
  • OAuthProvider::generateToken — Génère un jeton aléatoire
  • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
  • OAuthProvider::isRequestTokenEndpoint — Définit isRequestTokenEndpoint
  • OAuthProvider::removeRequiredParameter — Supprime un paramètre
  • OAuthProvider::reportProblem — Rapporte un problème
  • OAuthProvider::setParam — Définit un paramètre
  • OAuthProvider::setRequestTokenPath — Définit le chemin du jeton demandé
  • OAuthProvider::timestampNonceHandler — Définit le gestionnaire de rappel timestampNonceHandler
  • OAuthProvider::tokenHandler — Définit le gestionnaire de rappel tokenHandler

User Contributed Notes

There are no user contributed notes for this page.


Ajoute des paramètres requis

  • « OAuthProvider
  • OAuthProvider::callconsumerHandler »
  • PHP Manual
  • OAuthProvider
  • Ajoute des paramètres requis

OAuthProvider::addRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::addRequiredParameter — Ajoute des paramètres requis

Description

final public OAuthProvider::addRequiredParameter(string $req_params): bool

Ajoute des paramètres requis oauth provider.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

req_params

Les paramètres requis.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • OAuthProvider::removeRequiredParameter() - Supprime un paramètre

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");


Appelle la fonction de rappel consumerNonceHandler

  • « OAuthProvider::addRequiredParameter
  • OAuthProvider::callTimestampNonceHandler »
  • PHP Manual
  • OAuthProvider
  • Appelle la fonction de rappel consumerNonceHandler

OAuthProvider::callconsumerHandler

(No version information available, might only be in Git)

OAuthProvider::callconsumerHandler — Appelle la fonction de rappel consumerNonceHandler

Description

public OAuthProvider::callconsumerHandler(): void

Appelle la fonction de rappel consumer handler, qui a été définie par la méthode OAuthProvider::consumerHandler().

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

Émet une erreur E_ERROR si la fonction de rappel ne peut être appelée ou n'a pas été spécifiée.

Voir aussi

  • OAuthProvider::consumerHandler() - Définit la fonction de rappel consumerHandler

User Contributed Notes

There are no user contributed notes for this page.


Appelle la fonction de rappel timestampNonceHandler

  • « OAuthProvider::callconsumerHandler
  • OAuthProvider::calltokenHandler »
  • PHP Manual
  • OAuthProvider
  • Appelle la fonction de rappel timestampNonceHandler

OAuthProvider::callTimestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::callTimestampNonceHandler — Appelle la fonction de rappel timestampNonceHandler

Description

public OAuthProvider::callTimestampNonceHandler(): void

Appelle la fonction de rappel timestamp handler, qui a été définie par la méthode OAuthProvider::timestampNonceHandler().

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

Émet une erreur E_ERROR si la fonction de rappel ne peut être appelée ou n'a pas été spécifiée.

Voir aussi

  • OAuthProvider::timestampNonceHandler() - Définit le gestionnaire de rappel timestampNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


Appelle la fonction de rappel tokenNonceHandler

  • « OAuthProvider::callTimestampNonceHandler
  • OAuthProvider::checkOAuthRequest »
  • PHP Manual
  • OAuthProvider
  • Appelle la fonction de rappel tokenNonceHandler

OAuthProvider::calltokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::calltokenHandler — Appelle la fonction de rappel tokenNonceHandler

Description

public OAuthProvider::calltokenHandler(): void

Appelle la fonction de rappel token handler, qui a été définie par la méthode OAuthProvider::tokenHandler().

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

Émet une erreur E_ERROR si la fonction de rappel ne peut être appelée ou n'a pas été spécifiée.

Voir aussi

  • OAuthProvider::tokenHandler() - Définit le gestionnaire de rappel tokenHandler

User Contributed Notes

There are no user contributed notes for this page.


Vérifie une requête OAuth

  • « OAuthProvider::calltokenHandler
  • OAuthProvider::__construct »
  • PHP Manual
  • OAuthProvider
  • Vérifie une requête OAuth

OAuthProvider::checkOAuthRequest

(PECL OAuth >= 1.0.0)

OAuthProvider::checkOAuthRequest — Vérifie une requête OAuth

Description

public OAuthProvider::checkOAuthRequest(string $uri = ?, string $method = ?): void

Vérifie une requête OAuth.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

uri

L'URI, optionnel, ou un point final.

method

La méthode HTTP. Optionnel ; passez-y une constante parmi les constantes OAuth OAUTH_HTTP_METHOD_* .

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

Émet une erreur de niveau E_ERROR si la méthode HTTP ne peut être détectée.

Voir aussi

  • OAuthProvider::reportProblem() - Rapporte un problème

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;
}

?>


Construit un nouvel objet OAuthProvider

  • « OAuthProvider::checkOAuthRequest
  • OAuthProvider::consumerHandler »
  • PHP Manual
  • OAuthProvider
  • Construit un nouvel objet OAuthProvider

OAuthProvider::__construct

(PECL OAuth >= 1.0.0)

OAuthProvider::__construct — Construit un nouvel objet OAuthProvider

Description

public OAuthProvider::__construct(array $params_array = ?)

Initie un nouvel object OAuthProvider.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

params_array

Le fait de définir des paramètres optionnels est limité au SAPI CLI.

Valeurs de retour

Un object OAuthProvider.

Exemples

Exemple #1 Exemple avec OAuthProvider::__construct()

<?php
try {

$op = new OAuthProvider();

// Utilisation des fonctions de rappel définies par l'utilisateur
$op->consumerHandler(array($this, 'lookupConsumer'));
$op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
$op->tokenHandler(array($this, 'myTokenHandler'));

// Ignore le paramètre foo_uri
$op->setParam('foo_uri', NULL);

// Aucun jeton nécessaire pour ce point final
$op->setRequestTokenPath('/v1/oauth/request_token');

$op->checkOAuthRequest();

} catch (OAuthException $e) {

echo OAuthProvider::reportProblem($e);
}
?>

Voir aussi

  • OAuthProvider::setParam() - Définit un paramètre

User Contributed Notes

There are no user contributed notes for this page.


Définit la fonction de rappel consumerHandler

  • « OAuthProvider::__construct
  • OAuthProvider::generateToken »
  • PHP Manual
  • OAuthProvider
  • Définit la fonction de rappel consumerHandler

OAuthProvider::consumerHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::consumerHandler — Définit la fonction de rappel consumerHandler

Description

public OAuthProvider::consumerHandler(callable $callback_function): void

Définit la fonction de rappel consumer handler, qui pourra ensuite être appelée avec la méthode OAuthProvider::callConsumerHandler().

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

callback_function

Le nom de la fonction de rappel de type callable.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec 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;
}
?>

Voir aussi

  • OAuthProvider::callConsumerHandler() - Appelle la fonction de rappel consumerNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


Génère un jeton aléatoire

  • « OAuthProvider::consumerHandler
  • OAuthProvider::is2LeggedEndpoint »
  • PHP Manual
  • OAuthProvider
  • Génère un jeton aléatoire

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken — Génère un jeton aléatoire

Description

final public static OAuthProvider::generateToken(int $size, bool $strong = false): string

Génère une chaîne de caractères d'octets pseudo-aléatoires.

Liste de paramètres

size

La longueur désirée du jeton, en octets.

strong

Définit à true, signifie que /dev/random sera utilisé, sinon, ce sera /dev/urandom. Ce paramètre est ignoré sous Windows.

Valeurs de retour

Le jeton généré, sous la forme d'une chaîne de caractères d'octets.

Erreurs / Exceptions

Si le paramètre strong vaut true, alors, une alerte de niveau E_WARNING sera émise lorsque la fonction de rappel rand() est utilisée pour compléter les octets aléatoires manquant (i.e., lorsqu'il n'y a pas assez de données aléatoires initialement).

Exemples

Exemple #1 Exemple avec OAuthProvider::generateToken()

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t), PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

Résultat de l'exemple ci-dessus est similaire à :

4
b6a82c27

Notes

Note:

Lorsqu'il n'y a pas assez de données aléatoires de disponible sur le système, cette fonction complètera les octets manquant en utilisant la fonction PHP interne rand().

Voir aussi

  • openssl_random_pseudo_bytes() - Génère une chaine pseudo-aléatoire d'octets
  • mcrypt_create_iv() - Crée un vecteur d'initialisation (IV) à partir d'une source aléatoire

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

Description

public OAuthProvider::is2LeggedEndpoint(mixed $params_array): void

Le flux 2-legged, ou la demande de signature. Il ne requière pas de jeton.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

params_array

Valeurs de retour

Un object OAuthProvider .

Exemples

Exemple #1 Exemple avec OAuthProvider::is2LeggedEndpoint()

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

Voir aussi

  • OAuthProvider::__construct() - Construit un nouvel objet OAuthProvider

User Contributed Notes

There are no user contributed notes for this page.


Définit isRequestTokenEndpoint

  • « OAuthProvider::is2LeggedEndpoint
  • OAuthProvider::removeRequiredParameter »
  • PHP Manual
  • OAuthProvider
  • Définit isRequestTokenEndpoint

OAuthProvider::isRequestTokenEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::isRequestTokenEndpoint — Définit isRequestTokenEndpoint

Description

public OAuthProvider::isRequestTokenEndpoint(bool $will_issue_request_token): void

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

will_issue_request_token

Définit s'il émettra une demande de jeton ou non, ceci déterminant si la méthode OAuthProvider::tokenHandler() doit être appelée.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • OAuthProvider::setRequestTokenPath() - Définit le chemin du jeton demandé
  • OAuthProvider::reportProblem() - Rapporte un problème

User Contributed Notes

There are no user contributed notes for this page.


Supprime un paramètre

  • « OAuthProvider::isRequestTokenEndpoint
  • OAuthProvider::reportProblem »
  • PHP Manual
  • OAuthProvider
  • Supprime un paramètre

OAuthProvider::removeRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::removeRequiredParameter — Supprime un paramètre

Description

final public OAuthProvider::removeRequiredParameter(string $req_params): bool

Supprime un paramètre.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

req_params

Le paramètre à supprimer.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • OAuthProvider::setParam() - Définit un paramètre
  • OAuthProvider::addRequiredParameter() - Ajoute des paramètres requis

User Contributed Notes

There are no user contributed notes for this page.


Rapporte un problème

  • « OAuthProvider::removeRequiredParameter
  • OAuthProvider::setParam »
  • PHP Manual
  • OAuthProvider
  • Rapporte un problème

OAuthProvider::reportProblem

(PECL OAuth >= 1.0.0)

OAuthProvider::reportProblem — Rapporte un problème

Description

final public static OAuthProvider::reportProblem(string $oauthexception, bool $send_headers = true): string

Rapporte un problème sous la forme d'une exception OAuthException ; les problèmes possibles sont listés dans la section des constantes OAuth.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

oauthexception

L'exception OAuthException.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • OAuthProvider::checkOAuthRequest() - Vérifie une requête OAuth
  • OAuthProvider::isRequestTokenEndpoint() - Définit isRequestTokenEndpoint

User Contributed Notes

There are no user contributed notes for this page.


Définit un paramètre

  • « OAuthProvider::reportProblem
  • OAuthProvider::setRequestTokenPath »
  • PHP Manual
  • OAuthProvider
  • Définit un paramètre

OAuthProvider::setParam

(PECL OAuth >= 1.0.0)

OAuthProvider::setParam — Définit un paramètre

Description

final public OAuthProvider::setParam(string $param_key, mixed $param_val = ?): bool

Définit un paramètre.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

param_key

La clé du paramètre.

param_val

La valeur du paramètre ; optionnelle.

Pour exclure un paramètre de la vérification de signature, définir cette valeur à null.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • OAuthProvider::addRequiredParameter() - Ajoute des paramètres requis

User Contributed Notes

There are no user contributed notes for this page.


Définit le chemin du jeton demandé

  • « OAuthProvider::setParam
  • OAuthProvider::timestampNonceHandler »
  • PHP Manual
  • OAuthProvider
  • Définit le chemin du jeton demandé

OAuthProvider::setRequestTokenPath

(PECL OAuth >= 1.0.0)

OAuthProvider::setRequestTokenPath — Définit le chemin du jeton demandé

Description

final public OAuthProvider::setRequestTokenPath(string $path): bool

Définit le chemin du jeton demandé.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

path

Le chemin.

Valeurs de retour

true

Voir aussi

  • OAuthProvider::tokenHandler() - Définit le gestionnaire de rappel tokenHandler

User Contributed Notes

There are no user contributed notes for this page.


Définit le gestionnaire de rappel timestampNonceHandler

  • « OAuthProvider::setRequestTokenPath
  • OAuthProvider::tokenHandler »
  • PHP Manual
  • OAuthProvider
  • Définit le gestionnaire de rappel timestampNonceHandler

OAuthProvider::timestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::timestampNonceHandler — Définit le gestionnaire de rappel timestampNonceHandler

Description

public OAuthProvider::timestampNonceHandler(callable $callback_function): void

Définit le gestionnaire de rappel timestampNonceHandler, qui sera appelé plus tard avec la méthode OAuthProvider::callTimestampNonceHandler(). Les erreurs en rapport avec timestamp/nonce seront émises via ce gestionnaire de rappel.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

callback_function

Le nom de la fonction callback.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec 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;
}
?>

Voir aussi

  • OAuthProvider::callTimestampNonceHandler() - Appelle la fonction de rappel timestampNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


Définit le gestionnaire de rappel tokenHandler

  • « OAuthProvider::timestampNonceHandler
  • OAuthException »
  • PHP Manual
  • OAuthProvider
  • Définit le gestionnaire de rappel tokenHandler

OAuthProvider::tokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::tokenHandler — Définit le gestionnaire de rappel tokenHandler

Description

public OAuthProvider::tokenHandler(callable $callback_function): void

Définit le gestionnaire de rappel tokenHandler, qui sera appelé plus tard avec la méthode OAuthProvider::callTokenHandler().

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

callback_function

Le nom de la fonction callable.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec 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;
}
?>

Voir aussi

  • OAuthProvider::callTokenHandler() - Appelle la fonction de rappel tokenNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


La classe OAuthException

(PECL OAuth >= 0.99.1)

Introduction

Cette exception est émise quand des erreurs exceptionnelles surviennent durant l'utilisation de l'extension OAuth, et contient des informations pratiques pour déboguer.

Synopsis de la classe

class OAuthException extends Exception {
/* Propriétés */
public $lastResponse;
public $debugInfo;
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes héritées */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Propriétés

lastResponse

La réponse à l'exception survenue, s'il y en a

debugInfo

User Contributed Notes

There are no user contributed notes for this page.


SOAP

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Fonctions SOAP
    • is_soap_fault — Vérifie si SOAP retourne une erreur
    • use_soap_error_handler — Active le gestionnaire d'erreurs SOAP natif
  • SoapClient — La classe SoapClient
    • SoapClient::__call — Appelle une fonction SOAP (obsolète)
    • SoapClient::__construct — Constructeur SoapClient
    • SoapClient::__doRequest — Exécute une requête SOAP
    • SoapClient::__getCookies — Get list of cookies
    • SoapClient::__getFunctions — Retourne une liste de fonctions SOAP publiées
    • SoapClient::__getLastRequest — Retourne la dernière requête SOAP
    • SoapClient::__getLastRequestHeaders — Retourne les en-têtes de la dernière requête SOAP
    • SoapClient::__getLastResponse — Retourne la dernière réponse SOAP
    • SoapClient::__getLastResponseHeaders — Retourne les en-têtes de la dernière réponse SOAP
    • SoapClient::__getTypes — Retourne une liste des types SOAP
    • SoapClient::__setCookie — Définit un cookie pour les requêtes SOAP
    • SoapClient::__setLocation — Configure l'URL du service Web à utiliser
    • SoapClient::__setSoapHeaders — Ajoute un en-tête SOAP pour les requêtes suivantes
    • SoapClient::__soapCall — Appelle une fonction SOAP
  • SoapServer — La classe SoapServer
    • SoapServer::addFunction — Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP
    • SoapServer::addSoapHeader — Ajoute un en-tête SOAP à une réponse
    • SoapServer::__construct — Constructeur SoapServer
    • SoapServer::fault — Emet une erreur SoapServer
    • SoapServer::getFunctions — Retourne la liste des fonctions définies
    • SoapServer::handle — Traite une requête SOAP
    • SoapServer::setClass — Configure la classe qui sera utilisée pour gérer les requêtes SOAP
    • SoapServer::setObject — Configure l'objet qui sera utilisé pour gérer les requêtes SOAP
    • SoapServer::setPersistence — Active le mode persistant de SoapServer
  • SoapFault — La classe SoapFault
    • SoapFault::__construct — Constructeur SoapFault
    • SoapFault::__toString — Produit une représentation chaîne d'un objet SoapFault
  • SoapHeader — La classe SoapHeader
    • SoapHeader::__construct — Constructeur SoapHeader
  • SoapParam — La classe SoapParam
    • SoapParam::__construct — Constructeur SoapParam
  • SoapVar — La classe SoapVar
    • SoapVar::__construct — Constructeur SoapVar

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()


Introduction

L'extension SOAP peut être utilisée pour les échanges clients/serveurs SOAP. Elle supporte les spécifications » SOAP 1.1, » SOAP 1.2 et » WSDL 1.1.

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

Cette extension requière l'extension PHP libxml. Ceci signifie passer l'option de configuration --with-libxml, ou antérieur à PHP 7.4 l'option de configuration --enable-libxml, bien que ceci est accomplie implicitement car libxml est activé par défaut.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Pour activer le support de SOAP, configurez PHP avec --enable-soap.

User Contributed Notes

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
dbagnara 20-Aug-2016 10:02
for Ubuntu 16.04 LTS
sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service


Configuration à l'exécution

Le comportement de ces fonctions est affecté par la configuration dans le fichier php.ini.

Options de configuration SOAP
Nom | Défaut | Modifiable | Historique
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 |

Voici un éclaircissement sur l'utilisation des directives de configuration.

soap.wsdl_cache_enabled int

Active ou pas le cache WSDL.

soap.wsdl_cache_dir string

Configure le nom du dossier où l'extension SOAP peut mettre les fichiers de cache.

soap.wsdl_cache_ttl int

Configure la durée de vie des fichiers dans le cache, exprimé en secondes.

soap.wsdl_cache int

Si soap.wsdl_cache_enabled est actif, cette directive détermine le type de cache. Il peut prendre l'une des valeurs suivantes : WSDL_CACHE_NONE (0), WSDL_CACHE_DISK (1), WSDL_CACHE_MEMORY (2) ou WSDL_CACHE_BOTH (3). Cela peut aussi être configuré via le paramètre options dans les constructeurs de SoapClient ou SoapServer.

soap.wsdl_cache_limit int

Le nombre maximal de fichier WSDL en cache. La reception de nouveaux fichiers dans le cache, s'il est plein, causera l'effacement des plus anciens.

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.]


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

SOAP constants
Constante | Valeur | Description
SOAP_1_1 (int) | 1 | Spécifie l'utilisation de SOAP 1.1 lorsqu'elle est passée en tant qu'option soap_version à SoapServer::__construct() ou SoapClient::__construct().
SOAP_1_2 (int) | 2 | Spécifie l'utilisation de SOAP 1.2 lorsqu'il est passé en tant qu'option soap_version à SoapServer::__construct() ou SoapClient::__construct().
SOAP_PERSISTENCE_SESSION (int) | 1 | Spécifie l'utilisation de l'encodage SOAP lorsqu'elle est passée en tant qu'option use à la méthode SoapClient::__construct().
SOAP_PERSISTENCE_REQUEST (int) | 2 | Spécifie l'utilisation d'un encodage spécifique au service lorsqu'elle est passée en tant qu'option use à SoapClient::__construct().
SOAP_FUNCTIONS_ALL (int) | 999 |
SOAP_ENCODED (int) | 1 | Spécifie l'utilisation d'une liaison de style RPC lorsqu'elle est passée en tant qu'option style à SoapClient::__construct().
SOAP_LITERAL (int) | 2 | Spécifie l'utilisation d'une liaison de type document lorsque passée en tant que valeur style de l'option à SoapClient::__construct().
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 | Spécifie l'utilisation de l'en-tête "Accept-Encoding" lorsqu'elle est passée en tant que partie de l'option compression à SoapClient::__construct().
SOAP_COMPRESSION_GZIP (int) | 0 | Spécifie l'utilisation de la compression deflate lorsqu'elle est transmise dans le cadre de l'option compression de la méthode SoapClient::__construct().
SOAP_COMPRESSION_DEFLATE (int) | 16 | Spécifie l'utilisation de la compression deflate lorsqu'elle est transmise dans le cadre de l'option compression de la méthode SoapClient::__construct().
SOAP_AUTHENTICATION_BASIC (int) | 0 | Spécifie l'utilisation de l'authentification HTTP Basic lorsqu'elle est passée en tant qu'option authentication à SoapClient::__construct().
SOAP_AUTHENTICATION_DIGEST (int) | 1 | Spécifie l'utilisation de l'authentification HTTP Digest lorsqu'elle est passée en tant qu'option authentication à SoapClient::__construct().
SOAP_SSL_METHOD_TLS (int) | 0 | Utilisée avec l'option obsolète ssl_method de SoapClient::__construct().
SOAP_SSL_METHOD_SSLv2 (int) | 1 | Utilisée avec l'option ssl_method obsolète dans la méthode SoapClient::__construct().
SOAP_SSL_METHOD_SSLv3 (int) | 2 | Utilisée avec l'option obsolète ssl_method pour SoapClient::__construct().
SOAP_SSL_METHOD_SSLv23 (int) | 3 | Utilisée avec l'option obsolète ssl_method pour SoapClient::__construct().
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 (string) | http://www.w3.org/2001/XMLSchema |
XSD_1999_NAMESPACE (string) | http://www.w3.org/1999/XMLSchema |
SOAP_SINGLE_ELEMENT_ARRAYS (int) | 1 | Utilisée avec l'option features dans la méthode SoapClient::__construct().
SOAP_WAIT_ONE_WAY_CALLS (int) | 2 | Utilisée avec l'option features dans la méthode SoapClient::__construct().
SOAP_USE_XSI_ARRAY_TYPE (int) | 4 | Utilisée avec l'option features dans la méthode SoapClient::__construct().
WSDL_CACHE_NONE (int) | 0 | Désactive le cache WSDL lorsqu'il est utilisé dans l'option de configuration soap.wsdl_cache ou dans l'option wsdl_cache de SoapClient::__construct() et SoapServer::__construct().
WSDL_CACHE_DISK (int) | 1 | Indique l'utilisation du cache WSDL en mémoire uniquement lorsqu'il est utilisé dans l'option de configuration soap.wsdl_cache ou l'option wsdl_cache de SoapClient::__construct() et SoapServer::__construct().
WSDL_CACHE_MEMORY (int) | 2 | Spécifie l'utilisation du cache WSDL en mémoire vive uniquement lorsqu'il est utilisé dans l'option de configuration soap.wsdl_cache ou l'option wsdl_cache de SoapClient::__construct() et SoapServer::__construct().
WSDL_CACHE_BOTH (int) | 3 | Spécifie l'utilisation des caches WSDL en mémoire et sur disque lorsqu'elle est utilisée dans l'option de configuration soap.wsdl_cache ou l'option wsdl_cache de SoapClient::__construct() et SoapServer::__construct().

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.


Fonctions SOAP

Sommaire

  • is_soap_fault — Vérifie si SOAP retourne une erreur
  • use_soap_error_handler — Active le gestionnaire d'erreurs SOAP natif

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.


Vérifie si SOAP retourne une erreur

  • « Fonctions SOAP
  • use_soap_error_handler »
  • PHP Manual
  • Fonctions SOAP
  • Vérifie si SOAP retourne une erreur

is_soap_fault

(PHP 5, PHP 7, PHP 8)

is_soap_fault — Vérifie si SOAP retourne une erreur

Description

is_soap_fault(mixed $object): bool

is_soap_fault() sert à vérifier si l'API SOAP a échoué, sans utiliser les exceptions. Pour l'utiliser, créez un objet SoapClient avec l'option exceptions mise à zéro ou à false. Dans ce cas, la méthode SOAP va retourner un objet spécial SoapFault, qui encapsule les détails de l'erreur (code d'erreur, message, acteur et détails).

Si exceptions n'est pas configurée, SOAP va émettre une exception. is_soap_fault() vérifie si le paramètre fourni est un objet SoapFault.

Liste de paramètres

objet

L'objet à tester.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec is_soap_fault()

<?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);
}
?>

Exemple #2 Gestion des erreurs par exception avec SOAP

<?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);
}
?>

Voir aussi

  • SoapClient::__construct() - Constructeur SoapClient
  • SoapFault::__construct() - Constructeur SoapFault

User Contributed Notes

There are no user contributed notes for this page.


Active le gestionnaire d'erreurs SOAP natif

  • « is_soap_fault
  • SoapClient »
  • PHP Manual
  • Fonctions SOAP
  • Active le gestionnaire d'erreurs SOAP natif

use_soap_error_handler

(PHP 5, PHP 7, PHP 8)

use_soap_error_handler — Active le gestionnaire d'erreurs SOAP natif

Description

use_soap_error_handler(bool $enable = true): bool

use_soap_error_handler() active ou non le gestionnaire d'erreurs natif SOAP du serveur SOAP. Elle retourne la valeur précédemment utilisée. Si le paramètre handler est mis à true, le détail des erreurs du serveur SoapServer seront envoyées au client, comme message d'erreur SOAP. Si vaut false le gestionnaire d'erreur standard PHP sera utilisé. Le comportement par défaut est d'envoyer l'erreur au client sous forme de message SOAP.

Liste de paramètres

enable

Avec la valeur true, le détail des erreurs sera envoyé aux clients.

Valeurs de retour

Retourne la valeur originale.

Voir aussi

  • set_error_handler() - Spécifie une fonction utilisateur comme gestionnaire d'erreurs
  • set_exception_handler() - Définit une fonction utilisateur de gestion d'exceptions

User Contributed Notes

There are no user contributed notes for this page.


La classe SoapClient

(PHP 5, PHP 7, PHP 8)

Introduction

La classe SoapClient fournit un client pour les serveurs » SOAP 1.1 et » SOAP 1.2. Il peut être utilisé avec ou sans mode WSDL.

Synopsis de la classe

class SoapClient {
/* Propriétés */
private ?string $uri = null;
private ?int $style = null;
private ?int $use = null;
private ?string $location = null;
private bool $trace = false;
private ?int $compression = null;
private ?resource $sdl = null;
private ?resource $typemap = null;
private ?resource $httpsocket = null;
private ?resource $httpurl = null;
private ?string $_login = null;
private ?string $_password = null;
private bool $_use_digest = false;
private ?string $_digest = null;
private ?string $_proxy_host = null;
private ?int $_proxy_port = null;
private ?string $_proxy_login = null;
private ?string $_proxy_password = null;
private bool $_exceptions = true;
private ?string $_encoding = null;
private ?array $_classmap = null;
private ?int $_features = null;
private int $_connection_timeout;
private ?resource $_stream_context = null;
private ?string $_user_agent = null;
private bool $_keep_alive = true;
private ?int $_ssl_method = null;
private int $_soap_version;
private ?int $_use_proxy = null;
private array $_cookies = [];
private ?array $__default_headers = null;
private ?SoapFault $__soap_fault = null;
private ?string $__last_request = null;
private ?string $__last_response = null;
private ?string $__last_request_headers = null;
private ?string $__last_response_headers = null;
/* Méthodes */
public __construct(?string $wsdl, array $options = [])
public __call(string $name, array $args): mixed
public __doRequest(
string $request,
string $location,
string $action,
int $version,
bool $oneWay = false
): ?string
public __getCookies(): array
public __getFunctions(): ?array
public __getLastRequest(): ?string
public __getLastRequestHeaders(): ?string
public __getLastResponse(): ?string
public __getLastResponseHeaders(): ?string
public __getTypes(): ?array
public __setCookie(string $name, ?string $value = null): void
public __setLocation(?string $location = null): ?string
public __setSoapHeaders(SoapHeader|array|null $headers = null): bool
public __soapCall(
string $name,
array $args,
?array $options = null,
SoapHeader|array|null $inputHeaders = null,
array &$outputHeaders = null
): mixed
}

Propriétés

__default_headers

__last_request

__last_request_headers

__last_response

__last_response_headers

__soap_fault

_classmap

_connection_timeout

_cookies

_digest

_encoding

_exceptions

_features

_keep_alive

_login

_password

_proxy_host

_proxy_login

_proxy_password

_proxy_port

_soap_version

_ssl_method

_stream_context

_use_digest

_use_proxy

_user_agent

compression

httpsocket

httpurl

location

sdl

style

trace

typemap

uri

use

Sommaire

  • SoapClient::__call — Appelle une fonction SOAP (obsolète)
  • SoapClient::__construct — Constructeur SoapClient
  • SoapClient::__doRequest — Exécute une requête SOAP
  • SoapClient::__getCookies — Get list of cookies
  • SoapClient::__getFunctions — Retourne une liste de fonctions SOAP publiées
  • SoapClient::__getLastRequest — Retourne la dernière requête SOAP
  • SoapClient::__getLastRequestHeaders — Retourne les en-têtes de la dernière requête SOAP
  • SoapClient::__getLastResponse — Retourne la dernière réponse SOAP
  • SoapClient::__getLastResponseHeaders — Retourne les en-têtes de la dernière réponse SOAP
  • SoapClient::__getTypes — Retourne une liste des types SOAP
  • SoapClient::__setCookie — Définit un cookie pour les requêtes SOAP
  • SoapClient::__setLocation — Configure l'URL du service Web à utiliser
  • SoapClient::__setSoapHeaders — Ajoute un en-tête SOAP pour les requêtes suivantes
  • SoapClient::__soapCall — Appelle une fonction SOAP

User Contributed Notes

spam at kacke dot de 09-Sep-2022 08:46
In case a soap response returns nodes with the attribute xsi:nil="false", they are currently not processed by php-soapclient.

This seems to be a bug (not correct).

Workaround:

class mySoapClient extends SoapClient {
        public function __doRequest($request, $location, $action, $version, $one_way = 0) {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        $response = str_replace('xsi:nil="false"',"",$response);
        return $response;
    }
}

Took me a day. Hope it can help
Toppi
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.


Appelle une fonction SOAP (obsolète)

  • « SoapClient
  • SoapClient::__construct »
  • PHP Manual
  • SoapClient
  • Appelle une fonction SOAP (obsolète)

SoapClient::__call

(PHP 5, PHP 7, PHP 8)

SoapClient::__call — Appelle une fonction SOAP (obsolète)

Description

public SoapClient::__call(string $name, array $args): mixed

L'appel direct à cette méthode est obsolète. Habituellement, les fonctions SOAP peuvent être appelées comme méthodes de l'objet SoapClient ; dans les cas où ce n'est pas possible, ou bien qu'il est nécessaire de passer plus d'options, utilisez la méthode SoapClient::__soapCall().

Liste de paramètres

name

Le nom de la fonction SOAP à appeler.

args

Un tableau des arguments à passer à la fonction. Cela peut être soit un tableau ordonné, soit un tableau associatif. Notez que la plupart des serveurs SOAP exigent que les noms des paramètres soient fournis, auquel cas cela doit être un tableau associatif.

Valeurs de retour

Les fonctions SOAP peuvent renvoyer une ou plusieurs valeurs. Si seule une valeur est renvoyée par la fonction SOAP, la valeur de retour sera un scalaire. Si plusieurs valeurs sont renvoyées, un tableau associatif de paramètres de sortie nommés est renvoyé à la place.

En cas d'erreur, si l'objet SoapClient a été construit avec l'option exceptions définie sur false, un objet SoapFault sera renvoyé.

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>";
?>


Constructeur SoapClient

  • « SoapClient::__call
  • SoapClient::__doRequest »
  • PHP Manual
  • SoapClient
  • Constructeur SoapClient

SoapClient::__construct

(PHP 5, PHP 7, PHP 8)

SoapClient::__construct — Constructeur SoapClient

Description

public SoapClient::__construct(?string $wsdl, array $options = [])

Crée un objet SoapClient pour se connecter à un service SOAP.

Liste de paramètres

wsdl

URI du fichier WSDL ou null s'il travaille en mode non-WSDL.

Note:

Par défaut, le fichier WSDL sera mis en cache pour des raisons de performance. Pour désactiver ou configurer cette mise en cache, consultez la section SOAP Options de configuration et l'option cache_wsdl

options

Un tableau associatif spécifiant des options supplémentaires pour le client SOAP. Si le paramètre wsdl est fourni, ceci est facultatif?; sinon, au moins les paramètres location et url doivent être fournis.

location string

L'URL du serveur SOAP auquel envoyer la requête.

Requis si le paramètre wsdl n'est pas fourni. Si à la fois un paramètre wsdl et l'option location sont fournis, l'option location remplacera toute location spécifiée dans le fichier WSDL.

uri string

L'espace de noms cible du service SOAP.

Requis si le paramètre wsdl n'est pas fourni; sinon ignoré.

style int

Spécifie le style de liaison à utiliser pour ce client, en utilisant les constantes SOAP_RPC et SOAP_DOCUMENT. SOAP_RPC indique une liaison de style RPC, où le corps de la requête SOAP contient un encodage standard d'un appel de fonction. SOAP_DOCUMENT indique une liaison de style document, où le corps de la requête SOAP contient un document XML avec une signification définie par le service.

Si le paramètre wsdl est fourni, cette option est ignorée et le style est lu à partir du fichier WSDL.

Si ni cette option ni le paramètre wsdl ne sont fournis, le style RPC est utilisé.

use int

Spécifie le style d'encodage à utiliser pour ce client, en utilisant les constantes SOAP_ENCODED ou SOAP_LITERAL. SOAP_ENCODED indique un encodage utilisant les types définis dans la spécification SOAP. SOAP_LITERAL indique un encodage utilisant un schéma défini.

Si le paramètre wsdl est fourni, cette option est ignorée et l'encodage est lu à partir du fichier WSDL.

Si cette option et le paramètre wsdl ne sont pas fournis, le style "encoded" est utilisé.

soap_version int

Spécifie la version du protocole SOAP à utiliser : SOAP_1_1 pour SOAP 1.1, ou SOAP_1_2 pour SOAP 1.2.

Si omis, SOAP 1.1 est utilisé.

authentication int

Spécifie la méthode d'authentification lors de l'utilisation de l'authentification HTTP dans les requêtes. La valeur peut être soit SOAP_AUTHENTICATION_BASIC ou SOAP_AUTHENTICATION_DIGEST.

Si omis et que l'option login est fournie, l'authentification HTTP Basic est utilisée.

login string

Nom d'utilisateur à utiliser avec l'authentification HTTP Basic ou HTTP Digest.

password string

Mot de passe à utiliser avec l'authentification HTTP Basic ou HTTP Digest.

À ne pas confondre avec passphrase, qui est utilisé avec l'authentification par certificat client HTTPS.

local_cert string

Chemin vers un certificat client à utiliser avec l'authentification HTTPS. Il doit s'agir d'un fichier encodé en PEM contenant votre certificat et votre clé privée.

Le fichier peut également inclure une chaîne d'émetteurs, qui doit venir après le certificat client.

Peut également être défini via stream_context, qui permet également de spécifier un fichier de clé privée distinct.

passphrase string

Passphrase pour le certificat client spécifié dans l'option local_cert.

À ne pas confondre avec password, qui est utilisé avec l'authentification HTTP Basic ou HTTP Digest.

Peut également être défini via stream_context.

proxy_host string

Nom d'hôte à utiliser comme serveur mandataire pour les requêtes HTTP.

L'option proxy_port doit également être spécifiée.

proxy_port int

Port TCP à utiliser lors de la connexion au serveur mandataire spécifié dans proxy_host.

proxy_login string

Nom d'utilisateur facultatif pour s'authentifier auprès du serveur mandataire spécifié dans proxy_host, en utilisant l'authentification HTTP Basic.

proxy_password string

Mot de passe facultatif pour s'authentifier auprès du serveur mandataire spécifié dans proxy_host, en utilisant l'authentification HTTP Basic.

compression int

Active la compression des requêtes et des réponses SOAP HTTP.

La valeur doit être le résultat de l'opération OR binaire de trois parties : un SOAP_COMPRESSION_ACCEPT optionnel, pour envoyer l'en-tête "Accept-Encoding" ; soit SOAP_COMPRESSION_GZIP ou SOAP_COMPRESSION_DEFLATE pour indiquer l'algorithme de compression à utiliser ; et un nombre entre 1 et 9 pour indiquer le niveau de compression à utiliser dans la requête. Par exemple, pour activer la compression gzip bidirectionnelle avec le niveau de compression maximal, utilisez SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 9.

encoding string

Définit l'encodage de caractères interne. Les requêtes sont toujours envoyées en UTF-8 et converties depuis et vers cet encodage.

trace bool

Capture les informations de requête et de réponse, qui peuvent ensuite être
consultées à l'aide des méthodes
SoapClient::__getLastRequest(),
SoapClient::__getLastRequestHeaders(),
SoapClient::__getLastResponse(),
et SoapClient::__getLastResponseHeaders().

Si omis, la valeur par défaut est false

classmap array

Utilisé pour associer les types définis dans le WSDL aux classes PHP. Il doit être spécifié sous la forme d'un tableau associatif avec les noms de types du WSDL en tant que clés et les noms de classes PHP en tant que valeurs. Notez que les noms de types d'un élément ne correspondent pas nécessairement au nom de l'élément (balise).

Les noms de classe fournis doivent toujours être entièrement qualifiés avec tous les espaces de noms, et ne jamais commencer par un \. La forme correcte peut être générée en utilisant ::class.

Notez que lors de la création d'une classe, le constructeur ne sera pas appelé, mais les méthodes magiques __set() et __get() pour les propriétés individuelles le seront.

typemap array

Utilisé pour définir des correspondances de types à l'aide de fonctions de rappel définies par l'utilisateur. Chaque correspondance de type doit être un tableau avec les clés type_name (une chaîne de caractères spécifiant le type d'élément XML), type_ns (une chaîne de caractères contenant l'URI de l'espace de noms), from_xml (un appelable acceptant un paramètre de type chaîne de caractères et renvoyant un objet) et to_xml (un appelable acceptant un paramètre de type objet et renvoyant une chaîne de caractères).

exceptions bool

Définit si les erreurs génèrent des exceptions de type SoapFault.

Par défaut, c'est true

connection_timeout int

Définit un délai d'attente en secondes pour la connexion au service SOAP. Cette option ne définit pas un délai d'attente pour les services ayant une réponse lente. Pour limiter le temps d'attente des appels, l'option de configuration default_socket_timeout est disponible.

cache_wsdl int

Si le paramètre wsdl est spécifié et que l'option de configuration soap.wsdl_cache_enabled est activée, cette option détermine le type de mise en cache. L'une des constantes WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY ou WSDL_CACHE_BOTH.

Deux types de cache sont disponibles : le cache en mémoire, qui met en cache le WSDL dans la mémoire du processus en cours, et le cache sur disque, qui met en cache le WSDL dans un fichier sur le disque partagé entre tous les processus. Le répertoire à utiliser pour le cache sur disque est déterminé par l'option de configuration soap.wsdl_cache_dir. Les deux caches ont la même durée de vie, déterminée par l'option de configuration soap.wsdl_cache_ttl. Le cache en mémoire a également un nombre maximum d'entrées déterminé par l'option de configuration soap.wsdl_cache_limit.

Si non spécifié, l'option de configuration soap.wsdl_cache sera utilisée.

user_agent string

La valeur à utiliser dans l'en-tête HTTP User-Agent lors des requêtes.

Peut également être définie via stream_context.

Si non spécifié, l'agent utilisateur sera "PHP-SOAP/" suivi de la valeur de PHP_VERSION.

stream_context resource

Un contexte de flux créé par stream_context_create(), qui permet de définir des options supplémentaires.

Le contexte peut inclure des options de contexte socket, des options de contexte SSL, ainsi que certaines options de contexte HTTP sélectionnées : content_type, header, max_redirects, protocol_version, et user_agent.

Notez que les en-têtes HTTP suivants sont générés automatiquement ou à partir d'autres options, et seront ignorés s'ils sont spécifiés dans l'option de contexte 'header' : host, connection, user-agent, content-length, content-type, cookie, authorization et proxy-authorization.

features int

Un masque de bits pour activer une ou plusieurs des fonctionnalités suivantes :

SOAP_SINGLE_ELEMENT_ARRAYS

Lors du décodage d'une réponse en tableau, le comportement par défaut consiste à détecter si un nom d'élément apparaît une seule fois ou plusieurs fois dans un élément parent particulier. Pour les éléments qui n'apparaissent qu'une fois, une propriété d'objet permet un accès direct au contenu ; pour les éléments qui apparaissent plus d'une fois, la propriété contient un tableau avec le contenu de chaque élément correspondant.

Si la fonctionnalité SOAP_SINGLE_ELEMENT_ARRAYS est activée, les éléments qui n'apparaissent qu'une seule fois sont placés dans un tableau à un seul élément, de sorte que l'accès soit cohérent pour tous les éléments. Cela n'a d'effet que lors de l'utilisation d'un WSDL contenant un schéma pour la réponse. Consultez la section des examples pour une illustration.

SOAP_USE_XSI_ARRAY_TYPE

Lorsque l'option use option ou la propriété WSDL est définie sur encoded, force les tableaux à utiliser un type SOAP-ENC:Array, plutôt qu'un type spécifique au schéma.

SOAP_WAIT_ONE_WAY_CALLS

Attendre une réponse même si le WSDL indique une requête à sens unique.

keep_alive bool

une valeur booléenne définissant si envoyer l'en-tête Connection: Keep-Alive ou Connection: close.

Par défaut, c'est true

ssl_method string

Spécifie la version du protocole SSL ou TLS à utiliser avec les connexions HTTP sécurisées, au lieu de la négociation par défaut. Spécifier SOAP_SSL_METHOD_SSLv2 ou SOAP_SSL_METHOD_SSLv3 forcera l'utilisation de SSL 2 ou SSL 3, respectivement. Spécifier SOAP_SSL_METHOD_SSLv23 n'a aucun effet ; cette constante n'existe que pour des raisons de compatibilité ascendante. À partir de PHP 7.2, spécifier SOAP_SSL_METHOD_TLS n'a également aucun effet ; dans les versions antérieures, cela forçait l'utilisation de TLS 1.0.

Il est à noter que les versions SSL 2 et 3 sont considérées comme non sécurisées et peuvent ne pas être prises en charge par la bibliothèque OpenSSL installée.

Cette option est obsolète à partir de PHP 8.1.0. Une alternative plus flexible, qui permet de spécifier des versions individuelles de TLS, consiste à utiliser l'option contexte_de_flux avec le paramètre de contexte 'crypto_method'.

Exemple #1 Spécifier l'utilisation de TLS 1.3 uniquement

<?php
$context = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT
]
]);
$client = new SoapClient("some.wsdl", ['context' => $context]);

Erreurs / Exceptions

SoapClient::__construct() génèrera une erreur de type E_ERROR si les options location et uri ne sont pas fournies en mode non-WSDL.

Une exception de type SoapFault sera lancée si l'URI wsdl ne peut être chargée.

Exemples

Exemple #2 Example SoapClient::__construct()

<?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 | 9));

$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")));

$typemap = array(
array("type_ns" => "http://schemas.example.com",
"type_name" => "book",
"from_xml" => "unserialize_book",
"to_xml" => "serialize_book")
);
$client = new SoapClient("books.wsdl", array('typemap' => $typemap));

?>

Exemple #3 Utilisant la fonctionnalité SOAP_SINGLE_ELEMENT_ARRAYS

/* Assuming a response like this, and an appropriate WSDL:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:example">
<SOAP-ENV:Body>
<response>
<collection>
<item>Single</item>
</collection>
<collection>
<item>First</item>
<item>Second</item>
</collection>
</response>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/

echo "Default:\n";

$client = new TestSoapClient(__DIR__ . '/temp.wsdl');
$response = $client->exampleRequest();
var_dump( $response->collection[0]->item );
var_dump( $response->collection[1]->item );

echo "\nWith SOAP_SINGLE_ELEMENT_ARRAYS:\n";

$client = new TestSoapClient(__DIR__ . '/temp.wsdl', ['features' => SOAP_SINGLE_ELEMENT_ARRAYS]);
$response = $client->exampleRequest();
var_dump( $response->collection[0]->item );
var_dump( $response->collection[1]->item );

L'exemple ci-dessus va afficher :

Default:
string(6) "Single"
array(2) {
  [0] =>
  string(5) "First"
  [1] =>
  string(6) "Second"
}

With SOAP_SINGLE_ELEMENT_ARRAYS:
array(1) {
  [0] =>
  string(6) "Single"
}
array(2) {
  [0] =>
  string(5) "First"
  [1] =>
  string(6) "Second"
}

User Contributed Notes

There are no user contributed notes for this page.


Exécute une requête SOAP

  • « SoapClient::__construct
  • SoapClient::__getCookies »
  • PHP Manual
  • SoapClient
  • Exécute une requête SOAP

SoapClient::__doRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__doRequest — Exécute une requête SOAP

Description

public SoapClient::__doRequest(
string $request,
string $location,
string $action,
int $version,
bool $oneWay = false
): ?string

Exécute une requête SOAP.

Cette méthode peut être écrasée dans les sous-classes pour implémenter différents transporteurs, effectuer des opérations XML supplémentaires ou toute autre chose.

Liste de paramètres

request

La requête SOAP en XML.

location

L'URL de la requête.

action

L'action SOAP.

version

La version SOAP.

oneWay

Si oneWay prend la valeur de true, cette méthode ne retourne rien. Utilisez cette valeur quand une réponse n'est pas attendue.

Valeurs de retour

La réponse SOAP en XML.

Historique

Version | Description
8.0.0 | The type of oneWay is booléen now; formerly it was entier.

Exemples

Exemple #1 Exemple avec SoapClient::__doRequest()

<?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, $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=Windows-1252?)
                  SOAP_1_2 = content headers (Content-Type: application/soap+xml; CHARSET=Windows-1252; 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=Windows-1252; action="somesoapaction defined in $action"' was not the expected type 'text/xml; CHARSET=Windows-1252'.

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

Description

public SoapClient::__getCookies(): array

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Retourne une liste de fonctions SOAP publiées

  • « SoapClient::__getCookies
  • SoapClient::__getLastRequest »
  • PHP Manual
  • SoapClient
  • Retourne une liste de fonctions SOAP publiées

SoapClient::__getFunctions

(PHP 5, PHP 7, PHP 8)

SoapClient::__getFunctions — Retourne une liste de fonctions SOAP publiées

Description

public SoapClient::__getFunctions(): ?array

SoapClient::__getFunctions() retourne un tableau de fonctions SOAP publiées décrites dans le WSDL.

Note:

Cette fonction n'est disponible qu'en mode WSDL.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Le array de fonctions SOAP avec le type de retour, le nom de la fonction et les types des paramètres qu'accepte celle-ci.

Exemples

Exemple #1 Exemple avec SoapClient::__getFunctions()

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

L'exemple ci-dessus va afficher :

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)"
}

Voir aussi

  • SoapClient::__construct() - Constructeur SoapClient

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.


Retourne la dernière requête SOAP

  • « SoapClient::__getFunctions
  • SoapClient::__getLastRequestHeaders »
  • PHP Manual
  • SoapClient
  • Retourne la dernière requête SOAP

SoapClient::__getLastRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequest — Retourne la dernière requête SOAP

Description

public SoapClient::__getLastRequest(): ?string

Retourne le code XML de la dernière requête SOAP émise.

Note:

Cette méthode fonctionne uniquement si l'objet SoapClient a été créé avec l'option trace configuré à true.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

La dernière requête SOAP, sous forme de chaîne de code XML.

Exemples

Exemple #1 Exemple avec SoapClient::__getLastRequest()

<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

Voir aussi

  • SoapClient::__getLastRequestHeaders() - Retourne les en-têtes de la dernière requête SOAP
  • SoapClient::__getLastResponse() - Retourne la dernière réponse SOAP
  • SoapClient::__getLastResponseHeaders() - Retourne les en-têtes de la dernière réponse SOAP

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


Retourne les en-têtes de la dernière requête SOAP

  • « SoapClient::__getLastRequest
  • SoapClient::__getLastResponse »
  • PHP Manual
  • SoapClient
  • Retourne les en-têtes de la dernière requête SOAP

SoapClient::__getLastRequestHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequestHeaders — Retourne les en-têtes de la dernière requête SOAP

Description

public SoapClient::__getLastRequestHeaders(): ?string

Retourne les en-têtes de la dernière requête SOAP

Note:

Cette fonction n'est disponible que si l'objet SoapClient a été créé avec l'option trace à true

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Les dernieres entêtes SOAP.

Exemples

Exemple #1 SoapClient::__getLastRequestHeaders() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

Voir aussi

  • SoapClient::__getLastResponseHeaders() - Retourne les en-têtes de la dernière réponse SOAP
  • SoapClient::__getLastRequest() - Retourne la dernière requête SOAP
  • SoapClient::__getLastResponse() - Retourne la dernière réponse SOAP

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....


Retourne la dernière réponse SOAP

  • « SoapClient::__getLastRequestHeaders
  • SoapClient::__getLastResponseHeaders »
  • PHP Manual
  • SoapClient
  • Retourne la dernière réponse SOAP

SoapClient::__getLastResponse

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponse — Retourne la dernière réponse SOAP

Description

public SoapClient::__getLastResponse(): ?string

Retourne le code XML de la dernière réponse SOAP.

Note:

Cette fonction n'est disponible que si l'objet SoapClient a été créé avec l'option trace à true

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

La dernière réponse SOAP, sous forme de chaîne XML.

Exemples

Exemple #1 Exemple avec SoapClient::__getLastResponse()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>

Voir aussi

  • SoapClient::__getLastResponseHeaders() - Retourne les en-têtes de la dernière réponse SOAP
  • SoapClient::__getLastRequest() - Retourne la dernière requête SOAP
  • SoapClient::__getLastRequestHeaders() - Retourne les en-têtes de la dernière requête SOAP

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


Retourne les en-têtes de la dernière réponse SOAP

  • « SoapClient::__getLastResponse
  • SoapClient::__getTypes »
  • PHP Manual
  • SoapClient
  • Retourne les en-têtes de la dernière réponse SOAP

SoapClient::__getLastResponseHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponseHeaders — Retourne les en-têtes de la dernière réponse SOAP

Description

public SoapClient::__getLastResponseHeaders(): ?string

Retourne les entêtes de la dernière réponse SOAP.

Note:

Cette fonction n'est disponible que si l'objet SoapClient a été créé avec l'option trace à true

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Les en-têtes de la dernière réponse SOAP.

Exemples

Exemple #1 Exemple avec SoapClient::__getLastResponseHeaders()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
?>

Voir aussi

  • SoapClient::__getLastRequestHeaders() - Retourne les en-têtes de la dernière requête SOAP
  • SoapClient::__getLastRequest() - Retourne la dernière requête SOAP
  • SoapClient::__getLastResponse() - Retourne la dernière réponse SOAP

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


Retourne une liste des types SOAP

  • « SoapClient::__getLastResponseHeaders
  • SoapClient::__setCookie »
  • PHP Manual
  • SoapClient
  • Retourne une liste des types SOAP

SoapClient::__getTypes

(PHP 5, PHP 7, PHP 8)

SoapClient::__getTypes — Retourne une liste des types SOAP

Description

public SoapClient::__getTypes(): ?array

SoapClient::__getTypes() retourne la liste des types SOAP décrits dans le fichier WSDL du service Web courant.

Note:

Cette fonction n'est disponible qu'en mode WSDL.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Un array de types SOAP détaillant toutes les structures et les types

Exemples

Exemple #1 Exemple avec SoapClient::__getTypes()

<?php
$client = new SoapClient("http://soap.amazon.com/schemas3/AmazonWebServices.wsdl");
var_dump($client->__getTypes());
?>

L'exemple ci-dessus va afficher :

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;
}"
}

Voir aussi

  • SoapClient::__construct() - Constructeur SoapClient

User Contributed Notes

Serge Liatko 28-Dec-2022 05:40
Here is the fixed version of my previous code (@moderators , please delete my previous note )

Returns a more comprehensive array of SOAP Client types as an array

<?PHP
/**
 * @param \SoapClient $soap
 *
 * @return array The WSDL types data as an array.
 */
function read_wsdl_types( SoapClient $soap ): array {
    $wsdl_types = $soap->__getTypes();
    $lookup     = array();
    $regexes    = array(
        'atomic' => '/^([\w_]+)\s([\w_]+)$/mi',
        'list'   => '/^([\w_]+)\s([\w_]+)[ {]+([\w_]+)[ }]+$/mi',
        'struct' => '/([\w_]+)\s([\w_]+)[\s{]?([\w_]+)*[\s;}]?/mi',
    );
    foreach ( array_reverse( $wsdl_types ) as $wsdl_type ) {
        $matches = array();
        foreach ( $regexes as $type => $regex ) {
            if ( preg_match_all( $regex, $wsdl_type, $matches ) ) {
                break;
            }
        }
        if ( !empty( $matches[1] ) && !empty( $matches[2] ) ) {
            switch ( $type ) {
                case 'atomic':
                    $name            = array_shift( $matches[2] );
                    $data_type       = array_shift( $matches[1] );
                    $lookup[ $name ] = array(
                        'name'      => $name,
                        'type'      => $type,
                        'data_type' => $data_type,
                        'items'     => array(),
                    );
                    break;
                case 'list':
                    $name            = array_shift( $matches[2] );
                    $type            = array_shift( $matches[1] );
                    $items           = array_shift( $matches[3] );
                    $lookup[ $name ] = array(
                        'name'      => $name,
                        'type'      => $type,
                        'data_type' => $items,
                        'items'     => array(
                            array(
                                'name'      => '',
                                'data_type' => $items,
                            ),
                        ),
                    );
                    break;
                case 'struct':
                    $name  = array_shift( $matches[2] );
                    $type  = array_shift( $matches[1] );
                    $items = array();
                    foreach ( $matches[2] as $key => $item_name ) {
                        $items[ $key ] = array(
                            'name'      => $item_name,
                            'data_type' => $matches[1][ $key ],
                        );
                    }
                    $lookup[ $name ] = array(
                        'name'      => $name,
                        'type'      => $type,
                        'data_type' => $name,
                        'items'     => $items,
                    );
                    break;
            }
        }

    }

    array_walk( $lookup, function ( &$type, $key, $data ) {
        if ( !empty( $type['items'] ) ) {
            array_walk( $type['items'], function ( &$item, $key, $data ) {
                if ( !empty( $item['data_type'] ) ) {
                    $old_data_type     = $item['data_type'];
                    $item['type']      = $data[ $old_data_type ]['type'] ?? 'atomic';
                    $item['data_type'] = $data[ $old_data_type ]['data_type'] ?? $old_data_type;
                    $item['from']      = $data[ $old_data_type ]['name'] ?? '';
                }
            }, $data );
        }
    }, $lookup );

    return array_reverse( $lookup );
}
?>
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>';


Définit un cookie pour les requêtes SOAP

  • « SoapClient::__getTypes
  • SoapClient::__setLocation »
  • PHP Manual
  • SoapClient
  • Définit un cookie pour les requêtes SOAP

SoapClient::__setCookie

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

SoapClient::__setCookie — Définit un cookie pour les requêtes SOAP

Description

public SoapClient::__setCookie(string $name, ?string $value = null): void

Définit le cookie qui sera envoyé avec la requête SOAP.

Note:

L'appel à cette méthode affectera tous les appels suivants aux méthodes SoapClient.

Liste de paramètres

name

Le nom du cookie.

value

La valeur du cookie. Si non spécifié, le cookie sera effacé.

Valeurs de retour

Aucune valeur n'est retournée.

Historique

Version | Description
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.


Configure l'URL du service Web à utiliser

  • « SoapClient::__setCookie
  • SoapClient::__setSoapHeaders »
  • PHP Manual
  • SoapClient
  • Configure l'URL du service Web à utiliser

SoapClient::__setLocation

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

SoapClient::__setLocation — Configure l'URL du service Web à utiliser

Description

public SoapClient::__setLocation(?string $location = null): ?string

Configure l'URL cible, à qui seront envoyés les requêtes SOAP. Ce revient à spécifier l'option location lors de la construction du client SoapClient.

Note:

Cette méthode est optionnelle. SoapClient utilise l'URL indiquée dans le fichier WDSL par défaut.

Liste de paramètres

location

La nouvelle URL.

Valeurs de retour

L'ancienne URL.

Historique

Version | Description
8.0.3 | location est désormais nullable.

Exemples

Exemple #1 Exemple avec SoapClient::__setLocation()

<?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;

?>

Résultat de l'exemple ci-dessus est similaire à :

http://www.somethirdparty.com

Voir aussi

  • SoapClient::__construct() - Constructeur SoapClient

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.


Ajoute un en-tête SOAP pour les requêtes suivantes

  • « SoapClient::__setLocation
  • SoapClient::__soapCall »
  • PHP Manual
  • SoapClient
  • Ajoute un en-tête SOAP pour les requêtes suivantes

SoapClient::__setSoapHeaders

(PHP 5 >= 5.0.5, PHP 7, PHP 8)

SoapClient::__setSoapHeaders — Ajoute un en-tête SOAP pour les requêtes suivantes

Description

public SoapClient::__setSoapHeaders(SoapHeader|array|null $headers = null): bool

Définit un en-tête à utiliser dans les requêtes SOAP.

Note:

Cette méthode va remplacer la valeur précédente.

Liste de paramètres

headers

L'en-tête à configurer. Il peut être un objet SoapHeader ou un tableau d'objetcs SoapHeader. Si ce paramètre n'est pas spécifié ou défini à null, les en-têtes seront supprimés.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec SoapClient::__setSoapHeaders()

<?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);
?>

Exemple #2 Configuration d'en-têtes multiples pour SOAP

<?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);
?>


Appelle une fonction SOAP

  • « SoapClient::__setSoapHeaders
  • SoapServer »
  • PHP Manual
  • SoapClient
  • Appelle une fonction SOAP

SoapClient::__soapCall

(PHP 5, PHP 7, PHP 8)

SoapClient::__soapCall — Appelle une fonction SOAP

Description

public SoapClient::__soapCall(
string $name,
array $args,
?array $options = null,
SoapHeader|array|null $inputHeaders = null,
array &$outputHeaders = null
): mixed

Ceci est une fonction bas niveau de l'API qui est utilisée pour faire des appels SOAP. Habituellement, en mode WSDL, vous pouvez appeler simplement les fonctions SOAP comme des méthodes SoapClient. Cette méthode est pratique en mode non-WSDL lorsque soapaction est inconnu, uri est différente de la valeur par défaut ou lors de l'envoi et/ou de la réception d'en-têtes SOAP.

En cas d'erreur, un appel à une fonction SOAP peut causer un lancement d'exception par PHP ou retourner un objet SoapFault si les exceptions sont désactivées. Pour vérifier si l'appel à cette fonction n'arrive pas à attraper les exceptions SoapFault, vérifiez le résultat avec la fonction is_soap_fault().

Liste de paramètres

name

Le nom de la fonction SOAP à appeler.

args

Un tableau d'arguments à passer à la fonction. Cela peut être un tableau associatif ou ordonné. Notez que la plupart des serveurs SOAP nécessite des noms de paramètres, auquel cas, ce doit être un tableau associatif.

options

Un tableau associatif d'options à passer au client.

Une option de location pour le service Web distant.

Une option uri avec l'espace de noms cible du service SOAP.

L'option soapaction est l'action à appeler.

inputHeaders

Un tableau d'entêtes à envoyer avec la requête SOAP.

outputHeaders

Si fourni, ce tableau sera rempli avec les entêtes de la réponse SOAP retournée.

Valeurs de retour

Les fonctions SOAP retournent une ou plusieurs valeurs. Si une seule valeur est retournée par la fonction SOAP, la valeur retournée de __soapCall sera une valeur simple (e.g. un entier, une chaîne de caractères, etc.). Si plusieurs valeurs sont retournées, __soapCall retournera un tableau associatif contenant les noms des paramètres affichés.

En cas d'erreur, si l'objet SoapClient a été construit avec l'option exceptions qui valait false, un objet SoapFault sera retourné.

Exemples

Exemple #1 Exemple avec SoapClient::__soapCall()

<?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'));
?>

Voir aussi

  • SoapClient::__construct() - Constructeur SoapClient
  • SoapParam::__construct() - Constructeur SoapParam
  • SoapVar::__construct() - Constructeur SoapVar
  • SoapHeader::__construct() - Constructeur SoapHeader
  • SoapFault::__construct() - Constructeur SoapFault
  • is_soap_fault() - Vérifie si SOAP retourne une erreur

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.
Llu?s P?mies 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));

?>


La classe SoapServer

(PHP 5, PHP 7, PHP 8)

Introduction

La classe SoapServer fournit un serveur pour les protocoles » SOAP 1.1 et » SOAP 1.2. Il peut être utilisé avec ou sans le service de description WSDL.

Synopsis de la classe

class SoapServer {
/* Propriétés */
private ?SoapFault $__soap_fault = null;
/* Méthodes */
public __construct(?string $wsdl, array $options = [])
public addFunction(array|string|int $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 $request = null): void
public setClass(string $class, mixed ...$args): void
public setObject(object $object): void
public setPersistence(int $mode): void
}

Propriétés

service

__soap_fault

Sommaire

  • SoapServer::addFunction — Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP
  • SoapServer::addSoapHeader — Ajoute un en-tête SOAP à une réponse
  • SoapServer::__construct — Constructeur SoapServer
  • SoapServer::fault — Emet une erreur SoapServer
  • SoapServer::getFunctions — Retourne la liste des fonctions définies
  • SoapServer::handle — Traite une requête SOAP
  • SoapServer::setClass — Configure la classe qui sera utilisée pour gérer les requêtes SOAP
  • SoapServer::setObject — Configure l'objet qui sera utilisé pour gérer les requêtes SOAP
  • SoapServer::setPersistence — Active le mode persistant de SoapServer

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.


Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP

  • « SoapServer
  • SoapServer::addSoapHeader »
  • PHP Manual
  • SoapServer
  • Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP

SoapServer::addFunction

(PHP 5, PHP 7, PHP 8)

SoapServer::addFunction — Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP

Description

public SoapServer::addFunction(array|string|int $functions): void

Exporte une ou plusieurs fonctions pour les clients distants.

Liste de paramètres

functions

Pour exporter une seule fonction, il faut passer son nom dans ce paramètre en tant que chaîne de caractères.

Pour exporter plusieurs fonctions, il faut utiliser un tableau de noms de fonctions.

Pour exporter toutes les fonctions, il faut utiliser la constante spéciale SOAP_FUNCTIONS_ALL.

Note:

functions doit recevoir tous les arguments d'entrée dans le même ordre que celui défini dans le fichier WSDL (il ne doit recevoir aucun paramètre de sortie en tant qu'argument) et retourne une ou plusieurs valeurs. Pour retourner plusieurs valeurs, il doit retourner un tableau contenant le nom des paramètres de sortie.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec SoapServer::addFunction()

<?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);

?>

Voir aussi

  • SoapServer::__construct() - Constructeur SoapServer
  • SoapServer::setClass() - Configure la classe qui sera utilisée pour gérer les requêtes SOAP

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.


Ajoute un en-tête SOAP à une réponse

  • « SoapServer::addFunction
  • SoapServer::__construct »
  • PHP Manual
  • SoapServer
  • Ajoute un en-tête SOAP à une réponse

SoapServer::addSoapHeader

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SoapServer::addSoapHeader — Ajoute un en-tête SOAP à une réponse

Description

public SoapServer::addSoapHeader(SoapHeader $header): void

Ajoute un en-tête SOAP à la réponse courante.

Liste de paramètres

header

L'en-tête à renvoyer.

Valeurs de retour

Aucune valeur n'est retournée.

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.


Constructeur SoapServer

  • « SoapServer::addSoapHeader
  • SoapServer::fault »
  • PHP Manual
  • SoapServer
  • Constructeur SoapServer

SoapServer::__construct

(PHP 5, PHP 7, PHP 8)

SoapServer::__construct — Constructeur SoapServer

Description

public SoapServer::__construct(?string $wsdl, array $options = [])

Ce constructeur permet la création d'objets SoapServer en mode WSDL ou non-WSDL.

Liste de paramètres

wsdl

Pour utiliser le mode WSDL, il faut définir l'URI du fichier WSDL dans ce paramètre. Avec les autres situations, il faut définir ce paramètre à null et définir l'option uri.

options

Permet de définir une version SOAP par défaut (soap_version), un jeu de caractères d'encodage interne (encoding) et un URI acteur (actor).

L'option classmap peut être utilisée pour lier quelques types WSDL à des classes PHP. Cette option doit être un tableau avec les types WSDL en tant que clés et les noms des classes PHP en tant que valeurs.

L'option typemap est un tableau dont les clés sont type_name, type_ns (URI de l'espace de noms), from_xml (fonction de rappel acceptant un paramètre de type chaîne de caractères) et to_xml (fonction de rappel acceptant un paramètre de type objet).

L'option cache_wsdl prend une des valeurs WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY ou WSDL_CACHE_BOTH.

La dernière option est features qui peut être défini à SOAP_WAIT_ONE_WAY_CALLS, SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE.

L'option send_errors peut être défini à false pour envoyer un message d'erreur générique ("Internal error") au lieu du message d'erreur spécifique.

Exemples

Exemple #1 Exemples avec SoapServer::__construct()

<?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")));

?>

Voir aussi

  • SoapClient::__construct() - Constructeur SoapClient

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


Emet une erreur SoapServer

  • « SoapServer::__construct
  • SoapServer::getFunctions »
  • PHP Manual
  • SoapServer
  • Emet une erreur SoapServer

SoapServer::fault

(PHP 5, PHP 7, PHP 8)

SoapServer::fault — Emet une erreur SoapServer

Description

public SoapServer::fault(
string $code,
string $string,
string $actor = "",
mixed $details = null,
string $name = ""
): void

Envoie une réponse au client de la requête courante, avec un message d'erreur.

Note:

Cela n'est possible que durant l'exécution de la requête.

Liste de paramètres

code

Le code d'erreur à retourner.

string

Une description de l'erreur.

actor

Une chaîne identifiant l'acteur en cause.

details

Plus de détails sur la faute.

name

Le nom de l'erreur. Cela peut être utilisé pour sélectionner un nom dans un fichier WSDL.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • SoapFault::__construct() - Constructeur SoapFault

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


Retourne la liste des fonctions définies

  • « SoapServer::fault
  • SoapServer::handle »
  • PHP Manual
  • SoapServer
  • Retourne la liste des fonctions définies

SoapServer::getFunctions

(PHP 5, PHP 7, PHP 8)

SoapServer::getFunctions — Retourne la liste des fonctions définies

Description

public SoapServer::getFunctions(): array

SoapServer::getFunctions() retourne la liste de toutes les fonctions ajoutées à l'objet serveur SoapServer. Elle retourne la liste de toutes les fonctions ajoutées à l'aide des méthodes SoapServer::addFunction() et SoapServer::setClass().

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Un tableau de toutes les fonctions.

Exemples

Exemple #1 Exemple avec SoapServer::getFunctions()

<?php
$server = new SoapServer(NULL, array("uri" => "http://test-uri"));
$server->addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$server->handle();
} else {
echo "Ce serveur SOAP peut gérer les fonctions suivantes : ";
$functions = $server->getFunctions();
foreach($functions as $func) {
echo $func . "\n";
}
}
?>

Voir aussi

  • SoapServer::__construct() - Constructeur SoapServer
  • SoapServer::addFunction() - Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP
  • SoapServer::setClass() - Configure la classe qui sera utilisée pour gérer les requêtes SOAP

User Contributed Notes

There are no user contributed notes for this page.


Traite une requête SOAP

  • « SoapServer::getFunctions
  • SoapServer::setClass »
  • PHP Manual
  • SoapServer
  • Traite une requête SOAP

SoapServer::handle

(PHP 5, PHP 7, PHP 8)

SoapServer::handle — Traite une requête SOAP

Description

public SoapServer::handle(?string $request = null): void

Effectue une requête SOAP, appelle les fonctions nécessaires et envoie une réponse en retour.

Liste de paramètres

request

La requête SOAP. Si cet argument est omis, la requête est supposée être dans les données POST brûtes de la requête HTTP.

Valeurs de retour

Aucune valeur n'est retournée.

Historique

Version | Description
8.0.0 | request est désormais nullable.

Exemples

Exemple #1 Exemple avec SoapServer::handle()

<?php
function test($x)
{
return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Voir aussi

  • SoapServer::__construct() - Constructeur SoapServer

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());


Configure la classe qui sera utilisée pour gérer les requêtes SOAP

  • « SoapServer::handle
  • SoapServer::setObject »
  • PHP Manual
  • SoapServer
  • Configure la classe qui sera utilisée pour gérer les requêtes SOAP

SoapServer::setClass

(PHP 5, PHP 7, PHP 8)

SoapServer::setClass — Configure la classe qui sera utilisée pour gérer les requêtes SOAP

Description

public SoapServer::setClass(string $class, mixed ...$args): void

Exporte toute les méthodes de la classe spécifiée.

SoapServer::setClass() configure une classe qui servira de gestionnaire aux requêtes SOAP. L'objet pourra alors être rendu persistant à travers les requêtes pour une session PHP, avec la méthode SoapServer::setPersistence().

Liste de paramètres

class

Le nom de la classe exportée.

args

Ces paramètres optionnels seront passé par défaut au constructeur de la classe, durant la phase de création de l'objet.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • SoapServer::__construct() - Constructeur SoapServer
  • SoapServer::addFunction() - Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP
  • SoapServer::setPersistence() - Active le mode persistant de SoapServer

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();
?>


Configure l'objet qui sera utilisé pour gérer les requêtes SOAP

  • « SoapServer::setClass
  • SoapServer::setPersistence »
  • PHP Manual
  • SoapServer
  • Configure l'objet qui sera utilisé pour gérer les requêtes SOAP

SoapServer::setObject

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SoapServer::setObject — Configure l'objet qui sera utilisé pour gérer les requêtes SOAP

Description

public SoapServer::setObject(object $object): void

SoapServer::setObject() configure un objet qui servira de gestionnaire aux requêtes SOAP, plutôt qu'une simple classe, comme avec SoapServer::setClass().

Liste de paramètres

object

L'objet qui va gérer les requêtes.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • SoapServer::setClass() - Configure la classe qui sera utilisée pour gérer les requêtes SOAP

User Contributed Notes

There are no user contributed notes for this page.


Active le mode persistant de SoapServer

  • « SoapServer::setObject
  • SoapFault »
  • PHP Manual
  • SoapServer
  • Active le mode persistant de SoapServer

SoapServer::setPersistence

(PHP 5, PHP 7, PHP 8)

SoapServer::setPersistence — Active le mode persistant de SoapServer

Description

public SoapServer::setPersistence(int $mode): void

Cette fonction permet de changer la persistance d'un objet SoapServer entre les requêtes. Elle permet de sauvegarder les données entre les requêtes, au moyen des sessions PHP. Cette fonction n'a d'effet qu'après avoir exporté la liste des fonctions au moyen de SoapServer::setClass().

Note:

La constante de persistence SOAP_PERSISTENCE_SESSION rend uniquement les objets de la classe donnée persistants, mais non pas les données statiques. Dans ce cas, $this->bar au lieu de self::$bar.

Note:

SOAP_PERSISTENCE_SESSION serialise les données de l'objet entre les requêtes. Dans le cas des ressources, (par exemple PDO), __wakeup() et __sleep() devraient être utilisées.

Liste de paramètres

mode

Une des constantes suivantes :

SOAP_PERSISTENCE_REQUEST - Les données de SoapServer ne sont pas persistantes entre les requêtes. C'est le comportement par défaut de tout objet SoapServer après appel à setClass().

SOAP_PERSISTENCE_SESSION - Les données de SoapServer persistent entre les requêtes. Ceci est réalisé en sérialisant les données de la classe SoapServer dans $_SESSION['_bogus_session_name'], et ainsi session_start() doit être appelée avant de passer sous ce mode de persistance.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple SoapServer::setPersistence()

<?php
class MyFirstPersistentSoapServer {
private $resource; // (Par exemple PDO, mysqli, etc..)
public $myvar1;
public $myvar2;

public function __construct() {
$this->__wakeup(); // On appelle notre wakeup pour relancer notre ressource
}

public function __wakeup() {
$this->resource = CodeToStartOurResourceUp();
}

public function __sleep() {
// On s'assure d'enlever $resource ici, ainsi nos données peuvent persister en session
// Si on oublie, la désérialisation lors de la prochaine requête échouera et notre objet
// SoapObject ne sera donc pas persistant entre les requêtes.
return array('myvar1','myvar2');
}
}

try {
session_start();
$server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
$server->setClass('MyFirstPersistentSoapServer');
// setPersistence() DOIT être appelée après setClass(), car le comportement de setClass()
// affecte SESSION_PERSISTENCE_REQUEST.
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
} catch(SoapFault $e) {
error_log("SOAP ERROR: ". $e->getMessage());
}
?>

Voir aussi

  • SoapServer::setClass() - Configure la classe qui sera utilisée pour gérer les requêtes SOAP

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.


La classe SoapFault

(PHP 5, PHP 7, PHP 8)

Introduction

Représente une erreur SOAP.

Synopsis de la classe

class SoapFault extends Exception {
/* Propriétés */
public string $faultstring;
public ?string $faultcode = null;
public ?string $faultcodens = null;
public ?string $faultactor = null;
public mixed $detail = null;
public ?string $_name = null;
public mixed $headerfault = null;
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes */
public __construct(
array|string|null $code,
string $string,
?string $actor = null,
mixed $details = null,
?string $name = null,
mixed $headerFault = null
)
public __toString(): string
/* Méthodes héritées */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Propriétés

_name

detail

faultactor

faultcode

faultcodens

faultstring

headerfault

Sommaire

  • SoapFault::__construct — Constructeur SoapFault
  • SoapFault::__toString — Produit une représentation chaîne d'un objet 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


Constructeur SoapFault

  • « SoapFault
  • SoapFault::__toString »
  • PHP Manual
  • SoapFault
  • Constructeur SoapFault

SoapFault::__construct

(PHP 5, PHP 7, PHP 8)

SoapFault::__construct — Constructeur SoapFault

Description

public SoapFault::__construct(
array|string|null $code,
string $string,
?string $actor = null,
mixed $details = null,
?string $name = null,
mixed $headerFault = null
)

SoapFault sert à envoyer des erreurs SOAP depuis le PHP.faultcode, faultstring, faultactor et detail sont les éléments standards SOAP.

Liste de paramètres

faultcode

Le code erreur de SoapFault.

faultstring

Le message d'erreur de SoapFault.

faultactor

Une chaîne identifiant l'acteur qui a causé l'erreur.

detail

faultname

Peut être utilisé pour sélectionner l'encodage qui convient depuis WSDL.

headerfault

Peut être utilisé durant la gestion de l'entête SOAP pour rapporter une erreur dans l'en-tête de réponse.

Exemples

Exemple #1 Quelques exemples avec SoapFault

<?php
function test($x)
{
return new SoapFault("Server", "Un message d'erreur");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Il est possible d'utiliser le mécanisme des exceptions de PHP pour lancer des exceptions SoapFault.

Exemple #2 Emission d'exceptions SoapFault

<?php
function test($x)
{
throw new SoapFault("Server", "Un message d'erreur");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Voir aussi

  • SoapServer::fault() - Emet une erreur SoapServer
  • is_soap_fault() - Vérifie si SOAP retourne une erreur

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
?>


Produit une représentation chaîne d'un objet SoapFault

  • « SoapFault::__construct
  • SoapHeader »
  • PHP Manual
  • SoapFault
  • Produit une représentation chaîne d'un objet SoapFault

SoapFault::__toString

(PHP 5, PHP 7, PHP 8)

SoapFault::__toString — Produit une représentation chaîne d'un objet SoapFault

Description

public SoapFault::__toString(): string

Retourne une représentation en chaîne de l'objet SoapFault.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Une chaîne décrivant l'objet SoapFault.

User Contributed Notes

There are no user contributed notes for this page.


La classe SoapHeader

(PHP 5, PHP 7, PHP 8)

Introduction

Représente un en-tête SOAP.

Synopsis de la classe

class SoapHeader {
/* Propriétés */
public string $namespace;
public string $name;
public mixed $data = null;
public bool $mustUnderstand;
public string|int|null $actor;
/* Méthodes */
public __construct(
string $namespace,
string $name,
mixed $data = ?,
bool $mustunderstand = ?,
string $actor = ?
)
}

Propriétés

actor

data

mustUnderstand

name

namespace

Sommaire

  • SoapHeader::__construct — Constructeur SoapHeader

User Contributed Notes

mixmaster1413 at gmail dot com 22-Jun-2023 02:15
Something I came across that I feel should be noted here is if you come across the error "cannot be processed at the receiver, due to an addressfilter mismatch at the endpointdispatcher. check that the sender and receiver's endpointaddresses agree." and you are absolutely sure your protocols and the service URL matches, send 'To' SoapHeader.

$soapHeaders = array(
            new \SoapHeader('http://www.w3.org/2005/08/addressing', 'Action', 'your-action', true),
            new \SoapHeader('http://www.w3.org/2005/08/addressing', 'To', 'your-service-endpoint-url')
        );
        $soapClient->__setSoapHeaders($soapHeaders);
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>


Constructeur SoapHeader

  • « SoapHeader
  • SoapParam »
  • PHP Manual
  • SoapHeader
  • Constructeur SoapHeader

SoapHeader::__construct

(PHP 5, PHP 7, PHP 8)

SoapHeader::__construct — Constructeur SoapHeader

Description

public SoapHeader::__construct(
string $namespace,
string $name,
mixed $data = ?,
bool $mustunderstand = ?,
string $actor = ?
)

Construit un nouvel objet SoapHeader.

Liste de paramètres

namespace

L'espace de noms de l'élément d'entête SOAP.

name

Le nom de l'élément d'entête SOAP.

data

Un contenu de l'en-tête SOAP. Il peut être une valeur PHP ou un objet SoapVar.

mustUnderstand

Valeur de l'attribut mustUnderstand de l'élément d'entête SOAP.

actor

Valeur de l'attribut actor de l'élément d'entête SOAP.

Exemples

Exemple #1 Exemple avec SoapHeader::__construct()

<?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'));
?>

Voir aussi

  • SoapClient::__soapCall() - Appelle une fonction SOAP
  • SoapVar::__construct() - Constructeur SoapVar
  • SoapParam::__construct() - Constructeur SoapParam
  • SoapServer::addSoapHeader() - Ajoute un en-tête SOAP à une réponse

User Contributed Notes

There are no user contributed notes for this page.


La classe SoapParam

(PHP 5, PHP 7, PHP 8)

Introduction

Représente un paramètre dans un appel SOAP.

Synopsis de la classe

class SoapParam {
/* Propriétés */
public string $param_name;
public mixed $param_data;
/* Méthodes */
public __construct(mixed $data, string $name)
}

Propriétés

param_data

param_name

Sommaire

  • SoapParam::__construct — Constructeur SoapParam

User Contributed Notes

There are no user contributed notes for this page.


Constructeur SoapParam

  • « SoapParam
  • SoapVar »
  • PHP Manual
  • SoapParam
  • Constructeur SoapParam

SoapParam::__construct

(PHP 5, PHP 7, PHP 8)

SoapParam::__construct — Constructeur SoapParam

Description

public SoapParam::__construct(mixed $data, string $name)

Construit un nouvel objet SoapParam.

Liste de paramètres

data

Les données à passer ou à retourner. Vous pouvez passer ce paramètre directement en tant qu'une valeur PHP, mais dans ce cas, il sera nommé paramN et le service SOAP ne le comprendra pas.

name

Le nom du paramètre.

Exemples

Exemple #1 Exemple avec SoapParam::__construct()

<?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"));
?>

Voir aussi

  • SoapClient::__soapCall() - Appelle une fonction SOAP
  • SoapVar::__construct() - Constructeur SoapVar

User Contributed Notes

There are no user contributed notes for this page.


La classe SoapVar

(PHP 5, PHP 7, PHP 8)

Introduction

Une classe représentant une variable ou un objet qui utilise des services SOAP.

Synopsis de la classe

class SoapVar {
/* Propriétés */
public int $enc_type;
public mixed $enc_value = null;
public ?string $enc_stype = null;
public ?string $enc_ns = null;
public ?string $enc_name = null;
public ?string $enc_namens = null;
/* Méthodes */
public __construct(
mixed $data,
?int $encoding,
?string $typeName = null,
?string $typeNamespace = null,
?string $nodeName = null,
?string $nodeNamespace = null
)
}

Propriétés

enc_name

enc_namens

enc_ns

enc_type

enc_stype

enc_value

Sommaire

  • SoapVar::__construct — Constructeur SoapVar

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


Constructeur SoapVar

  • « SoapVar
  • Yar »
  • PHP Manual
  • SoapVar
  • Constructeur SoapVar

SoapVar::__construct

(PHP 5, PHP 7, PHP 8)

SoapVar::__construct — Constructeur SoapVar

Description

public SoapVar::__construct(
mixed $data,
?int $encoding,
?string $typeName = null,
?string $typeNamespace = null,
?string $nodeName = null,
?string $nodeNamespace = null
)

Construit un nouvel objet SoapVar.

Liste de paramètres

data

Les données à passer ou à retourner.

encoding

L'ID d'encodage, une des constantes XSD_....

type_name

Le nom du type.

type_namespace

Le type de l'espace de noms.

node_name

Le nom du nœud XML.

node_namespace

L'espace de noms du nœud XML.

Historique

Version | Description
8.0.3 | typeName, typeNamespace, nodeName, et nodeNamespace sont désormais nullable.

Exemples

Exemple #1 Exemple avec SoapVar::__construct()

<?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"));
?>

Voir aussi

  • SoapClient::__soapCall() - Appelle une fonction SOAP
  • SoapParam::__construct() - Constructeur SoapParam

User Contributed Notes

There are no user contributed notes for this page.


Yet Another RPC Framework

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Exemples
  • Yar_Server — La classe Yar_Server
    • Yar_Server::__construct — Enregistre un serveur
    • Yar_Server::handle — Démarre un serveur RPC
  • Yar_Client — La classe Yar_Client
    • Yar_Client::__call — Service d'appel
    • Yar_Client::__construct — Crée un client
    • Yar_Client::setOpt — Défini le contexte d'appel
  • Yar_Concurrent_Client — La classe Yar_Concurrent_Client
    • Yar_Concurrent_Client::call — Enregistre un appel concurrent
    • Yar_Concurrent_Client::loop — Envoi tous les appels
    • Yar_Concurrent_Client::reset — Nettoie tous les appels enregistré
  • Yar_Server_Exception — La classe Yar_Server_Exception
    • Yar_Server_Exception::getType — Récupérer le type de l'exception
  • Yar_Client_Exception — La classe Yar_Client_Exception
    • Yar_Client_Exception::getType — Récupérer le type de l'exception

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Yar est un framework RPC qui a pour but de fournir une façon simple de communication entre les applications PHP. Il apporte la possibilité d'appeler plusieurs services distants simultanément.

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

Si vous voulez utiliser msgpack comme packager, vous devez compiler Yar vous même avec l'option de configuration ./configure --enable-msgpack

User Contributed Notes

There are no user contributed notes for this page.


Installation

Cette extension » PECL n'est pas intégrée à PHP.

Des informations sur l'installation de ces extensions PECL peuvent être trouvées dans le chapitre du manuel intitulé Installation des extensions PECL. D'autres informations comme les notes sur les nouvelles versions, les téléchargements, les sources des fichiers, les informations concernant les mainteneurs ainsi qu'un CHANGELOG, peuvent être trouvées ici : » https://pecl.php.net/package/yar.

Aucune bibliothèque DLL pour cette extension PECL n'est actuellement disponible. Reportez-vous à la section Compilation sous 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/


Configuration à l'exécution

Le comportement de ces fonctions est affecté par la configuration dans le fichier php.ini.

Options de configuration Yar
Nom | Défaut | Modifiable | Historique
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_SYSTEM |

Voici un éclaircissement sur l'utilisation des directives de configuration.

yar.packager string

peut être php, json, et msgpack (nécessite une compilation avec le support msgpack)

yar.debug string

yar.connect_timeout int

délai d'attente maximal en ms

yar.timeout int

délai d'attente maximal en ms

yar.expose_info bool

si l'on doit ou non exposer les informations du service (lors de l'accès au serveur via GET)

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

YAR_VERSION (string)
YAR_CLIENT_PROTOCOL_HTTP (int)
YAR_OPT_PACKAGER (int)
YAR_OPT_TIMEOUT (int)
YAR_OPT_CONNECT_TIMEOUT (int)
YAR_OPT_HEADER (array)
Depuis 2.0.4
YAR_PACKAGER_PHP (string)
YAR_PACKAGER_JSON (string)
YAR_ERR_OKEY (int)
YAR_ERR_OUTPUT (int)
YAR_ERR_TRANSPORT (int)
YAR_ERR_REQUEST (int)
YAR_ERR_PROTOCOL (int)
YAR_ERR_PACKAGER (int)
YAR_ERR_EXCEPTION (int)

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Exemple #1 Exemple de serveur Yar

<?php

/* supposons que cette page est accessible via l'URL http://example.com/operator.php */

class Operator {

/**
* Ajout de deux opérandes
* @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;
}

/**
* Les méthodes protégées ne seront pas exposées
* @param interge
* @return interge
*/
protected function _add($a, $b) {
return $a + $b;
}
}

$server = new Yar_Server(new Operator());
$server->handle();
?>

Exemple #2 Accès au serveur depuis un navigateur (requête GET)

Résultat de l'exemple ci-dessus est similaire à :

Information du serveur Yar

Exemple #3 Exemple de client Yar

<?php
$client = new yar_client("http://example.com/operator.php");

/* Appel direct */
var_dump($client->add(1, 2));

/* Appel via un appel */
var_dump($client->call("add", array(3, 2)));

/* la méthode __add ne peut être appelée */
var_dump($client->_add(1, 2));
?>

Résultat de l'exemple ci-dessus est similaire à :

int(3)
int(5)
PHP Fatal error:  Uncaught exception 'Yar_Server_Exception' with message 'call to api Operator::_add() failed' in *

Exemple #4 Exemple de client Yar concurrent

<?php
function callback($ret, $callinfo) {
echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* enregistre l'appel async aux services distants */
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");

/* envoi toutes les requêtes et attend les réponses */
Yar_Concurrent_Client::loop();
?>

Résultat de l'exemple ci-dessus est similaire à :

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();

?>


La classe Yar_Server

(No version information available, might only be in Git)

Introduction

Synopsis de la classe

class Yar_Server {
/* Propriétés */
protected $_executor;
/* Méthodes */
final public __construct(Object $obj)
public handle(): bool
}

Propriétés

_executor

Sommaire

  • Yar_Server::__construct — Enregistre un serveur
  • Yar_Server::handle — Démarre un serveur RPC

User Contributed Notes

There are no user contributed notes for this page.


Enregistre un serveur

  • « Yar_Server
  • Yar_Server::handle »
  • PHP Manual
  • Yar_Server
  • Enregistre un serveur

Yar_Server::__construct

(PECL yar >= 1.0.0)

Yar_Server::__construct — Enregistre un serveur

Description

final public Yar_Server::__construct(Object $obj)

Configure un serveur Yar HTTP RPC. Toutes les méthodes publiques de l'objet $obj seront enregistrées comme un service RPC.

Liste de paramètres

obj

Un objet. Toutes les méthodes publiques de cet objet seront enregistrées comme services RPC.

Valeurs de retour

Une instance de la classe Yar_Server.

Exemples

Exemple #1 Exemple avec Yar_Server::__construct()

<?php
class API {
/**
* les informations seront générées automatiquement sur la page d'information du service.
* @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();
?>

Résultat de l'exemple ci-dessus est similaire à :

Voir aussi

  • Yar_Server::handle() - Démarre un serveur RPC
    •

User Contributed Notes

There are no user contributed notes for this page.


Démarre un serveur RPC

  • « Yar_Server::__construct
  • Yar_Client »
  • PHP Manual
  • Yar_Server
  • Démarre un serveur RPC

Yar_Server::handle

(PECL yar >= 1.0.0)

Yar_Server::handle — Démarre un serveur RPC

Description

public Yar_Server::handle(): bool

Démarre un serveur RPC HTTP, et le rend prêt à accepter des requêtes RPC.

Note:

Les appels RPC sont envoyés par des requêtes HTTP POST. Si une requête HTTP GET est envoyé à l'URI, les informations du service (commenté dans la section ci-dessous) seront affichées sur la page.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Un booléen.

Exemples

Exemple #1 Exemple avec Yar_Server::handle()

<?php
class API {
/**
* les informations seront générées automatiquement sur la page d'informations du service.
* @params
* @return
*/
public function some_method($parameter, $option = "foo") {
}

protected function client_can_not_see() {
}
}

$service = new Yar_Server(new API());
$service->handle();
?>

Résultat de l'exemple ci-dessus est similaire à :

Voir aussi

  • Yar_Server::__construct() - Enregistre un serveur
    •

User Contributed Notes

There are no user contributed notes for this page.


La classe Yar_Client

(No version information available, might only be in Git)

Introduction

Synopsis de la classe

class Yar_Client {
/* Propriétés */
protected $_protocol;
protected $_uri;
protected $_options;
protected $_running;
/* Méthodes */
public __call(string $method, array $parameters): void
final public __construct(string $url, array $options = ?)
public setOpt(int $name, mixed $value): Yar_Client|false
}

Propriétés

_protocol

_uri

_options

_running

Sommaire

  • Yar_Client::__call — Service d'appel
  • Yar_Client::__construct — Crée un client
  • Yar_Client::setOpt — Défini le contexte d'appel

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);
?>


Service d'appel

  • « Yar_Client
  • Yar_Client::__construct »
  • PHP Manual
  • Yar_Client
  • Service d'appel

Yar_Client::__call

(PECL yar >= 1.0.0)

Yar_Client::__call — Service d'appel

Description

public Yar_Client::__call(string $method, array $parameters): void

Envoi un appel à la méthode RPC distante.

Liste de paramètres

method

Nom de la méthode RPC distante.

parameters

Paramètres.

Valeurs de retour

Exemples

Exemple #1 Exemple avec Yar_Client::__call()

<?php

$client = new Yar_Client("http://host/api/");

/* Appel un service distant */
$result = $client->some_method("parameter");
?>

Résultat de l'exemple ci-dessus est similaire à :

Voir aussi

  • Yar_Client::setOpt() - Défini le contexte d'appel
    •

User Contributed Notes

There are no user contributed notes for this page.


Crée un client

  • « Yar_Client::__call
  • Yar_Client::setOpt »
  • PHP Manual
  • Yar_Client
  • Crée un client

Yar_Client::__construct

(PECL yar >= 1.0.0)

Yar_Client::__construct — Crée un client

Description

final public Yar_Client::__construct(string $url, array $options = ?)

Crée un Yar_Client sur un serveur Yar_Server.

Liste de paramètres

url

URL du serveur Yar.

Valeurs de retour

Une instance Yar_Client.

Exemples

Exemple #1 Exemple avec Yar_Client::__construct()

<?php
$client = new Yar_Client("http://host/api/");
?>

Résultat de l'exemple ci-dessus est similaire à :

Voir aussi

  • Yar_Client::__call() - Service d'appel
    •

  • Yar_Client::setOpt() - Défini le contexte d'appel
    •

User Contributed Notes

There are no user contributed notes for this page.


Défini le contexte d'appel

  • « Yar_Client::__construct
  • Yar_Concurrent_Client »
  • PHP Manual
  • Yar_Client
  • Défini le contexte d'appel

Yar_Client::setOpt

(PECL yar >= 1.0.0)

Yar_Client::setOpt — Défini le contexte d'appel

Description

public Yar_Client::setOpt(int $name, mixed $value): Yar_Client|false

Liste de paramètres

name

Peut être : YAR_OPT_PACKAGER, YAR_OPT_PERSISTENT (à besoin du support serveur), YAR_OPT_TIMEOUT, YAR_OPT_CONNECT_TIMEOUT, YAR_OPT_HEADER (depuis 2.0.4), YAR_OPT_PROXY (depuis 2.2.0)

value

Valeurs de retour

Retourne $this en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec Yar_Client::setOpt()

<?php

$cient = new Yar_Client("http://host/api/");

//Défini le délai d'attente maximal à 1s
$client->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);

//Défini le packager à JSON
$client->SetOpt(YAR_OPT_PACKAGER, "json");

//Défini l'en-tête personnalisée
$client->SetOpt(YAR_OPT_HEADER, array("hr1: val1", "hd2: val2"));

// Défini le proxy HTTP
$client->SetOpt(YAR_OPT_PROXY, "127.0.0.1:8888");

/* Appel le service distant */
$result = $client->some_method("parameter");
?>

Résultat de l'exemple ci-dessus est similaire à :

Voir aussi

  • Yar_Client::__call() - Service d'appel
    •

User Contributed Notes

There are no user contributed notes for this page.


La classe Yar_Concurrent_Client

(No version information available, might only be in Git)

Introduction

Synopsis de la classe

class Yar_Concurrent_Client {
/* Propriétés */
static $_callstack;
static $_callback;
static $_error_callback;
/* Méthodes */
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 = ?): bool
public static reset(): bool
}

Propriétés

_callstack

_callback

_error_callback

Sommaire

  • Yar_Concurrent_Client::call — Enregistre un appel concurrent
  • Yar_Concurrent_Client::loop — Envoi tous les appels
  • Yar_Concurrent_Client::reset — Nettoie tous les appels enregistré

User Contributed Notes

There are no user contributed notes for this page.


Enregistre un appel concurrent

  • « Yar_Concurrent_Client
  • Yar_Concurrent_Client::loop »
  • PHP Manual
  • Yar_Concurrent_Client
  • Enregistre un appel concurrent

Yar_Concurrent_Client::call

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::call — Enregistre un appel concurrent

Description

public static Yar_Concurrent_Client::call(
string $uri,
string $method,
array $parameters = ?,
callable $callback = ?,
callable $error_callback = ?,
array $options = ?
): int

Enregistre un appel RPC, mais ne l'envoie pas immédiatement ; il sera envoyé pendant l'appel à la méthode Yar_Concurrent_Client::loop()

Liste de paramètres

uri

L'URI du serveur RPC (http, tcp)

method

Nom du service (i.e. le nom de la méthode)

parameters

Paramètres

callback

Une fonction de rappel, qui sera appelée par le retour de la réponse.

Valeurs de retour

Un ID unique ; peut être utilisé pour identifier l'appel.

Exemples

Exemple #1 Exemple avec 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")); // si la fonction de rappel n'est pas spécifiée,
// la fonction de rappel de la boucle sera utilisée
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
// ce serveur accepte le packager json
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
// Délai d'attente maximal personnalisé

//Les requêtes ne sont pas envoyées pour le moment
?>

Résultat de l'exemple ci-dessus est similaire à :

Voir aussi

  • Yar_Concurrent_Client::loop() - Envoi tous les appels
    •

  • Yar_Concurrent_Client::reset() - Nettoie tous les appels enregistré
    •

  • Yar_Server::__construct() - Enregistre un serveur
    •

  • Yar_Server::handle() - Démarre un serveur RPC
    •

User Contributed Notes

There are no user contributed notes for this page.


Envoi tous les appels

  • « Yar_Concurrent_Client::call
  • Yar_Concurrent_Client::reset »
  • PHP Manual
  • Yar_Concurrent_Client
  • Envoi tous les appels

Yar_Concurrent_Client::loop

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::loop — Envoi tous les appels

Description

public static Yar_Concurrent_Client::loop(callable $callback = ?, callable $error_callback = ?): bool

Envoi tous les appels distants RPC enregistrés.

Liste de paramètres

callback

Si la fonction de rappel est définie, alors Yar appelera cette fonction de rappel après avoir envoyé tous les appels, et avant le retour des réponses, avec $callinfo vallant NULL.

Alors, si l'utilisateur ne spécifie pas de fonction de rappel lors de l'enregistrement d'appel concurrent, cette fonction de rappel sera utilisée pour gérer les réponses, sinon, la fonction de rappel spécifiée pendant l'enregistrement sera utilisée.

error_callback

Si la fonction de rappel est définie, alors Yar l'appelera lorsqu'une erreur surviendra.

Valeurs de retour

Exemples

Exemple #1 Exemple avec Yar_Concurrent_Client::loop()

<?php
function callback($retval, $callinfo) {
if ($callinfo == NULL) {
echo "Maintenant, toutes les requêtes ont été émises, et aucune réponse n'est pour l'instant disponible\n";
} else {
echo "Ceci est une réponse à un appel distant, le nom de la méthode est ", $callinfo["method"],
". La séquence d'appel est " , $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")); // Si la fonction de rappel n'est pas spécifiée
// la fonction de rappel de la boucle sera utilisée
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
// ce serveur accepte le packager json
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
//Délai d'attente maximal personnalisé

Yar_Concurrent_Client::loop("callback", "error_callback"); //Envoi les requêtes,
//error_callback est optionnel
?>

Résultat de l'exemple ci-dessus est similaire à :

Maintenant, toutes les requêtes ont été émises, et aucune réponse n'est pour l'instant disponible
Ceci est une réponse à un appel distant, le nom de la méthode est some_method. La séquence d'appel est 4
string(11) "some_method"
Ceci est une réponse à un appel distant, le nom de la méthode est some_method. La séquence d'appel est 1
string(11) "some_method"
Ceci est une réponse à un appel distant, le nom de la méthode est some_method. La séquence d'appel est 2
string(11) "some_method"
Ceci est une réponse à un appel distant, le nom de la méthode est some_method. La séquence d'appel est 3
string(11) "some_method"

Voir aussi

  • Yar_Concurrent_Client::call() - Enregistre un appel concurrent
  • Yar_Concurrent_Client::reset() - Nettoie tous les appels enregistré
  • Yar_Server::__construct() - Enregistre un serveur
  • Yar_Server::handle() - Démarre un serveur RPC

User Contributed Notes

There are no user contributed notes for this page.


Nettoie tous les appels enregistré

  • « Yar_Concurrent_Client::loop
  • Yar_Server_Exception »
  • PHP Manual
  • Yar_Concurrent_Client
  • Nettoie tous les appels enregistré

Yar_Concurrent_Client::reset

(PECL yar >= 1.2.4)

Yar_Concurrent_Client::reset — Nettoie tous les appels enregistré

Description

public static Yar_Concurrent_Client::reset(): bool

Nettoie tous les appels enregistré.

Liste de paramètres

Valeurs de retour

Exemples

Exemple #1 Exemple avec Yar_Concurrent_Client::reset()

Résultat de l'exemple ci-dessus est similaire à :

Voir aussi

  • Yar_Concurrent_Client::call() - Enregistre un appel concurrent
    •

  • Yar_Concurrent_Client::loop() - Envoi tous les appels
    •

  • Yar_Server::__construct() - Enregistre un serveur
    •

  • Yar_Server::handle() - Démarre un serveur RPC
    •

User Contributed Notes

There are no user contributed notes for this page.


La classe Yar_Server_Exception

(No version information available, might only be in Git)

Introduction

If service threw exceptions, A Yar_Server_Exception will be threw in client side.

Synopsis de la classe

class Yar_Server_Exception extends Exception {
/* Propriétés */
protected $_type;
/* Méthodes */
public getType(): string
/* Méthodes héritées */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Propriétés

message

code

file

line

_type

Sommaire

  • Yar_Server_Exception::getType — Récupérer le type de l'exception

User Contributed Notes

There are no user contributed notes for this page.


Récupérer le type de l'exception

  • « Yar_Server_Exception
  • Yar_Client_Exception »
  • PHP Manual
  • Yar_Server_Exception
  • Récupérer le type de l'exception

Yar_Server_Exception::getType

(PECL yar >= 1.0.0)

Yar_Server_Exception::getType — Récupérer le type de l'exception

Description

public Yar_Server_Exception::getType(): string

Récupère le type de l'exception émise par le serveur.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Une chaîne de caractères.

Exemples

Exemple #1 Exemple avec 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());
}

Résultat de l'exemple ci-dessus est similaire à :

string(16) "Custom_Exception"
string(6) "client"

Voir aussi

User Contributed Notes

There are no user contributed notes for this page.


La classe Yar_Client_Exception

(No version information available, might only be in Git)

Introduction

Synopsis de la classe

class Yar_Client_Exception extends Exception {
/* Propriétés */
/* Méthodes */
public getType(): void
/* Méthodes héritées */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Propriétés

message

code

file

line

Sommaire

  • Yar_Client_Exception::getType — Récupérer le type de l'exception

User Contributed Notes

There are no user contributed notes for this page.


Récupérer le type de l'exception

  • « Yar_Client_Exception
  • XML-RPC »
  • PHP Manual
  • Yar_Client_Exception
  • Récupérer le type de l'exception

Yar_Client_Exception::getType

(PECL yar >= 1.0.0)

Yar_Client_Exception::getType — Récupérer le type de l'exception

Description

public Yar_Client_Exception::getType(): void

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Exemples

Exemple #1 Exemple avec Yar_Client_Exception::getType()

<?php

/* ... */

?>

Résultat de l'exemple ci-dessus est similaire à :

...

Voir aussi

User Contributed Notes

There are no user contributed notes for this page.


XML-RPC

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Fonctions XML-RPC
    • xmlrpc_decode_request — Décode le code XML en variables PHP natives
    • xmlrpc_decode — Décode le XML en types PHP natifs
    • xmlrpc_encode_request — Génère le XML pour une méthode
    • xmlrpc_encode — Génère le code XML pour une valeur PHP
    • xmlrpc_get_type — Retourne le type XMLRPC d'une valeur PHP
    • xmlrpc_is_fault — Détermine si un tableau de valeurs représente un XMLRPC
    • xmlrpc_parse_method_descriptions — Décode le code XML en une liste de descriptions de méthodes
    • xmlrpc_server_add_introspection_data — Ajoute des données d'introspection
    • xmlrpc_server_call_method — Analyse une requête XML et appelle les méthodes associées
    • xmlrpc_server_create — Crée un serveur XMLRPC
    • xmlrpc_server_destroy — Détruit un serveur XMLRPC
    • xmlrpc_server_register_introspection_callback — Enregistre une fonction PHP pour générer la documentation
    • xmlrpc_server_register_method — Enregistre une fonction PHP avec une méthode
    • xmlrpc_set_type — Définit le type xmlrpc, base64 ou datetime, d'une valeur PHP

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Ces fonctions servent à écrire sur les serveurs XML-RPC, mais aussi sur les clients. Vous pouvez trouver plus d'informations sur XML-RPC sur » http://www.xmlrpc.com/, et plus de documentations sur cette extension et ces fonctions, sur » http://xmlrpc-epi.sourceforge.net/.

Avertissement

Cette extension est EXPERIMENTALE. Le comportement de cette extension, les noms de ses fonctions, et toute la documentation autour de cette extension peut changer sans préavis dans une prochaine version de PHP. Cette extension doit être utilisée à vos risques et périls.

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


Installation

Le support de XML-RPC n'est pas activé par défaut en PHP. Vous devez l'activer avec l'option de compilation --with-xmlrpc[=DIR].

User Contributed Notes

boldizar dot santo at gmail dot com 02-Aug-2023 08:23
For Linux Mint use the next cli command:
sudo apt-get install php-xmlrpc;
sudo service apache2 restart;
Lars 06-Mar-2023 08:51
Since PHP 8.0 the xmlrpc extension is not shipped with php any more.
Go to https://pecl.php.net/package/xmlrpc and download the latest version.

For linux you might use something like that:

$ wget https://pecl.php.net/get/xmlrpc-1.0.0RC3.tg
$ tar xfv xmlrpc-1.0.0RC3.tg
$ cd xmlrpc-1.0.0RC3
$ phpize && ./configure && make && make test && make install

Add the build extension in your php.ini section and don't forget to restart php-fpm or your webserver after the installation.

To verify the installation, you can use something like this (should at least return the line "xmlrpc"):
$ php -i | grep xmlrpc | grep -v "xmlrpc_error"
georgemilojevic at gmail dot com 11-Oct-2022 10:30
# For MacOS users (using M1 machine - Version: 12.5.1)

brew install pkg-config

pecl install channel://pecl.php.net/xmlrpc-1.0.0RC3

Then restart your apache, the extensions should be automatically added to php.ini and the output of phpinfo() should show it now
Clive 13-Apr-2022 10:41
Unless my host has deliberately installed it, PHP 8.0.17 still has xmlrpc included (1.0.0RC3).
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


Types de ressources

Cette extension définit une ressource serveur XML-RPC, retournée par la fonction xmlrpc_server_create().

User Contributed Notes

There are no user contributed notes for this page.


Fonctions XML-RPC

Sommaire

  • xmlrpc_decode_request — Décode le code XML en variables PHP natives
  • xmlrpc_decode — Décode le XML en types PHP natifs
  • xmlrpc_encode_request — Génère le XML pour une méthode
  • xmlrpc_encode — Génère le code XML pour une valeur PHP
  • xmlrpc_get_type — Retourne le type XMLRPC d'une valeur PHP
  • xmlrpc_is_fault — Détermine si un tableau de valeurs représente un XMLRPC
  • xmlrpc_parse_method_descriptions — Décode le code XML en une liste de descriptions de méthodes
  • xmlrpc_server_add_introspection_data — Ajoute des données d'introspection
  • xmlrpc_server_call_method — Analyse une requête XML et appelle les méthodes associées
  • xmlrpc_server_create — Crée un serveur XMLRPC
  • xmlrpc_server_destroy — Détruit un serveur XMLRPC
  • xmlrpc_server_register_introspection_callback — Enregistre une fonction PHP pour générer la documentation
  • xmlrpc_server_register_method — Enregistre une fonction PHP avec une méthode
  • xmlrpc_set_type — Définit le type xmlrpc, base64 ou datetime, d'une valeur PHP

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=Windows-1252");
    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


Décode le code XML en variables PHP natives

  • « Fonctions XML-RPC
  • xmlrpc_decode »
  • PHP Manual
  • Fonctions XML-RPC
  • Décode le code XML en variables PHP natives

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode_request — Décode le code XML en variables PHP natives

Description

xmlrpc_decode_request(string $xml, string &$method, string $encoding = ?): mixed
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

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.


Décode le XML en types PHP natifs

  • « xmlrpc_decode_request
  • xmlrpc_encode_request »
  • PHP Manual
  • Fonctions XML-RPC
  • Décode le XML en types PHP natifs

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode — Décode le XML en types PHP natifs

Description

xmlrpc_decode(string $xml, string $encoding = "iso-8859-1"): mixed
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Liste de paramètres

xml

Réponse XML retournée par la méthode XMLRPC.

encoding

Encodage d'entrée, supporté par iconv.

Valeurs de retour

Retourne soit un tableau, soit un entier, soit une chaîne, soit un booléen, en fonction de la réponse retournée par la méthode XMLRPC.

Exemples

Voir l'exemple fourni avec la documentation de la fonction xmlrpc_encode_request().

Voir aussi

  • xmlrpc_encode_request() - Génère le XML pour une méthode
  • xmlrpc_is_fault() - Détermine si un tableau de valeurs représente un XMLRPC

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);
?>


Génère le XML pour une méthode

  • « xmlrpc_decode
  • xmlrpc_encode »
  • PHP Manual
  • Fonctions XML-RPC
  • Génère le XML pour une méthode

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode_request — Génère le XML pour une méthode

Description

xmlrpc_encode_request(string $method, mixed $params, array $output_options = ?): string
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Liste de paramètres

method

Nom de la méthode à appeler.

params

Paramètres de la méthode, compatibles avec la signature de la méthode.

output_options

Tableau spécifiant les options de sortie pouvant contenir (les valeurs par défaut sont en gras) :

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (peut être une chaîne avec une valeur ou un tableau avec plusieurs valeurs)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, autres jeux de caractères supportés par iconv

Valeurs de retour

Retourne une chaîne contenant la représentation XML de la demande.

Exemples

Exemple #1 Exemple avec XMLRPC

<?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);
}
?>

Voir aussi

  • stream_context_create() - Crée un contexte de flux
  • file_get_contents() - Lit tout un fichier dans une chaîne
  • xmlrpc_decode() - Décode le XML en types PHP natifs

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.


Génère le code XML pour une valeur PHP

  • « xmlrpc_encode_request
  • xmlrpc_get_type »
  • PHP Manual
  • Fonctions XML-RPC
  • Génère le code XML pour une valeur PHP

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode — Génère le code XML pour une valeur PHP

Description

xmlrpc_encode(mixed $value): string
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

User Contributed Notes

There are no user contributed notes for this page.


Retourne le type XMLRPC d'une valeur PHP

  • « xmlrpc_encode
  • xmlrpc_is_fault »
  • PHP Manual
  • Fonctions XML-RPC
  • Retourne le type XMLRPC d'une valeur PHP

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_get_type — Retourne le type XMLRPC d'une valeur PHP

Description

xmlrpc_get_type(mixed $value): string

Particulièrement pratique pour les types chaînes de type base64 et datetime.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

value

Valeur PHP

Valeurs de retour

Retourne le type XML-RPC.

Exemples

Exemple #1 Exemple de type XML-RPC

<?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
?>

Voir aussi

  • xmlrpc_set_type() - Définit le type xmlrpc, base64 ou datetime, d'une valeur PHP

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.


Détermine si un tableau de valeurs représente un XMLRPC

  • « xmlrpc_get_type
  • xmlrpc_parse_method_descriptions »
  • PHP Manual
  • Fonctions XML-RPC
  • Détermine si un tableau de valeurs représente un XMLRPC

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

xmlrpc_is_fault — Détermine si un tableau de valeurs représente un XMLRPC

Description

xmlrpc_is_fault(array $arg): bool
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Liste de paramètres

arg

Tableau retourné par la fonction xmlrpc_decode().

Valeurs de retour

Retourne true si l'argument signifie fault, false sinon. La description de fault est disponible dans la variable $arg["faultString"], le code de fault est disponible dans la variable $arg["faultCode"].

Exemples

Retrouvez un exemple avec la fonction xmlrpc_encode_request().

Voir aussi

  • xmlrpc_decode() - Décode le XML en types PHP natifs

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']);
    }

?>


Décode le code XML en une liste de descriptions de méthodes

  • « xmlrpc_is_fault
  • xmlrpc_server_add_introspection_data »
  • PHP Manual
  • Fonctions XML-RPC
  • Décode le code XML en une liste de descriptions de méthodes

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_parse_method_descriptions — Décode le code XML en une liste de descriptions de méthodes

Description

xmlrpc_parse_method_descriptions(string $xml): array
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

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


Ajoute des données d'introspection

  • « xmlrpc_parse_method_descriptions
  • xmlrpc_server_call_method »
  • PHP Manual
  • Fonctions XML-RPC
  • Ajoute des données d'introspection

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_add_introspection_data — Ajoute des données d'introspection

Description

xmlrpc_server_add_introspection_data(resource $server, array $desc): int
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

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`


Analyse une requête XML et appelle les méthodes associées

  • « xmlrpc_server_add_introspection_data
  • xmlrpc_server_create »
  • PHP Manual
  • Fonctions XML-RPC
  • Analyse une requête XML et appelle les méthodes associées

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_call_method — Analyse une requête XML et appelle les méthodes associées

Description

xmlrpc_server_call_method(
resource $server,
string $xml,
mixed $user_data,
array $output_options = ?
): string
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

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);
?>


Crée un serveur XMLRPC

  • « xmlrpc_server_call_method
  • xmlrpc_server_destroy »
  • PHP Manual
  • Fonctions XML-RPC
  • Crée un serveur XMLRPC

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_create — Crée un serveur XMLRPC

Description

xmlrpc_server_create(): resource
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

User Contributed Notes

There are no user contributed notes for this page.


Détruit un serveur XMLRPC

  • « xmlrpc_server_create
  • xmlrpc_server_register_introspection_callback »
  • PHP Manual
  • Fonctions XML-RPC
  • Détruit un serveur XMLRPC

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_destroy — Détruit un serveur XMLRPC

Description

xmlrpc_server_destroy(resource $server): bool
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

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.


Enregistre une fonction PHP pour générer la documentation

  • « xmlrpc_server_destroy
  • xmlrpc_server_register_method »
  • PHP Manual
  • Fonctions XML-RPC
  • Enregistre une fonction PHP pour générer la documentation

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_introspection_callback — Enregistre une fonction PHP pour générer la documentation

Description

xmlrpc_server_register_introspection_callback(resource $server, string $function): bool
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

User Contributed Notes

ronadaassoc at gmail dot com 22-Oct-2022 05:51
<?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>
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>


Enregistre une fonction PHP avec une méthode

  • « xmlrpc_server_register_introspection_callback
  • xmlrpc_set_type »
  • PHP Manual
  • Fonctions XML-RPC
  • Enregistre une fonction PHP avec une méthode

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_method — Enregistre une fonction PHP avec une méthode

Description

xmlrpc_server_register_method(resource $server, string $method_name, string $function): bool
Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

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


Définit le type xmlrpc, base64 ou datetime, d'une valeur PHP

  • « xmlrpc_server_register_method
  • Extensions pour Windows uniquement »
  • PHP Manual
  • Fonctions XML-RPC
  • Définit le type xmlrpc, base64 ou datetime, d'une valeur PHP

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_set_type — Définit le type xmlrpc, base64 ou datetime, d'une valeur PHP

Description

xmlrpc_set_type(string &$value, string $type): bool

xmlrpc_set_type() définit le type XMLRPC, base64 ou datetime, pour une chaîne PHP.

Avertissement

Cette fonction est EXPERIMENTALE. Le comportement de cette fonction, son nom, et toute la documentation autour de cette fonction peut changer sans préavis dans une prochaine version de PHP. Cette fonction doit être utilisée à vos risques et périls.

Liste de paramètres

value

Valeur dont on veut modifier le type

type

base64 ou datetime

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient. En cas de réussite, value sera converti en objet.

Erreurs / Exceptions

Émet une alerte de type E_WARNING lorsque le type n'est pas supporté par XMLRPC.

Exemples

Exemple #1 Exemple avec xmlrpc_set_type()

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

Résultat de l'exemple ci-dessus est similaire à :

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

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).


Extensions pour Windows uniquement

  • COM — COM et .Net (Windows)
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Erreur et gestion des erreurs
    • Exemples
    • com — La classe com
    • dotnet — La classe dotnet
    • variant — La classe variant
    • COMPersistHelper — The COMPersistHelper class
    • com_exception — La classe The com_exception
    • Fonctions COM et .Net (Windows)
  • win32service
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Win32ServiceException — La class Win32ServiceException
    • Exemples
    • Fonctions win32service

User Contributed Notes

There are no user contributed notes for this page.


COM et .Net (Windows)

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Erreur et gestion des erreurs
  • Exemples
    • For Each
    • Tableaux et propriétés à la façon des tableaux de COM
  • com — La classe com
    • com::__construct — Constructeur de la classe com
  • dotnet — La classe dotnet
    • dotnet::__construct — Constructeur de la classe dotnet
  • variant — La classe variant
    • variant::__construct — Constructeur de la classe variant
  • 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 — La classe The com_exception
  • Fonctions COM et .Net (Windows)
    • com_create_guid — Génère un identifiant unique global (GUID)
    • com_event_sink — Connecte des événements d'un objet COM sur un objet PHP
    • com_get_active_object — Retourne un objet représentant l'instance actuelle d'un objet COM
    • com_load_typelib — Charge un Typelib
    • com_message_pump — Traite un message COM dans un délai donné
    • com_print_typeinfo — Affiche une définition de classe PHP pour une interface répartissable
    • variant_abs — Retourne la valeur absolue d'un variant
    • variant_add — "Ajoute" deux valeurs de variants et retourne le résultat
    • variant_and — Effectue un ET entre deux variants et retourne le résultat
    • variant_cast — Convertit un variant en un nouvel objet variant de type différent
    • variant_cat — Assemble deux valeurs variantes ensemble et retourne le résultat
    • variant_cmp — Compare deux variants
    • variant_date_from_timestamp — Retourne une représentation date en variant d'un timestamp Unix
    • variant_date_to_timestamp — Convertit une valeur date/temps variante en un timestamp Unix
    • variant_div — Retourne le résultat de la division de deux variants
    • variant_eqv — Effectue une équivalence de bits de deux variants
    • variant_fix — Récupère la portion entière d'un variant
    • variant_get_type — Retourne le type d'un objet variant
    • variant_idiv — Convertit des variants en valeurs entières, et effectue alors une division
    • variant_imp — Exécute une implication sur les bits de deux variants
    • variant_int — Retourne la partie entière d'un variant
    • variant_mod — Divise deux variantes et retourne le reste
    • variant_mul — Multiplie les valeurs de deux variants
    • variant_neg — Effectue une négation logique sur un variant
    • variant_not — Exécute une négation sur les bits sur un variant
    • variant_or — Performe une disjonction logique sur deux variants
    • variant_pow — Retourne le résultat de la fonction puissance avec deux variants
    • variant_round — Arrondit le variant au nombre spécifié de décimales
    • variant_set_type — Convertit un variant en un autre type "sur-place"
    • variant_set — Assigne une nouvelle valeur pour un objet variant
    • variant_sub — Soustrait la valeur du variant de droite de la valeur de celui de gauche
    • variant_xor — Exécute une exclusion logique sur deux 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);
?>


Introduction

COM est un acronyme pour Component Object Model; c'est une couche orientée objet (et services associés) au-dessus de DCE RPC (un standard libre) qui définit une convention de nommage commune permettant à un code écrit en n'importe quel langage de communiquer avec du code écrit dans un autre langage, pour peu que ces deux langages soient compatibles avec COM. Les codes n'ont pas besoin de faire partie du même exécutable. le code peut être chargé à partir d'une DLL, trouvé dans un autre processus fonctionnant sur le même serveur, ou, avec DCOM (Distributed COM), trouvé sur une machine distante, sans même que votre code ait à savoir où il se trouve.

Il y a une partie de COM connue sous le nom de OLE Automation qui comprend un jeu d'interfaces COM qui permettent de perdre l'attache aux objets COM, pour qu'ils puissent être découverts et appelés en cours d'exécution sans savoir au moment de la compilation comment l'objet fonctionne. L'extension COM de PHP utilise les interfaces OLE Automation pour vous permettre de créer et appeler des objets compatibles depuis vos scripts. Techniquement parlant, cela devrait vraiment s'appeler "the OLE Automation Extension for PHP", puisque tous les objets COM ne sont pas forcément compatibles OLE.

Maintenant, pourquoi voudriez-vous ou devriez-vous utiliser COM ? COM est l'une des méthodes les plus utilisées pour faire communiquer des applications et des composants sur les plates-formes Windows. En utilisant COM, vous pouvez ouvrir un document Microsoft Word, remplir un fichier de gabarit et le sauvegarder pour l'envoyer par courrier à votre visiteur. Vous pouvez aussi utiliser COM pour effectuer des tâches administratives sur votre réseau et configurer IIS ; ce ne sont que les utilisations les plus habituelles, vous pouvez faire beaucoup plus avec COM.

De plus, nous supportons l'instanciation et la création d'assemblées .Net utilisant une couche d'interopérabilité COM fournie par Microsoft.

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

Les fonctions COM ne sont disponibles que sous les versions Windows de PHP.

Le support .Net nécessite le gestionnaire .Net.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Cette extension requiert l'activation de php_com_dotnet.dll dans le fichier php.ini pour pouvoir utiliser ces fonctions.

Vous êtes responsable de l'installation des divers objets COM dont vous auriez besoin (comme Ms Word) ; nous ne pouvons tous les inclure dans PHP.

User Contributed Notes

There are no user contributed notes for this page.


Configuration à l'exécution

Le comportement de ces fonctions est affecté par la configuration dans le fichier php.ini.

Options de configuration pour COM
Nom | Défaut | Modifiable | Historique
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 | À partir de PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
Pour plus de détails sur les modes PHP_INI_*, reportez-vous à Où une directive de configuration peut être modifiée.

Voici un éclaircissement sur l'utilisation des directives de configuration.

com.allow_dcom

Si cette directive est activée, PHP aura la permission d'opérer comme un client D-COM (Distributed COM) et permettra à PHP d'instancier des objets COM sur un serveur distant.

com.autoregister_typelib

Si cette directive est activée, PHP essayera de déclarer des constantes provenant de la bibliothèque typelibrary des objets COM qu'il instancie, si ces objets implémentent l'interface demandée pour obtenir les données demandées. La sensibilité des constantes à la casse est contrôlée par la directive de configuration php.ini com.autoregister_casesensitive.

com.autoregister_verbose

Quand cette directive est activée, tout problème rencontré lors du chargement d'une typelibrary durant l'instanciation de l'objet sera reporté en utilisant le mécanisme d'erreurs de PHP. Par défaut, elle est désactivée, ce qui ne donne aucune indication sur l'échec de l'opération lors d'une recherche ou d'un chargement de la bibliothèque de type.

com.autoregister_casesensitive

Cette directive est activée par défaut et fait que les constantes trouvées dans les bibliothèques de types autochargé lors de l'instanciation d'objets COM seront enregistrées en mode sensible à la casse. Voyez com_load_typelib() pour plus de détails.

com.code_page

Cette directive permet de spécifier le code-page des jeux de caractères à utiliser lors de l'envoi et la réception de chaînes vers des objets COM. Si elle est vide, PHP pensera que vous voulez CP_ACP, qui est le code-page système ANSI par défaut.

Si le texte dans vos scripts est encodé avec un différent encodage ou jeu de caractères par défaut, configurer cette directive vous évitera d'avoir à passer tout votre code comme paramètre du constructeur de la classe com. Notez qu'en utilisant cette directive (comme toute configuration de PHP), votre code PHP perd en portabilité. Vous devez utiliser le paramètre du constructeur à chaque fois que possible.

com.dotnet_version

La version du framework .NET framework à utiliser pour les objets dotnet. La valeur de cette configuration correspond aux trois premiers numéros du numéro de la version du framework, séparé par des poins, et préxié par la lettre v, i.e. v4.0.30319.

com.typelib_file

Lorsqu'elle est configurée, cette directive doit être le chemin vers un fichier qui contient une liste de bibliothèques à charger au démarrage. Chaque ligne sera interprétée comme le nom de la bibliothèque de types et chargée comme si vous aviez utilisé com_load_typelib(). Les constantes seront enregistrées de façon persistante, pour que la bibliothèque ne soit chargée qu'une seule fois. Si le nom d'une bibliothèque de types se termine par #cis ou #case_insensitive, alors les constantes de cette bibliothèque de types seront enregistrées en mode insensible à la casse.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

Constantes COM
Constante | Valeur | Description | Notes
CLSCTX_INPROC_SERVER (int) | 1 | Le code qui crée et gère les objets de cette classe est une bibliothèque DLL qui est exécutée dans le même processus que l'appelant de la fonction, spécifiant ainsi le contexte de la classe. |
CLSCTX_INPROC_HANDLER (int) | 2 | Le code qui gère les objets de cette classe est un gestionnaire du processus. C'est une bibliothèque DLL qui s'exécute dans le processus client et implémente les structures côté client de cette classe lorsque l'on accède à ses instances à distance. |
CLSCTX_LOCAL_SERVER (int) | 4 | Le code d'exécution qui crée et gère les objets de cette classe s'exécute sur la même machine mais est chargé dans un espace séparé du processus. |
CLSCTX_REMOTE_SERVER (int) | 16 | Le contexte distant. Le code qui crée et gère les objets de cette classe s'exécute sur une machine différente. |
CLSCTX_SERVER (int) | 21 | Indique le code serveur, et si le processus est local ou distant. Correspond aux constantes CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER et CLSCTX_REMOTE_SERVER. |
CLSCTX_ALL (int) | 23 | Indique tous les contextes de la classe. Correspond aux constantes CLSCTX_INPROC_HANDLER et CLSCTX_SERVER. |
VT_NULL (int) | 1 | Référence de pointeur NULL. |
VT_EMPTY (int) | 0 | Une propriété, dont le type de l'indicateur est VT_EMPTY, n'a aucune donné accosiée ; aussi, la taille de la valeur est de zéro. |
VT_INT (int) | 22 | Valeur entière signée sur 4 octets (équivalent à VT_I4). |
VT_I1 (int) | 16 | Entier signé sur 1 octet. |
VT_I2 (int) | 2 | 2 octets représentant une valeur entière signée sur 2 octets. |
VT_I4 (int) | 3 | Entier signé sur 4 octets. |
VT_I8 (int) | 20 | Entier signé sur 8 octets. | Disponible à partir de PHP 7.0.0 (x64 uniquement).
VT_UINT (int) | 23 | Entier non signé sur 4 octets (équivalent à VT_UI4). |
VT_UI1 (int) | 17 | Entier non signé sur 1 octet. |
VT_UI2 (int) | 18 | Entier non signé sur 2 octets. |
VT_UI4 (int) | 19 | Entier non signé sur 4 octets. |
VT_UI8 (int) | 21 | Entier non signé sur 8 octets. | Disponible à partir de PHP 7.0.0 (x64 uniquement).
VT_R4 (int) | 4 | Valeur à virgule flottante IEEE sur 32 bits. |
VT_R8 (int) | 5 | Valeur à virgule flottante IEEE sur 64 bits. |
VT_BOOL (int) | 11 | Valeur booléenne. |
VT_ERROR (int) | 10 | Code erreur ; contient le code statut associé avec l'erreur. |
VT_CY (int) | 6 | Entier complémentaire de 8 octets (par tranche de 10.000). |
VT_DATE (int) | 7 | Nombre à virgule flottante de 64 bits, représentant le nombre de jours (et non de secondes) depuis le 01 Décembre 1899. Par exemple, January 1, 1900, vaut 2.0, January 2, 1900, vaut 3.0, et ainsi de suite). Stocké sous la même représentation que la constante VT_R8. |
VT_BSTR (int) | 8 | Pointeur vers une chaîne Unicode finissant par NULL. |
VT_DECIMAL (int) | 14 | Une structure décimale. |
VT_UNKNOWN (int) | 13 | Un pointeur vers un objet qui implémente l'interface IUnknown. |
VT_DISPATCH (int) | 9 | Un pointeur vers un objet a été spécifié. |
VT_VARIANT (int) | 12 | Un indicateur de type suivi par la valeur correspondante. VT_VARIANT peut être utilisé uniquement avec VT_BYREF. |
VT_ARRAY (int) | 8192 | Si l'indicateur de type est combiné avec VT_ARRAY via un opérateur OR, la valeur sera un pointeur vers un SAFEARRAY. VT_ARRAY peut utiliser l'opérateur OR avec les types de données suivantes : VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4, VT_INT, VT_UINT, VT_R4, VT_R8, VT_BOOL, VT_DECIMAL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DISPATCH, VT_UNKNOWN et VT_VARIANT. |
VT_BYREF (int) | 16384 | Si l'indicateur de type est combiné avec VT_BYREF via un opérateur OR, la valeur sera une référence. Les types de référence sont interprétés comme une référence vers les données, similaire au type de référence en C++. |
CP_ACP (int) | 0 | Le code page ANSI par défaut. |
CP_MACCP (int) | 2 | Le code page Macintosh. |
CP_OEMCP (int) | 1 | Le code page OEM par défaut. |
CP_UTF7 (int) | 65000 | Unicode (UTF-7). |
CP_UTF8 (int) | 65001 | Unicode (UTF-8). |
CP_SYMBOL (int) | 42 | Traduction des SYMBOL. |
CP_THREAD_ACP (int) | 3 | Le code page ANSI du thread courant. |
VARCMP_LT (int) | 0 | Le bstr de gauche est plus petit que le bstr de droite. |
VARCMP_EQ (int) | 1 | Les 2 paramètres sont égaux. |
VARCMP_GT (int) | 2 | Le bstr de gauche est plus grand que le bstr de droite. |
VARCMP_NULL (int) | 3 | Chaque expression vaut NULL. |
NORM_IGNORECASE (int) | 1 | Ignore la casse. |
NORM_IGNORENONSPACE (int) | 2 | Ignore les caractères non espacés. |
NORM_IGNORESYMBOLS (int) | 4 | Ignore les symboles. |
NORM_IGNOREWIDTH (int) | 131072 | Ignore la taille des caractères. |
NORM_IGNOREKANATYPE (int) | 65536 | Ignore le type Kana. |
NORM_IGNOREKASHIDA (int) | 262144 | Ignore les caractères Arabe kashida. | La disponibilité dépend de la bibliothèque sous-jacente.
DISP_E_DIVBYZERO (int) | -2147352558 | Une erreur retournée qui indique qu'une division par zéro a eu lieu. | À partir de PHP 7.0.0, la valeur est 2147614738 sur x64.
DISP_E_OVERFLOW (int) | -2147352566 | Une erreur qui indique qu'une valeur n'a pû être convertie en la représentation attendue. | À partir de PHP 7.0.0, la valeur est 2147614730 de sur x64
DISP_E_BADINDEX (int) | -2147352565 | Une erreur qui indique qu'un index de tableau n'existe pas. | À partir de PHP 7.0.0, la valeur est 2147614731 sur x64.
MK_E_UNAVAILABLE (int) | -2147221021 | Code statut iMoniker COM, retourné lors d'erreurs générées lorsque l'on a tenté d'appeler une fonction qui n'est pas disponible. | À partir de PHP 7.0.0, la valeur est 2147746275 sur x64.

User Contributed Notes

There are no user contributed notes for this page.


Erreur et gestion des erreurs

Cette extension lancera des instances de la classe com_exception pour toute erreur fatale reportée par COM. Toutes les exceptions COM ont une propriété code qui correspond à la valeur de retour HRESULT des diverses opérations COM. Vous pouvez utiliser ce code pour choisir de façon automatique comment gérer cette exception.

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Sommaire

  • For Each
  • Tableaux et propriétés à la façon des tableaux de COM

User Contributed Notes

There are no user contributed notes for this page.


For Each

Vous pouvez utiliser la structure de contrôle foreach de PHP pour passer en boucle à travers le contenu d'un IEnumVariant COM/OLE standard. Cela signifie que vous pouvez utiliser foreach aux endroits où vous auriez pu utiliser For Each dans du code VB/ASP.

Exemple #1 For Each en ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Exemple #2 Foreach en 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.


Tableaux et propriétés à la façon des tableaux de COM

Plusieurs objets COM exposent leurs propriétés comme tableaux, ou en utilisant un chemin d'accès à la façon des tableaux.

Vous pouvez :

  • Accédez aux tableaux multidimensionnels ou aux propriétés COM qui requièrent plusieurs paramètres comme si vous accédiez à un tableau. Vous pouvez aussi écrire ces propriétés en utilisant cette technique.

  • Bouclez sur les SafeArrays ("vrais" tableaux) en utilisant la structure de contrôle foreach. Cela fonctionne car un SafeArrays comporte des informations à propos de sa taille. Si une propriété à la façon des tableaux implémente IEnumVariant, alors vous pouvez aussi utiliser foreach pour cette propriété ; lisez For Each pour plus d'informations à ce sujet.

User Contributed Notes

There are no user contributed notes for this page.


La classe com

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

Introduction

La classe m vous permet d'instancier un objet COM compatible OLE et d'appeler ses méthodes et d'accéder à ses propriétés.

Synopsis de la classe

class com extends variant {
/* Méthodes */
public __construct(
string $module_name,
array|string|null $server_name = null,
int $codepage = CP_ACP,
string $typelib = ""
)
}

Méthodes surchargées

L'objet retourné est un objet surchargé, ce qui signifie que PHP ne voit aucune méthode fixe comme il le fait avec les classes habituelles ; au lieu de cela, chaque accès à une propriété ou une méthode est effectué à travers 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. PHP détectera automatiquement les méthodes qui acceptent les paramètres par référence, et convertira automatiquement les variables PHP classiques en une forme pouvant être passée par référence. Cela signifie que vous pouvez appeler les méthodes de façon naturelle ; vous n'avez pas d'efforts supplémentaires à faire dans votre code.

Exemples com

Exemple #1 Exemple com (1)

<?php
// démarrer Word
$word = new com("word.application") or die("Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}\n";

// l'ammener devant
$word->Visible = 1;

// ouvrir un document vide
$word->Documents->Add();

// faire des choses
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

// fermer Word
$word->Quit();

// libérer l'objet
$word = null;
?>

Exemple #2 Exemple com (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++; // incrémente rowcount
$rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs = null;
$conn = null;

?>

Sommaire

  • com::__construct — Constructeur de la classe com

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


Constructeur de la classe com

  • « com
  • dotnet »
  • PHP Manual
  • com
  • Constructeur de la classe com

com::__construct

(PHP 4 > 4.1.0, PHP 5, PHP 7, PHP 8)

com::__construct — Constructeur de la classe com

Description

public com::__construct(
string $module_name,
array|string|null $server_name = null,
int $codepage = CP_ACP,
string $typelib = ""
)

Construit un nouvel objet com.

Liste de paramètres

module_name
Peut être un ProgID, Class ID ou Moniker qui nomme le composant à charger. Un ProgID est typiquement le nom de l'application ou du DDL, suivit d'un point, suivit du nom de l'objet. Par exemple : Word.Application. Un Class ID est l'UUID qui identifie uniquement une classe donnée. Un Moniker est une forme spécial de nommage, similaire en concept à un schéma URL, qui identifie une ressource et spécifie comment il devrait être chargé? Pour un exemple, vous pouvez démarrer Word et récupérer un objet représentant un document word en spécifiant le chemin complet du document word en tant que nom de module, ou vous pouvez utiliser LDAP: en tant que Moniker pour utiliser l'interface ADSI à LDAP.
server_name
Le nom du server DCOM sur lequel le composant devrait être chargé et exécuté. Si null, l'objet est exécuté en utilisant le défaut pour l'application. La valeur par défaut est typiquement d'exécuter sur la machine locale, cependant l'administrateur peut avoir configuré l'application d'être lancé sur une machine différente. Si une valeur non-null est spécifiée pour le serveur, PHP refusera de charger l'objet à moins que l'option com.allow_dcom php.ini option soit définie à true.

Si server_name est un tableau, il devrait contenir les éléments suivant (sensible à la case!). À noter qu'ils sont tous optionnel (cependant vous devez définir l'Utilisateur et le Mot de Passe ensemble) ; si vous ommetez le paramètre Server, le serveur par défaut sera utilisé (comme dit ci-dessus), et l'instantiation de l'objet ne sera pas affecté par la php.ini directive com.allow_dcom.

Nom de serveur DCOM
Clé | Type | Description
Server | chaîne de caractères | Le nom du serveur
Username | chaîne de caractères | Le nom d'utilisateur pour se connecter en tant que.
Password | chaîne de caractères | Le mot de passe pour Username.
Domain | chaîne de caractères | Le domaine du serveur.
Drapeaux | entier | Une ou plusieur des constantes suivantes, assemblé ensemble grâce au OU logique : CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER et CLSCTX_ALL. La valeur par défaut si non définie ici est CLSCTX_SERVER si vous ommetez aussi Server, ou CLSCTX_REMOTE_SERVER si vous définissez un serveur. Vous devriez consultez la documentation de Microsoft pour CoCreateInstance pour plus d'information sur la signification de ces constantes ; vous devrez typiquement jamais les utiliser.

codepage
Défini la codepage qui est utilisé pour convertir les chaîne de caractères en chaîne de caractères unicode et vice versa. La conversion est appliqué quand une chaîne de caractères PHP est passé en tant que paramètre ou retourné depuis une méthode de cet objet COM. La code page est "collante", ce qui signifie que ça sera propagé aux objets et variants retourné depuis l'objet. Les valeurs possibles sont : CP_ACP (utilise la code page ANSI système par défaut - par défaut si ce paramètre est omit), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (utilise codepage/locale définie pour le thread en cours d'exécution ), CP_UTF7 et CP_UTF8. Vous pouvez aussi utiliser le numéro pour une codepage donnée ; consultez la documentation de Microsoft pour plus de détails sur les codepages et leurs valeurs numériques.

User Contributed Notes

There are no user contributed notes for this page.


La classe dotnet

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

Introduction

La classe dotnet vous autorise à instancier une classe depuis un ensemble .NET et d'appeler et accéder à ses propriétés, si la classe et les méthodes et les propriétés sont » visible pour COM.

Ni l'instantiation de classes static ni l'appel de méthodes statique est supporté. L'instanciation de classes génériques telles que System.Collections.Generic.List n'est pas non plus prise en charge.

Quelque classes .Net n'implémente pas IDispatch, donc bien qu'elles peuvent être instancié, appeller des méthodes ou accéder aux propriétés sur ces classes n'est pas supporté.

Note:

Vous devez installer le moteur d'exécution .Net sur votre serveur web pour tirer avantage de cette fonctionnalité.

Note:

Antérieur à PHP 8.0.0, le framework .Net 4.0 et ultérieurs ne sont pas supporté par la classe dotnet. Si des assemblages ont été régistré avec regasm.exe, les classes peuvent être instanciées en tant qu'objets com, cependant. À partir de PHP 8.0.0, le framework .Net 4.0 et les versions ultérieures sont supportés via la directive php.ini com.dotnet_version.

Synopsis de la classe

class dotnet extends variant {
/* Méthodes */
public __construct(string $assembly_name, string $datatype_name, int $codepage = CP_ACP)
}

Méthodes surchargées

L'objet retourné est un objet surchargé, ceci signifie que PHP ne voit pas les méthodes fixé comme il le fait avec les classes normales ; à la place tout accès de propriété ou méthode sont passés à travers COM et à partir de là à DOTNET. Dans d'autres mots, l'objet .Net est mappé via la couche d'interopérabilité COM fournie par le moteur d'exécution .Net.

Une fois que vous avez crée un objet dotnet, PHP le traite de façon identique à n'importe quel autre objet COM ; les mêmes règles s'appliquent.

Exemples dotnet

Exemple #1 Exemple dotnet

<?php
$stack = new dotnet("mscorlib", "System.Collections.Stack");
$stack->Push(".Net");
$stack->Push("Hello ");
echo $stack->Pop() . $stack->Pop();
?>

Sommaire

  • dotnet::__construct — Constructeur de la classe dotnet

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.


Constructeur de la classe dotnet

  • « dotnet
  • variant »
  • PHP Manual
  • dotnet
  • Constructeur de la classe dotnet

dotnet::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

dotnet::__construct — Constructeur de la classe dotnet

Description

public dotnet::__construct(string $assembly_name, string $datatype_name, int $codepage = CP_ACP)

Construit un nouvel objet dotnet.

Liste de paramètres

assembly_name
Spécifie l'assemblage qui doit être chargé.
datatype_name
Spécifie la classe dans cet assemblage à instancier.
codepage
Codepage à utiliser pour les transformations de chaîne de caractères unicode ; voir la classe com pour plus de détails sur les codepages.

User Contributed Notes

There are no user contributed notes for this page.


La classe variant

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

Introduction

Le VARIANT est l'équivalent COM de zval pour PHP ; c'est une structure qui peut contenir une valeur avec un intervalle de différent types possibles. La classe variant fournie par l'extension COM vous permet d'avoir plus de contrôle sur ce que PHP envoie et reçoit de COM.

Synopsis de la classe

class variant {
/* Méthodes */
public __construct(mixed $value = null, int $type = VT_EMPTY, int $codepage = CP_ACP)
}

Exemples variant

Exemple #1 Exemple variant

<?php
$v = new variant(42);
print "The type is " . variant_get_type($v) . "<br/>";
print "The value is " . $v . "<br/>";
?>

Note:

Lors du retour d'une valeur ou récupérer une propriété variant, le variant est converti en une valeur PHP seulement quand il y a une correspondance directe entre les types qui ne produiraient pas une perte d'information. Dans tous les autres cas, la valeur est retourné en tant qu'une instance de la classe variant. Vous pouvez forcer PHP de convertir ou évaluer le variant en tant que type PHP natif en utilisant les opérateurs de transtypage explicitement, ou implicitement vers une chaîne de caractères en l'affichant grâce à print. Vous pouvez utiliser la grande variété de fonctions variant pour effectuer des opérations arithmétrique sans forcer une conversion et risquer une perte de données.

Voir aussi variant_get_type().

Sommaire

  • variant::__construct — Constructeur de la classe variant

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.


Constructeur de la classe variant

  • « variant
  • COMPersistHelper »
  • PHP Manual
  • variant
  • Constructeur de la classe variant

variant::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

variant::__construct — Constructeur de la classe variant

Description

public variant::__construct(mixed $value = null, int $type = VT_EMPTY, int $codepage = CP_ACP)

Construit un nouvel objet variant.

Liste de paramètres

value
Valeur initiale. Si omit, ou défini à null un objet VT_EMPTY vide est crée.
type
Spécifie le type de contenue de l'objet variant. Les valeurs possibles sont l'une des constantes VT_XXX Constantes pré-définies. PHP peut détecter les paramètres passé par référence automatiquement ; Ils n'ont pas besoin d'être passé an tant qu'objets variant. Consultez la bibliothèque MSDN pour des informations additionnelles sur le type VARIANT.
codepage
Spécifie la codepage qui est utilisé pour convertir les chaîne de caractères vers unicode. Voir le paramètre avec le même nom dans la classe com pour plus d'informations.

User Contributed Notes

There are no user contributed notes for this page.


The COMPersistHelper class

(PHP 5, PHP 7, PHP 8)

Introduction

COMPersistHelper improves the interoperability of COM and PHP with regard to the php.ini directive open_basedir, and stream ressources.

Synopsis de la classe

final class COMPersistHelper {
/* Méthodes */
public __construct(?variant $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 $filename, bool $remember = true): bool
public SaveToStream(resource $stream): bool
}

Sommaire

  • 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

Description

public COMPersistHelper::__construct(?variant $variant = null)

Constructs a persistence helper object, usually associated with a variant.

Liste de paramètres

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

Description

public COMPersistHelper::GetCurFileName(): string|false

Retrieves the current name of the file associated with the object.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Returns the current name of the file associated with the object.

Erreurs / Exceptions

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

Description

public COMPersistHelper::GetMaxStreamSize(): int

Retrieves the size of the stream (in bytes) needed to save the object.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Returns the size of the stream (in bytes) needed to save the object.

Erreurs / Exceptions

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

Description

public COMPersistHelper::InitNew(): bool

Initializes an object to a default state.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

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

Description

public COMPersistHelper::LoadFromFile(string $filename, int $flags = 0): bool

Opens the specified file and initializes an object from the file contents.

Liste de paramètres

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.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

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

Description

public COMPersistHelper::LoadFromStream(resource $stream): bool

Initializes an object from the stream where it was saved previously.

Liste de paramètres

stream
The stream ressource from which to load the object.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

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

Description

public COMPersistHelper::SaveToFile(?string $filename, bool $remember = true): bool

Saves a copy of the object to the specified file.

Liste de paramètres

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.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Save() method failed.

Exemples

Exemple #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

Description

public COMPersistHelper::SaveToStream(resource $stream): bool

Saves an object to the specified stream.

Liste de paramètres

stream
The stream ressource to which to save the object.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

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.


La classe The com_exception

(PHP 5, PHP 7, PHP 8)

Introduction

Synopsis de la classe

final class com_exception extends Exception {
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes héritées */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Fonctions COM et .Net (Windows)

Voir aussi

Pour plus d'informations sur les objets COM, lisez les » spécifications COM. Vous pouvez trouver des informations utiles dans notre FAQ pour PHP et COM. Si vous voulez utiliser des applications MS Office sur le serveur, vous devez lire les informations ici : » Considerations for Server-Side Automation of Office.

Sommaire

  • com_create_guid — Génère un identifiant unique global (GUID)
  • com_event_sink — Connecte des événements d'un objet COM sur un objet PHP
  • com_get_active_object — Retourne un objet représentant l'instance actuelle d'un objet COM
  • com_load_typelib — Charge un Typelib
  • com_message_pump — Traite un message COM dans un délai donné
  • com_print_typeinfo — Affiche une définition de classe PHP pour une interface répartissable
  • variant_abs — Retourne la valeur absolue d'un variant
  • variant_add — "Ajoute" deux valeurs de variants et retourne le résultat
  • variant_and — Effectue un ET entre deux variants et retourne le résultat
  • variant_cast — Convertit un variant en un nouvel objet variant de type différent
  • variant_cat — Assemble deux valeurs variantes ensemble et retourne le résultat
  • variant_cmp — Compare deux variants
  • variant_date_from_timestamp — Retourne une représentation date en variant d'un timestamp Unix
  • variant_date_to_timestamp — Convertit une valeur date/temps variante en un timestamp Unix
  • variant_div — Retourne le résultat de la division de deux variants
  • variant_eqv — Effectue une équivalence de bits de deux variants
  • variant_fix — Récupère la portion entière d'un variant
  • variant_get_type — Retourne le type d'un objet variant
  • variant_idiv — Convertit des variants en valeurs entières, et effectue alors une division
  • variant_imp — Exécute une implication sur les bits de deux variants
  • variant_int — Retourne la partie entière d'un variant
  • variant_mod — Divise deux variantes et retourne le reste
  • variant_mul — Multiplie les valeurs de deux variants
  • variant_neg — Effectue une négation logique sur un variant
  • variant_not — Exécute une négation sur les bits sur un variant
  • variant_or — Performe une disjonction logique sur deux variants
  • variant_pow — Retourne le résultat de la fonction puissance avec deux variants
  • variant_round — Arrondit le variant au nombre spécifié de décimales
  • variant_set_type — Convertit un variant en un autre type "sur-place"
  • variant_set — Assigne une nouvelle valeur pour un objet variant
  • variant_sub — Soustrait la valeur du variant de droite de la valeur de celui de gauche
  • variant_xor — Exécute une exclusion logique sur deux 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


Génère un identifiant unique global (GUID)

  • « Fonctions COM et .Net (Windows)
  • com_event_sink »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Génère un identifiant unique global (GUID)

com_create_guid

(PHP 5, PHP 7, PHP 8)

com_create_guid — Génère un identifiant unique global (GUID)

Description

com_create_guid(): string|false

Génère un identifiant unique global (GUID).

Un GUID est généré de la même façon que DCE UUID, excepté le fait que la convention Microsoft inclut le GUID dans une parenthèse.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le GUID, sous la forme d'une chaîne de caractères, ou false si une erreur survient.

Voir aussi

  • uuid_create() dans l'extension PECL uuid

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.


Connecte des événements d'un objet COM sur un objet PHP

  • « com_create_guid
  • com_get_active_object »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Connecte des événements d'un objet COM sur un objet PHP

com_event_sink

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_event_sink — Connecte des événements d'un objet COM sur un objet PHP

Description

com_event_sink(variant $variant, object $sink_object, array|string|null $sink_interface = null): bool

Connecte des événements de l'objet COM variant sur un l'objet PHP sink_object.

Soyez prudent sur l'utilisation de cette fonctionnalité ; si vous faites quelque chose de similaire à l'exemple ci-dessous, cela n'a pas de sens de le lancer sur un serveur Web.

Liste de paramètres

variant

sink_object

sink_object devra être une instance de la classe avec des noms de méthodes suivant le dispinterface désiré ; vous devriez utiliser com_print_typeinfo() pour l'aide à la génération d'un gabarit de classe pour cela.

sink_interface

PHP devrait être capable d'utiliser le type par défaut de dispinterface spécifié par la Typelib associée avec l'objet variant, mais vous pouvez changer cela en spécifiant dans le paramètre sink_interface le dispinterface que vous souhaitez utiliser.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | sink_interface is nullable now.

Exemples

Exemple #1 Exemple de connexions d'événements COM

<?php
class IEEventSinker {
var $terminated = false;

function ProgressChange($progress, $progressmax) {
echo "Progression du téléchargement : $progress / $progressmax\n";
}

function DocumentComplete(&$dom, $url) {
echo "Document $url terminé\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;
?>

Notes

Attention

Antérieur à PHP 8.0.0, Prior to PHP 8.0.0, appeller exit() depuis n'importe quel gestionnaire d'événement n'est pas supporté, et peut causer PHP à planter. Ceci peut être contourné en lançant une exception depuis un gestionnaire d'événement, attrapant l'exception dans le code principal, et appeller exit() là.

Voir aussi

  • com_print_typeinfo() - Affiche une définition de classe PHP pour une interface répartissable
  • com_message_pump() - Traite un message COM dans un délai donné

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");
//...


Retourne un objet représentant l'instance actuelle d'un objet COM

  • « com_event_sink
  • com_load_typelib »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Retourne un objet représentant l'instance actuelle d'un objet COM

com_get_active_object

(PHP 5, PHP 7, PHP 8)

com_get_active_object — Retourne un objet représentant l'instance actuelle d'un objet COM

Description

com_get_active_object(string $prog_id, ?int $codepage = null): variant

com_get_active_object() est similaire à la création d'une nouvelle instance comd'un objet COM, excepté qu'elle ne retournera un objet à votre script uniquement si l'objet est actuellement instancié. Les applications OLE utilisent quelque chose de connu en tant que "Running Object Table" qui permet aux applications connues d'être exécutées juste une fois ; cette fonction expose la fonction GetActiveObject() de la bibliothèque COM pour récupérer un objet d'une instance en cours d'utilisation.

Liste de paramètres

prog_id

Le paramètre prog_id doit être soit le ProgID, soit le CLSID de l'objet dont vous voulez avoir l'accès (par exemple, Word.Application).

codepage

utilise les mêmes règles que dans la com classe.

Valeurs de retour

Si l'objet demandé est en cours d'exécution, la fonction retournera à votre script ce que toute autre objet COM retournerait.

Erreurs / Exceptions

Il y a beaucoup de raisons pour lesquelles cette fonction peut échouer. Dans cette situation, le code erreur de l'exception devrait être MK_E_UNAVAILABLE ; vous pouvez utiliser la méthode getCode de l'objet exception pour vérifier le code de l'exception.

Historique

Version | Description
8.0.0 | codepage est désormais nullable.

Notes

Avertissement

Utiliser la fonction com_get_active_object() sur un serveur web n'est pas toujours la meilleure idée. La plupart des applications COM/OLE ne sont pas faites pour gérer plus d'un client en concurrence, comme (et surtout !!) Microsoft Office. Vous devriez lire les » considérations pour les automatismes coté serveur pour Office pour plus d'informations sur les comportements généraux.

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.


Charge un Typelib

  • « com_get_active_object
  • com_message_pump »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Charge un Typelib

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

com_load_typelib — Charge un Typelib

Description

com_load_typelib(string $typelib, bool $case_insensitive = true): bool

Charge un Typelib et enregistre son contenu dans le moteur, comme s'ils avaient été définis en utilisant define().

Notez qu'il est plus efficace d'utiliser com.typelib-file php.ini l'option de configuration pour précharger et enregistrer les constantes, même si cela est moins flexible.

Si com.autoregister-typelib est activé, alors PHP essayera d'enregistrer automatiquement les constantes associées à l'objet COM lorsque vous créerez l'objet. Cela dépendra de l'interface fournie par l'objet COM lui-même et ne sera pas toujours possible.

Liste de paramètres

typelib

typelib peut être une des valeurs suivantes :

  • Le nom d'un fichier .tlb ou le module exécutable contenant le Typelib.

  • Le GUID du Typelib, suivi du numéro de version ; par exemple {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • Le nom du Typelib, e.g Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP va essayer de résoudre le Typelib dans cet ordre, et le processus prendra de plus en plus de ressources pour arriver à la fin de la liste ; la recherche du Typelib par son nom est manipulée physiquement en énumérant le registre jusqu'à ce qu'un résultat y soit trouvé.

case_insensitive

Le paramètre case_insensitive se comporte à l'inverse du paramètre $case_insensitive de la fonction define().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

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.


Traite un message COM dans un délai donné

  • « com_load_typelib
  • com_print_typeinfo »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Traite un message COM dans un délai donné

com_message_pump

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_message_pump — Traite un message COM dans un délai donné

Description

com_message_pump(int $timeout_milliseconds = 0): bool

Traite un message COM en attendant jusqu'à timeout_milliseconds millisecondes, ou bien en attendant qu'un message arrive dans la file d'attente.

Le but de cette fonction est d'acheminer les appels COM entre les éléments et de gérer les différentes synchronisations. Cela permet à votre script d'attendre efficacement les événements à déclencher, tout en gérant d'autres événements ou bien d'exécuter d'autres scripts en arrière-plan. Vous devriez l'utiliser dan une boucle, comme dans l'exemple de la fonction com_event_sink(), jusqu'à ce que vous ayez fini d'utiliser les objets COM liés à des événements.

Liste de paramètres

timeout_milliseconds

Le délai, en millisecondes.

Si vous ne spécifiez pas de valeur pour le paramètre timeout_milliseconds, alors il voudra 0. Une valeur à 0 signifie que les messages seront traités immédiatement ; s'il y a des messages dans la file d'attente, ils seront distribués aussitôt ; s'il n'y a aucun message dans la file d'attente, la fonction retournera false immédiatement sans attendre.

Valeurs de retour

Si un ou plusieurs messages arrivent avant le délai d'expiration, ils seront distribués et la fonction retournera true. Si le délai d'expiration survient et qu'aucun message n'est traité, la valeur retournée sera false.

User Contributed Notes

There are no user contributed notes for this page.


Affiche une définition de classe PHP pour une interface répartissable

  • « com_message_pump
  • variant_abs »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Affiche une définition de classe PHP pour une interface répartissable

com_print_typeinfo

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_print_typeinfo — Affiche une définition de classe PHP pour une interface répartissable

Description

com_print_typeinfo(variant|string $variant, ?string $dispatch_interface = null, bool $display_sink = false): bool

Aide à générer un squelette de classe pour l'utiliser comme évier d'événement. Vous pouvez également l'utiliser pour générer une sauvegarde de n'importe quel objet COM, à condition qu'il supporte assez d'interfaces d'introspection et que vous connaissiez le nom de l'interface que vous désirez afficher.

Liste de paramètres

variant

variant doit être soit une instance d'un objet COM, soit le nom d'une bibliothèque type (qui doit être résolu en accord des règles définies dans la fonction com_load_typelib()).

dispatch_interface

Le nom d'une interface descendante IDispatch que vous souhaitez afficher.

display_sink

Si le paramètre wantsink vaut true, l'interface d'évier correspondante sera affichée à la place.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • com_event_sink() - Connecte des événements d'un objet COM sur un objet PHP
  • com_load_typelib() - Charge un 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


Retourne la valeur absolue d'un variant

  • « com_print_typeinfo
  • variant_add »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Retourne la valeur absolue d'un variant

variant_abs

(PHP 5, PHP 7, PHP 8)

variant_abs — Retourne la valeur absolue d'un variant

Description

variant_abs(mixed $value): variant

Retourne la valeur absolue d'un variant.

Liste de paramètres

value

Le variant.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne la valeur absolue de value.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • abs() - Valeur absolue

User Contributed Notes

There are no user contributed notes for this page.


"Ajoute" deux valeurs de variants et retourne le résultat

  • « variant_abs
  • variant_and »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • "Ajoute" deux valeurs de variants et retourne le résultat

variant_add

(PHP 5, PHP 7, PHP 8)

variant_add — "Ajoute" deux valeurs de variants et retourne le résultat

Description

variant_add(mixed $left, mixed $right): variant

Ajoute left à right selon les règles suivantes (prises de la bibliothèque MSDN), qui correspondent à celles de Visual Basic :

Règle d'ajout des variants
Si | Alors
Les deux expressions sont des chaînes | Concaténation
Une expression est de type chaîne et l'autre est un caractère | Addition
Une expression est numérique est l'autre est une chaîne | Addition
Les deux expressions sont numériques | Addition
Une expression est NULL | NULL est retourné
Les deux expressions sont vides | Le sous-type entier est retourné

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne le résultat.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_sub() - Soustrait la valeur du variant de droite de la valeur de celui de gauche

User Contributed Notes

There are no user contributed notes for this page.


Effectue un ET entre deux variants et retourne le résultat

  • « variant_add
  • variant_cast »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Effectue un ET entre deux variants et retourne le résultat

variant_and

(PHP 5, PHP 7, PHP 8)

variant_and — Effectue un ET entre deux variants et retourne le résultat

Description

variant_and(mixed $left, mixed $right): variant

Effectue un ET sur les bits, selon la table de vérité suivante ; notez que cela est différent du ET normal.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Règles du ET variant
Si left est | Si right est | alors le résultat est
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

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_or() - Performe une disjonction logique sur deux variants

User Contributed Notes

There are no user contributed notes for this page.


Convertit un variant en un nouvel objet variant de type différent

  • « variant_and
  • variant_cat »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Convertit un variant en un nouvel objet variant de type différent

variant_cast

(PHP 5, PHP 7, PHP 8)

variant_cast — Convertit un variant en un nouvel objet variant de type différent

Description

variant_cast(variant $variant, int $type): variant

Cette fonction crée une copie de variant et effectue alors un transtypage pour forcer la copie à avoir le type donné par type.

Cette fonction est en fait la fonction VariantChangeType() de la bibliothèque COM ; consultez MSDN pour plus d'informations.

Liste de paramètres

variant

Le variant.

type

type doit être un type parmi les constantes VT_XXX.

Valeurs de retour

Retourne un variant du type fourni.

Voir aussi

  • variant_set_type() - Convertit un variant en un autre type "sur-place"

User Contributed Notes

There are no user contributed notes for this page.


Assemble deux valeurs variantes ensemble et retourne le résultat

  • « variant_cast
  • variant_cmp »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Assemble deux valeurs variantes ensemble et retourne le résultat

variant_cat

(PHP 5, PHP 7, PHP 8)

variant_cat — Assemble deux valeurs variantes ensemble et retourne le résultat

Description

variant_cat(mixed $left, mixed $right): variant

Assemble left avec right et retourne le résultat.

Cette fonction est équivalente à $left . $right.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne le résultat de la concaténation.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • Opérateurs de chaînes de caractères pour l'opérateur de concaténation

User Contributed Notes

There are no user contributed notes for this page.


Compare deux variants

  • « variant_cat
  • variant_date_from_timestamp »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Compare deux variants

variant_cmp

(PHP 5, PHP 7, PHP 8)

variant_cmp — Compare deux variants

Description

variant_cmp(
mixed $left,
mixed $right,
int $locale_id = LOCALE_SYSTEM_DEFAULT,
int $flags = 0
): int

Compare left avec right.

Cette fonction ne comparera que des valeurs scalaires, pas de tableaux ni d'enregistrements variants.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

locale_id

Locale Identifier valide à utiliser lors des comparaisons des chaînes (cela affecte la collation de la chaîne).

flags

flags peut être une ou plusieurs des valeurs suivantes, jointes avec des OR, et affecte les comparaisons de chaînes :

Options de comparaison Variant
Valeur | Signification
NORM_IGNORECASE | Compare avec sensibilité à la casse
NORM_IGNORENONSPACE | Ignore les caractères non-espaçants
NORM_IGNORESYMBOLS | Ignore les symboles
NORM_IGNOREWIDTH | Ignore la taille de la chaîne
NORM_IGNOREKANATYPE | Ignore le type Kana
NORM_IGNOREKASHIDA | Ignore les caractères arabes kashida

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne une des valeurs suivantes :

Résultats des comparaisons sur variants
Valeur | Signification
VARCMP_LT | left est plus petit que right
VARCMP_EQ | left est égal à right
VARCMP_GT | left est plus grand que right
VARCMP_NULL | left, right ou les deux sont null

User Contributed Notes

There are no user contributed notes for this page.


Retourne une représentation date en variant d'un timestamp Unix

  • « variant_cmp
  • variant_date_to_timestamp »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Retourne une représentation date en variant d'un timestamp Unix

variant_date_from_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_from_timestamp — Retourne une représentation date en variant d'un timestamp Unix

Description

variant_date_from_timestamp(int $timestamp): variant

Convertit timestamp depuis un timestamp Unix vers le type variant VT_DATE. Cela permet une interopérabilité plus facile des systèmes Unix de PHP et COM.

Liste de paramètres

timestamp

Un timestamp Unix.

Valeurs de retour

Retourne un variant VT_DATE.

Voir aussi

  • variant_date_to_timestamp() - Convertit une valeur date/temps variante en un timestamp Unix
  • mktime() - Retourne l'horodatage UNIX d'une date
  • time() - Retourne l'horodatage UNIX actuel

User Contributed Notes

There are no user contributed notes for this page.


Convertit une valeur date/temps variante en un timestamp Unix

  • « variant_date_from_timestamp
  • variant_div »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Convertit une valeur date/temps variante en un timestamp Unix

variant_date_to_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_to_timestamp — Convertit une valeur date/temps variante en un timestamp Unix

Description

variant_date_to_timestamp(variant $variant): ?int

Convertit variant d'une valeur VT_DATE (ou similaire) en un timestamp unix. Cela permet l'interopérabilité facile entre les parties Unix de PHP et COM.

Liste de paramètres

variant

Le variant.

Valeurs de retour

Retourne un timestamp Unix, ou null en cas d'échec.

Voir aussi

  • variant_date_from_timestamp() - Retourne une représentation date en variant d'un timestamp Unix
  • date() - Formate un horodatage Unix
  • strftime() - Formate une date/heure locale avec la configuration locale

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


Retourne le résultat de la division de deux variants

  • « variant_date_to_timestamp
  • variant_eqv »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Retourne le résultat de la division de deux variants

variant_div

(PHP 5, PHP 7, PHP 8)

variant_div — Retourne le résultat de la division de deux variants

Description

variant_div(mixed $left, mixed $right): variant

Divise left par right et retourne le résultat.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Règle de division des variants
Si | Alors
Les deux expressions sont des chaînes, dates, caractères, booléens | Double est retourné
Une expression est une chaîne et l'autre est un caractère | Division et double retournés
Une expression est numérique et l'autre est une chaîne | Division et double retournés
Les deux expressions sont numériques | Division et double retournés
Une des expressions est NULL | NULL est retourné
right est vide et left est tout mais non vide | Une com_exception avec code DISP_E_DIVBYZERO est lancée
left est vide et right est tout mais non vide. | 0 en tant que double est retourné
Les deux expressions sont vides | Une com_exception avec code DISP_E_OVERFLOW est lancée

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_idiv() - Convertit des variants en valeurs entières, et effectue alors une division

User Contributed Notes

There are no user contributed notes for this page.


Effectue une équivalence de bits de deux variants

  • « variant_div
  • variant_fix »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Effectue une équivalence de bits de deux variants

variant_eqv

(PHP 5, PHP 7, PHP 8)

variant_eqv — Effectue une équivalence de bits de deux variants

Description

variant_eqv(mixed $left, mixed $right): variant

Effectue une équivalence de bits de deux variants.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Si chaque bit dans left est égal au bit correspondant dans right alors la fonction retourne true, sinon elle retourne false.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

User Contributed Notes

There are no user contributed notes for this page.


Récupère la portion entière d'un variant

  • « variant_eqv
  • variant_get_type »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Récupère la portion entière d'un variant

variant_fix

(PHP 5, PHP 7, PHP 8)

variant_fix — Récupère la portion entière d'un variant

Description

variant_fix(mixed $value): variant

Récupère la portion entière d'un variant.

Liste de paramètres

value

Le variant.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Si value est négatif, le premier entier négatif plus grand ou égal au variant est retourné, sinon cette fonction retourne la portion entière de la valeur de value.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Notes

Avertissement

Cette documentation est basée sur la documentation MSDN ; il apparaît que cette fonction est la même que variant_int(), ou alors, il y a une erreur dans la documentation de MSDN.

Voir aussi

  • variant_int() - Retourne la partie entière d'un variant
  • variant_round() - Arrondit le variant au nombre spécifié de décimales
  • floor() - Arrondit à l'entier inférieur
  • ceil() - Arrondit au nombre supérieur
  • round() - Arrondit un nombre à virgule flottante

User Contributed Notes

There are no user contributed notes for this page.


Retourne le type d'un objet variant

  • « variant_fix
  • variant_idiv »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Retourne le type d'un objet variant

variant_get_type

(PHP 5, PHP 7, PHP 8)

variant_get_type — Retourne le type d'un objet variant

Description

variant_get_type(variant $variant): int

Retourne le type d'un objet variant.

Liste de paramètres

variant

L'objet variant.

Valeurs de retour

Retourne une valeur entière qui indique le type de variant, qui peut être une instance de com, dotnet ou de variant. La valeur de retour peut être comparée à l'une des constantes VT_XXX.

La valeur de retour pour les objets COM et DOTNET sera la plupart du temps VT_DISPATCH ; la seule raison qui fait que cette fonction marche avec ces classes est que COM et DOTNET sont des descendants de VARIANT.

Voir aussi

  • variant_set_type() - Convertit un variant en un autre type "sur-place"

User Contributed Notes

There are no user contributed notes for this page.


Convertit des variants en valeurs entières, et effectue alors une division

  • « variant_get_type
  • variant_imp »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Convertit des variants en valeurs entières, et effectue alors une division

variant_idiv

(PHP 5, PHP 7, PHP 8)

variant_idiv — Convertit des variants en valeurs entières, et effectue alors une division

Description

variant_idiv(mixed $left, mixed $right): variant

Convertit left et right en valeurs entières, et effectue alors une division entière.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Règles de divisions internes des variants
Si | Alors
Les deux expressions sont des chaînes, dates, caractères, booléens | Division et entier retournés
Une expression est une chaîne et l'autre est un caractère | Division
Une expression est numérique et l'autre est une chaîne | Division
Les deux expressions sont numériques | Division
Une des expressions est NULL | NULL est retourné
Les deux expressions sont vides | Une com_exception avec code DISP_E_DIVBYZERO est lancée

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_div() - Retourne le résultat de la division de deux variants

User Contributed Notes

There are no user contributed notes for this page.


Exécute une implication sur les bits de deux variants

  • « variant_idiv
  • variant_int »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Exécute une implication sur les bits de deux variants

variant_imp

(PHP 5, PHP 7, PHP 8)

variant_imp — Exécute une implication sur les bits de deux variants

Description

variant_imp(mixed $left, mixed $right): variant

Exécute une implication sur les bits de deux variants.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Table d'implication des variants
Si left est | Si right est | alors le résultat est
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

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

User Contributed Notes

There are no user contributed notes for this page.


Retourne la partie entière d'un variant

  • « variant_imp
  • variant_mod »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Retourne la partie entière d'un variant

variant_int

(PHP 5, PHP 7, PHP 8)

variant_int — Retourne la partie entière d'un variant

Description

variant_int(mixed $value): variant

Récupère la partie entière d'un variant.

Liste de paramètres

value

Le variant.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Si value est négatif, le premier entier négatif supérieur ou égal à ce variant est retourné, sinon cette fonction retourne la partie entière de la valeur de value.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_fix() - Récupère la portion entière d'un variant
  • variant_round() - Arrondit le variant au nombre spécifié de décimales
  • floor() - Arrondit à l'entier inférieur
  • ceil() - Arrondit au nombre supérieur
  • round() - Arrondit un nombre à virgule flottante

User Contributed Notes

There are no user contributed notes for this page.


Divise deux variantes et retourne le reste

  • « variant_int
  • variant_mul »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Divise deux variantes et retourne le reste

variant_mod

(PHP 5, PHP 7, PHP 8)

variant_mod — Divise deux variantes et retourne le reste

Description

variant_mod(mixed $left, mixed $right): variant

Divise left par right et retourne le reste.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne le reste de la division.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_div() - Retourne le résultat de la division de deux variants
  • variant_idiv() - Convertit des variants en valeurs entières, et effectue alors une division

User Contributed Notes

There are no user contributed notes for this page.


Multiplie les valeurs de deux variants

  • « variant_mod
  • variant_neg »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Multiplie les valeurs de deux variants

variant_mul

(PHP 5, PHP 7, PHP 8)

variant_mul — Multiplie les valeurs de deux variants

Description

variant_mul(mixed $left, mixed $right): variant

Multiplie left par right.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Les valeurs booléennes sont converties en -1 pour false et en 0 pour true

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Règles de multiplication des variants
Si | Alors
Les deux expressions sont du type chaîne, date, caractère ou booléen | Multiplication
Une expression est une chaîne et l'autre est un caractère | Multiplication
Une expression est numérique et l'autre est une chaîne | Multiplication
Les deux expressions sont numériques | Multiplication
Une des expressions est NULL | NULL est retourné
Les deux expressions sont vides | Une chaîne vide est retournée

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_div() - Retourne le résultat de la division de deux variants
  • variant_idiv() - Convertit des variants en valeurs entières, et effectue alors une division

User Contributed Notes

There are no user contributed notes for this page.


Effectue une négation logique sur un variant

  • « variant_mul
  • variant_not »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Effectue une négation logique sur un variant

variant_neg

(PHP 5, PHP 7, PHP 8)

variant_neg — Effectue une négation logique sur un variant

Description

variant_neg(mixed $value): variant

Effectue une négation logique sur value.

Liste de paramètres

value

Le variant.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne le résultat de la négation logique.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

User Contributed Notes

There are no user contributed notes for this page.


Exécute une négation sur les bits sur un variant

  • « variant_neg
  • variant_or »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Exécute une négation sur les bits sur un variant

variant_not

(PHP 5, PHP 7, PHP 8)

variant_not — Exécute une négation sur les bits sur un variant

Description

variant_not(mixed $value): variant

Exécute une négation sur les bits sur le paramètre value et retourne le résultat.

Liste de paramètres

value

Le variant.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne la négation. Si value vaut null, le résultat sera également null.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

User Contributed Notes

There are no user contributed notes for this page.


Performe une disjonction logique sur deux variants

  • « variant_not
  • variant_pow »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Performe une disjonction logique sur deux variants

variant_or

(PHP 5, PHP 7, PHP 8)

variant_or — Performe une disjonction logique sur deux variants

Description

variant_or(mixed $left, mixed $right): variant

Effectue une opération sur les bits de types OR, selon la table de vérité suivante. Notez que ceci est différent de l'expression OR normale.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Règles du OR Variant
Si left est | Si right est | alors le résultat est
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

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_and() - Effectue un ET entre deux variants et retourne le résultat
  • variant_xor() - Exécute une exclusion logique sur deux variants

User Contributed Notes

There are no user contributed notes for this page.


Retourne le résultat de la fonction puissance avec deux variants

  • « variant_or
  • variant_round »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Retourne le résultat de la fonction puissance avec deux variants

variant_pow

(PHP 5, PHP 7, PHP 8)

variant_pow — Retourne le résultat de la fonction puissance avec deux variants

Description

variant_pow(mixed $left, mixed $right): variant

Retourne le résultat de left à la puissance right.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne le résultat de left à la puissance right.

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • pow() - Expression exponentielle

User Contributed Notes

There are no user contributed notes for this page.


Arrondit le variant au nombre spécifié de décimales

  • « variant_pow
  • variant_set_type »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Arrondit le variant au nombre spécifié de décimales

variant_round

(PHP 5, PHP 7, PHP 8)

variant_round — Arrondit le variant au nombre spécifié de décimales

Description

variant_round(mixed $value, int $decimals): ?variant

Retourne la valeur de value arrondi à decimals décimales.

Liste de paramètres

value

Le variant.

decimals

Nombre de décimales.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Retourne la valeur arrondie, ou null en cas d'échec.

Voir aussi

  • round() - Arrondit un nombre à virgule flottante

User Contributed Notes

There are no user contributed notes for this page.


Convertit un variant en un autre type "sur-place"

  • « variant_round
  • variant_set »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Convertit un variant en un autre type "sur-place"

variant_set_type

(PHP 5, PHP 7, PHP 8)

variant_set_type — Convertit un variant en un autre type "sur-place"

Description

variant_set_type(variant $variant, int $type): void

Cette fonction est similaire variant_cast() à part que le variant est modifié "sur-place" ; aucun nouveau variant n'est créé. Les paramètres de cette fonction ont la même signification que ceux de variant_cast().

Liste de paramètres

variant

Le variant.

type

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • variant_cast() - Convertit un variant en un nouvel objet variant de type différent
  • variant_get_type() - Retourne le type d'un objet variant

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.


Assigne une nouvelle valeur pour un objet variant

  • « variant_set_type
  • variant_sub »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Assigne une nouvelle valeur pour un objet variant

variant_set

(PHP 5, PHP 7, PHP 8)

variant_set — Assigne une nouvelle valeur pour un objet variant

Description

variant_set(variant $variant, mixed $value): void

Convertit value en un variant et l'assigne à l'objet variant. Aucun nouvel objet n'est créé et l'ancienne valeur de variant est libérée.

Liste de paramètres

variant

Le variant.

value

Valeurs de retour

Aucune valeur n'est retournée.

User Contributed Notes

There are no user contributed notes for this page.


Soustrait la valeur du variant de droite de la valeur de celui de gauche

  • « variant_set
  • variant_xor »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Soustrait la valeur du variant de droite de la valeur de celui de gauche

variant_sub

(PHP 5, PHP 7, PHP 8)

variant_sub — Soustrait la valeur du variant de droite de la valeur de celui de gauche

Description

variant_sub(mixed $left, mixed $right): variant

Soustrait right de left.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Règles de soustraction des variants
Si | Alors
Les deux expressions sont des chaînes | Soustraction
Une expression est une chaîne et l'autre est un caractère | Soustraction
Une expression est numérique et l'autre est une chaîne | Soustraction.
Les deux expressions sont numériques | Soustraction
Une des expressions est NULL | NULL est retourné
Les deux expressions sont vides | Une chaîne vide est retournée

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_add() - "Ajoute" deux valeurs de variants et retourne le résultat

User Contributed Notes

There are no user contributed notes for this page.


Exécute une exclusion logique sur deux variants

  • « variant_sub
  • win32service »
  • PHP Manual
  • Fonctions COM et .Net (Windows)
  • Exécute une exclusion logique sur deux variants

variant_xor

(PHP 5, PHP 7, PHP 8)

variant_xor — Exécute une exclusion logique sur deux variants

Description

variant_xor(mixed $left, mixed $right): variant

Exécute une exclusion logique sur deux variants.

Liste de paramètres

left

L'opérande de gauche.

right

L'opérande de droite.

Note:

Comme pour toutes les fonctions arithmétiques, les paramètres pour cette fonction peuvent être soit un type PHP natif (entier, chaîne de caractères, nombre à virgule flottante, booléen ou null), ou une instance de la classe COM, VARIANT ou DOTNET. Les types PHP natifs seront convertis en VARIANT en utilisant les mêmes règles que celles trouvées dans le constructeur de la classe variant. Les objets COM et DOTNET auront la valeur de leur propriété par défaut récupérée et utilisée en tant que valeur VARIANT.

Les fonctions arithmétiques VARIANT sont interfacées sur les fonctions de la bibliothèque COM équivalentes ; pour plus d'informations sur ces fonctions, veuillez consulter la bibliothèque MSDN. Les fonctions PHP sont nommées de façon légèrement différentes : par exemple, variant_add(), en PHP, correspond à VarAdd() dans la documentation MSDN.

Valeurs de retour

Règles XOR pour les Variant
Si left est | Si right est | alors le résultat est
true | true | false
true | false | true
false | true | true
false | false | false
null | null | null

Erreurs / Exceptions

Lance une com_exception en cas d'échec.

Voir aussi

  • variant_or() - Performe une disjonction logique sur deux variants
  • variant_and() - Effectue un ET entre deux variants et retourne le résultat

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

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
    • Security consideration
  • Constantes pré-définies
    • Masque binaire de type de Service de Win32Service
    • Constantes de Status du Service de Win32Service
    • Constantes du Service de Control de Message de Win32Service
    • Masque binaire de Message de Control de Service de Win32Service
    • Constantes de Type de Demarrage du Service de Win32Service
    • Constantes de Control d'Erreur de Win32Service
    • Constantes de Service Flag de Win32Service
    • Codes d'Erreur Win32
    • Classes de Priorité de Base Win32
    • Actions de récupération Win32
    • Win32 Service informations
  • Win32ServiceException — La class Win32ServiceException
  • Exemples
  • Fonctions win32service
    • win32_continue_service — Reprise d'un service en pause
    • win32_create_service — Crée une nouvelle entrée pour service dans la base de données SCM
    • win32_delete_service — Supprime une entrée de service de la base de données SCM
    • win32_get_last_control_message — Retourne le dernier message de contrôle qui a été envoyé à ce service
    • win32_pause_service — Met en pause un service
    • win32_query_service_status — Questionne le statut d'un service
    • win32_send_custom_control — Envoyer un contrôle personnalisé au service
    • win32_set_service_exit_code — Définir ou renvoyer le code de sortie pour le service en cours d'exécution
    • win32_set_service_exit_mode — Définir ou renvoyer le mode de sortie pour le service en cours d'exécution
    • win32_set_service_status — Met à jour le statut d'un service
    • win32_start_service_ctrl_dispatcher — Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné
    • win32_start_service — Démarre un service
    • win32_stop_service — Arrête un 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.


Introduction

L'extension win32service est une extension spécifique à Windows qui autorise PHP à communiquer avec la Gestion de Contrôle de Service pour démarrer, arrêter, enregistrer ou effacer des services, et autorise aussi vos scripts PHP à s'exécuter en tant que service.

User Contributed Notes

There are no user contributed notes for this page.


Installation/Configuration

Sommaire

  • Pré-requis
  • Installation
  • Configuration à l'exécution
  • Types de ressources
  • Security consideration

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

Les versions de Windows prises en charge sont les mêmes que le package redistribuable Visual C++ utilisé pour construire PHP.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Des informations sur l'installation de ces extensions PECL peuvent être trouvées dans le chapitre du manuel intitulé Installation des extensions PECL. D'autres informations comme les notes sur les nouvelles versions, les téléchargements, les sources des fichiers, les informations concernant les mainteneurs ainsi qu'un CHANGELOG, peuvent être trouvées ici : » 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

Cette extension nécessite des privilèges d'administrateur pour certaines actions telles que create, delete, start, stop, pause et continue. Cette exigence peut provoquer une élévation des privilèges si le contrôle de service est disponible à partir de l'interface Web ou du contrôle à distance.

Vous pouvez définir l'ACL sur le service après l'avoir ajouté dans SCM pour déléguer les tâches d'administration courantes à un compte non administrateur ou à un compte de service. Pour plus d'instructions, voir la » Microsoft Knowledge Base.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Sommaire

  • Masque binaire de type de Service de Win32Service
  • Constantes de Status du Service de Win32Service
  • Constantes du Service de Control de Message de Win32Service
  • Masque binaire de Message de Control de Service de Win32Service
  • Constantes de Type de Demarrage du Service de Win32Service
  • Constantes de Control d'Erreur de Win32Service
  • Constantes de Service Flag de Win32Service
  • Codes d'Erreur Win32
  • Classes de Priorité de Base Win32
  • Actions de récupération Win32
  • Win32 Service informations

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

User Contributed Notes

There are no user contributed notes for this page.


Masque binaire de type de Service de Win32Service

  • « Constantes pré-définies
  • Constantes de Status du Service de Win32Service »
  • PHP Manual
  • Constantes pré-définies
  • Masque binaire de type de Service de Win32Service
Masque binaire de type de Service de Win32Service
Constante | Valeur | Description
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | Le service s'exécute dans son propre processus.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | Le service peut interagir avec le bureau. Cette option n'est pas disponible sur Windows Vista ou version ultérieure.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | Le service s'exécute dans son propre processus et peut interagir avec le bureau. Cette option n'est pas disponible sous Windows Vista et suivant.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Status du Service de Win32Service

  • « Masque binaire de type de Service de Win32Service
  • Constantes du Service de Control de Message de Win32Service »
  • PHP Manual
  • Constantes pré-définies
  • Constantes de Status du Service de Win32Service
Constantes de Status du Service de Win32Service
Constante | Valeur | Description
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | La continuation du service est en attente.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | La pause du service est en attente.
WIN32_SERVICE_PAUSED | 0x00000007 | Le service est en pause.
WIN32_SERVICE_RUNNING | 0x00000004 | Le service est en cours d'exécution.
WIN32_SERVICE_START_PENDING | 0x00000002 | Le service est en cours de démarrage.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | Le service est en cours d'arrêt.
WIN32_SERVICE_STOPPED | 0x00000001 | Le service est arrêté.

User Contributed Notes

There are no user contributed notes for this page.


Constantes du Service de Control de Message de Win32Service

  • « Constantes de Status du Service de Win32Service
  • Masque binaire de Message de Control de Service de Win32Service »
  • PHP Manual
  • Constantes pré-définies
  • Constantes du Service de Control de Message de Win32Service
Constantes du Service de Control de Message de Win32Service
Constante | Valeur | Description
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Avertit un service suspendu qu'il devrait reprendre.
WIN32_SERVICE_CONTROL_DEVICEEVENT | 0x0000000B |
WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE | 0x0000000C |
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Avertit un service qu'il doit rendre compte de informations sur son état actuel au gestionnaire de contrôle de service.
WIN32_SERVICE_CONTROL_NETBINDADD | 0x00000007 | Avertit un service réseau qu'il existe un nouveau composant pour la liaison.
WIN32_SERVICE_CONTROL_NETBINDDISABLE | 0x0000000A | Avertit un service réseau que l'une de ses liaisons a été désactivée.
WIN32_SERVICE_CONTROL_NETBINDENABLE | 0x00000009 | Avertit un service réseau qu'une liaison désactivée a été activée.
WIN32_SERVICE_CONTROL_NETBINDREMOVE | 0x00000008 | Avertit un service réseau qu'un composant pour la liaison a été supprimé.
WIN32_SERVICE_CONTROL_PARAMCHANGE | 0x00000006 | Avertit un service que ses paramètres de démarrage ont changé.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Avertit un service qu'il doit se mettre en pause.
WIN32_SERVICE_CONTROL_POWEREVENT | 0x0000000D |
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Avertit un service que le système va s'arrêter. Un service qui gère cette notification bloque l'arrêt du système jusqu'à l'arrêt du service ou jusqu'à ce que le délai preshutdown expire. Cette valeur n'est pas pris en charge par Windows Server 2003 et Windows XP/2000.
WIN32_SERVICE_CONTROL_SESSIONCHANGE | 0x0000000E |
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Avertit un service que le système s'arrête et que le service peut donc effectuer des tâches de nettoyage. Si un service accepte ce code de contrôle, il doit s'arrêter dès qu'il s'acquitte de ses tâches de nettoyage. Après l'envoie ce code de contrôle par l'ACM, aucun autre code de contrôle ne sera envoyé au service.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Avertit un service qu'il doit s'arrêter.

User Contributed Notes

There are no user contributed notes for this page.


Masque binaire de Message de Control de Service de Win32Service

  • « Constantes du Service de Control de Message de Win32Service
  • Constantes de Type de Demarrage du Service de Win32Service »
  • PHP Manual
  • Constantes pré-définies
  • Masque binaire de Message de Control de Service de Win32Service
Masque binaire de Message de Control de Service de Win32Service
Constante | Valeur | Description
WIN32_SERVICE_ACCEPT_HARDWAREPROFILECHANGE | 0x00000020 | Le service est notifié lorsque le profil matériel de l'ordinateur a changé. Cela permet au système d'envoyer des notifications WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE au service.
WIN32_SERVICE_ACCEPT_NETBINDCHANGE | 0x00000010 | Le service est un composant réseau qui peut accepter les modifications de sa liaison sans être arrêté et redémarré. Ce code de contrôle permet au service de recevoir les notifications WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_NETBINDENABLE, et WIN32_SERVICE_CONTROL_NETBINDDISABLE.
WIN32_SERVICE_ACCEPT_PARAMCHANGE | 0x00000008 | Le service peut relire ses paramètres de démarrage sans être arrêté et redémarré. Ce code de contrôle permet au service de recevoir des notifications WIN32_SERVICE_CONTROL_PARAMCHANGE.
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | Le service peut être mis en pause et continué. Ce code de control permet au service de recevoir les notifications WIN32_SERVICE_CONTROL_PAUSE et WIN32_SERVICE_CONTROL_CONTINUE.
WIN32_SERVICE_ACCEPT_POWEREVENT | 0x00000040 | Le service est notifié lorsque l'état d'alimentation de l'ordinateur a changé. Cela permet au système d'envoyer des notifications WIN32_SERVICE_CONTROL_POWEREVENT au service.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | Le service peut effectuer des tâche d'avant arrêt. Ce code de control permet au service de recevoir la notification WIN32_SERVICE_CONTROL_PRESHUTDOWN. Cette valeur n'est pas pris en charge par Windows Server 2003 et Windows XP/2000.
WIN32_SERVICE_ACCEPT_SESSIONCHANGE | 0x00000080 | Le service est notifié lorsque l'état de session de l'ordinateur a changé. Cela permet au système d'envoyer des notifications WIN32_SERVICE_CONTROL_SESSIONCHANGE au service. Windows 2000: cette valeur n'est pas prise en charge.
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | Le service est informé lorsque l'arrêt du système se produit. Ce code de control permet au service de recevoir la notification WIN32_SERVICE_CONTROL_SHUTDOWN.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | Le service peut être stoppé. Ce control permet au service de recevoir la notification WIN32_SERVICE_CONTROL_STOP.
WIN32_SERVICE_ACCEPT_TIMECHANGE | 0x00000200 | Le service est notifié lorsque l'heure système a changé. Cela permet au système d'envoyer des notifications WIN32_SERVICE_CONTROL_TIMECHANGE au service. Windows Server 2008, Windows Vista, Windows Server 2003 et Windows XP/2000: ce code de contrôle n'est pas pris en charge.
WIN32_SERVICE_ACCEPT_TRIGGEREVENT | 0x00000400 | Le service est notifié lorsqu'un événement pour lequel le service s'est enregistré se produit. Cela permet au système d'envoyer des notifications WIN32_SERVICE_CONTROL_TRIGGEREVENT au service. Windows Server 2008, Windows Vista, Windows Server 2003 et Windows XP/2000: ce code de contrôle n'est pas pris en charge.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Type de Demarrage du Service de Win32Service

  • « Masque binaire de Message de Control de Service de Win32Service
  • Constantes de Control d'Erreur de Win32Service »
  • PHP Manual
  • Constantes pré-définies
  • Constantes de Type de Demarrage du Service de Win32Service
Constantes de Type de Demarrage du Service de Win32Service
Constante | Valeur | Description
WIN32_SERVICE_BOOT_START | 0x00000000 | Un pilote de périphérique Démarré par le chargeur système. Cette valeur est valide uniquement pour les services de pilote.
WIN32_SERVICE_SYSTEM_START | 0x00000001 | Un pilote de périphérique Démarré par la fonction IoInitSystem. Cette valeur est valide uniquement pour les services de pilote.
WIN32_SERVICE_AUTO_START | 0x00000002 | Un service lancé automatiquement par le gestionnaire de contrôle de service au démarrage du système.
WIN32_SERVICE_DEMAND_START | 0x00000003 | Un service a démarré par le gestionnaire de contrôle de service quand un processus appel la fonction StartService.
WIN32_SERVICE_DISABLED | 0x00000004 | Un service qui ne peut pas être démarré. Les tentatives pour démarrer retourne un code d'erreur WIN32_ERROR_SERVICE_DISABLED .

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Control d'Erreur de Win32Service

  • « Constantes de Type de Demarrage du Service de Win32Service
  • Constantes de Service Flag de Win32Service »
  • PHP Manual
  • Constantes pré-définies
  • Constantes de Control d'Erreur de Win32Service
Constantes de Control d'Erreur de Win32Service
Constante | Valeur | Description
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | Le programme de démarrage ignore l'erreur et continue l'opération de démarrage.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | Le programme de démarrage enregistre l'erreur dans le journal des événements, mais il continue l'opération de démarrage.
WIN32_SERVICE_ERROR_SEVERE | 0x00000002 | Le programme de démarrage consigne l'erreur dans le journal des événements. Si la dernière configuration connue est lancée, l'opération de démarrage se poursuit. Sinon, le système est redémarré avec la dernière configuration connue-bonne.
WIN32_SERVICE_ERROR_CRITICAL | 0x00000003 | Le programme de démarrage consigne l'erreur dans le journal des événements, si possible. Si la dernière configuration connue est lancée, l'opération de démarrage échoue. Sinon, le système est redémarré avec la dernière bonne configuration connue.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Service Flag de Win32Service

  • « Constantes de Control d'Erreur de Win32Service
  • Codes d'Erreur Win32 »
  • PHP Manual
  • Constantes pré-définies
  • Constantes de Service Flag de Win32Service
Constantes de Service Flag de Win32Service
Constante | Valeur | Description
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | Le service s'exécute dans un processus système qui doit toujours être en cours d'exécution.

User Contributed Notes

There are no user contributed notes for this page.


Codes d'Erreur Win32

  • « Constantes de Service Flag de Win32Service
  • Classes de Priorité de Base Win32 »
  • PHP Manual
  • Constantes pré-définies
  • Codes d'Erreur Win32

Note:

Ces constantes ne sont plus utilisées à partir de Win32Service 1.0.0.

Codes d'Erreur Win32
Constante | Valeur | Description
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | Le gestionnaire de la base de données SMC ne dispose pas des droits d'accès appropriés.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | Une dépendance circulaire de service est spécifiée.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | La base de données spécifiée n'existe pas.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | Le service ne peut être stoppé car d'autres services en cours d'exécution dépendent de lui.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | Le nom d'affichage existe déjà dans la base de données du gestionnaire de service en tant que nom de service ou que nom d'affichage.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | Cette erreur est retournée si le programme est exécuté en application console plutôt qu'en tant que service. Si le programme est exécuté en tant qu'application console à des fins de débogage, il devrat être structuré afin que le code spécifique au service ne sois jamais appelé.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | Le tampon est trop petit pour la structure d'état de service. Rien n'a été écrit à la structure.
WIN32_ERROR_INVALID_DATA | 0x0000000D | Le structure d'état de service indiquée n'est pas valide.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | Le handle pour le gestionnaire de service de control spécifié est invalide.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | Le paramètre InfoLevel contient une valeur non prise en charge.
WIN32_ERROR_INVALID_NAME | 0x0000007B | Le nom de service spécifié n'est pas valide.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | Un paramètre spécifié n'est pas valide.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | Le nom d'utilisateur spécifié dans le paramètre user n'existe pas. Voir win32_create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | Le code de control demandé n'est pas valide, ou il est inacceptable pour le service.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | Le service de fichier binaire n'a pu être trouvé.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | Une instance du service est déjà en cours d'exécution.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | Le code de control demandé ne peut être envoyé au service car l'état du service est WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING ou WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | La base de données est verouillée.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | Le service dépend d'un service qui n'existe pas ou qui a été marqué pour suppression.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | Ce service dépend d'un autre service qui n'a pas pu démarrer.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | Le service a été désactivé.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | Le service spécifié n'existe pas en tant que service installé.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | Le service spécifié existe déjà dans la base de données.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | Le service n'a pas démarré en raison d'un échec de connexion. Cette erreur se produit si le service est configuré pour s'exécuter sous un compte qui n'a pas les droits "connecter en tant que service".
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | Le service spécifié a déjà été marqué pour suppression.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | Un thread n'a pas pu être créé pour le service.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | Le service n'a pas été démarré.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | Le processus du service a été démarré, mais il n'a pas appelé StartServiceCtrlDispatcher, ou le thread qui a appelé StartServiceCtrlDispatcher peut être bloqué dans une fonction du gestionnaire de contrôle.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | Le système s'arrête, cette fonction ne peut pas être appelée.
WIN32_ERROR_SERVICE_SPECIFIC_ERROR | 0x0000042A | Le service a retourné un code d'erreur spécifique au service.
WIN32_NO_ERROR | 0x00000000 | Aucune erreur.

User Contributed Notes

There are no user contributed notes for this page.


Classes de Priorité de Base Win32

  • « Codes d'Erreur Win32
  • Actions de récupération Win32 »
  • PHP Manual
  • Constantes pré-définies
  • Classes de Priorité de Base Win32
Classes de Priorité de Base Win32
Constante | Valeur | Description
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Processus ayant une priorité supérieure WIN32_NORMAL_PRIORITY_CLASS mais inférieure à WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Processsus ayant une priorité supperieur à WIN32_IDLE_PRIORITY_CLASS mais inférieure à WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Processus qui exécute des tâches critiques dans le temps qui doivent être exécutées immédiatement. Le thread du processus devance les threads de priorité normale ou au repos. Un exemple est la liste des tâches, qui doit répondre rapidement quand elle est appelée par l'utilisateur quel que sois la charge du système. Soyez extrêmement prudent lorsque vous utilisez la classe de haute priorité, car une application de classe de haute priorité peut utiliser presque tout le temps CPU disponible.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Processus dont les threads ne s'exécutent que lorsque le système est inactif. Les threads du processus sont devancés par les threads de tout processus en cours ayant une classe de plus grande priorité. Un exemple est un économiseur d'écran. Cette classe est héritée par les processus enfants.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Processus sans planification de besoins spéciaux.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Processus ayant la plus haute priorité possible. Les threads du processus devance les threads de tout autre processus, y compris les processus du système d'exploitation exécutant des tâches importantes. Par exemple, un processus en temps réel qui s'exécute un peu trop lentement peut causer des pertes d'ecriture du tampon sur le disque ou empecher à la souris de répondre.

User Contributed Notes

There are no user contributed notes for this page.


Actions de récupération Win32

  • « Classes de Priorité de Base Win32
  • Win32 Service informations »
  • PHP Manual
  • Constantes pré-définies
  • Actions de récupération Win32
Actions de récupération Win32
Constante | Valeur | Description
WIN32_SC_ACTION_NONE | 0x00000000 | Aucune action.
WIN32_SC_ACTION_RESTART | 0x00000001 | Redémarrer le service.
WIN32_SC_ACTION_REBOOT | 0x00000002 | Redémarrer le serveur.
WIN32_SC_ACTION_RUN_COMMAND | 0x00000003 | Exécuter un programme.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Service informations

  • « Actions de récupération Win32
  • Win32ServiceException »
  • PHP Manual
  • Constantes pré-définies
  • 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.


La class Win32ServiceException

(PECL win32service >=1.0.0)

Introduction

L’exception remplace l’ancien mécanisme où la valeur d’erreur devait être comparée aux constantes pour détecter quelle erreur a été émise. Le code de l’exception est égal à la valeur de la constante d’erreur et le message de l’exception est basé sur le nom de la constante correspondante.

Synopsis de la classe

class Win32ServiceException extends Exception {
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes héritées */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Exemple #1 Enregistre un script PHP pour exécuter en tant que service

<?php
win32_create_service(array(
'service' => 'dummyphp', # nom du service
'display' => 'sample dummy PHP service', # description courte
'description' => 'This is a dummy Windows service created using PHP.', # description longue
'params' => '"' . __FILE__ . '" run', # chemin vers le script et paramètres
));
?>

Exemple #2 Efface un service

<?php
win32_delete_service('dummyphp');
?>

Exemple #3 Exécution d'un service

<?php
if ($argv[1] == 'run') {
win32_start_service_ctrl_dispatcher('dummyphp');

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
# effectuer votre travail ici.
# essayez de ne pas prendre plus de 30 secondes avant de retourner au
# début de la boucle
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Fonctions win32service

Sommaire

  • win32_continue_service — Reprise d'un service en pause
  • win32_create_service — Crée une nouvelle entrée pour service dans la base de données SCM
  • win32_delete_service — Supprime une entrée de service de la base de données SCM
  • win32_get_last_control_message — Retourne le dernier message de contrôle qui a été envoyé à ce service
  • win32_pause_service — Met en pause un service
  • win32_query_service_status — Questionne le statut d'un service
  • win32_send_custom_control — Envoyer un contrôle personnalisé au service
  • win32_set_service_exit_code — Définir ou renvoyer le code de sortie pour le service en cours d'exécution
  • win32_set_service_exit_mode — Définir ou renvoyer le mode de sortie pour le service en cours d'exécution
  • win32_set_service_status — Met à jour le statut d'un service
  • win32_start_service_ctrl_dispatcher — Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné
  • win32_start_service — Démarre un service
  • win32_stop_service — Arrête un 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]);

?>


Reprise d'un service en pause

  • « Fonctions win32service
  • win32_create_service »
  • PHP Manual
  • Fonctions win32service
  • Reprise d'un service en pause

win32_continue_service

(PECL win32service >=0.1.0)

win32_continue_service — Reprise d'un service en pause

Description

win32_continue_service(string $servicename, string $machine = ?): void

Reprise d'un service en pause. Requiert des privilèges d'administrateur ou un compte avec les droits appropriés définis dans l'ACL du service.

Liste de paramètres

servicename

Le nom court du service.

machine

Nom de la machine (optionnel). Si omis, la machine locale sera utilisée.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Une ValueError est levée si la valeur du paramètre servicename est vide.

Une Win32ServiceException est levée en cas d'erreur.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.
PECL win32service 0.3.0 | Cette fonction ne requiert plus de compte d'administrateur si l'ACL est défini pour un autre compte.

Voir aussi

  • win32_start_service() - Démarre un service
  • win32_stop_service() - Arrête un service
  • win32_pause_service() - Met en pause un service
  • win32_send_custom_control() - Envoyer un contrôle personnalisé au service
  • Les codes erreur Win32

User Contributed Notes

There are no user contributed notes for this page.


Crée une nouvelle entrée pour service dans la base de données SCM

  • « win32_continue_service
  • win32_delete_service »
  • PHP Manual
  • Fonctions win32service
  • Crée une nouvelle entrée pour service dans la base de données SCM

win32_create_service

(PECL win32service >=0.1.0)

win32_create_service — Crée une nouvelle entrée pour service dans la base de données SCM

Description

win32_create_service(array $details, string $machine = ?): void

Tente d'ajouter un service dans la base de données SCM. Des privilèges d'administrateur sont nécessaires pour que cela réussisse.

Liste de paramètres

details

Un tableau des détails des services :

service

Le nom court du service. C'est le nom que vous utiliserez pour contrôler le service en utilisant la commande net. Le service doit être unique (deux services ne peuvent partager le même nom), et idéalement, devrait éviter d'avoir des espaces dans son nom.

display

Le nom d'affichage du service. C'est le nom que vous verrez dans l'Applet Services.

description

La description longue du service. C'est la description que vous verrez dans l'Applet des services.

user

Le nom de l'utilisateur sous lequel vous voulez que le service s'exécute. Si oublié, le service fonctionnera en tant que LocalSystem. Si le nom de l'utilisateur est spécifié, vous devez aussi fournir un mot de passe.

password

Le mot de passe qui correspond à user.

path

Le chemin complet au module exécutable qui sera démarré lorsque le service est démarré. Si oublié, le chemin du processus courant de PHP sera utilisé.

params

Paramètres de commande à passer au service lorsqu'il démarre. Si vous voulez exécuter un script PHP en tant que service, alors le premier paramètre devrait être le chemin complet au script PHP que vous prévoyez exécuter. Si le nom du script ou le chemin contiennent des espaces, alors, entourez le chemin complet du script PHP par des "

load_order

Contrôle le load_order. Cela n'est pas encore complètement supporté.

svc_type

Fixe le type de service. Si oublié, la valeur par défaut est WIN32_SERVICE_WIN32_OWN_PROCESS. Ne changez pas ceci à moins que vous savez vraiment ce que vous faites.

start_type

Spécifie comment le service devrait être démarré. La valeur par défaut est WIN32_SERVIDE_AUTO_START qui signifie que le service sera démarré lorsque la machine démarrera.

error_control

Informe le SCM à propos de ce qu'il devrait faire lorsqu'il détecte un problème avec le service. La valeur par défaut est WIN32_SERVER_ERROR_IGNORE. Le changement de cette valeur n'est pas encore complètement supporté.

delayed_start

Si delayed_start est défini à true, alors il informera le SCM que ce service doit être démarré après les services démarrés automatiquement et un certain délai.

N'importe quel service peut être marqué comme étant un service retardé après le démarrage automatique ; cependant, cette configuration n'a aucun effet tant que le paramètre start_type du service vaut WIN32_SERVICE_AUTO_START.

Cette configuration n'est application que sous Windows Vista et les serveurs Windows 2008 et suivants.

base_priority

Pour réduire l'impacte sur l'utilisation du processeur, il peut être nécessaire de définir une priorité plus basse qu'à la normale.

Le paramètre base_priority peut être défini à une des constantes définies dans les classes de basse priorité Win32.

dependencies

Pour définir les dépendances de votre service, il est nécessaire de définir ce paramètre avec la liste des noms des service dans un tableau.

recovery_delay

Ce paramètre défini le délai entre la défaillance et l'exécution de l'action de récupération. La valeur est en millisecondes.

La valeur par défaut est 60000.

recovery_action_1

L'action qui sera exécuté lors de la première défaillance. L'action par défaut est WIN32_SC_ACTION_NONE.

Le paramètre recovery_action_1 peut être défini avec l'une des constantes définie dans les Actions de récupération Win32.

recovery_action_2

L'action qui sera exécuté lors de la deuxième défaillance. L'action par défaut est WIN32_SC_ACTION_NONE.

Le paramètre recovery_action_2 peut être défini avec l'une des constantes définie dans les Actions de récupération Win32.

recovery_action_3

L'action qui sera exécuté lors des défaillances suivantes. L'action par défaut est WIN32_SC_ACTION_NONE.

Le paramètre recovery_action_3 peut être défini avec l'une des constantes définie dans les Actions de récupération Win32.

recovery_reset_period

Le compteur des défaillance sera réinitialisé après le délai défini dans ce paramètre. Le délai est exprimé en secondes.

La valeur par défaut est 86400.

recovery_enabled

Définir ce paramètre à true pour activer les options de récupération, et false pour les désactiver.

La valeur par défaut est false

recovery_reboot_msg

Ajouter ce paramètre pour définir le message enregistré dans le jounal d'évènements Windows avant le redémarrage. Utilisé uniquement si l'une des actions est défini à WIN32_SC_ACTION_REBOOT.

recovery_command

Ajouter ce paramètre pour définir la commande a exécuter lorsqu'une action est définie à WIN32_SC_ACTION_RUN_COMMAND.

machine

Le nom optionnel de la machine sur lequel vous voulez créer le service. Si oublié, cela utilisera la machine locale.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Une ValueError est levée si la valeur du paramètre serviceest vide.

Une ValueError est levée si la valeur du paramètre path est omis ou vide.

Une ValueError est levée si la valeur du paramètre svc_type est incorrect.

Une ValueError est levée si la valeur du paramètre start_type est incorrect.

Une ValueError est levée si la valeur du paramètre error_control est incorrect.

Une ValueError est levée si la valeur du paramètre base_priority est incorrect.

Une ValueError est levée si la valeur du paramètre recovery_delay n'est pas entre 0 et PHP_INT_MAX.

Une ValueError est levée si la valeur du paramètre recovery_action_1 est incorrect.

Une ValueError est levée si la valeur du paramètre recovery_action_2 est incorrect.

Une ValueError est levée si la valeur du paramètre recovery_action_3 est incorrect.

Une ValueError est levée si la valeur du paramètre recovery_reset_period n'est pas entre 0 et PHP_INT_MAX.

Une Win32ServiceException est levée en cas d'erreur.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.
PECL win32service 0.4.0 | Les paramètres dependencies, recovery_delay, recovery_action_1, recovery_action_2, recovery_action_3, recovery_reset_period, recovery_enabled, recovery_reboot_msg et recovery_command ont été ajoutés.

Exemples

Exemple #1 Exemple avec win32_create_service()

Crée un service dont le nom court est 'dummyphp'.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // le nom de votre service
'display' => 'service PHP simple PHP', // la description courte
'description' => 'Ceci est un service Windows créé en utilisant PHP', // la description longue
'params' => '"' . __FILE__ . '" run', // chemin vers le script ainsi que les paramètres
));
debug_zval_dump($x);
?>

Exemple #2 Un exemple win32_create_service() avec les dépendances

Crée un service dont le nom court est 'dummyphp' avec des dépendances.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // Le nom du service
'display' => 'service PHP simple PHP', // Une courte description
'description' => 'Ceci est un service Windows créé en utilisant PHP.', // Une longue description
'params' => '"' . __FILE__ . '" run', // chemin vers le script ainsi que les paramètres
'dependencies' => array("Netman"), // La liste des dépendances
));
debug_zval_dump($x);
?>

Exemple #3 Exemple de win32_create_service() avec les options de récupération

Crée un service dont le nom court est 'dummyphp' avec les options de récupération.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // Le nom du service
'display' => 'service PHP simple PHP', // Une courte description
'description' => 'Ceci est un service Windows créé en utilisant PHP.', // Une longue description
'params' => '"' . __FILE__ . '" run', // chemin vers le script ainsi que les paramètres
'recovery_delay' => 120000, // Les actions de récupération seront exécuté après 2 minutes
'recovery_action_1' => WIN32_SC_ACTION_RESTART, // Première défaillance, redémarrage du service
'recovery_action_2' => WIN32_SC_ACTION_RUN_COMMAND, // Deuxième défaillance, exécution d'une commande
'recovery_action_3' => WIN32_SC_ACTION_NONE, // Défaillance suivante, ne rien faire
'recovery_reset_period' => 86400, // Réinitialiser le compteur des défaillance après 1 jour (86400 minutes)
'recovery_enabled' => true, // Activer les options de récupération
'recovery_reboot_msg' => null, // Ne pas définir de message de redémarrage, il n'est pas utile.
'recovery_command' => "c:\clean-service.bat", // Lorsque l'action est WIN32_SC_ACTION_RUN_COMMAND, exécuter cette commande.
));
debug_zval_dump($x);
?>

Voir aussi

  • win32_delete_service() - Supprime une entrée de service de la base de données SCM
  • Les classes de basse priorité Win32
  • Les actions de récupération Win32
  • Les codes erreurs Win32

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


Supprime une entrée de service de la base de données SCM

  • « win32_create_service
  • win32_get_last_control_message »
  • PHP Manual
  • Fonctions win32service
  • Supprime une entrée de service de la base de données SCM

win32_delete_service

(PECL win32service >=0.1.0)

win32_delete_service — Supprime une entrée de service de la base de données SCM

Description

win32_delete_service(string $servicename, string $machine = ?): void

Essaie de supprimer un service de la base de données SCM. Les privilèges d'administrateur sont requis pour que cette fonction réussisse.

Cette fonction ne fait que marquer le service pour suppression. Si d'autre processus (comme l'Applet Services) sont ouverts, alors la suppression sera reportée jusqu'à ce que ces applications soient fermées. Si un service est marqué pour suppression, d'autres tentatives de suppression échoueront et les tentatives de créer un nouveau service avec ce nom échoueront aussi.

Liste de paramètres

servicename

Le nom court du service.

machine

Le nom optionnel de la machine. Si oublié, cela utilisera la machine locale.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Une ValueError est levée si la valeur du paramètre servicename est vide.

Une Win32ServiceException est levée en cas d'erreur.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.

Exemples

Exemple #1 Exemple avec win32_delete_service()

Supprime le service dummyphp.

<?php
win32_delete_service('dummyphp');
?>

Voir aussi

  • win32_create_service() - Crée une nouvelle entrée pour service dans la base de données SCM
  • Les codes erreur Win32

User Contributed Notes

There are no user contributed notes for this page.


Retourne le dernier message de contrôle qui a été envoyé à ce service

  • « win32_delete_service
  • win32_pause_service »
  • PHP Manual
  • Fonctions win32service
  • Retourne le dernier message de contrôle qui a été envoyé à ce service

win32_get_last_control_message

(PECL win32service >=0.1.0)

win32_get_last_control_message — Retourne le dernier message de contrôle qui a été envoyé à ce service

Description

win32_get_last_control_message(): int

Retourne le code de contrôle qui a été envoyé en dernier à ce processus de service. Lorsqu'il fonctionne en tant que service, vous devriez vérifier périodiquement pour déterminer si le service doit être arrêté.

Attention

Depuis la version 0.2.0, cette fonction fonctionne uniquement en ligne de commande. Elle est désactivé dans les autres cas.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne une constante de contrôle qui sera une parmi les constantes de contrôle des messages de service Win32Service : 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.

Si la valeur se situe entre 128 et 255, le code de contrôle est personnalisé.

Erreurs / Exceptions

Avant la version 1.0.0, si cette fonction est utilisé en dehors du SAPI "cli", une erreur E_ERROR sera émise.

À partir de la version 1.0.0, lancera une Win32ServiceException si le SAPI n'est pas "cli"

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 0.2.0 | Cette fonction fonctionne uniquement en ligne de commande.

Voir aussi

  • win32_start_service_ctrl_dispatcher() - Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné
  • win32_set_service_status() - Met à jour le statut d'un service
  • win32_set_service_exit_mode() - Définir ou renvoyer le mode de sortie pour le service en cours d'exécution
  • win32_set_service_exit_code() - Définir ou renvoyer le code de sortie pour le service en cours d'exécution
  • les constantes de contrôle des messages de service Win32Service

User Contributed Notes

There are no user contributed notes for this page.


Met en pause un service

  • « win32_get_last_control_message
  • win32_query_service_status »
  • PHP Manual
  • Fonctions win32service
  • Met en pause un service

win32_pause_service

(PECL win32service >=0.1.0)

win32_pause_service — Met en pause un service

Description

win32_pause_service(string $servicename, string $machine = ?): void

Met en pause un service. Requiert des privilèges d'administrateur ou un compte avec les droits appropriés définis dans l'ACL du service.

Liste de paramètres

servicename

Le nom court du service.

machine

Nom de la machine (optionnel). Si omis, la machine locale sera utilisée.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Une ValueError est levée si la valeur du paramètre servicename est vide.

Une Win32ServiceException est levée en cas d'erreur.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.
PECL win32service 0.3.0 | Cette fonction ne requiert plus de compte d'administrateur si l'ACL est défini pour un autre compte.

Voir aussi

  • win32_start_service() - Démarre un service
  • win32_stop_service() - Arrête un service
  • win32_continue_service() - Reprise d'un service en pause
  • win32_send_custom_control() - Envoyer un contrôle personnalisé au service
  • Les codes erreur Win32

User Contributed Notes

There are no user contributed notes for this page.


Questionne le statut d'un service

  • « win32_pause_service
  • win32_send_custom_control »
  • PHP Manual
  • Fonctions win32service
  • Questionne le statut d'un service

win32_query_service_status

(PECL win32service >=0.1.0)

win32_query_service_status — Questionne le statut d'un service

Description

win32_query_service_status(string $servicename, string $machine = ?): array

Questionne le statut courant pour un service, retournant un tableau d'informations.

Liste de paramètres

servicename

Le nom court du service.

machine

Le nom optionnel de la machine. Si oublié, cela utilisera la machine locale.

Valeurs de retour

Retourne un tableau contenant les informations suivantes en cas de succès.

Avant la version 1.0.0, false if there is a problem with the parameters or a Win32 Error Code on failure.

ServiceType

Le dwServiceType. Voir les masques de type de service Win32Service.

CurrentState

Le dwCurrentState. Voir les constantes de statut des services Win32Service.

ControlsAccepted

Quels contrôles de service sont acceptés par le service. Voir les masques acceptés pour les messages de contrôle de service Win32Service.

Win32ExitCode

Si le service quitte, le code de retour du processus. Cette valeur est égale à WIN32_ERROR_SERVICE_SPECIFIC_ERROR si le mode de sortie n'est pas gracieux. Voir codes d'erreur Win32Service et win32_set_service_exit_mode().

ServiceSpecificExitCode

Si le service quitte avec une condition d'erreur, le code spécifique du service qui sera enregistré dans le journal d'évènements est visible ici. Cette valeur est égale à la valeur définie par win32_set_service_exit_code().

CheckPoint

Si le service s'arrête, garde le nombre courant de point de contrôle. Ceci est utilisé par SCM comme un genre de battement de cœur pour détecter un processus de service arrêté. La valeur du point de contrôle est mieux interprétée en conjonction avec la valeur WaitHint.

WaitHint

Si le service s'arrête, il fixera un WaitHint à une valeur de point de contrôle qui indiquera l'exécution 100%. Cela peut être utilisé pour implanter un indicateur de progrès.

ProcessId

L'identifiant de processus de fenêtre. Si 0, le processus ne fonctionne pas.

ServiceFlags

Le dwServiceFlags. Voir les constantes utilisées pour les drapeaux des services Win32Service.

Erreurs / Exceptions

Une ValueError est levée si la valeur du paramètre servicename est vide.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant array, avant il était mixed.

Voir aussi

  • Les constantes Win32Service prédéfinies

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.


Envoyer un contrôle personnalisé au service

  • « win32_query_service_status
  • win32_set_service_exit_code »
  • PHP Manual
  • Fonctions win32service
  • Envoyer un contrôle personnalisé au service

win32_send_custom_control

(PECL win32service >=0.4.0)

win32_send_custom_control — Envoyer un contrôle personnalisé au service

Description

win32_send_custom_control(string $servicename, int $control, string $machine = ?): void

Voir » Microsoft ControlService function pour plus de détails.

Liste de paramètres

servicename

Le nom abrégé du service.

control

La valeur de contrôle personnalisé entre 128 et 255.

machine

Nom de la machine en option. Si omis, l'ordinateur local est utilisé.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Avant la version 1.0.0, si la valeur de contrôle n'est pas compris entre 128 et 255, cette fonction émet une erreur de niveau E_ERROR.

Une ValueError est levée si la valeur du paramètre servicename est vide.

Une ValueError est levé si la valeur du paramètre control n'est pas entre 128 et 255.

Une Win32ServiceException est levée en cas d'erreur.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.

Voir aussi

  • win32_start_service() - Démarre un service
  • win32_stop_service() - Arrête un service
  • win32_pause_service() - Met en pause un service
  • win32_continue_service() - Reprise d'un service en pause
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Définir ou renvoyer le code de sortie pour le service en cours d'exécution

  • « win32_send_custom_control
  • win32_set_service_exit_mode »
  • PHP Manual
  • Fonctions win32service
  • Définir ou renvoyer le code de sortie pour le service en cours d'exécution

win32_set_service_exit_code

(PECL win32service >=0.4.0)

win32_set_service_exit_code — Définir ou renvoyer le code de sortie pour le service en cours d'exécution

Description

win32_set_service_exit_code(int $exitCode = 1): int

Change ou retourne le code de sortie. Le code de sortie est utilisé uniquement si le mode de sortie n'est pas gracieux. Si la valeur n'est pas zéro, la configuration de récupération peut être utilisée après l'échec du service. Voir » les codes d'erreur système Microsoft pour plus de détails

Attention

Cette fonction fonctionne uniquement dans SAPI "cli". Sur d'autres SAPI, cette fonction est désactivée.

Liste de paramètres

exitCode

Le code de retour utilisé à la sortie.

Valeurs de retour

Retourne le code de sortie actuel ou l'ancien.

Erreurs / Exceptions

Avant la version 1.0.0, si cette fonction est utilisé en dehors du SAPI "cli", une erreur E_ERROR sera émise.

À partir de la version 1.0.0, lancera une Win32ServiceException si le SAPI n'est pas "cli"

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.

Voir aussi

  • win32_start_service_ctrl_dispatcher() - Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné
  • win32_set_service_status() - Met à jour le statut d'un service
  • win32_set_service_exit_mode() - Définir ou renvoyer le mode de sortie pour le service en cours d'exécution

User Contributed Notes

There are no user contributed notes for this page.


Définir ou renvoyer le mode de sortie pour le service en cours d'exécution

  • « win32_set_service_exit_code
  • win32_set_service_status »
  • PHP Manual
  • Fonctions win32service
  • Définir ou renvoyer le mode de sortie pour le service en cours d'exécution

win32_set_service_exit_mode

(PECL win32service >=0.4.0)

win32_set_service_exit_mode — Définir ou renvoyer le mode de sortie pour le service en cours d'exécution

Description

win32_set_service_exit_mode(bool $gracefulMode = true): bool

Si le paramètre gracefulMode est fourni, le mode de sortie est modifié. Lorsque le mode de sortie n'est pas gracefuly, le code de sortie utilisé peut être défini avec la fonction win32_set_service_exit_code().

Attention

Cette fonction fonctionne uniquement dans SAPI "cli". Sur d'autres SAPI, cette fonction est désactivée.

Liste de paramètres

gracefulMode

true pour la sortie gracieuse. false pour la sortie avec erreur.

Valeurs de retour

Retournez le mode de sortie actuel ou ancien.

Erreurs / Exceptions

Avant la version 1.0.0, si cette fonction est utilisé en dehors du SAPI "cli", une erreur E_ERROR sera émise.

À partir de la version 1.0.0, lancera une Win32ServiceException si le SAPI n'est pas "cli"

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.

Voir aussi

  • win32_start_service_ctrl_dispatcher() - Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné
  • win32_set_service_status() - Met à jour le statut d'un service
  • win32_set_service_exit_code() - Définir ou renvoyer le code de sortie pour le service en cours d'exécution

User Contributed Notes

There are no user contributed notes for this page.


Met à jour le statut d'un service

  • « win32_set_service_exit_mode
  • win32_start_service_ctrl_dispatcher »
  • PHP Manual
  • Fonctions win32service
  • Met à jour le statut d'un service

win32_set_service_status

(PECL win32service >=0.1.0)

win32_set_service_status — Met à jour le statut d'un service

Description

win32_set_service_status(int $status, int $checkpoint = 0): void

Informe le SCM d'un statut courant d'un service qui fonctionne. Cet appel est seulement valide pour un processus de service qui fonctionne.

Attention

Depuis la version 0.2.0, cette fonction fonctionne uniquement en ligne de commande. Elle est désactivé dans les autres cas.

Liste de paramètres

status

Le code de statut de service, un de 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

Cette valeur sera incrémentée par le service périodiquement pour reporter sa progression lors des opérations de démarrage, d'arrêt, de pause ou de reprise. Par exemple, le service incrémentera cette valeur lorsqu'il aura terminé chaque étape de son initialisation lors de son démarrage.

checkpoint n'est valide que lorsque status est une des constantes suivantes : WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING ou WIN32_SERVICE_PAUSE_PENDING.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Avant la version 1.0.0, si cette fonction est utilisé en dehors du SAPI "cli", une erreur E_ERROR sera émise.

À partir de la version 1.0.0, lancera une Win32ServiceException si le SAPI n'est pas "cli"

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.
PECL win32service 0.2.0 | Cette fonction fonctionne uniquement en ligne de commande.

Voir aussi

  • win32_start_service_ctrl_dispatcher() - Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné
  • win32_get_last_control_message() - Retourne le dernier message de contrôle qui a été envoyé à ce service
  • win32_set_service_exit_mode() - Définir ou renvoyer le mode de sortie pour le service en cours d'exécution
  • win32_set_service_exit_code() - Définir ou renvoyer le code de sortie pour le service en cours d'exécution
  • Les constantes de statut des services Win32Service

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;
}

?>


Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné

  • « win32_set_service_status
  • win32_start_service »
  • PHP Manual
  • Fonctions win32service
  • Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné

win32_start_service_ctrl_dispatcher

(PECL win32service >=0.1.0)

win32_start_service_ctrl_dispatcher — Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné

Description

win32_start_service_ctrl_dispatcher(string $name, bool $gracefulMode = true): void

Lorsque exécuté via le Gestionnaire de Contrôle de Service, un processus de service est requis pour "archiver" avec lui pour établir un service de surveillance et de communication ergonomique. Cette fonction effectue un archivage en démarrant un thread pour gérer les communications de bas niveau avec le gestionnaire de contrôle de service.

Une fois démarré, le processus du service doit faire 2 choses. La première est d'indiquer au Service Control Manager que le service est en cours d'exécution. La seconde est d'appeler la fonction win32_set_service_status() avec la constante WIN32_SERVICE_RUNNING. Si vous avez besoin de lancer des processus longs avant que le service ne soit lancé, alors vous pouvez utiliser la constante WIN32_SERVICE_START_PENDING. La seconde est de continuer à vérifier en utilisant le Service Control Manager sachant qu'il peut déterminer si le service se termine ou non. Ceci consiste à appeler, périodiquement, la fonction win32_get_last_control_message() et à traiter le code retourné.

Attention

Depuis la version 0.2.0, cette fonction fonctionne uniquement en ligne de commande. Elle est désactivé dans les autres cas.

Liste de paramètres

name

Le court nom du service, comme enregistré par win32_create_service().

gracefulMode

true pour la sortie gracieuse. false pour la sortie avec erreur. Voir win32_set_service_exit_mode() pour plus de détails.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Avant la version 1.0.0, si cette fonction est utilisé en dehors du SAPI "cli", une erreur E_ERROR sera émise.

À partir de la version 1.0.0, lancera une Win32ServiceException si le SAPI n'est pas "cli"

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.
PECL win32service 0.4.0 | Le paramètre gracefulMode a été ajouté.
PECL win32service 0.2.0 | Cette fonction fonctionne uniquement en ligne de commande.

Exemples

Exemple #1 Exemple avec win32_start_service_ctrl_dispatcher()

Vérifie si le service fonctionne sous SCM.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
die("Je ne fonctionne probablement pas sous le gestionnaire de contrôle de service");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Quelques processus longs à récupérer pendant que le service fonctionne.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
# effectuer votre travail ici.
# essayez de ne pas prendre plus de 30 secondes avant de retourner au
}
?>

Voir aussi

  • win32_set_service_status() - Met à jour le statut d'un service
  • win32_get_last_control_message() - Retourne le dernier message de contrôle qui a été envoyé à ce service
  • win32_set_service_exit_mode() - Définir ou renvoyer le mode de sortie pour le service en cours d'exécution
  • win32_set_service_exit_code() - Définir ou renvoyer le code de sortie pour le service en cours d'exécution
  • Les codes erreur Win32

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.


Démarre un service

  • « win32_start_service_ctrl_dispatcher
  • win32_stop_service »
  • PHP Manual
  • Fonctions win32service
  • Démarre un service

win32_start_service

(PECL win32service >=0.1.0)

win32_start_service — Démarre un service

Description

win32_start_service(string $servicename, string $machine = ?): void

Essaie de démarrer le service nommé. Requiert des privilèges d'administrateur ou un compte avec les droits appropriés définis dans l'ACL du service.

Liste de paramètres

servicename

Le nom court du service.

machine

Le nom optionnel de la machine. Si oublié, cela utilisera la machine locale.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Une ValueError est levée si la valeur du paramètre servicename est vide.

Une Win32ServiceException est levée en cas d'erreur.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.
PECL win32service 0.3.0 | Cette fonction ne requiert plus de compte d'administrateur si l'ACL est défini pour un autre compte.

Voir aussi

  • win32_stop_service() - Arrête un service
  • win32_pause_service() - Met en pause un service
  • win32_continue_service() - Reprise d'un service en pause
  • win32_send_custom_control() - Envoyer un contrôle personnalisé au service
  • Codes erreur Win32

User Contributed Notes

There are no user contributed notes for this page.


Arrête un service

  • « win32_start_service
  • Manipulation XML »
  • PHP Manual
  • Fonctions win32service
  • Arrête un service

win32_stop_service

(PECL win32service >=0.1.0)

win32_stop_service — Arrête un service

Description

win32_stop_service(string $servicename, string $machine = ?): void

Arrête un service nommé. Requiert des privilèges d'administrateur ou un compte avec les droits appropriés définis dans l'ACL du service.

Liste de paramètres

servicename

Le nom court du service.

machine

Le nom optionnel de la machine. Si oublié, cela utilisera la machine locale.

Valeurs de retour

Aucune valeur n'est retournée.

Avant la version 1.0.0, retournait WIN32_NO_ERROR on success, false if there is a problem with the parameters or a Win32 Error Code on failure.

Erreurs / Exceptions

Une ValueError est levée si la valeur du paramètre servicename est vide.

Une Win32ServiceException est levée en cas d'erreur.

Historique

Version | Description
PECL win32service 1.0.0 | Lance une ValueError si un paramètre est invalide, avant false était retourné.
PECL win32service 1.0.0 | Lance une Win32ServiceException en cas d'erreur, avant un Code d'erreur Win32 était retourné.
PECL win32service 1.0.0 | Le type de retour est maintenant void, avant il était mixed.
PECL win32service 0.3.0 | Cette fonction ne requiert plus de compte d'administrateur si l'ACL est défini pour un autre compte.

Voir aussi

  • win32_start_service() - Démarre un service
  • win32_pause_service() - Met en pause un service
  • win32_continue_service() - Reprise d'un service en pause
  • win32_send_custom_control() - Envoyer un contrôle personnalisé au service
  • Codes erreur Win32

User Contributed Notes

There are no user contributed notes for this page.


Manipulation XML

  • DOM — Model Objet d'un document
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Exemples
    • DOMAttr — La classe DOMAttr
    • DOMCdataSection — La classe DOMCdataSection
    • DOMCharacterData — La classe DOMCharacterData
    • DOMChildNode — L'interface DOMChildNode
    • DOMComment — La classe DOMComment
    • DOMDocument — La classe DOMDocument
    • DOMDocumentFragment — La classe DOMDocumentFragment
    • DOMDocumentType — La classe DOMDocumentType
    • DOMElement — La classe DOMElement
    • DOMEntity — La classe DOMEntity
    • DOMEntityReference — La classe DOMEntityReference
    • DOMException — La classe DOMException
    • DOMImplementation — La classe DOMImplementation
    • DOMNamedNodeMap — La classe DOMNamedNodeMap
    • DOMNode — La classe DOMNode
    • DOMNodeList — La classe DOMNodeList
    • DOMNotation — La classe DOMNotation
    • DOMParentNode — L'interface DOMParentNode
    • DOMProcessingInstruction — La classe DOMProcessingInstruction
    • DOMText — La classe DOMText
    • DOMXPath — La classe DOMXPath
    • DOM Fonctions
  • libxml
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • libXMLError — La classe libXMLError
    • Fonctions libxml
  • SimpleXML
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Exemples
    • SimpleXMLElement — La classe SimpleXMLElement
    • SimpleXMLIterator — La classe SimpleXMLIterator
    • Fonctions SimpleXML
  • WDDX
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Exemples
    • WDDX Fonctions
  • XMLDiff — XML : Différence et fusion
    • Introduction
    • Installation/Configuration
    • XMLDiff\Base — La classe XMLDiff\Base
    • XMLDiff\DOM — La classe XMLDiff\DOM
    • XMLDiff\Memory — La classe XMLDiff\Memory
    • XMLDiff\File — La classe XMLDiff\File
  • Analyseur syntaxique XML
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • gestionnaires d'événements
    • Problèmes de casse
    • Codes d'erreurs
    • Codage des caractères
    • Exemples
    • Fonctions d'analyse de fichier XML
    • XMLParser — La classe XMLParser
  • XMLReader
    • Introduction
    • Installation/Configuration
    • XMLReader — La classe XMLReader
  • XMLWriter
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Exemples
    • XMLWriter — La classe XMLWriter
  • XSL
    • Introduction
    • Installation/Configuration
    • Constantes pré-définies
    • Exemples
    • XSLTProcessor — La classe XSLTProcessor

User Contributed Notes

There are no user contributed notes for this page.


Model Objet d'un document

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Exemples
  • DOMAttr — La classe DOMAttr
    • DOMAttr::__construct — Crée un nouvel objet DOMAttr
    • DOMAttr::isId — Vérifie si l'attribut est un identifiant défini
  • DOMCdataSection — La classe DOMCdataSection
    • DOMCdataSection::__construct — Construit un nouvel objet DOMCdataSection
  • DOMCharacterData — La classe DOMCharacterData
    • DOMCharacterData::after — Adds nodes after the character data
    • DOMCharacterData::appendData — Ajoute la chaîne à la fin des données dans le nœud
    • DOMCharacterData::before — Adds nodes before the node
    • DOMCharacterData::deleteData — Supprime une sous-chaîne dans le nœud
    • DOMCharacterData::insertData — Insère une chaîne à la position spécifiée d'unité 16-bit
    • DOMCharacterData::remove — Removes the character data
    • DOMCharacterData::replaceData — Remplace une sous-chaîne dans le nœud DOMCharacterData
    • DOMCharacterData::replaceWith — Replaces the character data with new nodes
    • DOMCharacterData::substringData — Extrait un morceau de données dans le nœud
  • DOMChildNode — L'interface DOMChildNode
    • DOMChildNode::after — Ajoute des nœuds après le nœud
    • DOMChildNode::before — Ajoute des nœuds avant le nœud
    • DOMChildNode::remove — Supprime le nœud
    • DOMChildNode::replaceWith — Remplace le nœud par de nouveaux nœuds
  • DOMComment — La classe DOMComment
    • DOMComment::__construct — Crée un nouvel objet DOMComment
  • DOMDocument — La classe DOMDocument
    • DOMDocument::adoptNode — Transfer a node from another document
    • DOMDocument::append — Appends nodes after the last child node
    • DOMDocument::__construct — Crée un nouvel objet DOMDocument
    • DOMDocument::createAttribute — Crée un nouvel attribut
    • DOMDocument::createAttributeNS — Crée un nouvel attribut avec un espace de noms associé
    • DOMDocument::createCDATASection — Crée un nouveau nœud cdata
    • DOMDocument::createComment — Crée un nouveau nœud de commentaire
    • DOMDocument::createDocumentFragment — Crée un nouveau fragment de document
    • DOMDocument::createElement — Crée un nouveau nœud
    • DOMDocument::createElementNS — Crée un nouveau nœud avec un espace de noms associé
    • DOMDocument::createEntityReference — Crée un nouveau nœud de référence d'entité
    • DOMDocument::createProcessingInstruction — Crée un nouveau nœud PI
    • DOMDocument::createTextNode — Crée un nouveau nœud de texte
    • DOMDocument::getElementById — Cherche un élément avec un certain identifiant
    • DOMDocument::getElementsByTagName — Cherche tous les éléments qui ont le nom de la balise locale donné
    • DOMDocument::getElementsByTagNameNS — Recherche tous les éléments avec un nom de balise donné dans un espace de noms spécifié
    • DOMDocument::importNode — Importe un nœud dans le document courant
    • DOMDocument::load — Charge du XML depuis un fichier
    • DOMDocument::loadHTML — Charge du code HTML à partir d'une chaîne de caractères
    • DOMDocument::loadHTMLFile — Charge du HTML à partir d'un fichier
    • DOMDocument::loadXML — Charge du XML depuis une chaîne de caractères
    • DOMDocument::normalizeDocument — Normalise le document
    • DOMDocument::prepend — Prepends nodes before the first child node
    • DOMDocument::registerNodeClass — Enregistre la classe étendue utilisée pour créer un type de base de nœud
    • DOMDocument::relaxNGValidate — Effectue une validation relaxNG sur le document
    • DOMDocument::relaxNGValidateSource — Effectue une validation relaxNG sur le document
    • DOMDocument::replaceChildren — Replace children in document
    • DOMDocument::save — Sauvegarde l'arbre interne XML dans un fichier
    • DOMDocument::saveHTML — Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML
    • DOMDocument::saveHTMLFile — Sauvegarde un document interne dans un fichier en utilisant un formatage HTML
    • DOMDocument::saveXML — Sauvegarde l'arbre interne XML dans une chaîne de caractères
    • DOMDocument::schemaValidate — Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.
    • DOMDocument::schemaValidateSource — Valide un document selon un schéma
    • DOMDocument::validate — Valide un document en se basant sur sa DTD
    • DOMDocument::xinclude — Remplace les XIncludes dans un objet DOMDocument
  • DOMDocumentFragment — La classe DOMDocumentFragment
    • DOMDocumentFragment::append — Appends nodes after the last child node
    • DOMDocumentFragment::appendXML — Ajoute des données XML
    • DOMDocumentFragment::__construct — Construit un objet DOMDocumentFragment
    • DOMDocumentFragment::prepend — Prepends nodes before the first child node
    • DOMDocumentFragment::replaceChildren — Replace children in fragment
  • DOMDocumentType — La classe DOMDocumentType
  • DOMElement — La classe DOMElement
    • DOMElement::after — Adds nodes after the element
    • DOMElement::append — Appends nodes after the last child node
    • DOMElement::before — Adds nodes before the element
    • DOMElement::__construct — Crée un nouvel objet DOMElement
    • DOMElement::getAttribute — Retourne la valeur d'un attribut
    • DOMElement::getAttributeNames — Get attribute names
    • DOMElement::getAttributeNode — Retourne le nœud d'attribut
    • DOMElement::getAttributeNodeNS — Retourne le nœud d'attribut
    • DOMElement::getAttributeNS — Retourne la valeur de l'attribut
    • DOMElement::getElementsByTagName — Retourne les éléments par leur nom de balise
    • DOMElement::getElementsByTagNameNS — Récupère les éléments par leur espace de noms et leur localName
    • DOMElement::hasAttribute — Vérifie si un attribut existe
    • DOMElement::hasAttributeNS — Vérifie si un attribut existe
    • DOMElement::insertAdjacentElement — Insert adjacent element
    • DOMElement::insertAdjacentText — Insert adjacent text
    • DOMElement::prepend — Prepends nodes before the first child node
    • DOMElement::remove — Removes the element
    • DOMElement::removeAttribute — Efface un attribut
    • DOMElement::removeAttributeNode — Efface un attribut
    • DOMElement::removeAttributeNS — Efface un attribut
    • DOMElement::replaceChildren — Replace children in element
    • DOMElement::replaceWith — Replaces the element with new nodes
    • DOMElement::setAttribute — Ajoute un nouvel attribut, ou modifie un attribut existant
    • DOMElement::setAttributeNode — Ajoute un nouvel attribut à l'élément
    • DOMElement::setAttributeNodeNS — Ajoute un nouvel attribut à l'élément
    • DOMElement::setAttributeNS — Ajoute un nouvel attribut
    • DOMElement::setIdAttribute — Déclare l'attribut spécifié par son nom à être de type ID
    • DOMElement::setIdAttributeNode — Déclare l'attribut spécifié par le nœud à être de type ID
    • DOMElement::setIdAttributeNS — Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID
    • DOMElement::toggleAttribute — Toggle attribute
  • DOMEntity — La classe DOMEntity
  • DOMEntityReference — La classe DOMEntityReference
    • DOMEntityReference::__construct — Crée un nouvel objet DOMEntityReference
  • DOMException — La classe DOMException
  • DOMImplementation — La classe DOMImplementation
    • DOMImplementation::__construct — Crée un nouvel objet DOMImplementation
    • DOMImplementation::createDocument — Crée un objet DOM Document du type spécifié avec ses éléments
    • DOMImplementation::createDocumentType — Crée un objet DOMDocumentType vide
    • DOMImplementation::hasFeature — Teste si l'implémentation DOM implémente une fonctionnalité spécifique
  • DOMNamedNodeMap — La classe DOMNamedNodeMap
    • DOMNamedNodeMap::count — Récupère le nombre de nœuds dans la collection non triée (map)
    • DOMNamedNodeMap::getIterator — Retrieve an external iterator
    • DOMNamedNodeMap::getNamedItem — Retourne un nœud spécifié par son nom
    • DOMNamedNodeMap::getNamedItemNS — Retourne un nœud spécifié par son nom local et son espace de noms
    • DOMNamedNodeMap::item — Retourne un nœud selon son index
  • DOMNode — La classe DOMNode
    • DOMNode::appendChild — Ajoute un nouveau fils à la fin des fils
    • DOMNode::C14N — Canonise des nœuds en une chaîne
    • DOMNode::C14NFile — Canonise des nœuds en fichier
    • DOMNode::cloneNode — Clone un nœud
    • DOMNode::contains — Checks if node contains other node
    • DOMNode::getLineNo — Lit le numéro de ligne d'un nœud
    • DOMNode::getNodePath — Récupère un XPath pour un nœud
    • DOMNode::getRootNode — Get root node
    • DOMNode::hasAttributes — Vérifie si le nœud possède un attribut
    • DOMNode::hasChildNodes — Vérifie si le nœud possède des enfants
    • DOMNode::insertBefore — Ajoute un nouveau fils avant un nœud de référence.
    • DOMNode::isDefaultNamespace — Vérifie si l'espace de nom spécifié est l'espace de noms par défaut ou non
    • DOMNode::isEqualNode — Checks that both nodes are equal
    • DOMNode::isSameNode — Indique si deux nœuds sont identiques
    • DOMNode::isSupported — Vérifie si la fonctionnalité est disponible pour la version spécifiée
    • DOMNode::lookupNamespaceURI — Retourne l'URI de l'espace de noms selon le préfixe
    • DOMNode::lookupPrefix — Retourne le préfixe de l'espace de noms selon l'URI de l'espace de noms
    • DOMNode::normalize — Normalise le nœud
    • DOMNode::removeChild — Supprime un fils de la liste des enfants
    • DOMNode::replaceChild — Remplace un fils
  • DOMNodeList — La classe DOMNodeList
    • DOMNodeList::count — Récupère le nombre de nœuds dans la collection triée (list)
    • DOMNodeList::getIterator — Retrieve an external iterator
    • DOMNodeList::item — Retourne un nœud spécifié par son index
  • DOMNotation — La classe DOMNotation
  • DOMParentNode — L'interface DOMParentNode
    • DOMParentNode::append — Ajoute des nœuds après le dernier nœud enfant
    • DOMParentNode::prepend — Ajoute des nœuds avant le premier nœud enfant
    • DOMParentNode::replaceChildren — Replace children in node
  • DOMProcessingInstruction — La classe DOMProcessingInstruction
    • DOMProcessingInstruction::__construct — Crée un nouvel objet DOMProcessingInstruction
  • DOMText — La classe DOMText
    • DOMText::__construct — Crée un nouvel objet DOMText
    • DOMText::isElementContentWhitespace — Rapporte si le nœud textuel contient des caractères d'espacement blanc
    • DOMText::isWhitespaceInElementContent — Indique si ce nœud de texte contient des espaces blancs
    • DOMText::splitText — Coupe le nœud en deux nœuds à l'endroit spécifié
  • DOMXPath — La classe DOMXPath
    • DOMXPath::__construct — Crée un nouvel objet DOMXPath
    • DOMXPath::evaluate — Évalue une expression XPath donnée et retourne un résultat typé si possible
    • DOMXPath::query — Évalue l'expression XPath donnée
    • DOMXPath::registerNamespace — Enregistre l'espace de noms avec l'objet DOMXPath
    • DOMXPath::registerPhpFunctions — Enregistre une fonction PHP comme fonction XPath
  • DOM Fonctions
    • dom_import_simplexml — Transforme un objet SimpleXMLElement en un objet DOMElement

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


Introduction

L'extension DOM permet d'effectuer des opérations sur les documents XML et HTML via l'API DOM de PHP.

Note:

L'extension DOM utilise l'encodage UTF-8. Utilisez mb_convert_encoding(), UConverter::transcode(), ou iconv() pour manipuler d'autres encodages.

User Contributed Notes

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=Windows-1252\"></head><body>".$body."</body></html>");
// $doc will treat your HTML correctly as UTF-8.
?>


Installation

Cette extension est activée par défaut. Elle peut être désactivée en utilisant l'option de configuration : --disable-dom

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

Constantes XML
Constante | Valeur | Description
XML_ELEMENT_NODE (int) | 1 | Le nœud est un DOMElement
XML_ATTRIBUTE_NODE (int) | 2 | Le nœud est un DOMAttr
XML_TEXT_NODE (int) | 3 | Le nœud est un DOMText
XML_CDATA_SECTION_NODE (int) | 4 | Le nœud est un DOMCharacterData
XML_ENTITY_REF_NODE (int) | 5 | Le nœud est un DOMEntityReference
XML_ENTITY_NODE (int) | 6 | Le nœud est un DOMEntity
XML_PI_NODE (int) | 7 | Le nœud est un DOMProcessingInstruction
XML_COMMENT_NODE (int) | 8 | Le nœud est un DOMComment
XML_DOCUMENT_NODE (int) | 9 | Le nœud est un DOMDocument
XML_DOCUMENT_TYPE_NODE (int) | 10 | Le nœud est un DOMDocumentType
XML_DOCUMENT_FRAG_NODE (int) | 11 | Le nœud est un DOMDocumentFragment
XML_NOTATION_NODE (int) | 12 | Le nœud est un 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 |
Constantes DOMException
Constante | Valeur | Description
DOM_PHP_ERR (int) | 0 | Code erreur ne faisant pas partie de la spécification DOM. Utilisé pour les erreurs PHP.
DOM_INDEX_SIZE_ERR (int) | 1 | Si l'index ou la taille sont négatifs ou plus grands que la valeur autorisée.
DOMSTRING_SIZE_ERR (int) | 2 | Si la rangée spécifiée de texte ne tient pas dans le DOMString.
DOM_HIERARCHY_REQUEST_ERR (int) | 3 | Si un nœud est inséré à un endroit non autorisé
DOM_WRONG_DOCUMENT_ERR (int) | 4 | Si un nœud est utilisé dans un document autre que celui qui l'a créé.
DOM_INVALID_CHARACTER_ERR (int) | 5 | Si un caractère invalide ou non autorisé est spécifié, par exemple, dans un nom.
DOM_NO_DATA_ALLOWED_ERR (int) | 6 | Si des données sont spécifiées dans un nœud qui ne supporte pas les données.
DOM_NO_MODIFICATION_ALLOWED_ERR (int) | 7 | Si une tentative est faite de modifier un objet où les modifications ne sont pas autorisées.
DOM_NOT_FOUND_ERR (int) | 8 | Si une tentative est faite de référencer un nœud dans un contexte où il n'existe pas.
DOM_NOT_SUPPORTED_ERR (int) | 9 | Si l'implémentation ne supporte pas le type requis de l'objet ou de l'opération.
DOM_INUSE_ATTRIBUTE_ERR (int) | 10 | Si une tentative est faite d'ajouter un attribut qui est déjà utilisé autre part.
DOM_INVALID_STATE_ERR (int) | 11 | Si une tentative est faite d'utiliser un objet qui n'est pas, ou n'est plus, utilisable.
DOM_SYNTAX_ERR (int) | 12 | Si une chaîne de caractères invalide ou illégale est spécifiée.
DOM_INVALID_MODIFICATION_ERR (int) | 13 | Si une tentative est faite de modifier le type d'un objet fondamental.
DOM_NAMESPACE_ERR (int) | 14 | Si une tentative est faite de créer ou de modifier un objet dans un sens qui est incorrect au regard de l'espace de noms.
DOM_INVALID_ACCESS_ERR (int) | 15 | Si un paramètre ou une opération n'est pas supporté par l'objet fondamental.
DOM_VALIDATION_ERR (int) | 16 | Si un appel à une méthode tel que insertBefore ou removeChild voudrait rendre le nœud invalide avec le respect de la validation partielle, cette exception sera exécutée et l'opération ne sera pas effectuée.

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Beaucoup d'exemples de cette documentation requièrent un fichier XML. Nous allons utiliser le fichier book.xml qui contient les élements suivants :

Exemple #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.


La classe DOMAttr

(PHP 5, PHP 7, PHP 8)

Introduction

DOMAttr représente un attribut dans l'objet DOMElement.

Synopsis de la classe

class DOMAttr extends DOMNode {
/* Propriétés */
public readonly string $name;
public readonly bool $specified = true;
public string $value;
public readonly ?DOMElement $ownerElement;
public readonly mixed $schemaTypeInfo = null;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $name, string $value = "")
public isId(): bool
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

name

Le nom de l'attribut.

ownerElement

L'élément qui contient l'attribut ou null.

schemaTypeInfo

Pas encore implémenté, vaut toujours null.

specified

Pas encore implémenté, vaut toujours null.

value

La valeur de l'attribut.

Note:

Notez que les entités XML sont étendues lorsqu'une valeur est définie. Ainsi, le caractère & a une signification spéciale. Définir valeur à lui-même échouera lorsque valeur contient un &. Pour éviter l'expansion des entités, utilisez plutôt DOMElement::setAttribute().

Voir aussi

  • » Spécification W3C de l'Attr

Sommaire

  • DOMAttr::__construct — Crée un nouvel objet DOMAttr
  • DOMAttr::isId — Vérifie si l'attribut est un identifiant défini

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


Crée un nouvel objet DOMAttr

  • « DOMAttr
  • DOMAttr::isId »
  • PHP Manual
  • DOMAttr
  • Crée un nouvel objet DOMAttr

DOMAttr::__construct

(PHP 5, PHP 7, PHP 8)

DOMAttr::__construct — Crée un nouvel objet DOMAttr

Description

public DOMAttr::__construct(string $name, string $value = "")

Crée un nouvel objet DOMAttr. Cet objet est en lecture seule. Il peut être ajouté à un document, mais les nœuds additionnels ne peuvent pas être ajoutés à ce nœud tant que ce nœud est associé à un document. Pour créer un nœud accessible en écriture, utilisez DOMDocument::createAttribute.

Liste de paramètres

name

Le nom de l'attribut.

value

La valeur de l'attribut.

Exemples

Exemple #1 Création d'un nouvel objet DOMAttr

<?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();

?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="iso-8859-1"?>
<root attr="attrvalue" />

Voir aussi

  • DOMDocument::createAttribute() - Crée un nouvel attribut

User Contributed Notes

Anonymous 18-Sep-2014 10:48
The output should be:

<?xml version="1.0" encoding="iso-8859-1"?>
<root attr="attrvalue"/>


Vérifie si l'attribut est un identifiant défini

  • « DOMAttr::__construct
  • DOMCdataSection »
  • PHP Manual
  • DOMAttr
  • Vérifie si l'attribut est un identifiant défini

DOMAttr::isId

(PHP 5, PHP 7, PHP 8)

DOMAttr::isId — Vérifie si l'attribut est un identifiant défini

Description

public DOMAttr::isId(): bool

Cette fonction vérifie si l'attribut est un identifiant défini.

En accord avec le standard DOM, ceci requiert une DTD qui définit l'attribut ID qui est du type ID. Vous devez valider votre document avec la fonction DOMDocument::validate ou la fonction DOMDocument::validateOnParse avant d'utiliser cette fonction.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec DOMAttr::isId()

<?php

$doc = new DomDocument;

// Nous devons valider notre document avant de nous référer à l'ID
$doc->validateOnParse = true;
$doc->Load('book.xml');

// Nous récupérons l'attribut nommé id de l'élément chapter
$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.


La classe DOMCdataSection

(PHP 5, PHP 7, PHP 8)

Introduction

DOMCdataSection hérite de la classe DOMText pour la représentation textuelle de la construction du bloc CData.

Synopsis de la classe

class DOMCdataSection extends DOMText {
/* Propriétés héritées */
public readonly string $wholeText;
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $data)
/* Méthodes héritées */
public DOMText::isElementContentWhitespace(): bool
public DOMText::isWhitespaceInElementContent(): bool
public DOMText::splitText(int $offset): DOMText|false
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
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 $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Sommaire

  • DOMCdataSection::__construct — Construit un nouvel objet DOMCdataSection

User Contributed Notes

There are no user contributed notes for this page.


Construit un nouvel objet DOMCdataSection

  • « DOMCdataSection
  • DOMCharacterData »
  • PHP Manual
  • DOMCdataSection
  • Construit un nouvel objet DOMCdataSection

DOMCdataSection::__construct

(PHP 5, PHP 7, PHP 8)

DOMCdataSection::__construct — Construit un nouvel objet DOMCdataSection

Description

public DOMCdataSection::__construct(string $data)

Construit un nouveau nœud CDATA. Fonctionne comme la classe DOMText.

Liste de paramètres

data

La valeur du nœud CDATA. Si non fourni, un nœud CDATA vide sera créé.

Exemples

Exemple #1 Création d'un nouvel objet DOMCdataSection

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

Voir aussi

  • DOMText::__construct() - Crée un nouvel objet DOMText
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMCharacterData

(PHP 5, PHP 7, PHP 8)

Introduction

Représente un nœud contenant des données. Aucun nœud ne correspond à cette classe, mais d'autres nœuds en hérite.

Synopsis de la classe

class DOMCharacterData extends DOMNode implements DOMChildNode {
/* Propriétés */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public after(DOMNode|string ...$nodes): void
public appendData(string $data): true
public before(DOMNode|string ...$nodes): void
public deleteData(int $offset, int $count): bool
public insertData(int $offset, string $data): bool
public remove(): void
public replaceData(int $offset, int $count, string $data): bool
public replaceWith(DOMNode|string ...$nodes): void
public substringData(int $offset, int $count): string|false
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

data

Le contenu du nœud.

length

La taille du contenu.

nextElementSibling

L'élément frère suivant ou null.

previousElementSibling

L'élément frère précédent ou null.

Historique

Version | Description
8.0.0 | Les propriétés nextElementSibling et previousElementSibling ont été ajoutées.
8.0.0 | DOMCharacterData implémente désormais DOMChildNode.

Voir aussi

  • » Spécification W3C de CharacterData

Sommaire

  • DOMCharacterData::after — Adds nodes after the character data
  • DOMCharacterData::appendData — Ajoute la chaîne à la fin des données dans le nœud
  • DOMCharacterData::before — Adds nodes before the node
  • DOMCharacterData::deleteData — Supprime une sous-chaîne dans le nœud
  • DOMCharacterData::insertData — Insère une chaîne à la position spécifiée d'unité 16-bit
  • DOMCharacterData::remove — Removes the character data
  • DOMCharacterData::replaceData — Remplace une sous-chaîne dans le nœud DOMCharacterData
  • DOMCharacterData::replaceWith — Replaces the character data with new nodes
  • DOMCharacterData::substringData — Extrait un morceau de données dans le nœud

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


Adds nodes after the character data

  • « DOMCharacterData
  • DOMCharacterData::appendData »
  • PHP Manual
  • DOMCharacterData
  • Adds nodes after the character data

DOMCharacterData::after

(PHP 8)

DOMCharacterData::after — Adds nodes after the character data

Description

public DOMCharacterData::after(DOMNode|string ...$nodes): void

Adds the passed nodes after the element.

Liste de paramètres

nodes

Nœuds à ajouter après le nœud. Les chaînes de caractères sont automatiquement convertie en des nœuds textuels.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si le parent est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans parent est désormais sans effet pour aligner le comportement sur la spécification du DOM. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMCharacterData::after() example

Adds nodes after the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->after("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container><![CDATA[hello]]>beautiful<world/></container>

Voir aussi

  • DOMChildNode::after() - Ajoute des nœuds après le nœud
  • DOMCharacterData::before() - Adds nodes before the node

User Contributed Notes

There are no user contributed notes for this page.


Ajoute la chaîne à la fin des données dans le nœud

  • « DOMCharacterData::after
  • DOMCharacterData::before »
  • PHP Manual
  • DOMCharacterData
  • Ajoute la chaîne à la fin des données dans le nœud

DOMCharacterData::appendData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::appendData — Ajoute la chaîne à la fin des données dans le nœud

Description

public DOMCharacterData::appendData(string $data): true

Ajoute la chaîne data à la fin des données dans le nœud.

Liste de paramètres

data

La chaîne à ajouter.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.3.0 | Cette fonction a désormais un type de retour tentative de true.

Voir aussi

  • DOMCharacterData::deleteData() - Supprime une sous-chaîne dans le nœud
  • DOMCharacterData::insertData() - Insère une chaîne à la position spécifiée d'unité 16-bit
  • DOMCharacterData::replaceData() - Remplace une sous-chaîne dans le nœud DOMCharacterData
  • DOMCharacterData::substringData() - Extrait un morceau de données dans le nœud

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes before the node

  • « DOMCharacterData::appendData
  • DOMCharacterData::deleteData »
  • PHP Manual
  • DOMCharacterData
  • Adds nodes before the node

DOMCharacterData::before

(PHP 8)

DOMCharacterData::before — Adds nodes before the node

Description

public DOMCharacterData::before(DOMNode|string ...$nodes): void

Adds the passed nodes before the node.

Liste de paramètres

nodes

Nœuds à ajouter avant le nœud. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si le parent est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans parent est désormais sans effet pour aligner le comportement sur la spécification du DOM. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMCharacterData::before() example

Adds nodes before the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[world]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->before("hello", $doc->createElement("beautiful"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container>hello<beautiful/><![CDATA[world]]></container>

Voir aussi

  • DOMChildNode::before() - Ajoute des nœuds avant le nœud
  • DOMCharacterData::after() - Adds nodes after the character data

User Contributed Notes

There are no user contributed notes for this page.


Supprime une sous-chaîne dans le nœud

  • « DOMCharacterData::before
  • DOMCharacterData::insertData »
  • PHP Manual
  • DOMCharacterData
  • Supprime une sous-chaîne dans le nœud

DOMCharacterData::deleteData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::deleteData — Supprime une sous-chaîne dans le nœud

Description

public DOMCharacterData::deleteData(int $offset, int $count): bool

Efface count caractères à partir de la position offset.

Liste de paramètres

offset

La position à partir de laquelle on doit commencer à effacer.

count

Le nombre de caractères à effacer. SI la somme de offset et de count excède la longueur totale de la chaîne, alors tous les caractères jusqu'à la fin de la chaîne seront effacés.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

DOM_INDEX_SIZE_ERR

Lancé si offset est négatif ou plus grand que le nombre d'unités 16-bits dans les données ou si count est négatif.

Voir aussi

  • DOMCharacterData::appendData() - Ajoute la chaîne à la fin des données dans le nœud
  • DOMCharacterData::insertData() - Insère une chaîne à la position spécifiée d'unité 16-bit
  • DOMCharacterData::replaceData() - Remplace une sous-chaîne dans le nœud DOMCharacterData
  • DOMCharacterData::substringData() - Extrait un morceau de données dans le nœud

User Contributed Notes

There are no user contributed notes for this page.


Insère une chaîne à la position spécifiée d'unité 16-bit

  • « DOMCharacterData::deleteData
  • DOMCharacterData::remove »
  • PHP Manual
  • DOMCharacterData
  • Insère une chaîne à la position spécifiée d'unité 16-bit

DOMCharacterData::insertData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::insertData — Insère une chaîne à la position spécifiée d'unité 16-bit

Description

public DOMCharacterData::insertData(int $offset, string $data): bool

Insère la chaîne data à la position offset.

Liste de paramètres

offset

La position de l'insertion.

data

La chaîne à insérer.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

DOM_INDEX_SIZE_ERR

Lancé si offset est négatif ou plus grand que le nombre d'unités 16-bits dans les données.

Voir aussi

  • DOMCharacterData::appendData() - Ajoute la chaîne à la fin des données dans le nœud
  • DOMCharacterData::deleteData() - Supprime une sous-chaîne dans le nœud
  • DOMCharacterData::replaceData() - Remplace une sous-chaîne dans le nœud DOMCharacterData
  • DOMCharacterData::substringData() - Extrait un morceau de données dans le nœud

User Contributed Notes

There are no user contributed notes for this page.


Removes the character data

  • « DOMCharacterData::insertData
  • DOMCharacterData::replaceData »
  • PHP Manual
  • DOMCharacterData
  • Removes the character data

DOMCharacterData::remove

(PHP 8)

DOMCharacterData::remove — Removes the character data

Description

public DOMCharacterData::remove(): void

Removes the character data.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 DOMCharacterData::remove() example

Removes the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]><world/></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->remove();

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container><world/></container>

Voir aussi

  • DOMChildNode::remove() - Supprime le nœud
  • DOMCharacterData::after() - Adds nodes after the character data
  • DOMCharacterData::before() - Adds nodes before the node
  • DOMCharacterData::replaceWith() - Replaces the character data with new nodes
  • DOMNode::removeChild() - Supprime un fils de la liste des enfants

User Contributed Notes

There are no user contributed notes for this page.


Remplace une sous-chaîne dans le nœud DOMCharacterData

  • « DOMCharacterData::remove
  • DOMCharacterData::replaceWith »
  • PHP Manual
  • DOMCharacterData
  • Remplace une sous-chaîne dans le nœud DOMCharacterData

DOMCharacterData::replaceData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::replaceData — Remplace une sous-chaîne dans le nœud DOMCharacterData

Description

public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool

Remplace count caractères en partant de la position offset par les données data.

Liste de paramètres

offset

La position à partir de laquelle on commence le remplacement.

count

Le nombre de caractères à remplacer. Si la somme de offset et de count excède la longueur totale de la chaîne, alors tous les caractères jusqu'à la fin des données seront remplacés.

data

La chaîne utilisée pour remplacer les caractères sélectionnés.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

DOM_INDEX_SIZE_ERR

Lancé si offset est négatif ou plus grand que le nombre d'unités 16-bits dans les données ou si count est négatif.

Voir aussi

  • DOMCharacterData::appendData() - Ajoute la chaîne à la fin des données dans le nœud
  • DOMCharacterData::deleteData() - Supprime une sous-chaîne dans le nœud
  • DOMCharacterData::insertData() - Insère une chaîne à la position spécifiée d'unité 16-bit
  • DOMCharacterData::substringData() - Extrait un morceau de données dans le nœud

User Contributed Notes

There are no user contributed notes for this page.


Replaces the character data with new nodes

  • « DOMCharacterData::replaceData
  • DOMCharacterData::substringData »
  • PHP Manual
  • DOMCharacterData
  • Replaces the character data with new nodes

DOMCharacterData::replaceWith

(PHP 8)

DOMCharacterData::replaceWith — Replaces the character data with new nodes

Description

public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void

Replaces the character data with new nodes.

Liste de paramètres

nodes

Les nœuds de remplacement.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 DOMCharacterData::replaceWith() example

Replaces the character data with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container>beautiful<world/></container>

Voir aussi

  • DOMChildNode::replaceWith() - Remplace le nœud par de nouveaux nœuds
  • DOMCharacterData::after() - Adds nodes after the character data
  • DOMCharacterData::before() - Adds nodes before the node
  • DOMCharacterData::remove() - Removes the character data

User Contributed Notes

There are no user contributed notes for this page.


Extrait un morceau de données dans le nœud

  • « DOMCharacterData::replaceWith
  • DOMChildNode »
  • PHP Manual
  • DOMCharacterData
  • Extrait un morceau de données dans le nœud

DOMCharacterData::substringData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::substringData — Extrait un morceau de données dans le nœud

Description

public DOMCharacterData::substringData(int $offset, int $count): string|false

Retourne la sous-chaîne spécifiée.

Liste de paramètres

offset

La position du début de la chaîne à extraire.

count

Le nombre de caractères à extraire.

Valeurs de retour

La sous-chaîne spécifiée. Si la somme de offset et de count excède la longueur totale de la chaîne, alors toutes les unités 16-bits jusqu'à la fin des données seront retournées.

Erreurs / Exceptions

DOM_INDEX_SIZE_ERR

Lancé si offset est négatif ou plus grand que le nombre d'unités 16-bits dans les données ou si count est négatif.

Voir aussi

  • DOMCharacterData::appendData() - Ajoute la chaîne à la fin des données dans le nœud
  • DOMCharacterData::deleteData() - Supprime une sous-chaîne dans le nœud
  • DOMCharacterData::insertData() - Insère une chaîne à la position spécifiée d'unité 16-bit
  • DOMCharacterData::replaceData() - Remplace une sous-chaîne dans le nœud DOMCharacterData

User Contributed Notes

There are no user contributed notes for this page.


L'interface DOMChildNode

(PHP 8)

Sommaire de l'Interface

interface DOMChildNode {
/* Méthodes */
public after(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public remove(): void
public replaceWith(DOMNode|string ...$nodes): void
}

Sommaire

  • DOMChildNode::after — Ajoute des nœuds après le nœud
  • DOMChildNode::before — Ajoute des nœuds avant le nœud
  • DOMChildNode::remove — Supprime le nœud
  • DOMChildNode::replaceWith — Remplace le nœud par de nouveaux nœuds

User Contributed Notes

There are no user contributed notes for this page.


Ajoute des nœuds après le nœud

  • « DOMChildNode
  • DOMChildNode::before »
  • PHP Manual
  • DOMChildNode
  • Ajoute des nœuds après le nœud

DOMChildNode::after

(PHP 8)

DOMChildNode::after — Ajoute des nœuds après le nœud

Description

public DOMChildNode::after(DOMNode|string ...$nodes): void

Ajoute les nodes passés après le nœud.

Liste de paramètres

nodes

Nœuds à ajouter après le nœud. Les chaînes de caractères sont automatiquement convertie en des nœuds textuels.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si le parent est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans parent est désormais sans effet pour aligner le comportement sur la spécification du DOM. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Voir aussi

  • DOMChildNode::before() - Ajoute des nœuds avant le nœud
  • DOMChildNode::remove() - Supprime le nœud
  • DOMChildNode::replaceWith() - Remplace le nœud par de nouveaux nœuds
  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils

User Contributed Notes

There are no user contributed notes for this page.


Ajoute des nœuds avant le nœud

  • « DOMChildNode::after
  • DOMChildNode::remove »
  • PHP Manual
  • DOMChildNode
  • Ajoute des nœuds avant le nœud

DOMChildNode::before

(PHP 8)

DOMChildNode::before — Ajoute des nœuds avant le nœud

Description

public DOMChildNode::before(DOMNode|string ...$nodes): void

Ajoute les nodes passés avant le nœud.

Liste de paramètres

nodes

Nœuds à ajouter avant le nœud. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si le parent est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans parent est désormais sans effet pour aligner le comportement sur la spécification du DOM. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Voir aussi

  • DOMChildNode::after() - Ajoute des nœuds après le nœud
  • DOMChildNode::remove() - Supprime le nœud
  • DOMChildNode::replaceWith() - Remplace le nœud par de nouveaux nœuds

User Contributed Notes

There are no user contributed notes for this page.


Supprime le nœud

  • « DOMChildNode::before
  • DOMChildNode::replaceWith »
  • PHP Manual
  • DOMChildNode
  • Supprime le nœud

DOMChildNode::remove

(PHP 8)

DOMChildNode::remove — Supprime le nœud

Description

public DOMChildNode::remove(): void

Supprime le nœud.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • DOMChildNode::after() - Ajoute des nœuds après le nœud
  • DOMChildNode::before() - Ajoute des nœuds avant le nœud
  • DOMChildNode::replaceWith() - Remplace le nœud par de nouveaux nœuds
  • DOMNode::removeChild() - Supprime un fils de la liste des enfants

User Contributed Notes

There are no user contributed notes for this page.


Remplace le nœud par de nouveaux nœuds

  • « DOMChildNode::remove
  • DOMComment »
  • PHP Manual
  • DOMChildNode
  • Remplace le nœud par de nouveaux nœuds

DOMChildNode::replaceWith

(PHP 8)

DOMChildNode::replaceWith — Remplace le nœud par de nouveaux nœuds

Description

public DOMChildNode::replaceWith(DOMNode|string ...$nodes): void

Remplace le nœud par les nouveaux nodes. Une combinaison de DOMChildNode::remove() et DOMChildNode::append().

Liste de paramètres

nodes

Les nœuds de remplacement.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • DOMChildNode::after() - Ajoute des nœuds après le nœud
  • DOMChildNode::before() - Ajoute des nœuds avant le nœud
  • DOMChildNode::remove() - Supprime le nœud
  • DOMNode::replaceChild() - Remplace un fils

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMComment

(PHP 5, PHP 7, PHP 8)

Introduction

Représente un nœud de commentaire, délimité par <!-- et -->.

Synopsis de la classe

class DOMComment extends DOMCharacterData {
/* Propriétés héritées */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $data = "")
/* Méthodes héritées */
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
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 $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Voir aussi

  • » spécification W3C de Comment

Sommaire

  • DOMComment::__construct — Crée un nouvel objet DOMComment

User Contributed Notes

npelov at croler dot net 09-Sep-2021 04:41
Note that textContent property of a comment is not entity decoded, it is decoded in DOMElement::textContent :

<?php

   $xml = new DOMDocument();
    $xml->loadXML('<?xml version="1.0" encoding="utf-8"?>
      <configuration version="2">
      <!-- test &#45;&#45;&gt; -->
      test &#45;&#45;&gt;
      </configuration>'
    );
$xpath = new DOMXPath($xml);
$comments = $xpath->query('//comment()');
$elements = $xpath->query('//configuration');

echo $comments[0]->textContent;
// result: test &#45;&#45;&gt;

echo $elements[0]->textContent;
// result: test -->

?>


Crée un nouvel objet DOMComment

  • « DOMComment
  • DOMDocument »
  • PHP Manual
  • DOMComment
  • Crée un nouvel objet DOMComment

DOMComment::__construct

(PHP 5, PHP 7, PHP 8)

DOMComment::__construct — Crée un nouvel objet DOMComment

Description

public DOMComment::__construct(string $data = "")

Crée un nouvel objet DOMComment. Cet objet est en lecture seule. Il peut être ajouté à un document, mais les nœuds additionnels ne peuvent pas être ajoutés à ce nœud tant que ce nœud n'est pas associé à un document. Pour créer un nœud accessible en écriture, utilisez DOMDocument::createComment.

Liste de paramètres

data

La valeur du commentaire.

Exemples

Exemple #1 Création d'un nouveau 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> */

?>

Voir aussi

  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMDocument

(PHP 5, PHP 7, PHP 8)

Introduction

Représente un document HTML ou XML entier ; ce sera la racine de l'arbre document.

Synopsis de la classe

class DOMDocument extends DOMNode implements DOMParentNode {
/* Propriétés */
public readonly ?DOMDocumentType $doctype;
public readonly DOMImplementation $implementation;
public readonly ?DOMElement $documentElement;
public readonly ?string $actualEncoding;
public ?string $encoding;
public readonly ?string $xmlEncoding;
public bool $standalone;
public bool $xmlStandalone;
public ?string $version;
public ?string $xmlVersion;
public bool $strictErrorChecking;
public ?string $documentURI;
public readonly mixed $config;
public bool $formatOutput;
public bool $validateOnParse;
public bool $resolveExternals;
public bool $preserveWhiteSpace;
public bool $recover;
public bool $substituteEntities;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $version = "1.0", string $encoding = "")
public adoptNode(DOMNode $node): DOMNode|false
public append(DOMNode|string ...$nodes): void
public createAttribute(string $localName): DOMAttr|false
public createAttributeNS(?string $namespace, string $qualifiedName): DOMAttr|false
public createCDATASection(string $data): DOMCdataSection|false
public createComment(string $data): DOMComment
public createDocumentFragment(): DOMDocumentFragment
public createElement(string $localName, string $value = ""): DOMElement|false
public createElementNS(?string $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
public getElementById(string $elementId): ?DOMElement
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): bool
public loadHTML(string $source, int $options = 0): bool
public loadHTMLFile(string $filename, int $options = 0): bool
public loadXML(string $source, int $options = 0): bool
public normalizeDocument(): void
public prepend(DOMNode|string ...$nodes): void
public registerNodeClass(string $baseClass, ?string $extendedClass): bool
public relaxNGValidate(string $filename): bool
public relaxNGValidateSource(string $source): bool
public replaceChildren(DOMNode|string ...$nodes): void
public save(string $filename, int $options = 0): int|false
public saveHTML(?DOMNode $node = null): string|false
public saveHTMLFile(string $filename): int|false
public saveXML(?DOMNode $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
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

actualEncoding

Obsolète. L'encodage actuel du document, en lecture seule, équivalent à encoding.

childElementCount

Le nombre d'éléments enfants.

config

Obsolète. Configuration utilisée lorsque DOMDocument::normalizeDocument() est appelé.

doctype

Le Document Type Declaration associé avec ce document.

documentElement

L'objet DOMElement qui est le premier élément du document. S'il n'est pas trouvé, ceci est évalué à null.

documentURI

La localisation du document, ou null si indéfini.

encoding

L'encodage du document, tel que spécifié par la déclaration XML. Cet attribut n'est pas présent dans la spécification DOM Level 3 finale, mais représente la seule façon de manipuler l'encodage du document XML dans cette implémentation.

firstElementChild

Premier élément enfant ou null.

formatOutput

Formate élégamment le résultat avec une indentation et des espaces supplémentaires. Ce paramètre n'a aucun effet si le document a été chargé avec l'activation de preserveWhitespace.

implementation

L'objet DOMImplementation qui gère ce document.

lastElementChild

Dernier élément enfant ou null.

preserveWhiteSpace

Ne pas supprimer les espaces redondants. Vaut par défaut true. Définir ce paramètre à false a le même effet de définir à LIBXML_NOBLANKS le paramètre option de la méthode DOMDocument::load().

recover

Propriétaire. Active le mode "recovery", i.e. tente d'analyser un document mal formé. Cet attribut ne fait pas partie de la spécification DOM et est spécifique à libxml.

resolveExternals

Définissez-le à true pour charger des entités externes depuis la déclaration doctype. C'est utile pour inclure des entités dans vos documents XML.

standalone

Obsolète. Si le document est "standalone", ou non, tel que spécifié par la déclaration XML, correspondant à xmlStandalone.

strictErrorChecking

Lance une DOMException en cas d'erreur. Par défaut, vaut true.

substituteEntities

Propriétaire. Si l'on doit ou non substituer les entités. Cet attribut ne fait pas partie de la spécification DOM et est spécifique à libxml. Par défaut, false

Attention

Activer la substitution d'entités peut faciliter les attaques XML External Entity (XXE).

validateOnParse

Charge et valide la DTD. Par défaut, vaut false.

Attention

Activer la validation du DTD peut faciliter les attaques XML External Entity (XXE).

version

Obsolète. Version du XML, correspond à xmlVersion.

xmlEncoding

Un attribut spécifiant l'encodage du document. Il vaut null lorsque l'encodage n'est pas spécifié, ou lorsqu'il est inconnu, comme c'est le cas lorsque le document a été créé en mémoire.

xmlStandalone

Un attribut spécifiant si le document est "standalone". Il vaut false lorsque non spécifié.

xmlVersion

Un attribut spécifiant le numéro de version du document. S'il n'y a pas de déclaration et si le document supporte la fonctionnalité "XML", la valeur sera "1.0".

Historique

Version | Description
8.0.0 | DOMDocument implémente désormais DOMParentNode.
8.0.0 | La méthode non-implémenté DOMDocument::renameNode() a été retirée.

Notes

Note:

L'extension DOM utilise l'encodage UTF-8. Utilisez mb_convert_encoding(), UConverter::transcode(), ou iconv() pour manipuler d'autres encodages.

Note:

Lors de l'utilisation de json_encode() sur un objet DOMDocument le résultat sera celui d'encoder un objet vide.

Voir aussi

  • » Spécification W3C de Document

Sommaire

  • DOMDocument::adoptNode — Transfer a node from another document
  • DOMDocument::append — Appends nodes after the last child node
  • DOMDocument::__construct — Crée un nouvel objet DOMDocument
  • DOMDocument::createAttribute — Crée un nouvel attribut
  • DOMDocument::createAttributeNS — Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection — Crée un nouveau nœud cdata
  • DOMDocument::createComment — Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment — Crée un nouveau fragment de document
  • DOMDocument::createElement — Crée un nouveau nœud
  • DOMDocument::createElementNS — Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference — Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction — Crée un nouveau nœud PI
  • DOMDocument::createTextNode — Crée un nouveau nœud de texte
  • DOMDocument::getElementById — Cherche un élément avec un certain identifiant
  • DOMDocument::getElementsByTagName — Cherche tous les éléments qui ont le nom de la balise locale donné
  • DOMDocument::getElementsByTagNameNS — Recherche tous les éléments avec un nom de balise donné dans un espace de noms spécifié
  • DOMDocument::importNode — Importe un nœud dans le document courant
  • DOMDocument::load — Charge du XML depuis un fichier
  • DOMDocument::loadHTML — Charge du code HTML à partir d'une chaîne de caractères
  • DOMDocument::loadHTMLFile — Charge du HTML à partir d'un fichier
  • DOMDocument::loadXML — Charge du XML depuis une chaîne de caractères
  • DOMDocument::normalizeDocument — Normalise le document
  • DOMDocument::prepend — Prepends nodes before the first child node
  • DOMDocument::registerNodeClass — Enregistre la classe étendue utilisée pour créer un type de base de nœud
  • DOMDocument::relaxNGValidate — Effectue une validation relaxNG sur le document
  • DOMDocument::relaxNGValidateSource — Effectue une validation relaxNG sur le document
  • DOMDocument::replaceChildren — Replace children in document
  • DOMDocument::save — Sauvegarde l'arbre interne XML dans un fichier
  • DOMDocument::saveHTML — Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML
  • DOMDocument::saveHTMLFile — Sauvegarde un document interne dans un fichier en utilisant un formatage HTML
  • DOMDocument::saveXML — Sauvegarde l'arbre interne XML dans une chaîne de caractères
  • DOMDocument::schemaValidate — Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.
  • DOMDocument::schemaValidateSource — Valide un document selon un schéma
  • DOMDocument::validate — Valide un document en se basant sur sa DTD
  • DOMDocument::xinclude — Remplace les XIncludes dans un objet DOMDocument

User Contributed Notes

610010559 at qq dot com 17-Mar-2022 02:39
when you add the new element to formatted XML data through appendChild() method, you would the new element you add is not be formatted(that is not indexed, not line break).  here is my solution (in short load the xml without preserve white space, ), example show as below:
<?php
$doc = new \DOMDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;//that is key, default value is true.
$doc->loadXML($xmlStr);
$doc->appendChild($doc->createElement('php', '666'))
$formattedXMLStr = $doc->saveXML();//DOMDocument wold format the xml str for you
echo $formattedXMlStr;
?>
it take me some time to try it out. hope it save your time.
andreas at userbrain dot com 17-Nov-2021 01:16
After struggling with parsing and modifying partial HTML content for several hours, I came to this solution which does work for me and is relatively simple compared to what else I found online.

This solution fixes unwanted DOCTYPE and html, body tags as well as encoding issues.

<?php

// Assumption: content is utf-8 encoded
$content = "<h1>This is a heading</h1><p>This is a paragraph</p>";

// Load content to a div and specify encoding with a meta tag
$temp_dom = new DOMDocument();
$temp_dom->loadHTML("<meta http-equiv='Content-Type' content='CHARSET=Windows-1252' /><div>$content</div>");

// As loadHTML() adds a DOCTYPE as well as <html> and <body> tag, let’s create another DOMDocument and import just the nodes we want
$dom = new DOMDocument();
$first_div = $temp_dom->getElementsByTagName('div')[0];
$first_div_node = $dom->importNode($first_div, true);
$dom->appendChild($first_div_node);

// Do whatever you want to do
$dom->getElementsByTagName('h1')[0]->setAttribute('class', 'happy');

// You could also just echo $dom->saveHtml() if you don’t mind the div and whitespace
echo substr(trim($dom->saveHtml()), 5, -6);

// Outputs: <h1 class="happy">This is a heading</h1><p>This is a paragraph</p>
?>
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 );
?>


Transfer a node from another document

  • « DOMDocument
  • DOMDocument::append »
  • PHP Manual
  • DOMDocument
  • Transfer a node from another document

DOMDocument::adoptNode

(PHP >= 8.3)

DOMDocument::adoptNode — Transfer a node from another document

Description

public DOMDocument::adoptNode(DOMNode $node): DOMNode|false

Transfer a node from another document into the current document.

Liste de paramètres

node

The node to transfer.

Valeurs de retour

The node that was transfered, or false on error.

Erreurs / Exceptions

DOM_NOT_SUPPORTED_ERR

Raised if the node type is not supported for document transfers.

Exemples

Exemple #1 DOMDocument::adoptNode() example

Transfers the hello element from the first document to the second one.

<?php
$doc1 = new DOMDocument;
$doc1->loadXML("<container><hello><world/></hello></container>");
$hello = $doc1->documentElement->firstChild;

$doc2 = new DOMDocument;
$doc2->loadXML("<root/>");
$doc2->documentElement->appendChild($doc2->adoptNode($hello));

echo $doc1->saveXML() . PHP_EOL;
echo $doc2->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container/>

<?xml version="1.0"?>
<root><hello><world/></hello></root>

Voir aussi

  • DOMDocument::importNode() - Importe un nœud dans le document courant

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • « DOMDocument::adoptNode
  • DOMDocument::__construct »
  • PHP Manual
  • DOMDocument
  • Appends nodes after the last child node

DOMDocument::append

(PHP 8)

DOMDocument::append — Appends nodes after the last child node

Description

public DOMDocument::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMDocument::append() example

Adds nodes after the document root.

<?php
$doc = new DOMDocument;
$doc->loadXML("<hello/>");

$doc->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<hello/>
beautiful
<world/>

Voir aussi

  • DOMParentNode::append() - Ajoute des nœuds après le dernier nœud enfant
  • DOMDocument::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Crée un nouvel objet DOMDocument

  • « DOMDocument::append
  • DOMDocument::createAttribute »
  • PHP Manual
  • DOMDocument
  • Crée un nouvel objet DOMDocument

DOMDocument::__construct

(PHP 5, PHP 7, PHP 8)

DOMDocument::__construct — Crée un nouvel objet DOMDocument

Description

public DOMDocument::__construct(string $version = "1.0", string $encoding = "")

Crée un nouvel objet DOMDocument.

Liste de paramètres

version

Le numéro de version du document en tant que partie de la déclaration XML.

encoding

L'encodage du document en tant que partie de la déclaration XML.

Exemples

Exemple #1 Création d'un nouveau DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

Voir aussi

  • DOMImplementation::createDocument() - Crée un objet DOM Document du type spécifié avec ses éléments

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.


Crée un nouvel attribut

  • « DOMDocument::__construct
  • DOMDocument::createAttributeNS »
  • PHP Manual
  • DOMDocument
  • Crée un nouvel attribut

DOMDocument::createAttribute

(PHP 5, PHP 7, PHP 8)

DOMDocument::createAttribute — Crée un nouvel attribut

Description

public DOMDocument::createAttribute(string $localName): DOMAttr|false

Cette fonction crée une nouvelle instance de la classe DOMAttr. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

localName

Le nom de l'attribut.

Valeurs de retour

Le nouveau DOMAttr ou false si une erreur survient.

Erreurs / Exceptions

DOM_INVALID_CHARACTER_ERR

Émise si localName contient un caractère invalide.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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>


Crée un nouvel attribut avec un espace de noms associé

  • « DOMDocument::createAttribute
  • DOMDocument::createCDATASection »
  • PHP Manual
  • DOMDocument
  • Crée un nouvel attribut avec un espace de noms associé

DOMDocument::createAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createAttributeNS — Crée un nouvel attribut avec un espace de noms associé

Description

public DOMDocument::createAttributeNS(?string $namespace, string $qualifiedName): DOMAttr|false

Cette fonction crée une nouvelle instance de la classe DOMAttr. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

namespace

L'URI de l'espace de noms.

qualifiedName

Le nom de la balise et le préfixe de l'attribut, sous cette forme : préfixe:nomBalise.

Valeurs de retour

Le nouveau DOMAttr ou false si une erreur survient.

Erreurs / Exceptions

DOM_INVALID_CHARACTER_ERR

Lancé si qualifiedName contient un caractère invalide.

DOM_NAMESPACE_ERR

Lancé si qualifiedName est un nom qualifié malformé ou si qualifiedName a un suffixe et que namespace est null.

Historique

Version | Description
8.3.0 | Appeler cette méthode sans spécifier un préfixe choisira désormais un préfixe au lieu de supposer l'espace de noms par défaut. Auparavant, cela créait un attribut sans préfixe et appliquait incorrectement l'espace de noms à l'élément propriétaire car les espaces de noms par défaut ne s'appliquent pas aux attributs.
8.3.0 | Appeler cette méthode en utilisant un préfixe déjà déclaré sur l'élément propriétaire avec un URI d'espace de noms différent changera désormais le nouveau préfixe pour éviter de créer des conflits d'espace de noms. Cela aligne le comportement sur la spécification du DOM. Auparavant, cela déclenchait une DOMException avec le code DOM_NAMESPACE_ERR.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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>

    */

?>


Crée un nouveau nœud cdata

  • « DOMDocument::createAttributeNS
  • DOMDocument::createComment »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau nœud cdata

DOMDocument::createCDATASection

(PHP 5, PHP 7, PHP 8)

DOMDocument::createCDATASection — Crée un nouveau nœud cdata

Description

public DOMDocument::createCDATASection(string $data): DOMCdataSection|false

Cette fonction crée une nouvelle instance de la classe DOMCDATASection. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

data

Le contenu du cdata.

Valeurs de retour

Le nouveau DOMCDATASection ou false si une erreur survient.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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);
}
?>


Crée un nouveau nœud de commentaire

  • « DOMDocument::createCDATASection
  • DOMDocument::createDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau nœud de commentaire

DOMDocument::createComment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createComment — Crée un nouveau nœud de commentaire

Description

public DOMDocument::createComment(string $data): DOMComment

Cette fonction crée une nouvelle instance de la classe DOMComment. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

data

Le contenu du commentaire.

Valeurs de retour

Le nouveau DOMComment.

Historique

Version | Description
8.1.0 | En cas d'erreur, une DomException est désormais lancée. Auparavant, false était retourné.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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.


Crée un nouveau fragment de document

  • « DOMDocument::createComment
  • DOMDocument::createElement »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau fragment de document

DOMDocument::createDocumentFragment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createDocumentFragment — Crée un nouveau fragment de document

Description

public DOMDocument::createDocumentFragment(): DOMDocumentFragment

Cette fonction crée une nouvelle instance de la classe DOMDocumentFragment. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Le nouveau DOMDocumentFragment.

Historique

Version | Description
8.1.0 | En cas d'erreur, une DomException est désormais lancée. Auparavant, false était retourné.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

User Contributed Notes

info at ensostudio dot ru 14-Dec-2021 07:37
You can use fragments to set inner HTML:
<?php
$dom = new DOMImplementation();
$document = $dom->createDocument(null, 'html', $dom->createDocumentType('html'));

$div = $document->appendChild($document->createElement('div', '<small>test</small> me'));
echo $document->saveHTML($div);
// <div>&lt;small&gt;test&lt;/small&gt; me</div>

$div = $document->appendChild($document->createElement('div'));
$div->nodeValue = '<small>test</small> me';
echo $document->saveHTML($div);
// <div>&lt;small&gt;test&lt;/small&gt; me</div>

$div = $document->appendChild($document->createElement('div'));
$divInner = $document->createDocumentFragment();
$divInner->appendXML('<small>test</small> me');
$div->appendChild($divInner);
echo $document->saveHTML($div);
// <div><small>test</small> me</div>

?>


Crée un nouveau nœud

  • « DOMDocument::createDocumentFragment
  • DOMDocument::createElementNS »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau nœud

DOMDocument::createElement

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElement — Crée un nouveau nœud

Description

public DOMDocument::createElement(string $localName, string $value = ""): DOMElement|false

Cette fonction crée une nouvelle instance de la classe DOMElement. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

name

Le nom du tag de l'élément.

value

La valeur de l'élément. Par défaut, un élément vide sera créé. La valeur peut également être définie plus tard avec DOMElement::$nodeValue.

La valeur est utilisé textuellement à l'exception des références d'entités < et > qui seront échappées. Notez que & doit être échappé manuellement ; sinon ceci est considéré comme le début d'une référence d'entité. De plus " ne sera pas échappé.

Valeurs de retour

Retourne une nouvelle instance de la classe DOMElement ou false si une erreur survient.

Erreurs / Exceptions

DOM_INVALID_CHARACTER_ERR

Lancé si localName contient un caractère invalide.

Exemples

Exemple #1 Création d'un nouvel élément et insertion en tant que racine

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'Ceci est l\'élément racine !');

// Nous insérons le nouvel élément en tant que racine (enfant du document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="utf-8"?>
<test>Ceci est l'élément racine !</test>

Exemple #2 Passer comme value du texte contenant & non échappé

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('foo', 'me & you');
$dom->appendChild($element);
echo $dom->saveXML();
?>

Résultat de l'exemple ci-dessus est similaire à :

Warning: DOMDocument::createElement(): unterminated entity reference             you in /in/BjTCg on line 4
<?xml version="1.0" encoding="utf-8"?>
<foo/>

Notes

Note:

La valeur value ne sera pas échappée. Utilisez la méthode DOMDocument::createTextNode() pour créer un nœud de texte avec le support de l'échappement.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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))
//...
?>


Crée un nouveau nœud avec un espace de noms associé

  • « DOMDocument::createElement
  • DOMDocument::createEntityReference »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau nœud avec un espace de noms associé

DOMDocument::createElementNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElementNS — Crée un nouveau nœud avec un espace de noms associé

Description

public DOMDocument::createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false

Cette fonction crée un nouveau nœud avec un espace de noms associé. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

namespace

L'URI de l'espace de noms.

qualifiedName

Le nom qualifié de l'élément, en tant que préfixe:nomBalise.

value

La valeur de l'élément. Par défaut, un élément vide sera créé. Vous pouvez également définir la valeur plus tard en utilisant la fonction DOMElement::$nodeValue.

Valeurs de retour

Un nouveau DOMElement ou false si une erreur survient.

Erreurs / Exceptions

DOM_INVALID_CHARACTER_ERR

Lancé si qualifiedName contient un caractère invalide.

DOM_NAMESPACE_ERR

Lancé si qualifiedName est un nom qualifié malformé.

Exemples

Exemple #1 Création d'un nouvel élément et insertion en tant que racine

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'Ceci est l\'élément racine !');

// Nous insérons le nouvel élément en tant que racine (fils du document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="iso-8859-1"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">Ceci est l'élément racine !</xfoo:test>

Exemple #2 Un exemple avec un espace de noms en préfixe

<?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"; // Affiche : http://base.google.com/ns/1.0
echo $item->prefix, "\n"; // Affiche : g
echo $item->localName, "\n"; // Affiche : item_type
?>

L'exemple ci-dessus va afficher :

<?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

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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).


Crée un nouveau nœud de référence d'entité

  • « DOMDocument::createElementNS
  • DOMDocument::createProcessingInstruction »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau nœud de référence d'entité

DOMDocument::createEntityReference

(PHP 5, PHP 7, PHP 8)

DOMDocument::createEntityReference — Crée un nouveau nœud de référence d'entité

Description

public DOMDocument::createEntityReference(string $name): DOMEntityReference|false

Cette fonction crée une nouvelle instance de la classe DOMEntityReference. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

name

Le contenu de la référence de l'entité, e.g. la référence de l'entité sans le & initial et le ; final.

Valeurs de retour

Le nouveau DOMEntityReference ou false si une erreur survient.

Erreurs / Exceptions

DOM_INVALID_CHARACTER_ERR

Émise si name contient un caractère invalide.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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 ©


Crée un nouveau nœud PI

  • « DOMDocument::createEntityReference
  • DOMDocument::createTextNode »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau nœud PI

DOMDocument::createProcessingInstruction

(PHP 5, PHP 7, PHP 8)

DOMDocument::createProcessingInstruction — Crée un nouveau nœud PI

Description

public DOMDocument::createProcessingInstruction(string $target, string $data = ""): DOMProcessingInstruction|false

Cette fonction crée une nouvelle instance de la classe DOMProcessingInstruction. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

target

La cible de l'instruction gérée.

data

Le contenu de l'instruction gérée.

Valeurs de retour

Le nouveau DOMProcessingInstruction ou false si une erreur survient.

Erreurs / Exceptions

DOM_INVALID_CHARACTER_ERR

Emise si target contient un caractère invalide.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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>


Crée un nouveau nœud de texte

  • « DOMDocument::createProcessingInstruction
  • DOMDocument::getElementById »
  • PHP Manual
  • DOMDocument
  • Crée un nouveau nœud de texte

DOMDocument::createTextNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::createTextNode — Crée un nouveau nœud de texte

Description

public DOMDocument::createTextNode(string $data): DOMText

Cette fonction crée une nouvelle instance de la classe DOMText. Ce nœud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode::appendChild().

Liste de paramètres

data

Le contenu du texte.

Valeurs de retour

Un nouveau DOMText.

Historique

Version | Description
8.1.0 | En cas d'erreur, une DomException est désormais lancée. Auparavant, false était retourné.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMDocument::createAttribute() - Crée un nouvel attribut
  • DOMDocument::createAttributeNS() - Crée un nouvel attribut avec un espace de noms associé
  • DOMDocument::createCDATASection() - Crée un nouveau nœud cdata
  • DOMDocument::createComment() - Crée un nouveau nœud de commentaire
  • DOMDocument::createDocumentFragment() - Crée un nouveau fragment de document
  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé
  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité
  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI

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);
?>


Cherche un élément avec un certain identifiant

  • « DOMDocument::createTextNode
  • DOMDocument::getElementsByTagName »
  • PHP Manual
  • DOMDocument
  • Cherche un élément avec un certain identifiant

DOMDocument::getElementById

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementById — Cherche un élément avec un certain identifiant

Description

public DOMDocument::getElementById(string $elementId): ?DOMElement

Cette fonction est similaire à la fonction DOMDocument::getElementsByTagName mais cherche un élément avec un identifiant donné.

Pour que cette fonction fonctionne, vous devez soit définir les attributs ID avec DOMElement::setIdAttribute ou définir une DTD qui définit un attribut devant être de type ID. Dans le dernier cas, vous devez valider votre document avec DOMDocument::validate ou DOMDocument::$validateOnParse avant d'utiliser cette fonction.

Liste de paramètres

elementId

La valeur de l'identifiant unique pour un élément.

Valeurs de retour

Retourne un DOMElement ou null si l'élément n'est pas trouvé.

Exemples

Exemple #1 Exemple avec DOMDocument::getElementById()

L'exemple suivant utilise le fichier book.xml, dont le contenu est :

<?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;

// Nous devons valider notre document avant de nous référer à l'ID
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "L'élément dont l'ID est 'php-basics' est : " . $doc->getElementById('php-basics')->tagName . "\n";

?>

L'exemple ci-dessus va afficher :

L'élément dont l'ID est 'php-basics' est : chapter

Voir aussi

  • DOMDocument::getElementsByTagName() - Cherche tous les éléments qui ont le nom de la balise locale donné

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.


Cherche tous les éléments qui ont le nom de la balise locale donné

  • « DOMDocument::getElementById
  • DOMDocument::getElementsByTagNameNS »
  • PHP Manual
  • DOMDocument
  • Cherche tous les éléments qui ont le nom de la balise locale donné

DOMDocument::getElementsByTagName

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementsByTagName — Cherche tous les éléments qui ont le nom de la balise locale donné

Description

public DOMDocument::getElementsByTagName(string $qualifiedName): DOMNodeList

Cette fonction retourne une instance de la classe DOMNodeList contenant tous les éléments qui ont un nom de balise donné.

Liste de paramètres

qualifiedName

Le nom local (sans espace de nommage) de la balise à chercher. La valeur spéciale * correspond à toutes les balises.

Valeurs de retour

Un nouvel objet DOMNodeList contenant tous les éléments correspondants.

Exemples

Exemple #1 Exemple de base

<?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;
}
?>

L'exemple ci-dessus va afficher :

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

Voir aussi

  • DOMDocument::getElementsByTagNameNS() - Recherche tous les éléments avec un nom de balise donné dans un espace de noms spécifié

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


Recherche tous les éléments avec un nom de balise donné dans un espace de noms spécifié

  • « DOMDocument::getElementsByTagName
  • DOMDocument::importNode »
  • PHP Manual
  • DOMDocument
  • Recherche tous les éléments avec un nom de balise donné dans un espace de noms spécifié

DOMDocument::getElementsByTagNameNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementsByTagNameNS — Recherche tous les éléments avec un nom de balise donné dans un espace de noms spécifié

Description

public DOMDocument::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

Retourne un DOMNodeList de tous les éléments avec un nom local donné et une URI d'espace de noms.

Liste de paramètres

namespace

L'URI de l'espace de noms des éléments à chercher. La valeur spéciale "*" représente tous les espaces de noms. Passer null représente l'espace de noms vide.

localName

Le nom local des éléments à chercher. La valeur spéciale "*" représente tous les noms locaux.

Valeurs de retour

Un nouvel objet DOMNodeList contenant tous les éléments trouvés.

Historique

Version | Description
8.0.3 | namespace est désormais nullable.

Exemples

Exemple #1 Récupération de tous les éléments XInclude

<?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";
}
?>

L'exemple ci-dessus va afficher :

local name: include, prefix: xi
local name: fallback, prefix: xi

Voir aussi

  • DOMDocument::getElementsByTagName() - Cherche tous les éléments qui ont le nom de la balise locale donné

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
*/
?>


Importe un nœud dans le document courant

  • « DOMDocument::getElementsByTagNameNS
  • DOMDocument::load »
  • PHP Manual
  • DOMDocument
  • Importe un nœud dans le document courant

DOMDocument::importNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::importNode — Importe un nœud dans le document courant

Description

public DOMDocument::importNode(DOMNode $node, bool $deep = false): DOMNode|false

Cette fonction retourne une copie du nœud à importer et l'associe avec le document courant.

Liste de paramètres

node

Le nœud à importer.

deep

Si défini à true, cette méthode importera récursivement le sous-arbre situé sous le nœud node.

Note:

Pour copier les attributs des nœuds, le paramètre deep doit être défini à true

Valeurs de retour

Le nœud copié ou false si la copie a échouée.

Erreurs / Exceptions

DOMException est lancé si le nœud ne peut pas être importé.

Exemples

Exemple #1 Exemple avec DOMDocument::importNode()

Copie de nœuds entre plusieurs documents.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>Texte dans un fils</child></element></root>");

// Le nœud que nous voulons importer dans le nouveau document
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Création du nouveau document
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Ajout de quelques balises
$newdoc->loadXML("<root><someelement>Texte dans un élément</someelement></root>");

echo "Le nouveau document avant d'y copier le nœud :\n";
echo $newdoc->saveXML();

// Importation du nœud, ainsi que tous ses files, dans le document
$node = $newdoc->importNode($node, true);
// Et on l'ajoute dans le le nœud racine "<root>"
$newdoc->documentElement->appendChild($node);

echo "\nLe nouveau document après y avoir copié les nœuds :\n";
echo $newdoc->saveXML();
?>

L'exemple ci-dessus va afficher :

Le nouveau document avant d'y copier le nœud :
<?xml version="1.0"?>
<root>
  <someelement>Texte dans un élément</someelement>
</root>

Le nouveau document après y avoir copié les nœuds :
<?xml version="1.0"?>
<root>
  <someelement>Texte dans un élément</someelement>
  <element>
    <child>Texte dans un fils</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);
?>


Charge du XML depuis un fichier

  • « DOMDocument::importNode
  • DOMDocument::loadHTML »
  • PHP Manual
  • DOMDocument
  • Charge du XML depuis un fichier

DOMDocument::load

(PHP 5, PHP 7, PHP 8)

DOMDocument::load — Charge du XML depuis un fichier

Description

public DOMDocument::load(string $filename, int $options = 0): bool

Charge un document XML depuis un fichier.

Avertissement

Les chemins de style Unix avec des antislash peuvent conduire à des réductions de performance sous les systèmes Windows ; assurez-vous d'appeler la fonction realpath().

Liste de paramètres

filename

Le chemin vers le document XML.

options

L'opérateur OR des constantes d'options libxml.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

Si une chaîne vide est passée comme paramètre filename ou si le fichier est vide, une alerte sera générée. Cette alerte n'est pas générée par libxml, et ne peut être gérée en utilisant les fonctions de gestion d'erreur de libxml.

Historique

Version | Description
8.3.0 | Cette fonction a maintenant un type de retour bool provisoire.
8.0.0 | Appeler cette fonction de manière statique lèvera désormais une Error. Auparavant, une erreur E_DEPRECATED était générée.

Exemples

Exemple #1 Création d'un Document

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

Voir aussi

  • DOMDocument::loadXML() - Charge du XML depuis une chaîne de caractères
  • DOMDocument::save() - Sauvegarde l'arbre interne XML dans un fichier
  • DOMDocument::saveXML() - Sauvegarde l'arbre interne XML dans une chaîne de caractères

User Contributed Notes

Raf-sns 11-Nov-2023 06:19
Be carreful with the option "preserveWhiteSpace"

$dom = new DOMDocument;
// false -> this preserve white spaces
// true -> this will put all entries inline
$dom->preserveWhiteSpace = false;  // preserve white space !
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);
?>


Charge du code HTML à partir d'une chaîne de caractères

  • « DOMDocument::load
  • DOMDocument::loadHTMLFile »
  • PHP Manual
  • DOMDocument
  • Charge du code HTML à partir d'une chaîne de caractères

DOMDocument::loadHTML

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadHTML — Charge du code HTML à partir d'une chaîne de caractères

Description

public DOMDocument::loadHTML(string $source, int $options = 0): bool

Cette fonction analyse un document HTML contenu dans la chaîne source. Contrairement au XML, le HTML n'a pas besoin d'être bien formé pour être chargé.

Avertissement

Cette fonction analyse l'entrée à l'aide d'un analyseur HTML 4. Les règles d'analyse de HTML 5, que les navigateurs modernes utilisent, sont différentes. En fonction de l'entrée, il peut en résulter une structure DOM différente. Par conséquent, cette fonction ne peut pas être utilisée en toute sécurité pour assainir le code HTML.

Par exemple, certains éléments HTML fermeront implicitement un élément parent lorsqu'ils seront rencontrés. Les règles de fermeture automatique des éléments parents diffèrent entre HTML 4 et HTML 5, de sorte que la structure DOM que DOMDocument voit peut être différente de la structure DOM qu'un navigateur web voit, ce qui peut permettre à un attaquant de briser le code HTML résultant.

Liste de paramètres

source

La chaîne HTML.

options

Opération de 'OU' logique des constantes d'option libxml.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

Si une chaîne vide est passée comme paramètre source, une alerte sera générée. Cette alerte n'est pas générée par libxml, et ne peut être gérée en utilisant les fonctions de gestion d'erreur de libxml.

Bien que le HTML mal-formé devrait se charger avec succès, cette fonction peut générer une alerte de type E_WARNING lorsqu'elle rencontre une mauvaise balise. Les fonctions de gestion des erreurs libxml peuvent être utilisées pour gérer ces erreurs.

Historique

Version | Description
8.3.0 | Cette fonction a maintenant un type de retour bool provisoire.
8.0.0 | Appeler cette fonction de manière statique lèvera désormais une Error. Auparavant, une erreur E_DEPRECATED était générée.

Exemples

Exemple #1 Création d'un document

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

Voir aussi

  • DOMDocument::loadHTMLFile() - Charge du HTML à partir d'un fichier
  • DOMDocument::saveHTML() - Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML
  • DOMDocument::saveHTMLFile() - Sauvegarde un document interne dans un fichier en utilisant un formatage HTML

User Contributed Notes

Anonymous 19-May-2022 04:05
loadHTML() & loadHTMLFile() may always generate warnings if the html include some tags such as "nav, section, footer, etc" adopted as of HTML5 (in PHP 8.1.6).

Try to run below.

<?php

$file_name = 'PHP Runtime Configuration - Manual.html'; // Download this file from "https://www.php.net/manual/en/session.configuration.php" in advance.

$doc = new DOMDocument();
$doc->loadHTMLFile($file_name); // if set "LIBXML_NOERROR" as 2nd arg, no error
echo $doc->saveHTML();

// Warning: DOMDocument::loadHTMLFile(): Tag nav invalid in PHP Runtime Configuration - Manual.html, line: 63 in D:\xampp\htdocs\test\xml(dom)\loadHTML\index.php on line 6

?>
obayed dot opu at gmail dot com 10-Dec-2021 09:58
To support HTML5 you have to disable xml error handling by add `LIBXML_NOERROR` as an option of loadHTML method.

Example:

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><section>I'M UNSUPPORTED</section></body></html>", LIBXML_NOERROR);
echo $doc->saveHTML();
?>
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=Windows-1252">

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=Windows-1252">
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=Windows-1252">

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=Windows-1252">
    <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=Windows-1252">
  </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áº¡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=Windows-1252"/>
</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.


Charge du HTML à partir d'un fichier

  • « DOMDocument::loadHTML
  • DOMDocument::loadXML »
  • PHP Manual
  • DOMDocument
  • Charge du HTML à partir d'un fichier

DOMDocument::loadHTMLFile

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadHTMLFile — Charge du HTML à partir d'un fichier

Description

public DOMDocument::loadHTMLFile(string $filename, int $options = 0): bool

Cette fonction analyse un document HTML contenu dans le fichier filename. Contrairement au XML, le HTML n'a pas besoin d'être bien formé pour être chargé.

Avertissement

Cette fonction analyse l'entrée à l'aide d'un analyseur HTML 4. Les règles d'analyse de HTML 5, que les navigateurs modernes utilisent, sont différentes. En fonction de l'entrée, il peut en résulter une structure DOM différente. Par conséquent, cette fonction ne peut pas être utilisée en toute sécurité pour assainir le code HTML.

Par exemple, certains éléments HTML fermeront implicitement un élément parent lorsqu'ils seront rencontrés. Les règles de fermeture automatique des éléments parents diffèrent entre HTML 4 et HTML 5, de sorte que la structure DOM que DOMDocument voit peut être différente de la structure DOM qu'un navigateur web voit, ce qui peut permettre à un attaquant de briser le code HTML résultant.

Liste de paramètres

filename

Le chemin vers le fichier HTML.

options

Opération de 'OU' logique des constantes d'option libxml.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

Si une chaîne vide est passée comme paramètre filename ou que le fichier est vide, une alerte sera générée. Cette alerte n'est pas générée par libxml, et ne peut être gérée en utilisant les fonctions de gestion d'erreur de libxml.

Bien que le HTML mal-formé devrait se charger avec succès, cette fonction peut générer une alerte de type E_WARNING lorsqu'elle rencontre une mauvaise balise. Les fonctions de gestion des erreurs libxml peuvent être utilisées pour gérer ces erreurs.

Historique

Version | Description
8.3.0 | Cette fonction a maintenant un type de retour bool provisoire.
8.0.0 | Appeler cette fonction de manière statique lèvera désormais une Error. Auparavant, une erreur E_DEPRECATED était générée.

Exemples

Exemple #1 Création d'un document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Voir aussi

  • DOMDocument::loadHTML() - Charge du code HTML à partir d'une chaîne de caractères
  • DOMDocument::saveHTML() - Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML
  • DOMDocument::saveHTMLFile() - Sauvegarde un document interne dans un fichier en utilisant un formatage HTML

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.


Charge du XML depuis une chaîne de caractères

  • « DOMDocument::loadHTMLFile
  • DOMDocument::normalizeDocument »
  • PHP Manual
  • DOMDocument
  • Charge du XML depuis une chaîne de caractères

DOMDocument::loadXML

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadXML — Charge du XML depuis une chaîne de caractères

Description

public DOMDocument::loadXML(string $source, int $options = 0): bool

Charge un document XML depuis une chaîne de caractères.

Liste de paramètres

source

La chaîne de caractères contenant le XML.

options

L'opérateur OR des constantes libxml.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

Si une chaîne vide est passée comme paramètre source, une alerte sera générée. Cette alerte n'est pas générée par libxml, et ne peut être gérée en utilisant les fonctions de gestion d'erreur de libxml.

Historique

Version | Description
8.3.0 | Cette fonction a maintenant un type de retour bool provisoire.
8.0.0 | L'appel statique de cette fonction lèvera désormais une Error. Auparavant, une erreur E_DEPRECATED était générée.

Exemples

Exemple #1 Création d'un Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Voir aussi

  • DOMDocument::load() - Charge du XML depuis un fichier
  • DOMDocument::save() - Sauvegarde l'arbre interne XML dans un fichier
  • DOMDocument::saveXML() - Sauvegarde l'arbre interne XML dans une chaîne de caractères

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.


Normalise le document

  • « DOMDocument::loadXML
  • DOMDocument::prepend »
  • PHP Manual
  • DOMDocument
  • Normalise le document

DOMDocument::normalizeDocument

(PHP 5, PHP 7, PHP 8)

DOMDocument::normalizeDocument — Normalise le document

Description

public DOMDocument::normalizeDocument(): void

Cette méthode fonctionne comme si vous sauvegardiez le document puis vous le chargiez de nouveau, rendant le document sous une forme "normale".

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • » La spécification DOM
  • DOMNode::normalize() - Normalise le nœud

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.


Prepends nodes before the first child node

  • « DOMDocument::normalizeDocument
  • DOMDocument::registerNodeClass »
  • PHP Manual
  • DOMDocument
  • Prepends nodes before the first child node

DOMDocument::prepend

(PHP 8)

DOMDocument::prepend — Prepends nodes before the first child node

Description

public DOMDocument::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMDocument::prepend() example

Adds nodes before the document root.

<?php
$doc = new DOMDocument;
$doc->loadXML("<world/>");

$doc->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<hello/>
beautiful
<world/>

Voir aussi

  • DOMParentNode::prepend() - Ajoute des nœuds avant le premier nœud enfant
  • DOMDocument::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Enregistre la classe étendue utilisée pour créer un type de base de nœud

  • « DOMDocument::prepend
  • DOMDocument::relaxNGValidate »
  • PHP Manual
  • DOMDocument
  • Enregistre la classe étendue utilisée pour créer un type de base de nœud

DOMDocument::registerNodeClass

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMDocument::registerNodeClass — Enregistre la classe étendue utilisée pour créer un type de base de nœud

Description

public DOMDocument::registerNodeClass(string $baseClass, ?string $extendedClass): bool

Cette méthode vous permet d'enregistrer votre propre classe étendue DOM à utiliser ensuite dans l'extension DOM de PHP.

Cette méthode ne fait pas partie du standard DOM.

Attention

Les constructeur des objets des classes de nœud enregistré ne sont pas appelé.

Liste de paramètres

baseClass

La classe DOM qui vous voulez étendre. Vous pouvez trouver une liste de ces classes dans l'introduction du chapitre.

extendedClass

Le nom de votre classe étendue. Si la valeur null est fournie, toutes les classes enregistrées précédemment étendant baseClass seront supprimées.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Ajout d'un nouvelle méthode à DOMElement

<?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');

// À partir d'ici, l'ajout d'un élément à un autre se fait en un seul appel !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Exemple #2 Récupération d'éléments sous la forme d'une classe personnalisée

<?php
class myElement extends DOMElement {
public function __toString() {
return $this->nodeValue;
}
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>Text dans un fils</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// Et utilisons les avantages de la méthode __toString..
echo $element;
?>

L'exemple ci-dessus va afficher :

string(9) "myElement"
Text dans un fils

Exemple #3 Récupération du propriétaire du document

Lors de l'instanciation d'un DOMDocument personnalisé, la propriété ownerDocument se réfère à la classe instanciée. Cependant, si toutes les références à cette classe sont supprimées, elle sera détruite et une nouvelle instance de DOMDocument sera créée à la place. Pour cette raison, vous pouvez utiliser la méthode DOMDocument::registerNodeClass() avec DOMDocument

<?php
class MyDOMDocument extends DOMDocument {
}

class MyOtherDOMDocument extends DOMDocument {
}

// Création d'un document MyDOMDocument avec quelques fragments XML
$doc = new MyDOMDocument;
$doc->loadXML("<root><element><child>texte dans un fils</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// Le propriétaire courant du nœud est MyDOMDocument
var_dump(get_class($child->ownerDocument));
// MyDOMDocument est détruit
unset($doc);
// Et une nouvelle instance de DOMDocument est créée
var_dump(get_class($child->ownerDocument));

// Importation d'un nœud depuis MyDOMDocument
$newdoc = new MyOtherDOMDocument;
$child = $newdoc->importNode($child);

// Enregistre un DOMDocument personnalisé
$newdoc->registerNodeClass("DOMDocument", "MyOtherDOMDocument");

var_dump(get_class($child->ownerDocument));
unset($doc);
// Un nouveau MyOtherDOMDocument est créé
var_dump(get_class($child->ownerDocument));
?>

L'exemple ci-dessus va afficher :

string(13) "MyDOMDocument"
string(11) "DOMDocument"
string(18) "MyOtherDOMDocument"
string(18) "MyOtherDOMDocument"

Exemple #4 Les objets personalisé sont éphémère

Attention

Les objets de la classe de noeux registré sont éphém_re, c.à.d. ils sont détruit quand ils ne sont plus référencer depuis du code PHP, et recréé quand ils sont denouveaux récupérer. Ceci implque que des valeurs de propriétés personalisé seront perdu après la recréation.

<?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;
?>

L'exemple ci-dessus va afficher :

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().


Effectue une validation relaxNG sur le document

  • « DOMDocument::registerNodeClass
  • DOMDocument::relaxNGValidateSource »
  • PHP Manual
  • DOMDocument
  • Effectue une validation relaxNG sur le document

DOMDocument::relaxNGValidate

(PHP 5, PHP 7, PHP 8)

DOMDocument::relaxNGValidate — Effectue une validation relaxNG sur le document

Description

public DOMDocument::relaxNGValidate(string $filename): bool

Effectue une validation » relaxNG sur le document selon le schéma RNG défini par filename.

Liste de paramètres

filename

Le fichier RNG.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMDocument::relaxNGValidateSource() - Effectue une validation relaxNG sur le document
  • DOMDocument::schemaValidate() - Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.
  • DOMDocument::schemaValidateSource() - Valide un document selon un schéma
  • DOMDocument::validate() - Valide un document en se basant sur sa 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!


Effectue une validation relaxNG sur le document

  • « DOMDocument::relaxNGValidate
  • DOMDocument::replaceChildren »
  • PHP Manual
  • DOMDocument
  • Effectue une validation relaxNG sur le document

DOMDocument::relaxNGValidateSource

(PHP 5, PHP 7, PHP 8)

DOMDocument::relaxNGValidateSource — Effectue une validation relaxNG sur le document

Description

public DOMDocument::relaxNGValidateSource(string $source): bool

Effectue une validation » relaxNG sur le document selon le schéma RNG défini dans la chaîne source.

Liste de paramètres

source

Une chaîne contenant le schéma RNG.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMDocument::relaxNGValidate() - Effectue une validation relaxNG sur le document
  • DOMDocument::schemaValidate() - Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.
  • DOMDocument::schemaValidateSource() - Valide un document selon un schéma
  • DOMDocument::validate() - Valide un document en se basant sur sa DTD

User Contributed Notes

There are no user contributed notes for this page.


Replace children in document

  • « DOMDocument::relaxNGValidateSource
  • DOMDocument::save »
  • PHP Manual
  • DOMDocument
  • Replace children in document

DOMDocument::replaceChildren

(PHP 8 >= 8.3.0)

DOMDocument::replaceChildren — Replace children in document

Description

public DOMDocument::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the document with new nodes.

Liste de paramètres

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMDocument::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");

$doc->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
beautiful
<world/>

Voir aussi

  • DOMParentNode::replaceChildren() - Replace children in node
  • DOMDocument::append() - Appends nodes after the last child node
  • DOMDocument::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Sauvegarde l'arbre interne XML dans un fichier

  • « DOMDocument::replaceChildren
  • DOMDocument::saveHTML »
  • PHP Manual
  • DOMDocument
  • Sauvegarde l'arbre interne XML dans un fichier

DOMDocument::save

(PHP 5, PHP 7, PHP 8)

DOMDocument::save — Sauvegarde l'arbre interne XML dans un fichier

Description

public DOMDocument::save(string $filename, int $options = 0): int|false

Crée un document XML depuis la représentation DOM. Cette fonction est habituellement appelée après la construction d'un nouveau document DOM, comme dans l'exemple ci-dessous.

Liste de paramètres

filename

Le chemin où sera sauvegardé le document XML.

options

Options additionnelles. Actuellement, seul LIBXML_NOEMPTYTAG est supporté.

Valeurs de retour

Retourne le nombre d'octets écrit ou false si une erreur survient.

Exemples

Exemple #1 Sauvegarde d'un arbre DOM dans un fichier

<?php

$doc = new DOMDocument('1.0');
// nous voulons un bel affichage
$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 'Écrit : ' . $doc->save("/tmp/test.xml") . ' bytes'; // Écrit : 72 bytes

?>

Voir aussi

  • DOMDocument::save()
  • DOMDocument::load() - Charge du XML depuis un fichier
  • DOMDocument::loadXML() - Charge du XML depuis une chaîne de caractères

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


Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML

  • « DOMDocument::save
  • DOMDocument::saveHTMLFile »
  • PHP Manual
  • DOMDocument
  • Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML

DOMDocument::saveHTML

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveHTML — Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML

Description

public DOMDocument::saveHTML(?DOMNode $node = null): string|false

Crée un document HTML depuis une représentation DOM. Cette fonction est habituellement appelée après la construction d'un tout nouveau document DOM, comme dans l'exemple ci-dessous.

Liste de paramètres

node

Paramètre optionnel pour afficher une portion du document.

Valeurs de retour

Retourne le code HTML ou false si une erreur survient.

Exemples

Exemple #1 Sauvegarde d'un arbre HTML dans une chaîne de caractères

<?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('Ceci est le titre');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

Voir aussi

  • DOMDocument::saveHTML()
  • DOMDocument::loadHTML() - Charge du code HTML à partir d'une chaîne de caractères
  • DOMDocument::loadHTMLFile() - Charge du HTML à partir d'un fichier

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=Windows-1252" 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.
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();
}
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> */

?>
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;
}
?>
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>


Sauvegarde un document interne dans un fichier en utilisant un formatage HTML

  • « DOMDocument::saveHTML
  • DOMDocument::saveXML »
  • PHP Manual
  • DOMDocument
  • Sauvegarde un document interne dans un fichier en utilisant un formatage HTML

DOMDocument::saveHTMLFile

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveHTMLFile — Sauvegarde un document interne dans un fichier en utilisant un formatage HTML

Description

public DOMDocument::saveHTMLFile(string $filename): int|false

Crée un document HTML depuis une représentation DOM. Cette fonction est habituellement appelée après la construction d'un tout nouveau document DOM, comme dans l'exemple ci-dessous.

Liste de paramètres

filename

Le chemin où l'on doit sauvegarder le document HTML.

Valeurs de retour

Retourne le nombre d'octets écrit ou false si une erreur survient.

Exemples

Exemple #1 Sauvegarde d'un arbre HTML dans un fichier

<?php

$doc = new DOMDocument('1.0');
// nous voulons un joli affichage
$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('Ceci est le titre');
$text = $title->appendChild($text);

echo 'Écrit : ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Écrit : 129 bytes

?>

Voir aussi

  • DOMDocument::saveHTML() - Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML
  • DOMDocument::loadHTML() - Charge du code HTML à partir d'une chaîne de caractères
  • DOMDocument::loadHTMLFile() - Charge du HTML à partir d'un fichier

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=Windows-1252">
<title>Russian language</title>
</head>
<body>Ðóññêèé ÿçûê</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=Windows-1252">
<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=Windows-1252"><title>Test</title></head><body></body></html>

?>
Note that saveHTMLFile() adds a UTF-8 meta tag despite the ISO-8859-1 document encoding.


Sauvegarde l'arbre interne XML dans une chaîne de caractères

  • « DOMDocument::saveHTMLFile
  • DOMDocument::schemaValidate »
  • PHP Manual
  • DOMDocument
  • Sauvegarde l'arbre interne XML dans une chaîne de caractères

DOMDocument::saveXML

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveXML — Sauvegarde l'arbre interne XML dans une chaîne de caractères

Description

public DOMDocument::saveXML(?DOMNode $node = null, int $options = 0): string|false

Crée un document XML depuis la représentation DOM. Cette fonction est habituellement appelée après la création d'un tout nouveau document DOM, comme dans l'exemple ci-dessous.

Liste de paramètres

node

Utilisez ce paramètre pour afficher uniquement un nœud spécifique sans déclaration XML plutôt que la totalité du document.

options

Options additionnelles. Les options LIBXML_NOEMPTYTAG et LIBXML_NOXMLDECL sont supportées. Antérieur à PHP 8.3.0, uniquement l'option LIBXML_NOEMPTYTAG est supporté.

Valeurs de retour

Retourne le XML ou false si une erreur survient.

Erreurs / Exceptions

DOM_WRONG_DOCUMENT_ERR

Lancé si node est issu d'un autre document.

Historique

Version | Description
8.3.0 | LIBXML_NOXMLDECL est désormais supporté.

Exemples

Exemple #1 Sauvegarde de l'arbre DOM dans une chaîne de caractères

<?php

$doc = new DOMDocument('1.0');
// nous voulons un joli affichage
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('Ceci est le titre');
$text = $title->appendChild($text);

echo "Récupération de tout le document :\n";
echo $doc->saveXML() . "\n";

echo "Récupération du titre, uniquement :\n";
echo $doc->saveXML($title);

?>

L'exemple ci-dessus va afficher :

Récupération de tout le document :
<?xml version="1.0"?>
<book>
  <title>Ceci est le titre</title>
</book>

Récupération du titre, uniquement :
<title>Ceci est le titre</title>

Voir aussi

  • DOMDocument::save() - Sauvegarde l'arbre interne XML dans un fichier
  • DOMDocument::load() - Charge du XML depuis un fichier
  • DOMDocument::loadXML() - Charge du XML depuis une chaîne de caractères

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.


Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.

  • « DOMDocument::saveXML
  • DOMDocument::schemaValidateSource »
  • PHP Manual
  • DOMDocument
  • Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.

DOMDocument::schemaValidate

(PHP 5, PHP 7, PHP 8)

DOMDocument::schemaValidate — Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.

Description

public DOMDocument::schemaValidate(string $filename, int $flags = 0): bool

Valide un document selon un schéma contenu dans un fichier donné.

Liste de paramètres

filename

Le chemin vers le fichier contenant le schéma.

flags

Un masque de drapeaux de validation du schéma Libxml. Actuellement, la seule valeur supportée est LIBXML_SCHEMA_CREATE. Disponible depuis Libxml 2.6.14.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMDocument::schemaValidateSource() - Valide un document selon un schéma
  • DOMDocument::relaxNGValidate() - Effectue une validation relaxNG sur le document
  • DOMDocument::relaxNGValidateSource() - Effectue une validation relaxNG sur le document
  • DOMDocument::validate() - Valide un document en se basant sur sa 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


Valide un document selon un schéma

  • « DOMDocument::schemaValidate
  • DOMDocument::validate »
  • PHP Manual
  • DOMDocument
  • Valide un document selon un schéma

DOMDocument::schemaValidateSource

(PHP 5, PHP 7, PHP 8)

DOMDocument::schemaValidateSource — Valide un document selon un schéma

Description

public DOMDocument::schemaValidateSource(string $source, int $flags = 0): bool

Valide un document selon le schéma défini dans la chaîne donnée.

Liste de paramètres

source

Une chaîne contenant le schéma.

flags

Un masque de drapeau de validation de schéma Libxml. Actuellement, la seule valeur supportée est LIBXML_SCHEMA_CREATE. Disponible depuis Libxml 2.6.14.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMDocument::schemaValidate() - Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.
  • DOMDocument::relaxNGValidate() - Effectue une validation relaxNG sur le document
  • DOMDocument::relaxNGValidateSource() - Effectue une validation relaxNG sur le document
  • DOMDocument::validate() - Valide un document en se basant sur sa DTD

User Contributed Notes

There are no user contributed notes for this page.


Valide un document en se basant sur sa DTD

  • « DOMDocument::schemaValidateSource
  • DOMDocument::xinclude »
  • PHP Manual
  • DOMDocument
  • Valide un document en se basant sur sa DTD

DOMDocument::validate

(PHP 5, PHP 7, PHP 8)

DOMDocument::validate — Valide un document en se basant sur sa DTD

Description

public DOMDocument::validate(): bool

Valide un document en se basant sur sa DTD.

Vous pouvez utiliser la propriété validateOnParse de la classe DOMDocument pour effectuer une validation DTD.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient. Si le document n'a aucune DTD d'attachée, cette méthode retournera false.

Exemples

Exemple #1 Exemple de validation DTD

<?php
$dom = new DOMDocument;
$dom->load('book.xml');
if ($dom->validate()) {
echo "Ce document est valide !\n";
}
?>

Vous pouvez également valider votre fichier XML en le chargeant :

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->load('book.xml');
?>

Voir aussi

  • DOMDocument::schemaValidate() - Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.
  • DOMDocument::schemaValidateSource() - Valide un document selon un schéma
  • DOMDocument::relaxNGValidate() - Effectue une validation relaxNG sur le document
  • DOMDocument::relaxNGValidateSource() - Effectue une validation relaxNG sur le 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();
?>


Remplace les XIncludes dans un objet DOMDocument

  • « DOMDocument::validate
  • DOMDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Remplace les XIncludes dans un objet DOMDocument

DOMDocument::xinclude

(PHP 5, PHP 7, PHP 8)

DOMDocument::xinclude — Remplace les XIncludes dans un objet DOMDocument

Description

public DOMDocument::xinclude(int $options = 0): int|false

Cette méthode remplace les » XIncludes dans un objet DOMDocument.

Note:

Vu que la bibliothèque libxml2 résout automatiquement les entités, cette méthode peut produire des résultats non attendus si le fichier XML inclus a une DTD d'attachée.

Liste de paramètres

options

Opération de 'OU' logique des constantes d'option libxml.

Valeurs de retour

Retourne le nombre de XIncludes du document, -1 si une erreur survient lors du processus, ou false s'il n'y a aucune substitution.

Exemples

Exemple #1 Exemple avec DOMDocument::xinclude()

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Les livres d'une autre personne</title>
<para>
<xi:include href="book.xml">
<xi:fallback>
<error>xinclude: book.xml n'a pas été trouvé</error>
</xi:fallback>
</xi:include>
</para>
</chapter>
EOD;

$dom = new DOMDocument;

// Nous voulons un joli affichage
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// chargement de la chaîne XML définie ci-dessus
$dom->loadXML($xml);

// remplacement des xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

Résultat de l'exemple ci-dessus est similaire à :

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Les livres d'une autre personne</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();

?>


La classe DOMDocumentFragment

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMDocumentFragment extends DOMNode implements DOMParentNode {
/* Propriétés */
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct()
public append(DOMNode|string ...$nodes): void
public appendXML(string $data): bool
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

childElementCount

Le nombre d'éléments enfants.

firstElementChild

Premier élément enfant ou null.

lastElementChild

Dernier élément enfant ou null.

Historique

Version | Description
8.0.0 | Les propriétés firstElementChild, lastElementChild et childElementCount ont été ajoutées.
8.0.0 | DOMDocumentFragment implémente désormais DOMParentNode.

Sommaire

  • DOMDocumentFragment::append — Appends nodes after the last child node
  • DOMDocumentFragment::appendXML — Ajoute des données XML
  • DOMDocumentFragment::__construct — Construit un objet DOMDocumentFragment
  • DOMDocumentFragment::prepend — Prepends nodes before the first child node
  • DOMDocumentFragment::replaceChildren — Replace children in fragment

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) {
}


Appends nodes after the last child node

  • « DOMDocumentFragment
  • DOMDocumentFragment::appendXML »
  • PHP Manual
  • DOMDocumentFragment
  • Appends nodes after the last child node

DOMDocumentFragment::append

(PHP 8)

DOMDocumentFragment::append — Appends nodes after the last child node

Description

public DOMDocumentFragment::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMDocumentFragment::append() example

Appends nodes in the fragment.

<?php
$doc = new DOMDocument;
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement("hello"));

$fragment->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML($fragment);
?>

L'exemple ci-dessus va afficher :

<hello/>beautiful<world/>

Voir aussi

  • DOMParentNode::append() - Ajoute des nœuds après le dernier nœud enfant
  • DOMDocumentFragment::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Ajoute des données XML

  • « DOMDocumentFragment::append
  • DOMDocumentFragment::__construct »
  • PHP Manual
  • DOMDocumentFragment
  • Ajoute des données XML

DOMDocumentFragment::appendXML

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

DOMDocumentFragment::appendXML — Ajoute des données XML

Description

public DOMDocumentFragment::appendXML(string $data): bool

Ajoute des données XML brutes à un DOMDocumentFragment.

Cette méthode ne fait pas partie du standard DOM. Elle a été créée pour simplifier l'ajout d'un fragment XML dans un DOMDocument.

Si vous voulez respecter les standards, vous devez créer un DOMDocument temporaire avec une racine et parcourir les nœuds enfants de vos données XML pour les ajouter.

Liste de paramètres

data

XML à ajouter.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Ajout de données XML à votre 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();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

User Contributed Notes

Thanks to Christoph. 07-Jun-2022 01:50
Strings such as " ' & < > may need to be escaped in advance.
In that case, you can use htmlspecialchars().
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


Construit un objet DOMDocumentFragment

  • « DOMDocumentFragment::appendXML
  • DOMDocumentFragment::prepend »
  • PHP Manual
  • DOMDocumentFragment
  • Construit un objet DOMDocumentFragment

DOMDocumentFragment::__construct

(PHP 5, PHP 7, PHP 8)

DOMDocumentFragment::__construct — Construit un objet DOMDocumentFragment

Description

public DOMDocumentFragment::__construct()

Liste de paramètres

Cette fonction ne contient aucun paramètre.

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • « DOMDocumentFragment::__construct
  • DOMDocumentFragment::replaceChildren »
  • PHP Manual
  • DOMDocumentFragment
  • Prepends nodes before the first child node

DOMDocumentFragment::prepend

(PHP 8)

DOMDocumentFragment::prepend — Prepends nodes before the first child node

Description

public DOMDocumentFragment::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMDocumentFragment::prepend() example

Prepends nodes before the fragment root.

<?php
$doc = new DOMDocument;
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement("world"));

$fragment->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML($fragment);
?>

L'exemple ci-dessus va afficher :

<hello/>beautiful<world/>

Voir aussi

  • DOMParentNode::prepend() - Ajoute des nœuds avant le premier nœud enfant
  • DOMDocumentFragment::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Replace children in fragment

  • « DOMDocumentFragment::prepend
  • DOMDocumentType »
  • PHP Manual
  • DOMDocumentFragment
  • Replace children in fragment

DOMDocumentFragment::replaceChildren

(PHP 8 >= 8.3.0)

DOMDocumentFragment::replaceChildren — Replace children in fragment

Description

public DOMDocumentFragment::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the document fragment with new nodes.

Liste de paramètres

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMDocumentFragment::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$fragment = $doc->createDocumentFragment();
$fragment->append("hello");

$fragment->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML($fragment);
?>

L'exemple ci-dessus va afficher :

beautiful
<world/>

Voir aussi

  • DOMParentNode::replaceChildren() - Replace children in node
  • DOMDocumentFragment::append() - Appends nodes after the last child node
  • DOMDocumentFragment::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMDocumentType

(PHP 5, PHP 7, PHP 8)

Introduction

Chaque DOMDocument a un attribut doctype dont la valeur est soit null, soit un objet DOMDocumentType.

Synopsis de la classe

class DOMDocumentType extends DOMNode {
/* Propriétés */
public readonly string $name;
public readonly DOMNamedNodeMap $entities;
public readonly DOMNamedNodeMap $notations;
public readonly string $publicId;
public readonly string $systemId;
public readonly ?string $internalSubset;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

publicId

L'identifiant public du subset externe.

systemId

L'identifiant système du subset externe. Ce peut être une URI absolue ou non.

name

Le nom de la DTD ; i.e., le nom suivant immédiatement le mot clé DOCTYPE.

entities

Un DOMNamedNodeMap contenant l'entité général, à la fois externe et interne, déclaré dans la DTD.

notations

Un DOMNamedNodeMap contenant les notations, déclarées dans la DTD.

internalSubset

Le subset interne, sous la forme d'une chaîne de caractères, ou null s'il n'y en a pas. Cette chaîne ne contient pas les crochets délimiteurs.

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMElement

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* Propriétés */
public readonly string $tagName;
public string $className;
public string $id;
public readonly mixed $schemaTypeInfo = null;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $qualifiedName, ?string $value = null, string $namespace = "")
public after(DOMNode|string ...$nodes): void
public append(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public getAttribute(string $qualifiedName): string
public getAttributeNames(): array
public getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false
public getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null
public getAttributeNS(?string $namespace, string $localName): string
public getElementsByTagName(string $qualifiedName): DOMNodeList
public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList
public hasAttribute(string $qualifiedName): bool
public hasAttributeNS(?string $namespace, string $localName): bool
public insertAdjacentElement(string $where, DOMElement $element): ?DOMElement
public insertAdjacentText(string $where, string $data): void
public prepend(DOMNode|string ...$nodes): void
public remove(): void
public removeAttribute(string $qualifiedName): bool
public removeAttributeNode(DOMAttr $attr): DOMAttr|false
public removeAttributeNS(?string $namespace, string $localName): void
public replaceChildren(DOMNode|string ...$nodes): void
public replaceWith(DOMNode|string ...$nodes): 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 $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 toggleAttribute(string $qualifiedName, ?bool $force = null): bool
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

childElementCount

Le nombre d'éléments enfants.

firstElementChild

Premier élément enfant ou null.

lastElementChild

Dernier élément enfant ou null.

nextElementSibling

L'élément frère suivant ou null.

previousElementSibling

L'élément frère précédent ou null.

schemaTypeInfo

Pas encore implémenté, retourne toujours null

tagName

Le nom de l'élément

className

Une chaîne représentant les classes de l'élément, séparé par des espaces

id

L'ID de l'élément

Historique

Version | Description
8.0.0 | Les propriétés firstElementChild, lastElementChild, childElementCount, previousElementSibling et nextElementSibling ont été ajoutées.
8.0.0 | DOMElement implémente désormais DOMParentNode et DOMChildNode.

Notes

Note:

L'extension DOM utilise l'encodage UTF-8. Utilisez mb_convert_encoding(), UConverter::transcode(), ou iconv() pour manipuler d'autres encodages.

Sommaire

  • DOMElement::after — Adds nodes after the element
  • DOMElement::append — Appends nodes after the last child node
  • DOMElement::before — Adds nodes before the element
  • DOMElement::__construct — Crée un nouvel objet DOMElement
  • DOMElement::getAttribute — Retourne la valeur d'un attribut
  • DOMElement::getAttributeNames — Get attribute names
  • DOMElement::getAttributeNode — Retourne le nœud d'attribut
  • DOMElement::getAttributeNodeNS — Retourne le nœud d'attribut
  • DOMElement::getAttributeNS — Retourne la valeur de l'attribut
  • DOMElement::getElementsByTagName — Retourne les éléments par leur nom de balise
  • DOMElement::getElementsByTagNameNS — Récupère les éléments par leur espace de noms et leur localName
  • DOMElement::hasAttribute — Vérifie si un attribut existe
  • DOMElement::hasAttributeNS — Vérifie si un attribut existe
  • DOMElement::insertAdjacentElement — Insert adjacent element
  • DOMElement::insertAdjacentText — Insert adjacent text
  • DOMElement::prepend — Prepends nodes before the first child node
  • DOMElement::remove — Removes the element
  • DOMElement::removeAttribute — Efface un attribut
  • DOMElement::removeAttributeNode — Efface un attribut
  • DOMElement::removeAttributeNS — Efface un attribut
  • DOMElement::replaceChildren — Replace children in element
  • DOMElement::replaceWith — Replaces the element with new nodes
  • DOMElement::setAttribute — Ajoute un nouvel attribut, ou modifie un attribut existant
  • DOMElement::setAttributeNode — Ajoute un nouvel attribut à l'élément
  • DOMElement::setAttributeNodeNS — Ajoute un nouvel attribut à l'élément
  • DOMElement::setAttributeNS — Ajoute un nouvel attribut
  • DOMElement::setIdAttribute — Déclare l'attribut spécifié par son nom à être de type ID
  • DOMElement::setIdAttributeNode — Déclare l'attribut spécifié par le nœud à être de type ID
  • DOMElement::setIdAttributeNS — Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID
  • DOMElement::toggleAttribute — Toggle attribute

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


Adds nodes after the element

  • « DOMElement
  • DOMElement::append »
  • PHP Manual
  • DOMElement
  • Adds nodes after the element

DOMElement::after

(PHP 8)

DOMElement::after — Adds nodes after the element

Description

public DOMElement::after(DOMNode|string ...$nodes): void

Adds the passed nodes after the element.

Liste de paramètres

nodes

Nœuds à ajouter après le nœud. Les chaînes de caractères sont automatiquement convertie en des nœuds textuels.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si le parent est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans parent est désormais sans effet pour aligner le comportement sur la spécification du DOM. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMElement::after() example

Adds nodes after the hello element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<hello/>");
$container = $doc->documentElement;

$container->after("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<hello/>
beautiful
<world/>

Voir aussi

  • DOMChildNode::after() - Ajoute des nœuds après le nœud
  • DOMElement::before() - Adds nodes before the element

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • « DOMElement::after
  • DOMElement::before »
  • PHP Manual
  • DOMElement
  • Appends nodes after the last child node

DOMElement::append

(PHP 8)

DOMElement::append — Appends nodes after the last child node

Description

public DOMElement::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMElement::append() example

Appends nodes in the container element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container>hello </container>");
$world = $doc->documentElement;

$world->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container>hello beautiful<world/></container>

Voir aussi

  • DOMParentNode::append() - Ajoute des nœuds après le dernier nœud enfant
  • DOMElement::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes before the element

  • « DOMElement::append
  • DOMElement::__construct »
  • PHP Manual
  • DOMElement
  • Adds nodes before the element

DOMElement::before

(PHP 8)

DOMElement::before — Adds nodes before the element

Description

public DOMElement::before(DOMNode|string ...$nodes): void

Adds the passed nodes before the element.

Liste de paramètres

nodes

Nœuds à ajouter avant le nœud. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si le parent est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans parent est désormais sans effet pour aligner le comportement sur la spécification du DOM. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMElement::before() example

Adds nodes before the hello element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<world/>");
$world = $doc->documentElement;

$world->before("hello", $doc->createElement("beautiful"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

hello
<beautiful/>
<world/>

Voir aussi

  • DOMChildNode::before() - Ajoute des nœuds avant le nœud
  • DOMElement::after() - Adds nodes after the element

User Contributed Notes

There are no user contributed notes for this page.


Crée un nouvel objet DOMElement

  • « DOMElement::before
  • DOMElement::getAttribute »
  • PHP Manual
  • DOMElement
  • Crée un nouvel objet DOMElement

DOMElement::__construct

(PHP 5, PHP 7, PHP 8)

DOMElement::__construct — Crée un nouvel objet DOMElement

Description

public DOMElement::__construct(string $qualifiedName, ?string $value = null, string $namespace = "")

Crée un nouvel objet DOMElement. Cet objet est en lecture seule. Il peut être ajouté à un document, mais les nœuds additionnels ne peuvent pas être ajoutés à ce nœud tant qu'il est associé à un document. Pour créer un nœud accessible en écriture, utilisez DOMDocument::createElement ou DOMDocument::createElementNS.

Liste de paramètres

qualifiedName

Le nom de l'élément. Lorsqu'il est passé dans l'URI de l'espace de nom, le nom de l'élément doit comporter un préfixe pour être associé à l'URI.

value

La valeur de l'élément.

namespace

Un espace de nom de l'URI pour créer l'élément dans un espace de nom spécifique.

Exemples

Exemple #1 Création d'un nouveau 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="iso-8859-1"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

Voir aussi

  • DOMDocument::createElement() - Crée un nouveau nœud
  • DOMDocument::createElementNS() - Crée un nouveau nœud avec un espace de noms associé

User Contributed Notes

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


Retourne la valeur d'un attribut

  • « DOMElement::__construct
  • DOMElement::getAttributeNames »
  • PHP Manual
  • DOMElement
  • Retourne la valeur d'un attribut

DOMElement::getAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttribute — Retourne la valeur d'un attribut

Description

public DOMElement::getAttribute(string $qualifiedName): string

Récupère la valeur d'un attribut avec le nom qualifiedName pour le nœud courant.

Liste de paramètres

qualifiedName

Le nom de l'attribut.

Valeurs de retour

La valeur de l'attribut ou une chaîne vide si aucun attribut avec le nom qualifiedName donné n'est trouvé.

Voir aussi

  • DOMElement::hasAttribute() - Vérifie si un attribut existe
  • DOMElement::setAttribute() - Ajoute un nouvel attribut, ou modifie un attribut existant
  • DOMElement::removeAttribute() - Efface un attribut

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

- - - - - - - - - - - - - -


Get attribute names

  • « DOMElement::getAttribute
  • DOMElement::getAttributeNode »
  • PHP Manual
  • DOMElement
  • Get attribute names

DOMElement::getAttributeNames

(PHP 8 >= 8.3.0)

DOMElement::getAttributeNames — Get attribute names

Description

public DOMElement::getAttributeNames(): array

Get attribute names.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Return attribute names.

Exemples

Exemple #1 DOMElement::getAttributeNames() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<html xmlns:some="some:ns" some:test="a" test2="b"/>');
var_dump($dom->documentElement->getAttributeNames());
?>

L'exemple ci-dessus va afficher :

array(3) {
 [0]=>
 string(10) "xmlns:some"
 [1]=>
 string(9) "some:test"
 [2]=>
 string(5) "test2"
}

User Contributed Notes

There are no user contributed notes for this page.


Retourne le nœud d'attribut

  • « DOMElement::getAttributeNames
  • DOMElement::getAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Retourne le nœud d'attribut

DOMElement::getAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNode — Retourne le nœud d'attribut

Description

public DOMElement::getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false

Retourne le nœud d'attribut avec le nom qualifiedName pour l'élément courant.

Liste de paramètres

qualifiedName

Le nom de l'attribut.

Valeurs de retour

Le nœud d'attribut. Notez que pour la déclaration de namespace XML (les attributs xmlns et xmlns:*) une instance de DOMNameSpaceNode est retourné au lieu de DOMAttr.

Voir aussi

  • DOMElement::hasAttribute() - Vérifie si un attribut existe
  • DOMElement::setAttributeNode() - Ajoute un nouvel attribut à l'élément
  • DOMElement::removeAttributeNode() - Efface un attribut

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


Retourne le nœud d'attribut

  • « DOMElement::getAttributeNode
  • DOMElement::getAttributeNS »
  • PHP Manual
  • DOMElement
  • Retourne le nœud d'attribut

DOMElement::getAttributeNodeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNodeNS — Retourne le nœud d'attribut

Description

public DOMElement::getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null

Retourne le nœud d'attribut dans l'espace de noms namespace avec le nom local localName pour le nœud courant.

Liste de paramètres

namespace

L'URI de l'espace de noms.

localName

Le nom local.

Valeurs de retour

Le nœud d'attribut. Notez que pour la déclaration de namespace XML (les attributs xmlns et xmlns:*) une instance de DOMNameSpaceNode est retourné au lieu d'un objet DOMAttr.

Voir aussi

  • DOMElement::hasAttributeNS() - Vérifie si un attribut existe
  • DOMElement::setAttributeNodeNS() - Ajoute un nouvel attribut à l'élément
  • DOMElement::removeAttributeNode() - Efface un attribut

User Contributed Notes

There are no user contributed notes for this page.


Retourne la valeur de l'attribut

  • « DOMElement::getAttributeNodeNS
  • DOMElement::getElementsByTagName »
  • PHP Manual
  • DOMElement
  • Retourne la valeur de l'attribut

DOMElement::getAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNS — Retourne la valeur de l'attribut

Description

public DOMElement::getAttributeNS(?string $namespace, string $localName): string

Récupère la valeur de l'attribut dans l'espace de noms namespace avec le nom local localName pour le nœud courant.

Liste de paramètres

namespace

L'URI de l'espace de noms.

localName

Le nom local.

Valeurs de retour

La valeur de l'attribut, ou une chaîne vide si aucun attribut avec le nom local localName donné et dans l'espace de noms namespace n'est trouvé.

Voir aussi

  • DOMElement::hasAttributeNS() - Vérifie si un attribut existe
  • DOMElement::setAttributeNS() - Ajoute un nouvel attribut
  • DOMElement::removeAttributeNS() - Efface un attribut

User Contributed Notes

There are no user contributed notes for this page.


Retourne les éléments par leur nom de balise

  • « DOMElement::getAttributeNS
  • DOMElement::getElementsByTagNameNS »
  • PHP Manual
  • DOMElement
  • Retourne les éléments par leur nom de balise

DOMElement::getElementsByTagName

(PHP 5, PHP 7, PHP 8)

DOMElement::getElementsByTagName — Retourne les éléments par leur nom de balise

Description

public DOMElement::getElementsByTagName(string $qualifiedName): DOMNodeList

Cette fonction retourne une nouvelle instance de la classe DOMNodeList contenant tous les éléments descendants avec un nom de balise qualifiedName donné, dans l'ordre dans lequel ils sont rencontrés lors du parcours de l'arbre de cet élément.

Liste de paramètres

qualifiedName

Le nom de la balise. Utilisez le caractère générique * pour récupérer tous les éléments contenus dans l'arbre de l'élément.

Valeurs de retour

Cette fonction retourne une nouvelle instance de la classe DOMNodeList contenant tous les éléments correspondants.

Voir aussi

  • DOMElement::getElementsByTagNameNS() - Récupère les éléments par leur espace de noms et leur localName

User Contributed Notes

There are no user contributed notes for this page.


Récupère les éléments par leur espace de noms et leur localName

  • « DOMElement::getElementsByTagName
  • DOMElement::hasAttribute »
  • PHP Manual
  • DOMElement
  • Récupère les éléments par leur espace de noms et leur localName

DOMElement::getElementsByTagNameNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getElementsByTagNameNS — Récupère les éléments par leur espace de noms et leur localName

Description

public DOMElement::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

Cette fonction récupère tous les éléments descendants avec un nom local localName et un espace de noms namespace donnés.

Liste de paramètres

namespace

L'URI de l'espace de noms des éléments à chercher. La valeur spéciale "*" représente tous les espaces de noms. Passer null représente l'espace de noms vide.

localName

Le nom local des éléments à chercher. La valeur spéciale "*" représente tous les noms locaux.

Valeurs de retour

Cette fonction retourne un nouvel objet de la classe DOMNodeList contenant tous les éléments correspondants dans l'ordre dans lesquels ils sont rencontrés lors du parcours de l'arbre de cet élément.

Historique

Version | Description
8.0.3 | namespace est désormais nullable.

Voir aussi

  • DOMElement::getElementsByTagNameNS()

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.


Vérifie si un attribut existe

  • « DOMElement::getElementsByTagNameNS
  • DOMElement::hasAttributeNS »
  • PHP Manual
  • DOMElement
  • Vérifie si un attribut existe

DOMElement::hasAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::hasAttribute — Vérifie si un attribut existe

Description

public DOMElement::hasAttribute(string $qualifiedName): bool

Indique si un attribut nommé qualifiedName existe en tant que membre de l'élément.

Liste de paramètres

qualifiedName

Le nom de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMElement::hasAttributeNS() - Vérifie si un attribut existe
  • DOMElement::getAttribute() - Retourne la valeur d'un attribut
  • DOMElement::setAttribute() - Ajoute un nouvel attribut, ou modifie un attribut existant
  • DOMElement::removeAttribute() - Efface un attribut

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si un attribut existe

  • « DOMElement::hasAttribute
  • DOMElement::insertAdjacentElement »
  • PHP Manual
  • DOMElement
  • Vérifie si un attribut existe

DOMElement::hasAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::hasAttributeNS — Vérifie si un attribut existe

Description

public DOMElement::hasAttributeNS(?string $namespace, string $localName): bool

Vérifie si un attribut dans l'espace de noms namespace nommé localName existe en tant que membre de l'élément.

Liste de paramètres

namespace

L'URI de l'espace de noms.

localName

Le nom local.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMElement::hasAttribute() - Vérifie si un attribut existe
  • DOMElement::getAttributeNS() - Retourne la valeur de l'attribut
  • DOMElement::setAttributeNS() - Ajoute un nouvel attribut
  • DOMElement::removeAttributeNS() - Efface un attribut

User Contributed Notes

There are no user contributed notes for this page.


Insert adjacent element

  • « DOMElement::hasAttributeNS
  • DOMElement::insertAdjacentText »
  • PHP Manual
  • DOMElement
  • Insert adjacent element

DOMElement::insertAdjacentElement

(PHP 8 >= 8.3.0)

DOMElement::insertAdjacentElement — Insert adjacent element

Description

public DOMElement::insertAdjacentElement(string $where, DOMElement $element): ?DOMElement

Inserts an element at a relative position given by where.

Liste de paramètres

where

  • beforebegin - Insert before the target element.
  • afterbegin - Insert as the first child of the target element.
  • beforeend - Insert as the last child of the target element.
  • afterend - Insert after the target element.

element

The element to insert.

Valeurs de retour

Return DOMElement or null on failure.

Exemples

Exemple #1 DOMElement::insertAdjacentElement() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><container><p>foo</p></container>');
$container = $dom->documentElement;
$p = $container->firstElementChild;

$p->insertAdjacentElement('beforebegin', $dom->createElement('A'));
echo $dom->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container><A/><p>foo</p></container>

Voir aussi

  • DOMElement::insertAdjacentText() - Insert adjacent text

User Contributed Notes

There are no user contributed notes for this page.


Insert adjacent text

  • « DOMElement::insertAdjacentElement
  • DOMElement::prepend »
  • PHP Manual
  • DOMElement
  • Insert adjacent text

DOMElement::insertAdjacentText

(PHP 8 >= 8.3.0)

DOMElement::insertAdjacentText — Insert adjacent text

Description

public DOMElement::insertAdjacentText(string $where, string $data): void

Inserts text at a relative position given by where.

Liste de paramètres

where

  • beforebegin - Insert before the target element.
  • afterbegin - Insert as the first child of the target element.
  • beforeend - Insert as the last child of the target element.
  • afterend - Insert after the target element.

data

The string to insert.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 DOMElement::insertAdjacentText() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><container><p>H</p></container>');

$container = $dom->documentElement;
$p = $container->firstElementChild;

$p->insertAdjacentText("afterbegin", "P");
$p->insertAdjacentText("beforeend", "P");

echo $dom->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container><p>PHP</p></container>

Voir aussi

  • DOMElement::insertAdjacentElement() - Insert adjacent element

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • « DOMElement::insertAdjacentText
  • DOMElement::remove »
  • PHP Manual
  • DOMElement
  • Prepends nodes before the first child node

DOMElement::prepend

(PHP 8)

DOMElement::prepend — Prepends nodes before the first child node

Description

public DOMElement::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMElement::prepend() example

Prepends nodes in the container element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container> world</container>");
$world = $doc->documentElement;

$world->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container><hello/>beautiful world</container>

Voir aussi

  • DOMParentNode::prepend() - Ajoute des nœuds avant le premier nœud enfant
  • DOMElement::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Removes the element

  • « DOMElement::prepend
  • DOMElement::removeAttribute »
  • PHP Manual
  • DOMElement
  • Removes the element

DOMElement::remove

(PHP 8)

DOMElement::remove — Removes the element

Description

public DOMElement::remove(): void

Removes the element.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 DOMElement::remove() example

Removes the element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/><world/></container>");
$hello = $doc->documentElement->firstChild;

$hello->remove();

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container><world/></container>

Voir aussi

  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::replaceWith() - Replaces the element with new nodes
  • DOMNode::removeChild() - Supprime un fils de la liste des enfants

User Contributed Notes

There are no user contributed notes for this page.


Efface un attribut

  • « DOMElement::remove
  • DOMElement::removeAttributeNode »
  • PHP Manual
  • DOMElement
  • Efface un attribut

DOMElement::removeAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttribute — Efface un attribut

Description

public DOMElement::removeAttribute(string $qualifiedName): bool

Efface l'attribut nommé qualifiedName de l'élément.

Liste de paramètres

qualifiedName

Le nom de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule.

Voir aussi

  • DOMElement::hasAttribute() - Vérifie si un attribut existe
  • DOMElement::getAttribute() - Retourne la valeur d'un attribut
  • DOMElement::setAttribute() - Ajoute un nouvel attribut, ou modifie un attribut existant

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;

?>


Efface un attribut

  • « DOMElement::removeAttribute
  • DOMElement::removeAttributeNS »
  • PHP Manual
  • DOMElement
  • Efface un attribut

DOMElement::removeAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttributeNode — Efface un attribut

Description

public DOMElement::removeAttributeNode(DOMAttr $attr): DOMAttr|false

Efface l'attribut attr de l'élément.

Liste de paramètres

attr

Le nœud de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule.

DOM_NOT_FOUND_ERROR

Lancé si attr n'est pas un attribut de l'élément.

Voir aussi

  • DOMElement::hasAttribute() - Vérifie si un attribut existe
  • DOMElement::getAttributeNode() - Retourne le nœud d'attribut
  • DOMElement::setAttributeNode() - Ajoute un nouvel attribut à l'élément

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.


Efface un attribut

  • « DOMElement::removeAttributeNode
  • DOMElement::replaceChildren »
  • PHP Manual
  • DOMElement
  • Efface un attribut

DOMElement::removeAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttributeNS — Efface un attribut

Description

public DOMElement::removeAttributeNS(?string $namespace, string $localName): void

Retire l'attribut localName dans l'espace de noms namespace de l'élément.

Liste de paramètres

namespace

L'URI de l'espace de noms.

localName

Le nom local.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Émise si le nœud est en lecture seule.

Voir aussi

  • DOMElement::hasAttributeNS() - Vérifie si un attribut existe
  • DOMElement::getAttributeNS() - Retourne la valeur de l'attribut
  • DOMElement::setAttributeNS() - Ajoute un nouvel attribut

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());

?>


Replace children in element

  • « DOMElement::removeAttributeNS
  • DOMElement::replaceWith »
  • PHP Manual
  • DOMElement
  • Replace children in element

DOMElement::replaceChildren

(PHP 8 >= 8.3.0)

DOMElement::replaceChildren — Replace children in element

Description

public DOMElement::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the element with new nodes.

Liste de paramètres

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMElement::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$container = $doc->documentElement;

$container->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
beautiful
<world/>

Voir aussi

  • DOMParentNode::replaceChildren() - Replace children in node
  • DOMElement::replaceWith() - Replaces the element with new nodes
  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::remove() - Removes the element

User Contributed Notes

There are no user contributed notes for this page.


Replaces the element with new nodes

  • « DOMElement::replaceChildren
  • DOMElement::setAttribute »
  • PHP Manual
  • DOMElement
  • Replaces the element with new nodes

DOMElement::replaceWith

(PHP 8)

DOMElement::replaceWith — Replaces the element with new nodes

Description

public DOMElement::replaceWith(DOMNode|string ...$nodes): void

Replaces the element with new nodes.

Liste de paramètres

nodes

Les nœuds de remplacement.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 DOMElement::replaceWith() example

Replaces the element with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<container>beautiful<world/></container>

Voir aussi

  • DOMChildNode::replaceWith() - Remplace le nœud par de nouveaux nœuds
  • DOMElement::replaceChildren() - Replace children in element
  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::remove() - Removes the element

User Contributed Notes

There are no user contributed notes for this page.


Ajoute un nouvel attribut, ou modifie un attribut existant

  • « DOMElement::replaceWith
  • DOMElement::setAttributeNode »
  • PHP Manual
  • DOMElement
  • Ajoute un nouvel attribut, ou modifie un attribut existant

DOMElement::setAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttribute — Ajoute un nouvel attribut, ou modifie un attribut existant

Description

public DOMElement::setAttribute(string $qualifiedName, string $value): DOMAttr|bool

Ajoute un attribut avec comme nom qualifiedName et comme valeur value. Si l'attribut n'existe pas, il sera créé.

Liste de paramètres

qualifiedName

Le nom de l'attribut.

value

La valeur de l'attribut.

Valeurs de retour

Le DOMAttr crée ou modifié, ou false si une erreur survient.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule.

Exemples

Exemple #1 Ajout d'un attribut

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

Voir aussi

  • DOMElement::hasAttribute() - Vérifie si un attribut existe
  • DOMElement::getAttribute() - Retourne la valeur d'un attribut
  • DOMElement::removeAttribute() - Efface un attribut

User Contributed Notes

info at ensostudio dot ru 02-Dec-2021 06:17
Solution to render HTML 5 tags with attributes with/without value:
<?php
$dom = new DOMImplementation();
$doc = $dom->createDocument(null, 'html', $dom->createDocumentType('html'));

$tag = $doc->appendChild($doc->createElement('input'));
$tag->setAttribute('type', 'text');
$tag->setAttribute('disabled', '');

echo $doc->saveHTML($tag); // <input type="text" disabled="">

$doc->normalize(); // normalize attributes
echo $doc->saveHTML($tag); // <input type="text" disabled>
?>
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">


Ajoute un nouvel attribut à l'élément

  • « DOMElement::setAttribute
  • DOMElement::setAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Ajoute un nouvel attribut à l'élément

DOMElement::setAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNode — Ajoute un nouvel attribut à l'élément

Description

public DOMElement::setAttributeNode(DOMAttr $attr): DOMAttr|null|false

Ajoute un nouvel attribut attr à l'élément. Si un attribut du même nom existe déjà sur l'élément, cet attribut est remplacé par attr.

Liste de paramètres

attr

L'attribut.

Valeurs de retour

Retourne l'ancien attribut s'il a été remplacé ou null s'il n'y avait pas d'ancien attribut. Si une erreur DOM_WRONG_DOCUMENT_ERR est déclenchée, et que strictErrorChecking est false, alors false est renvoyé.

Erreurs / Exceptions

DOM_WRONG_DOCUMENT_ERR

Lancé si attr appartient à un document différent de celui de l'élément.

Voir aussi

  • DOMElement::hasAttribute() - Vérifie si un attribut existe
  • DOMElement::getAttributeNode() - Retourne le nœud d'attribut
  • DOMElement::removeAttributeNode() - Efface un attribut

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>


Ajoute un nouvel attribut à l'élément

  • « DOMElement::setAttributeNode
  • DOMElement::setAttributeNS »
  • PHP Manual
  • DOMElement
  • Ajoute un nouvel attribut à l'élément

DOMElement::setAttributeNodeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNodeNS — Ajoute un nouvel attribut à l'élément

Description

public DOMElement::setAttributeNodeNS(DOMAttr $attr): DOMAttr|null|false

Ajoute un nouvel attribut attr à l'élément, en tenant compte de l'espace de noms (namespace): Si un attribut du même nom existe déjà sur l'élément, cet attribut est remplacé par attr.

Liste de paramètres

attr

Le nom de l'attribut.

Valeurs de retour

Retourne l'ancien attribut s'il a été remplacé ou null s'il n'y avait pas d'ancien attribut. Si une erreur DOM_WRONG_DOCUMENT_ERR est déclenchée, et que strictErrorChecking est false, alors false est renvoyé.

Erreurs / Exceptions

DOM_WRONG_DOCUMENT_ERR

Lancé si attr appartient à un document différent de celui de l'élément.

Voir aussi

  • DOMElement::hasAttributeNS() - Vérifie si un attribut existe
  • DOMElement::getAttributeNodeNS() - Retourne le nœud d'attribut
  • DOMElement::removeAttributeNode() - Efface un attribut

User Contributed Notes

There are no user contributed notes for this page.


Ajoute un nouvel attribut

  • « DOMElement::setAttributeNodeNS
  • DOMElement::setIdAttribute »
  • PHP Manual
  • DOMElement
  • Ajoute un nouvel attribut

DOMElement::setAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNS — Ajoute un nouvel attribut

Description

public DOMElement::setAttributeNS(?string $namespace, string $qualifiedName, string $value): void

Ajoute un attribut avec comme espace de noms namespace et comme nom name avec comme valeur value. Si l'attribut n'existe pas, il sera créé.

Liste de paramètres

namespace

L'URI de l'espace de noms.

qualifiedName

Le nom qualifié de l'attribut, sous la forme prefixe:nomdebalise.

value

La valeur de l'attribut.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule.

DOM_NAMESPACE_ERR

Lancé si qualifiedName est un nom qualifié malformé ou si qualifiedName a un préfixe et un namespace qui vaut null.

Voir aussi

  • DOMElement::hasAttributeNS() - Vérifie si un attribut existe
  • DOMElement::getAttributeNodeNS() - Retourne le nœud d'attribut
  • DOMElement::removeAttributeNode() - Efface un attribut

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'
    );
?>


Déclare l'attribut spécifié par son nom à être de type ID

  • « DOMElement::setAttributeNS
  • DOMElement::setIdAttributeNode »
  • PHP Manual
  • DOMElement
  • Déclare l'attribut spécifié par son nom à être de type ID

DOMElement::setIdAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttribute — Déclare l'attribut spécifié par son nom à être de type ID

Description

public DOMElement::setIdAttribute(string $qualifiedName, bool $isId): void

Déclare l'attribut qualifiedName afin qu'il soit de type ID.

Liste de paramètres

qualifiedName

Le nom de l'attribut.

isId

Définissez à true si vous voulez que qualifiedName soit de type ID, false sinon.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Envoyé si le nœud est en lecture seule.

DOM_NOT_FOUND

Envoyé si qualifiedName n'est pas un attribut de cet élément.

Voir aussi

  • DOMDocument::getElementById() - Cherche un élément avec un certain identifiant
  • DOMElement::setIdAttributeNode() - Déclare l'attribut spécifié par le nœud à être de type ID
  • DOMElement::setIdAttributeNS() - Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID

User Contributed Notes

There are no user contributed notes for this page.


Déclare l'attribut spécifié par le nœud à être de type ID

  • « DOMElement::setIdAttribute
  • DOMElement::setIdAttributeNS »
  • PHP Manual
  • DOMElement
  • Déclare l'attribut spécifié par le nœud à être de type ID

DOMElement::setIdAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttributeNode — Déclare l'attribut spécifié par le nœud à être de type ID

Description

public DOMElement::setIdAttributeNode(DOMAttr $attr, bool $isId): void

Déclare l'attribut spécifié par attr afin qu'il soit de type ID.

Liste de paramètres

attr

L'attribut du nœud.

isId

Définissez à true si vous voulez que name soit de type ID, false sinon.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Envoyé si le nœud est en lecture seule.

DOM_NOT_FOUND

Envoyé si name n'est pas un attribut de cet élément.

Voir aussi

  • DOMDocument::getElementById() - Cherche un élément avec un certain identifiant
  • DOMElement::setIdAttribute() - Déclare l'attribut spécifié par son nom à être de type ID
  • DOMElement::setIdAttributeNS() - Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID

User Contributed Notes

There are no user contributed notes for this page.


Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID

  • « DOMElement::setIdAttributeNode
  • DOMElement::toggleAttribute »
  • PHP Manual
  • DOMElement
  • Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID

DOMElement::setIdAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttributeNS — Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID

Description

public DOMElement::setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void

Déclare l'attribut spécifié par qualifiedName et namespace afin qu'il soit de type ID.

Liste de paramètres

namespace

L'URI de l'espace de nom de l'attribut.

qualifiedName

Le nom local de l'attribut, sous la forme prefix:tagname.

isId

Définissez à true si vous voulez que name soit de type ID, false sinon.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Émise si le nœud est en lecture seule.

DOM_NOT_FOUND

Émise si name n'est pas un attribut de cet élément.

Voir aussi

  • DOMDocument::getElementById() - Cherche un élément avec un certain identifiant
  • DOMElement::setIdAttribute() - Déclare l'attribut spécifié par son nom à être de type ID
  • DOMElement::setIdAttributeNode() - Déclare l'attribut spécifié par le nœud à être de type ID

User Contributed Notes

There are no user contributed notes for this page.


Toggle attribute

  • « DOMElement::setIdAttributeNS
  • DOMEntity »
  • PHP Manual
  • DOMElement
  • Toggle attribute

DOMElement::toggleAttribute

(PHP 8 >= 8.3.0)

DOMElement::toggleAttribute — Toggle attribute

Description

public DOMElement::toggleAttribute(string $qualifiedName, ?bool $force = null): bool

Toggle the attribute.

Liste de paramètres

qualifiedName

The qualified name of the attribute.

force

  • if null, the function will toggle the attribute.
  • if true, the function adds the attribute.
  • if false, the function removes the attribute.

Valeurs de retour

Returns true if the attribute is present after finishing the call, false otherwise.

Exemples

Exemple #1 DOMElement::toggleAttribute() example

<?php

$dom = new DOMDocument();
$dom->loadXML("<?xml version='1.0'?><container selected=\"\"/>");

var_dump($dom->documentElement->toggleAttribute('selected'));
echo $dom->saveXML() . PHP_EOL;

var_dump($dom->documentElement->toggleAttribute('selected'));
echo $dom->saveXML();
?>

L'exemple ci-dessus va afficher :

bool(false)
<?xml version="1.0"?>
<container/>

bool(true)
<?xml version="1.0"?>
<container selected=""/>

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMEntity

(PHP 5, PHP 7, PHP 8)

Introduction

Cette interface représente une entité connue, analysée ou non, dans un document XML.

Synopsis de la classe

class DOMEntity extends DOMNode {
/* Propriétés */
public readonly ?string $publicId;
public readonly ?string $systemId;
public readonly ?string $notationName;
public readonly ?string $actualEncoding = null;
public readonly ?string $encoding = null;
public readonly ?string $version = null;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

publicId

L'identifiant public associé avec l'entité, si spécifiée, et null sinon.

systemId

L'identifiant système associé avec l'entité, si spécifiée, et null sinon. Peut-être une URI absolue ou non.

notationName

Pour les entités non analysées, le nom de la notation de l'entité. Pour les entités analysées, vaut null.

actualEncoding

Un attribut spécifiant l'encodage utilisé pour cette entité au moment de l'analyse, lorsque c'est une entité analysée externe. Vaut null si c'est une entité depuis un subset interne ou si l'encodage est inconnu.

encoding

Un attribut spécifiant (faisant partie de la déclaration) l'encodage de l'entité, lorsque c'est une entité analysée externe. Vaut null sinon.

version

Un attribut spécifiant (faisant partie de la déclaration) le numéro de version de l'entité, lorsque c'est une entité analysée externe. Vaut null sinon.

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMEntityReference

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMEntityReference extends DOMNode {
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $name)
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Sommaire

  • DOMEntityReference::__construct — Crée un nouvel objet DOMEntityReference

User Contributed Notes

There are no user contributed notes for this page.


Crée un nouvel objet DOMEntityReference

  • « DOMEntityReference
  • DOMException »
  • PHP Manual
  • DOMEntityReference
  • Crée un nouvel objet DOMEntityReference

DOMEntityReference::__construct

(PHP 5, PHP 7, PHP 8)

DOMEntityReference::__construct — Crée un nouvel objet DOMEntityReference

Description

public DOMEntityReference::__construct(string $name)

Crée un nouvel objet DOMEntityReference.

Liste de paramètres

name

Le nom de la référence à l'entité.

Exemples

Exemple #1 Création d'un nouveau 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></root> */

?>

Voir aussi

  • DOMDocument::createEntityReference() - Crée un nouveau nœud de référence d'entité

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMException

(PHP 5, PHP 7, PHP 8)

Introduction

Les opérations DOM lancent des exceptions lors de circonstances particulières, i.e., lorsqu'il est impossible d'exécuter une opération pour des raisons logiques.

Voir aussi Les exceptions.

Synopsis de la classe

final class DOMException extends Exception {
/* Propriétés */
public int $code;
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes héritées */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Propriétés

code

Un entier indiquant le type d'erreur généré

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMImplementation

(PHP 5, PHP 7, PHP 8)

Introduction

La classe DOMImplementation fournit des méthodes pour effectuer des opérations qui sont indépendantes d'une instance particulière du modèle objet d'un document.

Synopsis de la classe

class DOMImplementation {
/* Méthodes */
public createDocument(?string $namespace = null, string $qualifiedName = "", ?DOMDocumentType $doctype = null): DOMDocument|false
public createDocumentType(string $qualifiedName, string $publicId = "", string $systemId = ""): DOMDocumentType|false
public hasFeature(string $feature, string $version): bool
}

Sommaire

  • DOMImplementation::__construct — Crée un nouvel objet DOMImplementation
  • DOMImplementation::createDocument — Crée un objet DOM Document du type spécifié avec ses éléments
  • DOMImplementation::createDocumentType — Crée un objet DOMDocumentType vide
  • DOMImplementation::hasFeature — Teste si l'implémentation DOM implémente une fonctionnalité spécifique

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


Crée un nouvel objet DOMImplementation

  • « DOMImplementation
  • DOMImplementation::createDocument »
  • PHP Manual
  • DOMImplementation
  • Crée un nouvel objet DOMImplementation

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Crée un nouvel objet DOMImplementation

Description

DOMImplementation::__construct()

Crée un nouvel objet DOMImplementation.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

User Contributed Notes

There are no user contributed notes for this page.


Crée un objet DOM Document du type spécifié avec ses éléments

  • « DOMImplementation::__construct
  • DOMImplementation::createDocumentType »
  • PHP Manual
  • DOMImplementation
  • Crée un objet DOM Document du type spécifié avec ses éléments

DOMImplementation::createDocument

(PHP 5, PHP 7, PHP 8)

DOMImplementation::createDocument — Crée un objet DOM Document du type spécifié avec ses éléments

Description

public DOMImplementation::createDocument(?string $namespace = null, string $qualifiedName = "", ?DOMDocumentType $doctype = null): DOMDocument|false

Crée un objet DOMDocument du type spécifié avec ces éléments du document.

Liste de paramètres

namespace

L'URI de l'espace de noms des éléments du document à créer.

qualifiedName

Le nom qualifié des éléments du document à créer.

doctype

Le type de document à créer ou null.

Valeurs de retour

Un nouvel objet DOMDocument ou false en cas d'erreur. Si namespace, qualifiedName, et doctype sont nulles, le DOMDocument retourné est vide avec aucun élément de document.

Erreurs / Exceptions

DOM_WRONG_DOCUMENT_ERR

Lancé si doctype a déjà été utilisé avec un document différent ou a été créé depuis une implémentation différente.

DOM_NAMESPACE_ERR

Lancé s'il y a une erreur dans l'espace de noms, déterminé par namespace et qualifiedName.

Historique

Version | Description
8.0.3 | namespace est désormais nullable.
8.0.0 | doctype est désormais nullable.
8.0.0 | Appeler cette fonction de manière statique lèvera désormais une Error. Auparavant, une erreur E_DEPRECATED était générée.

Voir aussi

  • DOMDocument::__construct() - Crée un nouvel objet DOMDocument
  • DOMImplementation::createDocumentType() - Crée un objet DOMDocumentType vide

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=Windows-1252" />
    <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);
?>


Crée un objet DOMDocumentType vide

  • « DOMImplementation::createDocument
  • DOMImplementation::hasFeature »
  • PHP Manual
  • DOMImplementation
  • Crée un objet DOMDocumentType vide

DOMImplementation::createDocumentType

(PHP 5, PHP 7, PHP 8)

DOMImplementation::createDocumentType — Crée un objet DOMDocumentType vide

Description

public DOMImplementation::createDocumentType(string $qualifiedName, string $publicId = "", string $systemId = ""): DOMDocumentType|false

Crée un objet DOMDocumentType vide. Les déclarations et notations d'entités ne sont pas disponibles. Les expansions de références d'entités et les ajouts d'attributs par défaut ne sont pas non plus effectués.

Liste de paramètres

qualifiedName

Le nom qualifié du type de document à créer.

publicId

L'identifiant publique externe du sous-ensemble.

systemId

L'identifiant système externe du sous-ensemble.

Valeurs de retour

Un nouveau nœud DOMDocumentType avec son ownerDocument défini à null ou false en cas d'erreur.

Erreurs / Exceptions

DOM_NAMESPACE_ERR

Levée si il y a une erreur avec l'espace de noms, déterminé par qualifiedName.

Historique

Version | Description
8.0.0 | Appeler cette fonction de manière statique lèvera désormais une Error. Auparavant, une erreur E_DEPRECATED était générée.

Exemples

Exemple #1 Création d'un document avec une DTD attachée

<?php

// Création d'une instance de la classe DOMImplementation
$imp = new DOMImplementation;

// Création d'une instance DOMDocumentType
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Création d'une instance DOMDocument
$dom = $imp->createDocument("", "", $dtd);

// Définition des autres propriétés
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Création d'un élément vide
$element = $dom->createElement('graph');

// Ajout de l'élément
$dom->appendChild($element);

// Récupère et affiche le document
echo $dom->saveXML();

?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Voir aussi

  • DOMImplementation::createDocument() - Crée un objet DOM Document du type spécifié avec ses éléments

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.


Teste si l'implémentation DOM implémente une fonctionnalité spécifique

  • « DOMImplementation::createDocumentType
  • DOMNamedNodeMap »
  • PHP Manual
  • DOMImplementation
  • Teste si l'implémentation DOM implémente une fonctionnalité spécifique

DOMImplementation::hasFeature

(PHP 5, PHP 7, PHP 8)

DOMImplementation::hasFeature — Teste si l'implémentation DOM implémente une fonctionnalité spécifique

Description

public DOMImplementation::hasFeature(string $feature, string $version): bool

Teste si l'implémentation DOM implémente une fonctionnalité feature spécifique.

Vous pouvez trouver une liste de toutes les fonctionnalités dans la section » Conformance de la spécification DOM.

Liste de paramètres

feature

La fonctionnalité à tester.

version

Le numéro de version de la fonctionnalité feature à tester. Dans le niveau 2, ceci peut être soit 2.0 ou 1.0.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | Appeler cette fonction de manière statique lèvera désormais une Error. Auparavant, une erreur E_DEPRECATED était générée.

Exemples

Exemple #1 Test votre implémentation DOM

<?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 "A la fonctionnalité $name\n";
} else {
echo "N'a pas la fonctionnalité $name\n";
}
}

?>

Voir aussi

  • DOMNode::isSupported() - Vérifie si la fonctionnalité est disponible pour la version spécifiée

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMNamedNodeMap

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMNamedNodeMap implements IteratorAggregate, Countable {
/* Propriétés */
public readonly int $length;
/* Méthodes */
public count(): int
public getIterator(): Iterator
public getNamedItem(string $qualifiedName): ?DOMNode
public getNamedItemNS(?string $namespace, string $localName): ?DOMNode
public item(int $index): ?DOMNode
}

Propriétés

length

Le nombre de nœuds dans la carte. L'intervalle des indices des nœuds fils valides est de 0 à length - 1, inclusif.

Historique

Version | Description
8.0.0 | Les méthodes non implémentées DOMNamedNodeMap::setNamedItem(), DOMNamedNodeMap::removeNamedItem(), DOMNamedNodeMap::setNamedItemNS() et DOMNamedNodeMap::removeNamedItem() ont été supprimées.
8.0.0 | La classe DOMNamedNodeMap implémente désormais IteratorAggregate. Auparavant, seule Traversable était implémentée.

Sommaire

  • DOMNamedNodeMap::count — Récupère le nombre de nœuds dans la collection non triée (map)
  • DOMNamedNodeMap::getIterator — Retrieve an external iterator
  • DOMNamedNodeMap::getNamedItem — Retourne un nœud spécifié par son nom
  • DOMNamedNodeMap::getNamedItemNS — Retourne un nœud spécifié par son nom local et son espace de noms
  • DOMNamedNodeMap::item — Retourne un nœud selon son 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


Récupère le nombre de nœuds dans la collection non triée (map)

  • « DOMNamedNodeMap
  • DOMNamedNodeMap::getIterator »
  • PHP Manual
  • DOMNamedNodeMap
  • Récupère le nombre de nœuds dans la collection non triée (map)

DOMNamedNodeMap::count

(PHP 7 >= 7.2.0, PHP 8)

DOMNamedNodeMap::count — Récupère le nombre de nœuds dans la collection non triée (map)

Description

public DOMNamedNodeMap::count(): int

Récupère le nombre de nœuds dans la collection non triée (map).

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le nombre de nœuds dans la collection non triée, ce qui est identique à la propriété length.

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an external iterator

  • « DOMNamedNodeMap::count
  • DOMNamedNodeMap::getNamedItem »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieve an external iterator

DOMNamedNodeMap::getIterator

(PHP 8)

DOMNamedNodeMap::getIterator — Retrieve an external iterator

Description

public DOMNamedNodeMap::getIterator(): Iterator

Returns an external iterator for the named node map.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Une instance d'un objet qui implémente un Iterator ou l'interface Traversable.

Erreurs / Exceptions

Émet une Exception en cas d'échec.

Voir aussi

  • IteratorAggregate::getIterator() - Retourne un itérateur externe

User Contributed Notes

There are no user contributed notes for this page.


Retourne un nœud spécifié par son nom

  • « DOMNamedNodeMap::getIterator
  • DOMNamedNodeMap::getNamedItemNS »
  • PHP Manual
  • DOMNamedNodeMap
  • Retourne un nœud spécifié par son nom

DOMNamedNodeMap::getNamedItem

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::getNamedItem — Retourne un nœud spécifié par son nom

Description

public DOMNamedNodeMap::getNamedItem(string $qualifiedName): ?DOMNode

Récupère un nœud spécifié par son nodeName.

Liste de paramètres

qualifiedName

Le nodeName du nœud à récupérer.

Valeurs de retour

Un nœud (de n'importe quel type) avec un nodeName spécifié, ou null si aucun nœud n'est trouvé.

Voir aussi

  • DOMNamedNodeMap::getNamedItemNS() - Retourne un nœud spécifié par son nom local et son espace de noms

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"
?>


Retourne un nœud spécifié par son nom local et son espace de noms

  • « DOMNamedNodeMap::getNamedItem
  • DOMNamedNodeMap::item »
  • PHP Manual
  • DOMNamedNodeMap
  • Retourne un nœud spécifié par son nom local et son espace de noms

DOMNamedNodeMap::getNamedItemNS

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::getNamedItemNS — Retourne un nœud spécifié par son nom local et son espace de noms

Description

public DOMNamedNodeMap::getNamedItemNS(?string $namespace, string $localName): ?DOMNode

Retourne un nœud spécifié par son nom local localName et son espace de noms namespace.

Liste de paramètres

namespace

L'URI de l'espace de noms du nœud à récupérer.

localName

Le nom local du nœud à récupérer.

Valeurs de retour

Un nœud, de n'importe quel type ou null si aucun nœud n'est trouvé.

Voir aussi

  • DOMNamedNodeMap::getNamedItemNS()

User Contributed Notes

There are no user contributed notes for this page.


Retourne un nœud selon son index

  • « DOMNamedNodeMap::getNamedItemNS
  • DOMNode »
  • PHP Manual
  • DOMNamedNodeMap
  • Retourne un nœud selon son index

DOMNamedNodeMap::item

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::item — Retourne un nœud selon son index

Description

public DOMNamedNodeMap::item(int $index): ?DOMNode

Retourne un nœud spécifié par index dans l'objet DOMNamedNodeMap.

Liste de paramètres

index

Index dans cette carte.

Valeurs de retour

Le nœud à la position index dans la carte, ou null si ce n'est pas un index valide (plus grand que ou égal au nombre de nœuds dans cette carte).

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."\"";
        }
    }
}
?>


La classe DOMNode

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMNode {
/* Propriétés */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public appendChild(DOMNode $node): DOMNode|false
public C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public cloneNode(bool $deep = false): DOMNode|false
public contains(DOMNode|DOMNameSpaceNode|null $other): bool
public getLineNo(): int
public getNodePath(): ?string
public getRootNode(array $options = null): DOMNode
public hasAttributes(): bool
public hasChildNodes(): bool
public insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public isDefaultNamespace(string $namespace): bool
public isEqualNode(?DOMNode $otherNode): bool
public isSameNode(DOMNode $otherNode): bool
public isSupported(string $feature, string $version): bool
public lookupNamespaceURI(?string $prefix): ?string
public lookupPrefix(string $namespace): ?string
public normalize(): void
public removeChild(DOMNode $child): DOMNode|false
public replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

nodeName

Retourne le nom, le plus précis, pour le type de nœud courant

nodeValue

La valeur de ce nœud, suivant son type. Contrairement aux spécifications W3C, la valeur du nœud des nœuds DOMElement est égale à DOMNode::textContent au lieu de null.

nodeType

Récupère le type du nœud. Une des constantes XML_xxx_NODE

parentNode

Le parent de ce nœud. Si ce type de nœud n'existe pas, ceci retournera null.

parentElement

L'élément pare de cet élément. S'il n'y a pas de tel élément, ceci retourne null.

childNodes

Un DOMNodeList qui contient tous les enfants de ce nœud. S'il n'y a aucun enfant, ce sera un DOMNodeList vide.

firstChild

Le premier enfant de ce nœud. S'il n'y a aucun nœud de ce type, retourne null.

lastChild

Le dernier enfant de ce nœud. S'il n'y a aucun nœud de ce type, retourne null.

previousSibling

Le nœud précédant immédiatement ce nœud. S'il n'y a aucun nœud, retourne null.

nextSibling

Le nœud suivant immédiatement ce nœud. S'il n'y a aucun nœud, retourne null.

attributes

Un DOMNamedNodeMap contenant les attributs de ce nœud (si c'est un DOMElement) ou null sinon.

isConnected

Si le nœud est connecté à un document ou non

ownerDocument

L'objet DOMDocument associé avec ce nœud, ou null si ce nœud est un DOMDocument.

namespaceURI

L'espace de nom de l'URL pour ce nœud, ou null s'il n'est pas spécifié.

prefix

Le préfixe de l'espace de nom de ce nœud.

localName

Retourne la partie locale du nom qualifié du nœud.

baseURI

La base de l'URL absolue du nœud, ou null si l'implémentation n'a pas réussi à obtenir l'URL absolue.

textContent

Le contenu textuel de ce nœud et de ces descendants.

Historique

Version | Description
8.3.0 | Les propriétés DOMNode::$parentElement, et DOMNode::$isConnected ont été ajouté.
8.0.0 | Les méthodes non implémentées DOMNode::compareDocumentPosition(), DOMNode::isEqualNode(), DOMNode::getFeature(), DOMNode::setUserData() et DOMNode::getUserData() ont été supprimées.

Notes

Note:

L'extension DOM utilise l'encodage UTF-8. Utilisez mb_convert_encoding(), UConverter::transcode(), ou iconv() pour manipuler d'autres encodages.

Voir aussi

  • » La spécification W3C specification d'un nœud

Sommaire

  • DOMNode::appendChild — Ajoute un nouveau fils à la fin des fils
  • DOMNode::C14N — Canonise des nœuds en une chaîne
  • DOMNode::C14NFile — Canonise des nœuds en fichier
  • DOMNode::cloneNode — Clone un nœud
  • DOMNode::contains — Checks if node contains other node
  • DOMNode::getLineNo — Lit le numéro de ligne d'un nœud
  • DOMNode::getNodePath — Récupère un XPath pour un nœud
  • DOMNode::getRootNode — Get root node
  • DOMNode::hasAttributes — Vérifie si le nœud possède un attribut
  • DOMNode::hasChildNodes — Vérifie si le nœud possède des enfants
  • DOMNode::insertBefore — Ajoute un nouveau fils avant un nœud de référence.
  • DOMNode::isDefaultNamespace — Vérifie si l'espace de nom spécifié est l'espace de noms par défaut ou non
  • DOMNode::isEqualNode — Checks that both nodes are equal
  • DOMNode::isSameNode — Indique si deux nœuds sont identiques
  • DOMNode::isSupported — Vérifie si la fonctionnalité est disponible pour la version spécifiée
  • DOMNode::lookupNamespaceURI — Retourne l'URI de l'espace de noms selon le préfixe
  • DOMNode::lookupPrefix — Retourne le préfixe de l'espace de noms selon l'URI de l'espace de noms
  • DOMNode::normalize — Normalise le nœud
  • DOMNode::removeChild — Supprime un fils de la liste des enfants
  • DOMNode::replaceChild — Remplace un fils

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=Windows-1252"><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.


Ajoute un nouveau fils à la fin des fils

  • « DOMNode
  • DOMNode::C14N »
  • PHP Manual
  • DOMNode
  • Ajoute un nouveau fils à la fin des fils

DOMNode::appendChild

(PHP 5, PHP 7, PHP 8)

DOMNode::appendChild — Ajoute un nouveau fils à la fin des fils

Description

public DOMNode::appendChild(DOMNode $node): DOMNode|false

Cette fonction ajoute un fils à une liste de fils existante ou crée une nouvelle liste de fils. Le fils peut être créé avec, e.g. DOMDocument::createElement(), DOMDocument::createTextNode(), etc. ou simplement en utilisant tout autre nœud.

Lors de l'utilisation d'un nœud existant, il sera supprimé.

Liste de paramètres

node

Le nœud fils à ajouter.

Valeurs de retour

Le nœud fils ajouté ou false en cas d'erreur.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule ou si le parent précédent le nœud à insérer est en lecture seule.

DOM_HIERARCHY_REQUEST_ERR

Lancé si le nœud est d'un type qui n'autorise pas d'enfant du type du nœud node, ou si le nœud à ajouter est un des nœuds ancêtres ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Lancé si node a été créé depuis un document différent que celui qui a créé ce nœud.

Exemples

L'exemple suivant ajoutera un nouveau nœud à un document nouveau.

Exemple #1 Ajout d'un fils

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Exemple #2 Enfant imbriqué

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

Voir aussi

  • DOMChildNode::after() - Ajoute des nœuds après le nœud
  • DOMNode::insertBefore() - Ajoute un nouveau fils avant un nœud de référence.
  • DOMNode::removeChild() - Supprime un fils de la liste des enfants
  • DOMNode::replaceChild() - Remplace un fils

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>


Canonise des nœuds en une chaîne

  • « DOMNode::appendChild
  • DOMNode::C14NFile »
  • PHP Manual
  • DOMNode
  • Canonise des nœuds en une chaîne

DOMNode::C14N

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMNode::C14N — Canonise des nœuds en une chaîne

Description

public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false

Canonise des nœuds en une chaîne de caractères.

Liste de paramètres

exclusive

Active l'analyse des seuls nœuds correspondant à l'Xpath ou aux préfixes d'espace de noms fournis.

withComments

Conserve les commentaires dans la sortie.

xpath

Un tableau de xpath utilisés pour filtrer les nœuds.

nsPrefixes

Un tableau de préfixes d'espaces de noms utilisés pour filtrer les nœuds.

Valeurs de retour

Retourne les nœuds canonisés, sous la forme d'une chaîne de caractères ou false si une erreur survient

Voir aussi

  • DOMNode::C14NFile() - Canonise des nœuds en fichier

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 );


Canonise des nœuds en fichier

  • « DOMNode::C14N
  • DOMNode::cloneNode »
  • PHP Manual
  • DOMNode
  • Canonise des nœuds en fichier

DOMNode::C14NFile

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMNode::C14NFile — Canonise des nœuds en fichier

Description

public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false

Canonise des nœuds en fichier.

Liste de paramètres

uri

Chemin vers lequel le fichier sera créé.

exclusive

Active l'analyse des seuls nœuds correspondant à l'xpath ou préfixes d'espace de noms fournis.

withComments

Conserve les commentaires dans la sortie.

xpath

Un tableau d'xpath utilisés pour filtrer les nœuds.

nsPrefixes

Un tableau de préfixes d'espace de noms utilisés pour filtrer les nœuds.

Valeurs de retour

Nombre d'octets écrits ou false si une erreur survient

Voir aussi

  • DOMNode::C14N() - Canonise des nœuds en une chaîne

User Contributed Notes

There are no user contributed notes for this page.


Clone un nœud

  • « DOMNode::C14NFile
  • DOMNode::contains »
  • PHP Manual
  • DOMNode
  • Clone un nœud

DOMNode::cloneNode

(PHP 5, PHP 7, PHP 8)

DOMNode::cloneNode — Clone un nœud

Description

public DOMNode::cloneNode(bool $deep = false): DOMNode|false

Crée une copie d'un nœud.

Liste de paramètres

deep

Indique si l'on doit copier tous les nœuds fils. Ce paramètre vaut false par défaut.

Valeurs de retour

Le nœud cloné.

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();

?>


Checks if node contains other node

  • « DOMNode::cloneNode
  • DOMNode::getLineNo »
  • PHP Manual
  • DOMNode
  • Checks if node contains other node

DOMNode::contains

(PHP 8 >= 8.3.0)

DOMNode::contains — Checks if node contains other node

Description

public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool

Checks if node contains other node.

Liste de paramètres

other

Node to be checked.

Valeurs de retour

Returns true if node contains other node, false otherwise.

Exemples

Exemple #1 DOMNode::contains() example

<?php

$dom = new DOMDocument();
$dom->loadXML(<<<XML
<!DOCTYPE HTML>
<html>
<body>
<main>
<p>Hello, world!</p>
</main>
</body>
</html>
XML);

$xpath = new DOMXPath($dom);
$main = $xpath->query("//main")[0];

var_dump($dom->documentElement->contains($main));
?>

L'exemple ci-dessus va afficher :

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Lit le numéro de ligne d'un nœud

  • « DOMNode::contains
  • DOMNode::getNodePath »
  • PHP Manual
  • DOMNode
  • Lit le numéro de ligne d'un nœud

DOMNode::getLineNo

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DOMNode::getLineNo — Lit le numéro de ligne d'un nœud

Description

public DOMNode::getLineNo(): int

Lit le numéro de ligne d'un nœud.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le numéro de ligne de définition du nœud.

Exemples

Exemple #1 Exemple avec DOMNode::getLineNo()

<?php
// XML de l'exemple
$xml = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<node />
</root>
XML;

// Création d'un objet DOMDocument
$dom = new DOMDocument;

// Chargement du XML
$dom->loadXML($xml);

// Affichage du numéro de ligne du nœud.
printf('Le nœud <node> est défini à la ligne %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

L'exemple ci-dessus va afficher :

Le nœud <node> est défini à la ligne 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.


Récupère un XPath pour un nœud

  • « DOMNode::getLineNo
  • DOMNode::getRootNode »
  • PHP Manual
  • DOMNode
  • Récupère un XPath pour un nœud

DOMNode::getNodePath

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMNode::getNodePath — Récupère un XPath pour un nœud

Description

public DOMNode::getNodePath(): ?string

Récupère un chemin XPath pour le nœud.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne un chaîne de caractères contenant le XPath, ou null si une erreur survient.

Exemples

Exemple #1 Exemple avec DOMNode::getNodePath()

<?php
// Crée une nouvelle instance DOMDocument
$dom = new DOMDocument;

// Charge le XML
$dom->loadXML('
<fruits>
<apples>
<apple>braeburn</apple>
<apple>granny smith</apple>
</apples>
<pears>
<pear>conference</pear>
</pears>
</fruits>
');

// Affiche le XPath pour chaque élément
foreach ($dom->getElementsByTagName('*') as $node) {
echo $node->getNodePath() . "\n";
}
?>

L'exemple ci-dessus va afficher :

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

Voir aussi

  • DOMXPath

User Contributed Notes

There are no user contributed notes for this page.


Get root node

  • « DOMNode::getNodePath
  • DOMNode::hasAttributes »
  • PHP Manual
  • DOMNode
  • Get root node

DOMNode::getRootNode

(PHP 8 >= 8.3.0)

DOMNode::getRootNode — Get root node

Description

public DOMNode::getRootNode(array $options = null): DOMNode

Get root node.

Liste de paramètres

options

This parameter has no effect yet.

Valeurs de retour

Returns the root node.

Exemples

Exemple #1 DOMNode::getRootNode() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><html><body/></html>');

var_dump($dom->documentElement->firstElementChild->getRootNode() === $dom);
?>

L'exemple ci-dessus va afficher :

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si le nœud possède un attribut

  • « DOMNode::getRootNode
  • DOMNode::hasChildNodes »
  • PHP Manual
  • DOMNode
  • Vérifie si le nœud possède un attribut

DOMNode::hasAttributes

(PHP 5, PHP 7, PHP 8)

DOMNode::hasAttributes — Vérifie si le nœud possède un attribut

Description

public DOMNode::hasAttributes(): bool

Cette méthode vérifie si un nœud possède des attributs. Le nœud testé doit être un XML_ELEMENT_NODE.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMNode::hasChildNodes() - Vérifie si le nœud possède des enfants

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si le nœud possède des enfants

  • « DOMNode::hasAttributes
  • DOMNode::insertBefore »
  • PHP Manual
  • DOMNode
  • Vérifie si le nœud possède des enfants

DOMNode::hasChildNodes

(PHP 5, PHP 7, PHP 8)

DOMNode::hasChildNodes — Vérifie si le nœud possède des enfants

Description

public DOMNode::hasChildNodes(): bool

Cette fonction vérifie si un nœud possède des enfants.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMImplementation::hasFeature() - Teste si l'implémentation DOM implémente une fonctionnalité spécifique

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

- - - - - - - - - - - - - -


Ajoute un nouveau fils avant un nœud de référence.

  • « DOMNode::hasChildNodes
  • DOMNode::isDefaultNamespace »
  • PHP Manual
  • DOMNode
  • Ajoute un nouveau fils avant un nœud de référence.

DOMNode::insertBefore

(PHP 5, PHP 7, PHP 8)

DOMNode::insertBefore — Ajoute un nouveau fils avant un nœud de référence.

Description

public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false

Cette fonction insère un nouveau nœud juste avant le nœud de référence. Si vous comptez faire des modifications plus tard sur l'enfant ajouté, vous devez utiliser le nœud retourné.

Lors de l'utilisation d'un nœud existant, il sera déplacé.

Liste de paramètres

node

Le nouveau nœud.

child

Le nœud référencé. Si non spécifié, node sera ajouté aux fils.

Valeurs de retour

Le nœud inséré ou false en cas d'erreur.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule ou si le parent précédent le nœud à insérer est en lecture seule.

DOM_HIERARCHY_REQUEST_ERR

Lancé si ce nœud est d'un type qui n'autorise pas de fils du type du nœud node, ou si le nœud à ajouter est un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Lancé si node a été créé depuis un document différent que celui qui a créé ce nœud.

DOM_NOT_FOUND

Lancé si child n'est pas un fils de ce nœud.

Voir aussi

  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils

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);


Vérifie si l'espace de nom spécifié est l'espace de noms par défaut ou non

  • « DOMNode::insertBefore
  • DOMNode::isEqualNode »
  • PHP Manual
  • DOMNode
  • Vérifie si l'espace de nom spécifié est l'espace de noms par défaut ou non

DOMNode::isDefaultNamespace

(PHP 5, PHP 7, PHP 8)

DOMNode::isDefaultNamespace — Vérifie si l'espace de nom spécifié est l'espace de noms par défaut ou non

Description

public DOMNode::isDefaultNamespace(string $namespace): bool

Vérifie si namespace est l'espace de noms par défaut.

Liste de paramètres

namespace

L'URI de l'espace de noms à vérifier.

Valeurs de retour

Retourne true si namespace est l'espace de noms par défaut, false sinon.

User Contributed Notes

There are no user contributed notes for this page.


Checks that both nodes are equal

  • « DOMNode::isDefaultNamespace
  • DOMNode::isSameNode »
  • PHP Manual
  • DOMNode
  • Checks that both nodes are equal

DOMNode::isEqualNode

(PHP 8 >= 8.3.0)

DOMNode::isEqualNode — Checks that both nodes are equal

Description

public DOMNode::isEqualNode(?DOMNode $otherNode): bool

Checks that both nodes are equal.

Liste de paramètres

otherNode

The node.

Valeurs de retour

Returns true if both nodes are equal, false otherwise.

Exemples

Exemple #1 DOMNode::isEqualNode() example

<?php

$dom1 = (new DOMDocument())->createElement('h1', 'Hello World!');
$dom2 = (new DOMDocument())->createElement('h1', 'Hello World!');

var_dump($dom1->isEqualNode($dom2));
?>

L'exemple ci-dessus va afficher :

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Indique si deux nœuds sont identiques

  • « DOMNode::isEqualNode
  • DOMNode::isSupported »
  • PHP Manual
  • DOMNode
  • Indique si deux nœuds sont identiques

DOMNode::isSameNode

(PHP 5, PHP 7, PHP 8)

DOMNode::isSameNode — Indique si deux nœuds sont identiques

Description

public DOMNode::isSameNode(DOMNode $otherNode): bool

Cette fonction indique si deux nœuds sont identiques. La comparaison n'est pas basée sur le contenu.

Liste de paramètres

otherNode

Le nœud à comparer.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si la fonctionnalité est disponible pour la version spécifiée

  • « DOMNode::isSameNode
  • DOMNode::lookupNamespaceURI »
  • PHP Manual
  • DOMNode
  • Vérifie si la fonctionnalité est disponible pour la version spécifiée

DOMNode::isSupported

(PHP 5, PHP 7, PHP 8)

DOMNode::isSupported — Vérifie si la fonctionnalité est disponible pour la version spécifiée

Description

public DOMNode::isSupported(string $feature, string $version): bool

Vérifie si la fonctionnalité feature demandée est supportée par la version version spécifiée.

Liste de paramètres

feature

La fonctionnalité à tester. Voir l'exemple de DOMImplementation::hasFeature() pour une liste de fonctionnalités.

version

Le numéro de la version de la fonctionnalité feature à tester.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • DOMImplementation::hasFeature() - Teste si l'implémentation DOM implémente une fonctionnalité spécifique

User Contributed Notes

There are no user contributed notes for this page.


Retourne l'URI de l'espace de noms selon le préfixe

  • « DOMNode::isSupported
  • DOMNode::lookupPrefix »
  • PHP Manual
  • DOMNode
  • Retourne l'URI de l'espace de noms selon le préfixe

DOMNode::lookupNamespaceURI

(PHP 5, PHP 7, PHP 8)

DOMNode::lookupNamespaceURI — Retourne l'URI de l'espace de noms selon le préfixe

Description

public DOMNode::lookupNamespaceURI(?string $prefix): ?string

Retourne l'URI de l'espace de noms selon le préfixe prefix.

Liste de paramètres

prefix

Le préfixe à rechercher. Si ce paramètre est null, la méthode renverra l'URI de l'espace de noms par défaut, s'il existe.

Valeurs de retour

Renvoie l'URI de l'espace de noms associé, ou null s'il n'en est pas trouvé.

Voir aussi

  • DOMNode::lookupPrefix() - Retourne le préfixe de l'espace de noms selon l'URI de l'espace de noms

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);
?>


Retourne le préfixe de l'espace de noms selon l'URI de l'espace de noms

  • « DOMNode::lookupNamespaceURI
  • DOMNode::normalize »
  • PHP Manual
  • DOMNode
  • Retourne le préfixe de l'espace de noms selon l'URI de l'espace de noms

DOMNode::lookupPrefix

(PHP 5, PHP 7, PHP 8)

DOMNode::lookupPrefix — Retourne le préfixe de l'espace de noms selon l'URI de l'espace de noms

Description

public DOMNode::lookupPrefix(string $namespace): ?string

Retourne le préfixe de l'espace du nœud selon l'URI de l'espace de noms.

Liste de paramètres

namespace

L'URI de l'espace de noms.

Valeurs de retour

Le préfixe de l'espace de noms ou null en cas d'erreur.

Voir aussi

  • DOMNode::lookupNamespaceUri() - Retourne l'URI de l'espace de noms selon le préfixe

User Contributed Notes

There are no user contributed notes for this page.


Normalise le nœud

  • « DOMNode::lookupPrefix
  • DOMNode::removeChild »
  • PHP Manual
  • DOMNode
  • Normalise le nœud

DOMNode::normalize

(PHP 5, PHP 7, PHP 8)

DOMNode::normalize — Normalise le nœud

Description

public DOMNode::normalize(): void

Supprime les nœuds de texte vides et fusionne les nœuds de texte adjacents dans ce nœud ainsi que tous ces enfants.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • » La spécification DOM
  • DOMDocument::normalizeDocument() - Normalise le 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.


Supprime un fils de la liste des enfants

  • « DOMNode::normalize
  • DOMNode::replaceChild »
  • PHP Manual
  • DOMNode
  • Supprime un fils de la liste des enfants

DOMNode::removeChild

(PHP 5, PHP 7, PHP 8)

DOMNode::removeChild — Supprime un fils de la liste des enfants

Description

public DOMNode::removeChild(DOMNode $child): DOMNode|false

Cette fonction supprime un fils de la liste des enfants.

Liste de paramètres

child

Le fils à effacer.

Valeurs de retour

Si le fils ne peut être effacé, la fonction retourne l'ancien fils ou false en cas d'erreur.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule.

DOM_NOT_FOUND

Lancé si child n'est pas un fils de ce nœud.

Exemples

L'exemple suivant va effacer l'élément chapter de notre document XML.

Exemple #1 Effacement d'un fils

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// Nous récupérons le chapitre et l'effaçons du livre
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="iso-8859-1"?>
<!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>

Voir aussi

  • DOMChildNode::remove() - Supprime le nœud
  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMNode::replaceChild() - Remplace un fils

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) !!!
}
?>


Remplace un fils

  • « DOMNode::removeChild
  • DOMNodeList »
  • PHP Manual
  • DOMNode
  • Remplace un fils

DOMNode::replaceChild

(PHP 5, PHP 7, PHP 8)

DOMNode::replaceChild — Remplace un fils

Description

public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false

Cette fonction remplace le fils child par le nouveau nœud spécifié. Si node est déjà un fils, il ne sera pas ajouté une seconde fois. Si le remplacement réussi, l'ancien nœud sera retourné.

Liste de paramètres

node

Le nouveau nœud. Il doit être membre du document cible, i.e. créé par une des méthodes de DOMDocument->createXXX() ou importé dans le document par DOMDocument::importNode.

child

L'ancien nœud.

Valeurs de retour

L'ancien nœud ou false si une erreur survient.

Erreurs / Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Lancé si le nœud est en lecture seule ou si le parent précédent du nœud à insérer est en lecture seule.

DOM_HIERARCHY_REQUEST_ERR

Lancé si le nœud est d'un type qui n'autorise pas les fils du type du nœud node, ou si le nœud à insérer est un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Émise si node a été créé depuis un document différent que celui qui a créé ce nœud.

DOM_NOT_FOUND

Lancé si child n'est pas un fils de ce nœud.

Voir aussi

  • DOMChildNode::replaceWith() - Remplace le nœud par de nouveaux nœuds
  • DOMNode::appendChild() - Ajoute un nouveau fils à la fin des fils
  • DOMNode::removeChild() - Supprime un fils de la liste des enfants

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)


La classe DOMNodeList

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMNodeList implements IteratorAggregate, Countable {
/* Propriétés */
public readonly int $length;
/* Méthodes */
public count(): int
public getIterator(): Iterator
public item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null
}

Propriétés

length

Le nombre de nœuds dans la liste. L'intervalle valide des indices des nœuds fils est 0 à length - 1, inclus.

Historique

Version | Description
8.0.0 | DOMNodeList implémente désormais IteratorAggregate. Auparavant, Traversable était implémenté à la place.
7.2.0 | L'interface Countable est implémentée et retourne la valeur de la propriété length.

Voir aussi

  • » Les spécifications W3C de NodeList

Sommaire

  • DOMNodeList::count — Récupère le nombre de nœuds dans la collection triée (list)
  • DOMNodeList::getIterator — Retrieve an external iterator
  • DOMNodeList::item — Retourne un nœud spécifié par son index

User Contributed Notes

niko at yopmail dot com 03-Apr-2021 03:13
It's worth to mention that DOMNodeList is not an Array,  so you have to convert first to an array before to use for, foreach or array_map, array_filter, array_walk functions.

Use iterator_to_array to make the conversion ( since PHP 5.1.0 ) .

<code>
  /* @ suppress warning var_dump not yet implemented for class */

@array_walk( iterator_to_array( $Some_NodeList ), 'var_dump' ) );

foreach( iterator_to_array( $Some_NodeList ) as $node )
    @var_dump( $node );

</code>

Hope is usefull.
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.


Récupère le nombre de nœuds dans la collection triée (list)

  • « DOMNodeList
  • DOMNodeList::getIterator »
  • PHP Manual
  • DOMNodeList
  • Récupère le nombre de nœuds dans la collection triée (list)

DOMNodeList::count

(PHP 7 >= 7.2.0, PHP 8)

DOMNodeList::count — Récupère le nombre de nœuds dans la collection triée (list)

Description

public DOMNodeList::count(): int

Récupère le nombre de nœuds dans la collection triée (list).

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le nombre de nœuds dans la collection triée, ce qui est identique à la propriété length.

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


Retrieve an external iterator

  • « DOMNodeList::count
  • DOMNodeList::item »
  • PHP Manual
  • DOMNodeList
  • Retrieve an external iterator

DOMNodeList::getIterator

(PHP 8)

DOMNodeList::getIterator — Retrieve an external iterator

Description

public DOMNodeList::getIterator(): Iterator

Returns an external iterator for the node list.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Une instance d'un objet qui implémente un Iterator ou l'interface Traversable.

Erreurs / Exceptions

Émet une Exception en cas d'échec.

Voir aussi

  • IteratorAggregate::getIterator() - Retourne un itérateur externe

User Contributed Notes

There are no user contributed notes for this page.


Retourne un nœud spécifié par son index

  • « DOMNodeList::getIterator
  • DOMNotation »
  • PHP Manual
  • DOMNodeList
  • Retourne un nœud spécifié par son index

DOMNodeList::item

(PHP 5, PHP 7, PHP 8)

DOMNodeList::item — Retourne un nœud spécifié par son index

Description

public DOMNodeList::item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null

Retourne un nœud spécifié par son index dans l'objet DOMNodeList.

Astuce

Si vous avez besoin de connaître le nombre de nœuds dans la collection, utilisez la propriété length de l'objet DOMNodeList.

Liste de paramètres

index

L'index du nœud dans la collection.

Valeurs de retour

Le nœud à la position index dans la DOMNodeList, ou null si ce n'est pas un index valide.

Exemples

Exemple #1 Parcours de toutes les entrées de la 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";
}

?>

Alternativement, vous pouvez utiliser la structure foreach, qui est une manière plus convenable :

<?php

foreach ($items as $item) {
echo $item->nodeValue . "\n";
}

?>

L'exemple ci-dessus va afficher :

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;
}

?>


La classe DOMNotation

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMNotation extends DOMNode {
/* Propriétés */
public readonly string $publicId;
public readonly string $systemId;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

publicId

systemId

User Contributed Notes

There are no user contributed notes for this page.


L'interface DOMParentNode

(PHP 8)

Sommaire de l'Interface

interface DOMParentNode {
/* Méthodes */
public append(DOMNode|string ...$nodes): void
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
}

Sommaire

  • DOMParentNode::append — Ajoute des nœuds après le dernier nœud enfant
  • DOMParentNode::prepend — Ajoute des nœuds avant le premier nœud enfant
  • DOMParentNode::replaceChildren — Replace children in node

User Contributed Notes

There are no user contributed notes for this page.


Ajoute des nœuds après le dernier nœud enfant

  • « DOMParentNode
  • DOMParentNode::prepend »
  • PHP Manual
  • DOMParentNode
  • Ajoute des nœuds après le dernier nœud enfant

DOMParentNode::append

(PHP 8)

DOMParentNode::append — Ajoute des nœuds après le dernier nœud enfant

Description

public DOMParentNode::append(DOMNode|string ...$nodes): void

Ajoute un ou plusieurs nodes à la liste des enfants après le dernier nœud enfant.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Voir aussi

  • DOMParentNode::prepend() - Ajoute des nœuds avant le premier nœud enfant

User Contributed Notes

There are no user contributed notes for this page.


Ajoute des nœuds avant le premier nœud enfant

  • « DOMParentNode::append
  • DOMParentNode::replaceChildren »
  • PHP Manual
  • DOMParentNode
  • Ajoute des nœuds avant le premier nœud enfant

DOMParentNode::prepend

(PHP 8)

DOMParentNode::prepend — Ajoute des nœuds avant le premier nœud enfant

Description

public DOMParentNode::prepend(DOMNode|string ...$nodes): void

Ajoute un ou plusieurs nodes à la liste des enfants avant le premier nœud enfant.

Liste de paramètres

nodes

Les nœuds à ajouter. Les chaînes de caractères sont automatiquement convertie en des nœuds de texte.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Appeler cette méthode sur un nœud sans document propriétaire fonctionne désormais. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Voir aussi

  • DOMParentNode::append() - Ajoute des nœuds après le dernier nœud enfant

User Contributed Notes

There are no user contributed notes for this page.


Replace children in node

  • « DOMParentNode::prepend
  • DOMProcessingInstruction »
  • PHP Manual
  • DOMParentNode
  • Replace children in node

DOMParentNode::replaceChildren

(PHP 8 >= 8.3.0)

DOMParentNode::replaceChildren — Replace children in node

Description

public DOMParentNode::replaceChildren(DOMNode|string ...$nodes): void

Replace children in node.

Liste de paramètres

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valeurs de retour

Aucune valeur n'est retournée.

Erreurs / Exceptions

DOM_HIERARCHY_REQUEST_ERR

Levée si ce nœud est d'un type qui n'autorise pas les enfants du type de l'un des nodes transmis, ou si le nœud à insérer est l'un des ancêtres de ce nœud ou ce nœud lui-même.

DOM_WRONG_DOCUMENT_ERR

Levée si l'un des nodes transmis a été créé à partir d'un document différent de celui qui a créé ce nœud.

Historique

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Auparavant, cela déclenchait une DOMException avec le code DOM_HIERARCHY_REQUEST_ERR.

Exemples

Exemple #1 DOMParentNode::replaceChildren() example

<?php

$dom = new DOMDocument();
$dom->loadHTML('<!DOCTYPE HTML><html><p>hi</p> test <p>hi2</p></html>');

$dom->documentElement->replaceChildren('foo', $dom->createElement('p'), 'bar');
echo $dom->saveXML();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE HTML>
<html>foo<p/>bar</html>

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMProcessingInstruction

(PHP 5, PHP 7, PHP 8)

Synopsis de la classe

class DOMProcessingInstruction extends DOMNode {
/* Propriétés */
public readonly string $target;
public string $data;
/* Propriétés héritées */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $name, string $value = "")
/* Méthodes héritées */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

target

data

Sommaire

  • DOMProcessingInstruction::__construct — Crée un nouvel objet DOMProcessingInstruction

User Contributed Notes

There are no user contributed notes for this page.


Crée un nouvel objet DOMProcessingInstruction

  • « DOMProcessingInstruction
  • DOMText »
  • PHP Manual
  • DOMProcessingInstruction
  • Crée un nouvel objet DOMProcessingInstruction

DOMProcessingInstruction::__construct

(PHP 5, PHP 7, PHP 8)

DOMProcessingInstruction::__construct — Crée un nouvel objet DOMProcessingInstruction

Description

public DOMProcessingInstruction::__construct(string $name, string $value = "")

Crée un nouvel objet DOMProcessingInstruction. Cet objet est en lecture seule. Il peut être ajouté à un document, mais les nœuds additionnels ne peuvent pas être ajoutés à ce nœud tant qu'il est associé à un document. Pour créer un nœud accessible en écriture, utilisez DOMDocument::createProcessingInstruction.

Liste de paramètres

name

Le nom du tag de l'instruction.

value

La valeur de l'instruction.

Exemples

Exemple #1 Création d'un nouveau DOMProcessingInstruction

<?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 "Bonjour le monde !"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Bonjour le monde !"; ?></body></html>

Voir aussi

  • DOMDocument::createProcessingInstruction() - Crée un nouveau nœud PI

User Contributed Notes

There are no user contributed notes for this page.


La classe DOMText

(PHP 5, PHP 7, PHP 8)

Introduction

La classe DOMText hérite de DOMCharacterData et représente le contenu textuel de DOMElement ou DOMAttr.

Synopsis de la classe

class DOMText extends DOMCharacterData {
/* Propriétés */
public readonly string $wholeText;
/* Propriétés héritées */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Méthodes */
public __construct(string $data = "")
public isElementContentWhitespace(): bool
public isWhitespaceInElementContent(): bool
public splitText(int $offset): DOMText|false
/* Méthodes héritées */
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
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 $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriétés

wholeText

Contient tout le texte des nœuds de texte adjacents (c'est à dire, des nœuds qui ne sont pas séparés par des balises Element, Comment ou Processing Instruction).

Historique

Version | Description
8.0.0 | La méthode non implémentée DOMText::replaceWholeText() a été supprimée.

Sommaire

  • DOMText::__construct — Crée un nouvel objet DOMText
  • DOMText::isElementContentWhitespace — Rapporte si le nœud textuel contient des caractères d'espacement blanc
  • DOMText::isWhitespaceInElementContent — Indique si ce nœud de texte contient des espaces blancs
  • DOMText::splitText — Coupe le nœud en deux nœuds à l'endroit spécifié

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 );
      }
    }
  }
}


Crée un nouvel objet DOMText

  • « DOMText
  • DOMText::isElementContentWhitespace »
  • PHP Manual
  • DOMText
  • Crée un nouvel objet DOMText

DOMText::__construct

(PHP 5, PHP 7, PHP 8)

DOMText::__construct — Crée un nouvel objet DOMText

Description

public DOMText::__construct(string $data = "")

Crée un nouvel objet DOMText.

Liste de paramètres

data

La valeur du nœud texte. Si aucune n'est fournie, un nœud texte vide est créé.

Exemples

Exemple #1 Création d'un nouveau 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>valeur racine</root> */

?>

Voir aussi

  • DOMDocument::createTextNode() - Crée un nouveau nœud de texte

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.


Rapporte si le nœud textuel contient des caractères d'espacement blanc

  • « DOMText::__construct
  • DOMText::isWhitespaceInElementContent »
  • PHP Manual
  • DOMText
  • Rapporte si le nœud textuel contient des caractères d'espacement blanc

DOMText::isElementContentWhitespace

(No version information available, might only be in Git)

DOMText::isElementContentWhitespace — Rapporte si le nœud textuel contient des caractères d'espacement blanc

Description

public DOMText::isElementContentWhitespace(): bool

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

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.


Indique si ce nœud de texte contient des espaces blancs

  • « DOMText::isElementContentWhitespace
  • DOMText::splitText »
  • PHP Manual
  • DOMText
  • Indique si ce nœud de texte contient des espaces blancs

DOMText::isWhitespaceInElementContent

(PHP 5, PHP 7, PHP 8)

DOMText::isWhitespaceInElementContent — Indique si ce nœud de texte contient des espaces blancs

Description

public DOMText::isWhitespaceInElementContent(): bool

Indique si un nœud de texte ne contient que des espaces ou est vide. Cette détermination est faite durant le chargement du document.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne true si le nœud contient zéro ou plusieurs caractères blancs et rien d'autre. Retourne false sinon.

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


Coupe le nœud en deux nœuds à l'endroit spécifié

  • « DOMText::isWhitespaceInElementContent
  • DOMXPath »
  • PHP Manual
  • DOMText
  • Coupe le nœud en deux nœuds à l'endroit spécifié

DOMText::splitText

(PHP 5, PHP 7, PHP 8)

DOMText::splitText — Coupe le nœud en deux nœuds à l'endroit spécifié

Description

public DOMText::splitText(int $offset): DOMText|false

Coupe le nœud en deux nœuds à l'endroit spécifié offset, en gardant les deux dans l'arbre comme parents.

Après la césure, ce nœud contiendra tout le texte jusqu'à offset. Un nouveau nœud avec le reste du texte sera retourné. Si le nœud d'origine possède un parent, le nouveau nœud est inséré à la suite du nœud courant. Lorsque offset est égal à la taille du nœud, le nouveau nœud est vide.

Liste de paramètres

offset

La position de la césure, commençant à 0.

Valeurs de retour

Le nouveau nœud du même type, qui contient tout le contenu à partir de la position 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());
}
?>


La classe DOMXPath

(PHP 5, PHP 7, PHP 8)

Introduction

Support de XPath 1.0.

Synopsis de la classe

class DOMXPath {
/* Propriétés */
public readonly DOMDocument $document;
public bool $registerNodeNamespaces;
/* Méthodes */
public __construct(DOMDocument $document, bool $registerNodeNS = true)
public evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed
public query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed
public registerNamespace(string $prefix, string $namespace): bool
public registerPhpFunctions(string|array|null $restrict = null): void
}

Propriétés

document

registerNodeNamespaces

Quand définie à true, les espaces de noms dans le nœud sont enregistrés.

Historique

Version | Description
8.0.0 | La propriété registerNodeNamespaces a été ajoutée.

Sommaire

  • DOMXPath::__construct — Crée un nouvel objet DOMXPath
  • DOMXPath::evaluate — Évalue une expression XPath donnée et retourne un résultat typé si possible
  • DOMXPath::query — Évalue l'expression XPath donnée
  • DOMXPath::registerNamespace — Enregistre l'espace de noms avec l'objet DOMXPath
  • DOMXPath::registerPhpFunctions — Enregistre une fonction PHP comme fonction XPath

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.
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";
    }
  }
}
?>


Crée un nouvel objet DOMXPath

  • « DOMXPath
  • DOMXPath::evaluate »
  • PHP Manual
  • DOMXPath
  • Crée un nouvel objet DOMXPath

DOMXPath::__construct

(PHP 5, PHP 7, PHP 8)

DOMXPath::__construct — Crée un nouvel objet DOMXPath

Description

public DOMXPath::__construct(DOMDocument $document, bool $registerNodeNS = true)

Crée un nouvel objet DOMXPath.

Liste de paramètres

document

L'objet DOMDocument associé à l'objet 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.


Évalue une expression XPath donnée et retourne un résultat typé si possible

  • « DOMXPath::__construct
  • DOMXPath::query »
  • PHP Manual
  • DOMXPath
  • Évalue une expression XPath donnée et retourne un résultat typé si possible

DOMXPath::evaluate

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

DOMXPath::evaluate — Évalue une expression XPath donnée et retourne un résultat typé si possible

Description

public DOMXPath::evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Exécute l'expression XPath expression et retourne un résultat typé si possible.

Liste de paramètres

expression

L'expression XPath à exécuter.

contextNode

Le paramètre optionnel contextNode peut être spécifié pour effectuer des requêtes XPath relatives. Par défaut, les requêtes sont relatives à l'élément root.

registerNodeNS

Le paramètre optionnel registerNodeNS peut être renseigné pour désactiver l'enregistrement automatique du nœud de contexte.

Valeurs de retour

Retourne un résultat typé si possible ou un DOMNodeList contenant tous les nœuds correspondant à l'expression XPath expression.

Si le paramètre expression est mal formé ou bien si le paramètre contextNode est invalide, la méthode DOMXPath::evaluate() retournera false.

Exemples

Exemple #1 Récupération du nombre total de livres anglais

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// notre requête est relative au nœud tbody
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "Il y a $entries livres anglais\n";

?>

L'exemple ci-dessus va afficher :

Il y a 2 livres anglais

Voir aussi

  • DOMXPath::query() - Évalue l'expression XPath donnée

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

            }
        }
    }
?>


Évalue l'expression XPath donnée

  • « DOMXPath::evaluate
  • DOMXPath::registerNamespace »
  • PHP Manual
  • DOMXPath
  • Évalue l'expression XPath donnée

DOMXPath::query

(PHP 5, PHP 7, PHP 8)

DOMXPath::query — Évalue l'expression XPath donnée

Description

public DOMXPath::query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Évalue l'expression expression XPath donnée.

Liste de paramètres

expression

L'expression XPath à exécuter.

contextNode

Le paramètre optionnel contextNode peut être spécifié pour effectuer des requêtes XPath relative. Par défaut, les requêtes sont relatives à l'élément racine.

registerNodeNS

Le paramètre optionnel registerNodeNS peut être renseigné pour désactiver l'enregistrement automatique du nœud de contexte.

Valeurs de retour

Retourne un DOMNodeList contenant tous les nœuds correspondant à l'expression expression XPath donnée. Toutes les expressions qui ne retournent pas de nœud retourneront un DOMNodeList vide.

Si le paramètre expression est malformé ou le paramètre contextNode est invalide, DOMXPath::query() retournera false.

Exemples

Exemple #1 Récupération de tous les livres anglais

<?php

$doc = new DOMDocument;

// Nous ne voulons pas nous soucier des espaces blancs
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Nous commençons à l'élément racine
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
echo "Livre trouvé {$entry->previousSibling->previousSibling->nodeValue}," .
" par {$entry->previousSibling->nodeValue}\n";
}
?>

L'exemple ci-dessus va afficher :

Livre trouvé : The Grapes of Wrath, par John Steinbeck
Livre trouvé : The Pearl, par John Steinbeck

Nous pouvons également utiliser le paramètre contextNode pour raccourcir notre expression :

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// notre requête est relative au nœud tbody
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
echo "Livre trouvé : {$entry->previousSibling->previousSibling->nodeValue}," .
" par {$entry->previousSibling->nodeValue}\n";
}
?>

Voir aussi

  • DOMXPath::query()

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


Enregistre l'espace de noms avec l'objet DOMXPath

  • « DOMXPath::query
  • DOMXPath::registerPhpFunctions »
  • PHP Manual
  • DOMXPath
  • Enregistre l'espace de noms avec l'objet DOMXPath

DOMXPath::registerNamespace

(PHP 5, PHP 7, PHP 8)

DOMXPath::registerNamespace — Enregistre l'espace de noms avec l'objet DOMXPath

Description

public DOMXPath::registerNamespace(string $prefix, string $namespace): bool

Enregistre l'espace de noms namespace et le prefix avec l'objet DOMXPath.

Liste de paramètres

prefix

Le préfixe.

namespace

L'URI de l'espace de noms.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

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.


Enregistre une fonction PHP comme fonction XPath

  • « DOMXPath::registerNamespace
  • DOM Fonctions »
  • PHP Manual
  • DOMXPath
  • Enregistre une fonction PHP comme fonction XPath

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DOMXPath::registerPhpFunctions — Enregistre une fonction PHP comme fonction XPath

Description

public DOMXPath::registerPhpFunctions(string|array|null $restrict = null): void

Cette méthode active la possibilité d'utiliser des fonctions PHP dans des expressions XPath.

Liste de paramètres

restrict

Utilisez ce paramètre uniquement pour autoriser certaines fonctions à être appelées depuis XPath.

Ce paramètre peut être soit une chaîne de caractères (un nom de fonction) ou un tableau de noms de fonctions.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Les exemples suivants utilisent le fichier book.xml qui contient les données suivantes :

Exemple #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>

Exemple #2 Exemple avec DOMXPath::registerPHPFunctions() et php:functionString

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Enregistre l'espace de noms php (nécessaire)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Enregistre les fonctions PHP (Aucune restriction)
$xpath->registerPHPFunctions();

// Appèle la fonction substr sur le titre du livre
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "{$nodes->length} livres trouvés dont le titre commence par 'PHP':\n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title par $author\n";
}

?>

Résultat de l'exemple ci-dessus est similaire à :

2 livres trouvés dont le titre commence par 'PHP':
PHP Basics par Jim Smith
PHP Secrets par Jenny Smythe

Exemple #3 Exemple avec DOMXPath::registerPHPFunctions() et php:function

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Enregistre l'espace de noms php (nécessaire)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Enregistre des fonctions PHP (has_multiple uniquement)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
// Retourne true s'il y a plus d'un auteur
return count($nodes) > 1;
}
// Filtre les livres dont les auteurs sont multiples
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Livres avec plusieurs auteurs :\n";
foreach ($books as $book) {
echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

Résultat de l'exemple ci-dessus est similaire à :

Livres avec plusieurs auteurs :
PHP Basics

Voir aussi

  • DOMXPath::registerNamespace() - Enregistre l'espace de noms avec l'objet DOMXPath
  • DOMXPath::query() - Évalue l'expression XPath donnée
  • DOMXPath::evaluate() - Évalue une expression XPath donnée et retourne un résultat typé si possible

User Contributed Notes

There are no user contributed notes for this page.


DOM Fonctions

Sommaire

  • dom_import_simplexml — Transforme un objet SimpleXMLElement en un objet DOMElement

User Contributed Notes

There are no user contributed notes for this page.


Transforme un objet SimpleXMLElement en un objet DOMElement

  • « DOM Fonctions
  • libxml »
  • PHP Manual
  • DOM Fonctions
  • Transforme un objet SimpleXMLElement en un objet DOMElement

dom_import_simplexml

(PHP 5, PHP 7, PHP 8)

dom_import_simplexml — Transforme un objet SimpleXMLElement en un objet DOMElement

Description

dom_import_simplexml(object $node): DOMElement

dom_import_simplexml() transforme l'objet SimpleXML node en un objet DOMElement. Le nouvel objet peut être utilisé en tant que nœud natif DOMElement.

Liste de paramètres

node

Le nœud SimpleXMLElement.

Valeurs de retour

Le nœud DOMElement ajouté.

Historique

Version | Description
8.0.0 | Cette fonction ne retourne désormais plus null en cas d'échec.

Exemples

Exemple #1 Importation d'un objet SimpleXML dans DOM avec dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
echo 'Erreur lors de l\'analyse du document';
exit;
}

$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);

echo $dom->saveXML();

?>

Voir aussi

  • simplexml_import_dom() - Construit un objet SimpleXMLElement à partir d'un objet DOM

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

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation pour les versions de PHP >= 7.4
    • Installation pour les versions de PHP < 7.4
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • libXMLError — La classe libXMLError
  • Fonctions libxml
    • libxml_clear_errors — Vide le buffer d'erreur libxml
    • libxml_disable_entity_loader — Désactive le chargement des entités externes
    • libxml_get_errors — Lit le tableau d'erreurs
    • libxml_get_external_entity_loader — Get the current external entity loader
    • libxml_get_last_error — Lit la dernière erreur libxml
    • libxml_set_external_entity_loader — Change le chargeur d'entités externes par défaut
    • libxml_set_streams_context — Configure le contexte de flux pour la prochaine opération libxml
    • libxml_use_internal_errors — Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Ces fonctions et constantes sont disponibles depuis PHP 5.1.0 et si vous avez compilé PHP avec les extensions basées sur libxml, c'est à dire DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XML, XMLReader, XMLRPC et XMLWriter.

User Contributed Notes

There are no user contributed notes for this page.


Installation/Configuration

Sommaire

  • Pré-requis
  • Installation pour les versions de PHP >= 7.4
  • Installation pour les versions de PHP < 7.4
  • Configuration à l'exécution
  • Types de ressources

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

Cette extension requiert » libxml >= 2.9.0 à partir de PHP 8.0.0. Antérieur à PHP 8.0, libxml doit être >= 2.6.0.

User Contributed Notes

There are no user contributed notes for this page.


Installation pour les versions de PHP >= 7.4

L'extension libxml est activée par défaut, bien qu'elle puisse être désactivée avec l'option --without-libxml.

PHP utilise pkg-config pour sélectionner le bon fichier de bibliothèque, les fichiers d'en-tête et les indicateurs de compilation à utiliser pour libxml2. Pour s'assurer que la version souhaitée de libxml2 est sélectionnée, la variable d'environnement PKG_CONFIG_PATH peut être utilisée pour contrôler le chemin de recherche de pkg-config avant d'exécuter le script de configuration :

PKG_CONFIG_PATH="/chemin/vers/préfixe/libxml2/lib/pkgconfig:/lib/pkgconfig"

User Contributed Notes

mansourjabin at gmail dot com 06-Nov-2023 05:35
Critical Note: In PHP 7.4, an issue presents itself when interfacing with libxml version 2.10.2. If you're deploying PHP 7.4 and wish to maintain operational stability, ensure that libxml is aligned to version 2.9.10. This version has been verified to work seamlessly with PHP 7.4, thereby preventing potential conflicts.
KiralyCraft 19-Sep-2022 05:51
Please note that this option does not seem to work for PHP 8.1.10 anymore.


Installation pour les versions de PHP < 7.4

L'extension libxml est activé par défaut, et il peut être désactivé avec l'option --disable-libxml.

La directive optionnelle --with-libxml-dir est utilisée pour spécifier le dossier où libxml se trouve sur le système sur lequel PHP est compilé. À défaut de l'utilisation de cette option, les dossiers par défaut seront analysés. Le processus configure vérifie les dossiers où se trouve libxml (spécifiquement, xml2-config), dans cet ordre :

  1. Le dossier ([DIR]) spécifié avec l'option --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

Si le processus configure ne peut trouver le fichier xml2-config dans le dossier spécifié par l'option --with-libxml-dir, alors, il continuera et analysera les dossiers par défaut.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

LIBXML_BIGLINES (int)
Permet de signaler correctement les numéros de ligne supérieurs à 65535.

Note:

Uniquement disponible dans PHP 7.0.0 avec Libxml >= 2.9.0

LIBXML_COMPACT (int)
Active l'optimisation de l'allocation de petits nœuds. Ceci pourrait augmenter la rapidité de votre application sans avoir besoin de changer votre code.

Note:

Seulement disponible dans Libxml >= 2.6.21

LIBXML_DTDATTR (int)
Attribut de DTD par défaut
LIBXML_DTDLOAD (int)
Charge le sous-ensemble externe
LIBXML_DTDVALID (int)
Valide avec la DTD
Attention

Activer la validation du DTD peut faciliter les attaques par entités externes XML (XXE).

LIBXML_HTML_NOIMPLIED (int)
Définit le drapeau HTML_PARSE_NOIMPLIED, qui désactive l'ajout automatique des éléments html/body...

Note:

Uniquement disponible en Libxml >= 2.7.7 (depuis PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (int)
Définit le drapeau HTML_PARSE_NODEFDTD, qui empèche l'ajout automatique d'un doctype si aucun n'est trouvé.

Note:

Only available in Libxml >= 2.7.8 (as of PHP >= 5.4.0)

LIBXML_NOBLANKS (int)
Suppression des nœuds vides
LIBXML_NOCDATA (int)
Fusion des CDATA en nœuds de texte
LIBXML_NOEMPTYTAG (int)
Agrandit les balises vides (par exemple, <br/> en <br></br>)

Note:

Cette option est actuellement disponible uniquement avec les fonctions DOMDocument::save et DOMDocument::saveXML.

LIBXML_NOENT (int)
Substitution des entités
Attention

Activer la substitution d'entiter peut faciliter les attaques XML External Entity (XXE).

LIBXML_NOERROR (int)
Suppression du rapport d'erreur
LIBXML_NONET (int)
Désactivation du réseau lors du chargement de document
LIBXML_NOWARNING (int)
Suppression des rapports d'alerte
LIBXML_NOXMLDECL (int)
Annule la déclaration XML lors de la sauvegarde du document

Note:

Seulement disponible dans Libxml >= 2.6.21

LIBXML_NSCLEAN (int)
Suppression des espaces de noms redondants
LIBXML_PARSEHUGE (int)
Affecte le drapeau XML_PARSE_HUGE. Désactive toute limite du parseur codée en dur. Ceci affecte les limites comme la profondeur maximale d'un document ou l'entité récursion, mais aussi les limites de la taille du texte des nœuds.

Note:

Seulement disponible depuis Libxml >= 2.7.0 (depuis PHP >= 5.3.2 et PHP >= 5.2.12)

LIBXML_PEDANTIC (int)
Définit le drapeau XML_PARSE_PEDANTIC, qui active le rapport d'erreur pedantic.

Note:

Available as of PHP >= 5.4.0

LIBXML_XINCLUDE (int)
Implémentation de la substitution XInclude
LIBXML_ERR_ERROR (int)
Erreur non-fatale
LIBXML_ERR_FATAL (int)
Erreur fatale
LIBXML_ERR_NONE (int)
Aucune erreur
LIBXML_ERR_WARNING (int)
Une alerte simple
LIBXML_VERSION (int)
libxml version sous la forme 20605 ou 20617
LIBXML_DOTTED_VERSION (string)
libxml version sous la forme 2.6.5 ou 2.6.17
LIBXML_SCHEMA_CREATE (int)
Crée la valeur par défaut/fixée du nœud durant la validation du schéma XSD

Note:

Uniquement disponible en Libxml >= 2.6.14 (à partir de PHP >= 5.5.2)

User Contributed Notes

Ismael Miguel 07-Jul-2023 10:53
If you want to save without the XML declaration, and LIBXML_NOXMLDECL doesn't work for you, you can just do this:

<?php
$doc = new \DOMDocument('1.0', 'UTF-8');
$doc->loadXML($xml, LIBXML_*);

echo $doc->saveXML($doc->firstElementChild);
?>

This will output the XML without the XML declaration and without using the flag.
You also don't need to do fiddly replacements and pray that it works.
siraic at gmail dot com 24-Mar-2021 12:10
The name of the constant LIBXML_NOENT is very misleading. Adding this flag actually causes the parser to load and insert the external entities. Omitting it leaves the tags untouched, which is probably what you want.
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/>


La classe libXMLError

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Introduction

Contient diverses informations sur les erreurs émises par la bibliothèque libxml. Les codes erreurs sont décrits dans la » documentation officielle de l'API xmlError.

Synopsis de la classe

class libXMLError {
/* Propriétés */
public int $level;
public int $code;
public int $column;
public string $message;
public string $file;
public int $line;
}

Propriétés

level

la sévérité de l'erreur (une des constantes suivantes : LIBXML_ERR_WARNING, LIBXML_ERR_ERROR ou LIBXML_ERR_FATAL)

code

Le code de l'erreur.

column

La colonne dans laquelle l'erreur est survenue.

Note:

Cette propriété n'est pas totalement implémentée par la bibliothèque libxml ; aussi, 0 est souvent retourné.

message

Le message d'erreur, s'il y en a.

file

Le nom du fichier, ou vide si le XML a été chargé depuis une chaîne.

line

La ligne depuis laquelle l'erreur est survenue.

User Contributed Notes

There are no user contributed notes for this page.


Fonctions libxml

Sommaire

  • libxml_clear_errors — Vide le buffer d'erreur libxml
  • libxml_disable_entity_loader — Désactive le chargement des entités externes
  • libxml_get_errors — Lit le tableau d'erreurs
  • libxml_get_external_entity_loader — Get the current external entity loader
  • libxml_get_last_error — Lit la dernière erreur libxml
  • libxml_set_external_entity_loader — Change le chargeur d'entités externes par défaut
  • libxml_set_streams_context — Configure le contexte de flux pour la prochaine opération libxml
  • libxml_use_internal_errors — Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure

User Contributed Notes

There are no user contributed notes for this page.


Vide le buffer d'erreur libxml

  • « Fonctions libxml
  • libxml_disable_entity_loader »
  • PHP Manual
  • Fonctions libxml
  • Vide le buffer d'erreur libxml

libxml_clear_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_clear_errors — Vide le buffer d'erreur libxml

Description

libxml_clear_errors(): void

libxml_clear_errors() vide le buffer d'erreur libxml.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Voir aussi

  • libxml_get_errors() - Lit le tableau d'erreurs
  • libxml_get_last_error() - Lit la dernière erreur libxml

User Contributed Notes

There are no user contributed notes for this page.


Désactive le chargement des entités externes

  • « libxml_clear_errors
  • libxml_get_errors »
  • PHP Manual
  • Fonctions libxml
  • Désactive le chargement des entités externes

libxml_disable_entity_loader

(PHP 5 >= 5.2.11, PHP 7, PHP 8)

libxml_disable_entity_loader — Désactive le chargement des entités externes

Avertissement

Cette fonction est OBSOLÈTE à partir de PHP 8.0.0. Dépendre de cette fonction est fortement déconseillé.

Description

libxml_disable_entity_loader(bool $disable = true): bool

Active ou désactive le chargement des entités externes. Il est à noter que désactiver le chargement d'entités externes peut causer des problèmes lors du chargement de documents XML. Cependant à partir de libxml 2.9.0 la substitution d'entités est désactivé par défaut, ainsi il n'est pas nécessaire de désactiver le chargement des entités externes, sauf s'il y a le besoin de résoudre les références d'entités internes avec LIBXML_NOENT. Généralement, il est préférable d'utiliser libxml_set_external_entity_loader() pour réprimer le chargement d'entités externes.

Liste de paramètres

disable

Désactive (true) ou active (false) le chargement des entités externes par les extensions libxml (telles que DOM, XMLWriter et XMLReader).

Valeurs de retour

Retourne la configuration précédente.

Voir aussi

  • libxml_use_internal_errors() - Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure
  • libxml_set_external_entity_loader() - Change le chargeur d'entités externes par défaut
  • La constante LIBXML_NOENT

User Contributed Notes

editor at geekkb.com 27-Apr-2023 02:46
There is an extra \ should be deleted before PHP_VERSION_ID in the code which suconghou posted 2 years ago.

if (PHP_VERSION_ID < 80000) {
    libxml_disable_entity_loader(true);
}
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


Lit le tableau d'erreurs

  • « libxml_disable_entity_loader
  • libxml_get_external_entity_loader »
  • PHP Manual
  • Fonctions libxml
  • Lit le tableau d'erreurs

libxml_get_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_get_errors — Lit le tableau d'erreurs

Description

libxml_get_errors(): array

Retourne un tableau d'erreurs.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

libxml_get_errors() retourne un tableau avec les objets LibXMLError qui représentent les erreurs, ou bien un tableau vide s'il n'y a pas d'erreurs.

Exemples

Exemple #1 Exemple avec libxml_get_errors()

Cet exemple montre comment créer un gestionnaire d'erreurs libxml simple.

<?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";
}

?>

L'exemple ci-dessus va afficher :

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

Voir aussi

  • libxml_get_last_error() - Lit la dernière erreur libxml
  • libxml_clear_errors() - Vide le buffer d'erreur libxml

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)


Get the current external entity loader

  • « libxml_get_errors
  • libxml_get_last_error »
  • PHP Manual
  • Fonctions libxml
  • Get the current external entity loader

libxml_get_external_entity_loader

(PHP 8 >= 8.2.0)

libxml_get_external_entity_loader — Get the current external entity loader

Description

libxml_get_external_entity_loader(): ?callable

Get external entity loader previously installed by libxml_set_external_entity_loader().

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

The external entity loader previously installed by libxml_set_external_entity_loader(). If that function was never called, or if it was called with null, null will be returned.

Voir aussi

  • libxml_set_external_entity_loader() - Change le chargeur d'entités externes par défaut

User Contributed Notes

There are no user contributed notes for this page.


Lit la dernière erreur libxml

  • « libxml_get_external_entity_loader
  • libxml_set_external_entity_loader »
  • PHP Manual
  • Fonctions libxml
  • Lit la dernière erreur libxml

libxml_get_last_error

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_get_last_error — Lit la dernière erreur libxml

Description

libxml_get_last_error(): LibXMLError|false

libxml_get_last_error() lit la dernière erreur libxml.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

libxml_get_last_error() retourne un objet LibXMLError s'il y a une erreur, et false sinon.

Voir aussi

  • libxml_get_errors() - Lit le tableau d'erreurs
  • libxml_clear_errors() - Vide le buffer d'erreur libxml

User Contributed Notes

There are no user contributed notes for this page.


Change le chargeur d'entités externes par défaut

  • « libxml_get_last_error
  • libxml_set_streams_context »
  • PHP Manual
  • Fonctions libxml
  • Change le chargeur d'entités externes par défaut

libxml_set_external_entity_loader

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

libxml_set_external_entity_loader — Change le chargeur d'entités externes par défaut

Description

libxml_set_external_entity_loader(?callable $resolver_function): bool

Change le chargeur d'entités externes par défaut. Ceci peut être utilisé pour réprimer l'expansion d'entités externes arbitraire pour prévenir les attaques XXE, même si LIBXML_NOENT a été définie pour l'opération respective, et ceci est généralement préférable à appeler libxml_disable_entity_loader().

Liste de paramètres

resolver_function

Un callable avec la signature suivante :

resolver(?string $public_id, string $system_id, array $context): resource|string|null
public_id
L'ID public.
system_id
L'ID système.
context
Un tableau contenant quatre éléments "directory", "intSubName", "extSubURI" et "extSubSystem".
Cette callable devrait retourner une ressource, une chaîne de caractères par laquelle une ressource peut être ouverte. Si null est retourné, la résolution de référence d'entité échouera.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec libxml_set_external_entity_loader()

<?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());
?>

L'exemple ci-dessus va afficher :

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

Voir aussi

  • libxml_disable_entity_loader() - Désactive le chargement des entités externes
  • libxml_get_external_entity_loader() - Get the current external entity loader

User Contributed Notes

There are no user contributed notes for this page.


Configure le contexte de flux pour la prochaine opération libxml

  • « libxml_set_external_entity_loader
  • libxml_use_internal_errors »
  • PHP Manual
  • Fonctions libxml
  • Configure le contexte de flux pour la prochaine opération libxml

libxml_set_streams_context

(PHP 5, PHP 7, PHP 8)

libxml_set_streams_context — Configure le contexte de flux pour la prochaine opération libxml

Description

libxml_set_streams_context(resource $context): void

libxml_set_streams_context() configure le contexte de flux pour la prochaine opération libxml.

Liste de paramètres

context

La ressource de contexte de flux, créé avec la fonction stream_context_create().

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec libxml_set_streams_context()

<?php

$opts = array(
'http' => array(
'user_agent' => 'PHP libxml agent',
)
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// lit un fichier via HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

Voir aussi

  • stream_context_create() - Crée un contexte de flux

User Contributed Notes

There are no user contributed notes for this page.


Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure

  • « libxml_set_streams_context
  • SimpleXML »
  • PHP Manual
  • Fonctions libxml
  • Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure

libxml_use_internal_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_use_internal_errors — Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure

Description

libxml_use_internal_errors(?bool $use_errors = null): bool

libxml_use_internal_errors() vous permet de désactiver le gestionnaire d'erreurs libxml standard, et d'activer votre propre gestionnaire d'erreur.

Liste de paramètres

use_errors

Active (true) le gestionnaire d'erreurs utilisateur ou le désactive (false). La désactivation effacera aussi toutes les erreurs libxml existantes.

Valeurs de retour

libxml_use_internal_errors() retourne la valeur précédemment configurée pour use_errors.

Historique

Version | Description
8.0.0 | use_errors est désormais nullable. Auparavant, sa valeur par défaut était false.

Exemples

Exemple #1 Exemple avec libxml_use_internal_errors()

Cet exemple montre l'utilisation de base des erreurs libxml, et la valeur retournée par cette fonction.

<?php

// active la gestion d'erreur personnalisée
var_dump(libxml_use_internal_errors(true));

// Chargement du document
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
foreach (libxml_get_errors() as $error) {
// gérer les erreurs ici
}

libxml_clear_errors();
}

?>

L'exemple ci-dessus va afficher :

bool(false)

Voir aussi

  • libxml_clear_errors() - Vide le buffer d'erreur libxml
  • libxml_get_errors() - Lit le tableau d'erreurs

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

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Exemples
    • Utilisation de base SimpleXML
    • Traitement des erreurs XML
  • SimpleXMLElement — La classe SimpleXMLElement
    • SimpleXMLElement::addAttribute — Ajoute un attribut à l'élément SimpleXML
    • SimpleXMLElement::addChild — Ajoute un élément enfant au nœud XML
    • SimpleXMLElement::asXML — Retourne une chaîne XML basée sur un élément SimpleXML
    • SimpleXMLElement::attributes — Identifie les attributs d'un élément
    • SimpleXMLElement::children — Cherche les fils d'un nœud donné
    • SimpleXMLElement::__construct — Crée un nouvel objet SimpleXMLElement
    • SimpleXMLElement::count — Compte le nombre de fils pour un élément
    • SimpleXMLElement::current — Retourne l'entrée courante
    • SimpleXMLElement::getDocNamespaces — Retourne les espaces de noms déclarés dans un document
    • SimpleXMLElement::getName — Récupère le nom d'un élément XML
    • SimpleXMLElement::getNamespaces — Retourne les espaces de noms utilisés dans un document
    • SimpleXMLElement::getChildren — Renvoie les sous-éléments de l'élément courant
    • SimpleXMLElement::hasChildren — Vérifie si l'élément actuel a des sous-éléments
    • SimpleXMLElement::key — Retourne la clé courante
    • SimpleXMLElement::next — Se déplace sur l'élément suivant
    • SimpleXMLElement::registerXPathNamespace — Crée un contexte préfixe/ns pour la prochaine requête XPath
    • SimpleXMLElement::rewind — Replace le pointeur au début
    • SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Retourne le contenu sous forme de chaine
    • SimpleXMLElement::valid — Vérifie si l'élément actuel est valide
    • SimpleXMLElement::xpath — Exécute une requête Xpath sur des données XML
  • SimpleXMLIterator — La classe SimpleXMLIterator
  • Fonctions SimpleXML
    • simplexml_import_dom — Construit un objet SimpleXMLElement à partir d'un objet DOM
    • simplexml_load_file — Convertit un fichier XML en objet
    • simplexml_load_string — Convertit une chaîne XML en objet

User Contributed Notes

reibeltel at gmail dot com 16-Feb-2022 05:53
I rewrite the function to convert xml object to array because my case is more simple:

function xmlObjToArr($obj) {

    $array = [];
    foreach($obj as $item){
        $row = [];
        foreach($item as $key => $val){
            $col = array(
                (string)$key => (string)$val
            );
            array_push($row,$col);

        }
        array_push($array,$row);
    }

    return $array;
}
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.


Introduction

L'extension SimpleXML fournit des outils très simples et faciles à utiliser pour convertir du XML en un objet qui peut être manipulé avec ses propriétés et les itérateurs de tableaux.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Cette extension est activée par défaut. Elle peut être désactivée en utilisant l'option de configuration : --disable-simplexml

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


Exemples

Sommaire

  • Utilisation de base SimpleXML
  • Traitement des erreurs XML

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.


Utilisation de base SimpleXML

Plusieurs exemples de ce chapitre requièrent une chaîne XML. Plutôt que de la répéter à chaque exemple, nous allons la placer dans un fichier que nous inclurons dans chacun d'entre eux. Le contenu de ce fichier est illustré par l'exemple qui suit. Autrement, vous pouvez créer un document XML et le lire avec simplexml_load_file().

Exemple #1 Fichier avec une chaîne XML qui sera inclus partout

<?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;
?>

La simplicité de SimpleXML apparaît plus clairement lorsqu'on essaye d'extraire une chaîne ou un nombre d'un document XML basique.

Exemple #2 Lecture de <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

L'exemple ci-dessus va afficher :

   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.

L'accès aux éléments d'un document XML qui contient des caractères non permis par rapport à la convention de nommage de PHP (e.g. les mots clés) est possible en encapsulant le nom de l'élément entre crochets et apostrophes.

Exemple #3 Récupération de <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

L'exemple ci-dessus va afficher :

PHP solves all my web problems

Exemple #4 Accéder à un élément non-unique avec SimpleXML

Lorsque plusieurs instances d'un élément existent en tant que fils d'un élément père unique, les techniques normales d'itération peuvent être appliquées.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Pour chaque <character>, nous affichons un <name>. */
foreach ($movies->movie->characters->character as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

L'exemple ci-dessus va afficher :

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Note:

Les propriétés ($movies->movie dans notre précédent exemple) ne sont pas des tableaux. Ceux sont des objets itérables et accessibles.

Exemple #5 Utilisation des attributs

Jusque là, nous n'avons couvert que la lecture des noms d'éléments et leurs valeurs. SimpleXML peut aussi atteindre leurs attributs. L'accès aux attributs d'un élément se fait de la même façon que l'accès aux éléments d'un tableau.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Accès au node <rating> du premier <movie>.
* Affichage des attributs de <rating> également. */
foreach ($movies->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Récupération des attributs comme indices d'éléments
case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>

L'exemple ci-dessus va afficher :

7 thumbs up5 stars

Exemple #6 Comparaison des éléments et des attributs avec du texte

Pour comparer un élément ou un attribut avec une chaîne de caractères ou pour le passer à une fonction qui nécessite une chaîne de caractères, vous devez le transtyper en une chaîne en utilisant (string). Sinon, PHP traitera l'élément comme un objet.

<?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);
?>

L'exemple ci-dessus va afficher :

My favorite movie.PHP: Behind the Parser

Exemple #7 Comparaison de 2 éléments

Deux objets SimpleXMLElement sont considérés comme différents même s'ils pointent vers le même élément.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2);
?>

L'exemple ci-dessus va afficher :

bool(false)

Exemple #8 Utilisation de XPath

SimpleXML inclut le support embarqué de XPath. Pour trouver tous les éléments <character> :

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>

'//' sert de joker. Pour spécifier un chemin absolu, enlevez un slash.

L'exemple ci-dessus va afficher :

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Exemple #9 Attribuer des valeurs

Les données dans SimpleXML n'ont pas à être constantes. L'objet permet la manipulation de tous ces éléments.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

L'exemple ci-dessus va afficher :

<?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>

Exemple #10 Ajout d'éléments et d'attributs

SimpleXML est capable d'ajouter facilement des enfants et des attributs.

<?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();
?>

L'exemple ci-dessus va afficher :

<?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>

Exemple #11 Interopérabilité DOM

PHP possède un mécanisme pour convertir les nœuds XML entre les formats SimpleXML et DOM. Cet exemple montre comment changer un élément DOM en SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Erreur lors de l\'analyse du document';
exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

L'exemple ci-dessus va afficher :

blah

User Contributed Notes

Josef 01-Sep-2021 06:54
How to find out if a Node exists:

<?xml version='1.0' standalone='yes'?>
<book>
  <author>Josef</author>
  <isbn></isbn>
</book>

empty($xml->isbn) will be true
isset($xml->isbn) will be true

empty($xml->title) will be true
isset($xml->title) will be false
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.
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.
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.


Traitement des erreurs XML

Le traitement des erreurs XML lors du chargement d'un document est une tâche simple. En utilisant les fonctionnalités libxml, il est possible de supprimer toutes les erreurs XML lors du chargement d'un document, puis, de les parcourir.

L'objet libXMLError, retourné par la fonction libxml_get_errors(), contient plusieurs propriétés dont le message, la ligne et la colonne (position) de l'erreur.

Exemple #1 Chargement de chaînes XML cassées

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
echo "Erreur lors du chargement du XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>

L'exemple ci-dessus va afficher :

Erreur lors du chargement du 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

Voir aussi

  • 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);
?>


La classe SimpleXMLElement

(PHP 5, PHP 7, PHP 8)

Introduction

Représente un élément du document XML.

Synopsis de la classe

class SimpleXMLElement implements Stringable, Countable, RecursiveIterator {
/* Méthodes */
public __construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)
public addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
public addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement
public asXML(?string $filename = null): string|bool
public attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public count(): int
public current(): SimpleXMLElement
public getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false
public getName(): string
public getNamespaces(bool $recursive = false): array
public getChildren(): ?SimpleXMLElement
public hasChildren(): bool
public key(): string
public next(): void
public registerXPathNamespace(string $prefix, string $namespace): bool
public rewind(): void
public __toString(): string
public valid(): bool
public xpath(string $expression): array|null|false
}

Historique

Version | Description
8.0.0 | La classe SimpleXMLElement implémente désormais Stringable, Countable et RecursiveIterator.

Sommaire

  • SimpleXMLElement::addAttribute — Ajoute un attribut à l'élément SimpleXML
  • SimpleXMLElement::addChild — Ajoute un élément enfant au nœud XML
  • SimpleXMLElement::asXML — Retourne une chaîne XML basée sur un élément SimpleXML
  • SimpleXMLElement::attributes — Identifie les attributs d'un élément
  • SimpleXMLElement::children — Cherche les fils d'un nœud donné
  • SimpleXMLElement::__construct — Crée un nouvel objet SimpleXMLElement
  • SimpleXMLElement::count — Compte le nombre de fils pour un élément
  • SimpleXMLElement::current — Retourne l'entrée courante
  • SimpleXMLElement::getDocNamespaces — Retourne les espaces de noms déclarés dans un document
  • SimpleXMLElement::getName — Récupère le nom d'un élément XML
  • SimpleXMLElement::getNamespaces — Retourne les espaces de noms utilisés dans un document
  • SimpleXMLElement::getChildren — Renvoie les sous-éléments de l'élément courant
  • SimpleXMLElement::hasChildren — Vérifie si l'élément actuel a des sous-éléments
  • SimpleXMLElement::key — Retourne la clé courante
  • SimpleXMLElement::next — Se déplace sur l'élément suivant
  • SimpleXMLElement::registerXPathNamespace — Crée un contexte préfixe/ns pour la prochaine requête XPath
  • SimpleXMLElement::rewind — Replace le pointeur au début
  • SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Retourne le contenu sous forme de chaine
  • SimpleXMLElement::valid — Vérifie si l'élément actuel est valide
  • SimpleXMLElement::xpath — Exécute une requête Xpath sur des données XML

User Contributed Notes

ohcc at 163 dot com 12-Jun-2023 03:28
You can remove SimpleXMLElement nodes using php's unset() language construct.

<?php
    $xml = <<<'EOT'
<users>
    <user>
        <name>orange</name>
        <sex>male</sex>
        <homepage>wuxiancheng.cn</homepage>
    </user>
    <user>
        <name>tangerine</name>
        <sex>male</sex>
        <homepage>51-n.com</homepage>
    </user>
</users>
EOT;
    $sxe = new SimpleXMLElement($xml);
    // This will remove the first user node
    unset($sxe->user[0]);
    // This will remove all user nodes
    unset($sxe->user);
    echo $sxe->asXML();
?>
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.


Ajoute un attribut à l'élément SimpleXML

  • « SimpleXMLElement
  • SimpleXMLElement::addChild »
  • PHP Manual
  • SimpleXMLElement
  • Ajoute un attribut à l'élément SimpleXML

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addAttribute — Ajoute un attribut à l'élément SimpleXML

Description

public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void

Ajoute un attribut à l'élément SimpleXML.

Liste de paramètres

qualifiedName

Le nom de l'attribut à ajouter.

value

La valeur de l'attribut.

namespace

Si spécifié, l'espace de nom auquel l'attribut appartient.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Note:

Les exemples listés incluent parfois example.php, ceci fait référence à la chaine XML du premier exemple de l'utilisation de base.

Exemple #1 Ajoute des attributs et enfants à un élément SimpleXML

<?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();

?>

Résultat de l'exemple ci-dessus est similaire à :

<?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>

Voir aussi

  • SimpleXMLElement::addChild() - Ajoute un élément enfant au nœud XML
  • Utilisation de base SimpleXML

User Contributed Notes

caffeinatedbits 09-Dec-2022 10:50
Just found another gem. Need to remove an attribute? That's simple too!

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

unset($animals->Dog['breed']);

echo $animals->Dog->asXML();
// <Dog/>

?>
caffeinatedbits 09-Dec-2022 10:26
I needed a way to update an attribute, but I could not find any documented way to do this.

After much experimentation, here's my findings of what works - the answer was so simple it took me 8 tries to figure it out :-)

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #6 - maybe directly modifying the attributes() Iterator like an array will secretly call __set() magic method?

TL;DR: yep

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #7 - maybe I don't even need to call attributes() at all?

TL;DR: I sure don't!

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #8 - Maybe I never needed to call addAttribute() in the first place?

TL;DR: nope, I can skip that altogether!

<?php

...

$animals->Dog['breed'] = "chihuahua";
// works!

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

FYI: I also submitted another separate note with what does NOT work just in case you, like me, are curious and tempted to try another way.
caffeinatedbits 09-Dec-2022 10:25
I needed a way to update an attribute, but I could not find any documented way to do this.

TL;DR: It's not only possible, but unbelievably simple. See the other note I submitted for what actually works (sorry, I could not fit it all in a single note due to the 4095 character limit).

After much experimentation, here's my findings of what does NOT work; hopefully, it saves you the time and frustration it cost me.

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #1 - attempt to call addAttribute() twice

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

?>

Test #2 - attempt to iterate attributes() (an Iterator) by reference

TL;DR: An iterator cannot be used with foreach by reference

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

try {
    foreach ($animals->Dog->attributes() as $attr => &$value) {
        if ("breed" === $attr) {
            $value = "poodle";
        }
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // An iterator cannot be used with foreach by reference
}

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #3 - attempt to re-parse child element and then call addAttribute() on the newly parsed element, as suggested in a note I found here

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog = new SimpleXMLElement($animals->asXML());

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #4 - attempt to modify @attributes array element

TL;DR: PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";
// PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #5 - cast attributes() to array and set value of 'breed' element

TL;DR: does not update value in original object

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = (array) $animals->Dog->attributes();
// array(1) {
//     ["@attributes"]=>
//   array(1) {
//         ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>
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>


Ajoute un élément enfant au nœud XML

  • « SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML »
  • PHP Manual
  • SimpleXMLElement
  • Ajoute un élément enfant au nœud XML

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addChild — Ajoute un élément enfant au nœud XML

Description

public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement

Ajoute un élément enfant au nœud et retourne un SimpleXMLElement de l'enfant.

Liste de paramètres

qualifiedName

Le nom de l'élément enfant à ajouter.

value

Si spécifié, la valeur de l'élément enfant.

namespace

Si spécifié, l'espace de nom auquel l'élément enfant appartient.

Valeurs de retour

La méthode addChild retourne un objet SimpleXMLElement représentant l'enfant à ajouter au nœud XML en cas de succès; null en cas d'échec.

Exemples

Note:

Les exemples listés incluent parfois example.php, ceci fait référence à la chaine XML du premier exemple de l'utilisation de base.

Exemple #1 Ajoute des attributs et des enfants à un élément SimpleXML

<?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();

?>

Résultat de l'exemple ci-dessus est similaire à :

<?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>

Voir aussi

  • SimpleXMLElement::addAttribute() - Ajoute un attribut à l'élément SimpleXML
  • Utilisation de base SimpleXML

User Contributed Notes

fluxlicious at gmail dot com 23-Jan-2023 11:18
The class below allows you to write CDATA and to add additional attributes.

<?php
class SimpleXMLElementExtended extends \SimpleXMLElement
{
    public function addChildWithCData($name, $value)
    {
        $child = parent::addChild($name);
        $element = dom_import_simplexml($child);
        $docOwner = $element->ownerDocument;
        $element->appendChild($docOwner->createCDATASection($value));
        return $child;
    }
}
?>

Example:
<?php
        $xml = new SimpleXMLElementExtended('<xml></xml>');
        $content = $xml->addChildWithCData('content', 'Title of the page');
        $content->addAttribute('id', 1);
        $content->addAttribute('enabled', 'true');

        // Output:
        // <xml>
        //   <content id="1" enabled="true"><![CDATA[Title of the page]]></content>
        // </xml>
?>
caffeinatedbits 09-Dec-2022 11:31
Just in case anyone else, like me, was trying to figure out a way to remove child elements...

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

unset($animals->Dog[2]);

echo $animals->asXML();

// <?xml version="1.0" encoding="utf-8"?>
// <Animals>
//         <Dog breed="chihuahua"/>
//         <Dog breed="poodle"/>
//
// </Animals>

?>

Note: you cannot remove elements while iterating children, otherwise it will break the Iterator. Example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

$allowed_breeds = [
    'chihuahua',
    'poodle'
];

try {
    $index = 0;
    foreach ($animals->Dog as $dog) {
        if (!in_array($dog['breed'], $allowed_breeds)) {
            unset($animals->Dog[$index]);
        }
        $index++;
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // SimpleXMLElement is not properly initialized
}

?>
carlos dot eduardo dot debiasi at gmail dot com 22-Apr-2021 01:23
I create this function so you can through and array build the XML, this allows multiple keys with the same value.
The structure must follow

[
    'key' => 'nameOfTheKey',
    'attributes' => ['id' => '1'],
    'fields' => [
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '2'],
        ['key' => 'fieldWithChild', 'fields' => [
            ['key' => 'car', 'value' => '2'],
            ['key' => 'human', 'value' => '3'],
        ]],
    ]
];

Function:
 function toXml(\SimpleXMLElement $node, array $data)
    {
        foreach ($data as $key => $value) {
            $key = $value['key'];
            if (isset($value['value'])) {
                    $newNode = $node->addChild($key, $value['value']);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            } else {
                $newNode = $node->addChild($key);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            }
            if (isset($value['fields'])) {
                foreach ($value['fields'] as $keyField => $valueField) {
                    $this->toXml($newNode, [$keyField => $valueField]);
                }
            }
        }
    }
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.


Retourne une chaîne XML basée sur un élément SimpleXML

  • « SimpleXMLElement::addChild
  • SimpleXMLElement::attributes »
  • PHP Manual
  • SimpleXMLElement
  • Retourne une chaîne XML basée sur un élément SimpleXML

SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML — Retourne une chaîne XML basée sur un élément SimpleXML

Description

public SimpleXMLElement::asXML(?string $filename = null): string|bool

Formate les données de l'objet parent en XML 1.0.

Liste de paramètres

filename

Si une chaîne de caractères est spécifié, la fonction écrit les données au fichier au lieu de les retourner.

Valeurs de retour

Si le paramètre filename n'est pas spécifié, la fonction retourne une chaîne de caractères en cas de succès et false en cas d'erreur. Si le paramètre est spécifié, elle retourne true si le fichier a été écrit correctement et false autrement.

Historique

Version | Description
8.0.0 | filename est désormais nullable.

Exemples

Exemple #1 Obtenir du XML avec SimpleXML

<?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();

?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

SimpleXMLElement::asXML() fonctionne aussi avec les résultats Xpath :

Exemple #2 Utilisation de SimpleXMLElement::asXML() avec les résultats de SimpleXMLElement::xpath()

<?php
// Suite de l'exemple plus haut.

/* On cherche <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo $node->asXML();
}
?>

L'exemple ci-dessus va afficher :

<c>text</c><c>stuff</c>

Voir aussi

  • SimpleXMLElement::__toString() - Retourne le contenu sous forme de chaine
  • Utilisation de base SimpleXML

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');


Identifie les attributs d'un élément

  • « SimpleXMLElement::asXML
  • SimpleXMLElement::children »
  • PHP Manual
  • SimpleXMLElement
  • Identifie les attributs d'un élément

SimpleXMLElement::attributes

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::attributes — Identifie les attributs d'un élément

Description

public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

Fournit les attributs et les valeurs définies dans une balise XML.

Note: SimpleXML ajoute des propriétés itératives pour presque toutes ses méthodes. Celles-ci ne peuvent être vues en utilisant var_dump() ou tout autre fonction qui examine les objets.

Liste de paramètres

namespaceOrPrefix

Un espace de noms optionnel pour les attributs récupérés

isPrefix

Par défaut, vaut false

Valeurs de retour

Retourne un objet SimpleXMLElement permettant de retrouver tous les attributs d'une balise.

Retourne null si appelé sur un objet SimpleXMLElement qui représente déjà un attribut et non une balise.

Exemples

Exemple #1 Interprétation d'une chaîne XML

<?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";
}
?>

L'exemple ci-dessus va afficher :

name="one"
game="lonely"

Voir aussi

  • Utilisation de base SimpleXML

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;
  }
}
?>


Cherche les fils d'un nœud donné

  • « SimpleXMLElement::attributes
  • SimpleXMLElement::__construct »
  • PHP Manual
  • SimpleXMLElement
  • Cherche les fils d'un nœud donné

SimpleXMLElement::children

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::children — Cherche les fils d'un nœud donné

Description

public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

Cette méthode cherche les fils d'un élément. Le résultat suit les règles de l'itération normale.

Note: SimpleXML ajoute des propriétés itératives pour presque toutes ses méthodes. Celles-ci ne peuvent être vues en utilisant var_dump() ou tout autre fonction qui examine les objets.

Liste de paramètres

namespaceOrPrefix

Un espace de noms XML.

isPrefix

Si isPrefix vaut true, namespaceOrPrefix sera considéré comme un préfixe. S'il vaut false, namespaceOrPrefix sera considéré comme une URL vers un espace de noms.

Valeurs de retour

Retourne un élément SimpleXMLElement que le nœud possède un fils ou pas, sauf si le noeud représente un attribut, auquel cas null est retourné.

Exemples

Exemple #1 Parcours d'un pseudo-tableau children()

<?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'];
}
}
}
?>

L'exemple ci-dessus va afficher :

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Exemple #2 Utilisation des espaces de noms

<?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)

Voir aussi

  • SimpleXMLElement::count() - Compte le nombre de fils pour un élément
  • count() - Compte tous les éléments d'un tableau ou dans un objet Countable

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


Crée un nouvel objet SimpleXMLElement

  • « SimpleXMLElement::children
  • SimpleXMLElement::count »
  • PHP Manual
  • SimpleXMLElement
  • Crée un nouvel objet SimpleXMLElement

SimpleXMLElement::__construct

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::__construct — Crée un nouvel objet SimpleXMLElement

Description

public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)

Crée un nouvel objet SimpleXMLElement.

Liste de paramètres

data

Une chaîne de caractères XML bien formée ou le chemin d'accès ou un URL pointant à un document XML si dataIsURL vaut true.

options

Optionnellement utilisé pour spécifier des paramètres Libxml additionnels, qui affecte la lecture de documents XML. Les options affectant la sortie des documents XML (par exemple LIBXML_NOEMPTYTAG) sont ignorée silencieusement.

Note:

Il peut être nécessaire de passer LIBXML_PARSEHUGE pour pouvoir traiter des nœuds de texte profondément imbriqués ou très volumineux.

dataIsURL

Par défaut, dataIsURL vaut false. Utilisez true pour spécifier que le paramètre data est un chemin d'accès ou un URL pointant à un document XML au lieu d'une chaîne de caractères de données.

namespaceOrPrefix

Préfixe d'espace de noms ou URI.

isPrefix

true si namespaceOrPrefix est un préfix, false sinon. Valeur par défaut : false.

Erreurs / Exceptions

Produit un message d'erreur de type E_WARNING pour chaque erreur trouvée dans les données XML et lance également une exception si les données XML ne peuvent être analysées.

Astuce

Utilisez la fonction libxml_use_internal_errors() pour supprimer toutes les erreurs XML et la fonction libxml_get_errors() pour les parcourir.

Exemples

Note:

Les exemples listés incluent parfois example.php, ceci fait référence à la chaine XML du premier exemple de l'utilisation de base.

Exemple #1 Crée un objet SimpleXMLElement

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

L'exemple ci-dessus va afficher :

PHP: Behind the Parser

Exemple #2 Crée un objet SimpleXMLElement à partir d'un URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

Voir aussi

  • Utilisation de base SimpleXML
  • simplexml_load_string() - Convertit une chaîne XML en objet
  • simplexml_load_file() - Convertit un fichier XML en objet
  • Traitement des erreurs XML
  • libxml_use_internal_errors() - Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure
  • libxml_set_streams_context() - Configure le contexte de flux pour la prochaine opération libxml

User Contributed Notes

info at ensostudio dot ru 20-Aug-2021 04:22
Extended SimpleXMLElement:
<?php
class XmlElement extends \SimpleXMLElement
{
    public static function factory(string $root): self
    {
        return new static('<?xml version="1.0" encoding="UTF-8"?><'.$root.'/>', LIBXML_BIGLINES | LIBXML_COMPACT);
    }

    /**
      * @param iterable $attributes An array of element attributes as name/value pairs
      * @return $this
      */
    public function addAttributes(iterable $attributes)
    {
        foreach ($attributes as $name => $value) {
            $this->addAttribute($name, $value);
        }

        return $this;
    }

    /**
      * @param string $name The sub-element name
      * @param string|array|null $valueOrAttributes The sub-element value or an array of attributes
      * @param string|null $namespace The sub-element namespace
      * @return static|null
      */
    public function addChild($name, $valueOrAttributes = null, $namespace = null)
    {
        if (is_array($valueOrAttributes)) {
            $child = parent::addChild($name, null, $namespace);
            foreach ($valueOrAttributes as $name => $value) {
                $child->addAttribute($name, $value);
            }
        } else {
            $child = parent::addChild($name, $valueOrAttributes, $namespace);
        }

        return $child;
    }

    /**
      * @param iterable $childs An array of sub-elements as name/value(or attributes) pairs
      * @return $this
      */
    public function addChilds(iterable $childs)
    {
        foreach ($childs as $name => $value) {
            $this->addChild($name, $value);
        }

        return $this;
    }
}
?>
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.


Compte le nombre de fils pour un élément

  • « SimpleXMLElement::__construct
  • SimpleXMLElement::current »
  • PHP Manual
  • SimpleXMLElement
  • Compte le nombre de fils pour un élément

SimpleXMLElement::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SimpleXMLElement::count — Compte le nombre de fils pour un élément

Description

public SimpleXMLElement::count(): int

Cette méthode compte le nombre de fils d'un élément.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le nombre de fils d'un élément.

Exemples

Exemple #1 Comptage du nombre de fils

<?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());
}
?>

L'exemple ci-dessus va afficher :

Person 1 has got 3 children.
Person 2 has got 5 children.

Voir aussi

  • SimpleXMLElement::children() - Cherche les fils d'un nœud donné

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
?>


Retourne l'entrée courante

  • « SimpleXMLElement::count
  • SimpleXMLElement::getDocNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Retourne l'entrée courante

SimpleXMLElement::current

(No version information available, might only be in Git)

SimpleXMLElement::current — Retourne l'entrée courante

Description

public SimpleXMLElement::current(): SimpleXMLElement
Avertissement

Antérieur à PHP 8.0, SimpleXMLElement::current() n'était déclarée que sur la sous-classe SimpleXMLIterator.

Cette méthode retourne l'élément courant comme un objet SimpleXMLElement.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne l'élément courant comme un objet SimpleXMLElement.

Erreurs / Exceptions

Lance une Error en cas d'échec.

Historique

Version | Description
8.1.0 | Une Error est lancée si SimpleXMLElement::current() est appelée sur un itérateur invalide. Auparavant, null était returné.

Exemples

Exemple #1 Retourne l'élément courant

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP basics</book><book>XML basics</book></books>');

$xmlElement->rewind(); // Retour au premier élément, sinon current() ne fonctionne pas
var_dump($xmlElement->current());
?>

L'exemple ci-dessus va afficher :

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

Voir aussi

  • SimpleXMLElement::key() - Retourne la clé courante
  • SimpleXMLElement::next() - Se déplace sur l'élément suivant
  • SimpleXMLElement::rewind() - Replace le pointeur au début
  • SimpleXMLElement::valid() - Vérifie si l'élément actuel est valide
  • SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Retourne les espaces de noms déclarés dans un document

  • « SimpleXMLElement::current
  • SimpleXMLElement::getName »
  • PHP Manual
  • SimpleXMLElement
  • Retourne les espaces de noms déclarés dans un document

SimpleXMLElement::getDocNamespaces

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SimpleXMLElement::getDocNamespaces — Retourne les espaces de noms déclarés dans un document

Description

public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false

Retourne les espaces de noms déclarés dans un document.

Liste de paramètres

recursive

Si spécifié, retourne tous les espaces de noms déclarés dans les nœuds parents et enfants. Sinon, retourne uniquement les espaces de noms déclarés dans le nœud racine.

fromRoot

Vous permet de vérifier récursivement les espaces de noms sous un nœud fils au lieu d'effectuer cette vérification depuis la racine du document XML.

Valeurs de retour

La méthode getDocNamespaces retourne un tableau d'espaces de noms avec leurs URL associées.

Exemples

Exemple #1 Récupère les espaces de noms du document

<?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);

?>

L'exemple ci-dessus va afficher :

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Exemple #2 Travail avec plusieurs espaces de noms

<?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);

?>

L'exemple ci-dessus va afficher :

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Voir aussi

  • SimpleXMLElement::getNamespaces() - Retourne les espaces de noms utilisés dans un document
  • SimpleXMLElement::registerXPathNamespace() - Crée un contexte préfixe/ns pour la prochaine requête XPath

User Contributed Notes

There are no user contributed notes for this page.


Récupère le nom d'un élément XML

  • « SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Récupère le nom d'un élément XML

SimpleXMLElement::getName

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::getName — Récupère le nom d'un élément XML

Description

public SimpleXMLElement::getName(): string

Récupère le nom d'un élément XML.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

La méthode getName retourne un nom sous la forme de chaîne de caractères d'une balise XML référencé par l'objet SimpleXMLElement.

Exemples

Note:

Les exemples listés incluent parfois example.php, ceci fait référence à la chaine XML du premier exemple de l'utilisation de base.

Exemple #1 Récupère les noms des éléments XML

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
echo $child->getName() . "\n";
}

?>

L'exemple ci-dessus va afficher :

movies
movie

User Contributed Notes

There are no user contributed notes for this page.


Retourne les espaces de noms utilisés dans un document

  • « SimpleXMLElement::getName
  • SimpleXMLElement::getChildren »
  • PHP Manual
  • SimpleXMLElement
  • Retourne les espaces de noms utilisés dans un document

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SimpleXMLElement::getNamespaces — Retourne les espaces de noms utilisés dans un document

Description

public SimpleXMLElement::getNamespaces(bool $recursive = false): array

Retourne les espaces de noms utilisés dans un document.

Liste de paramètres

recursive

Si spécifié, retourne tous les espaces de noms utilisés dans les nœuds parents et enfants. Sinon, retourne uniquement les espaces de noms utilisés dans le nœud racine.

Valeurs de retour

La méthode getNamespaces retourne un tableau d'espaces de noms avec leurs URL associés.

Exemples

Exemple #1 Récupère les espaces de noms utilisés dans un document

<?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);

?>

L'exemple ci-dessus va afficher :

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

Voir aussi

  • SimpleXMLElement::getDocNamespaces() - Retourne les espaces de noms déclarés dans un document
  • SimpleXMLElement::registerXPathNamespace() - Crée un contexte préfixe/ns pour la prochaine requête XPath

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;
}

?>


Renvoie les sous-éléments de l'élément courant

  • « SimpleXMLElement::getNamespaces
  • SimpleXMLElement::hasChildren »
  • PHP Manual
  • SimpleXMLElement
  • Renvoie les sous-éléments de l'élément courant

SimpleXMLElement::getChildren

(No version information available, might only be in Git)

SimpleXMLElement::getChildren — Renvoie les sous-éléments de l'élément courant

Description

public SimpleXMLElement::getChildren(): ?SimpleXMLElement
Avertissement

Antérieur à PHP 8.0, SimpleXMLElement::getChildren() n'était déclarée que sur la sous-classe SimpleXMLIterator.

Cette méthode retourne un objet SimpleXMLElement contenant les sous-éléments de l'élémenmt courant SimpleXMLElement.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne un objet SimpleXMLElement contenant les sous-éléments de l'objet courant.

Exemples

Exemple #1 Lecture des sous-éléments de l'objet courant

<?php
$xml = <<<XML
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
</book>
<book>XML basics</book>
</books>
XML;

$xmlElement = new SimpleXMLElement($xml);
for ($xmlElement->rewind(); $xmlElement->valid(); $xmlElement->next()) {
foreach($xmlElement->getChildren() as $name => $data) {
echo "The $name is '$data' from the class " . get_class($data) . "\n";
}
}
?>

L'exemple ci-dessus va afficher :

The title is 'PHP Basics' from the class SimpleXMLElement
The author is 'Jim Smith' from the class SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Vérifie si l'élément actuel a des sous-éléments

  • « SimpleXMLElement::getChildren
  • SimpleXMLElement::key »
  • PHP Manual
  • SimpleXMLElement
  • Vérifie si l'élément actuel a des sous-éléments

SimpleXMLElement::hasChildren

(No version information available, might only be in Git)

SimpleXMLElement::hasChildren — Vérifie si l'élément actuel a des sous-éléments

Description

public SimpleXMLElement::hasChildren(): bool
Avertissement

Antérieur à PHP 8.0, SimpleXMLElement::hasChildren() n'était déclarée que sur la sous-classe SimpleXMLIterator.

Cette méthode vérifie si l'objet courant SimpleXMLElement a des sous-éléments.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

true si l'entrée courante a des sous-éléments, false sinon.

Exemples

Exemple #1 Vérifie si un élément a des sous-éléments

<?php
$xml = <<<XML
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
</book>
<book>XML basics</book>
</books>
XML;

$xmlElement = new SimpleXMLElement($xml);
for ($xmlElement->rewind(); $xmlElement->valid(); $xmlElement->next()) {
if ($xmlElement->hasChildren()) {
var_dump($xmlElement->current());
}
}
?>

L'exemple ci-dessus va afficher :

object(SimpleXMLElement)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}

User Contributed Notes

There are no user contributed notes for this page.


Retourne la clé courante

  • « SimpleXMLElement::hasChildren
  • SimpleXMLElement::next »
  • PHP Manual
  • SimpleXMLElement
  • Retourne la clé courante

SimpleXMLElement::key

(No version information available, might only be in Git)

SimpleXMLElement::key — Retourne la clé courante

Description

public SimpleXMLElement::key(): string
Avertissement

Antérieur à PHP 8.0, SimpleXMLElement::key() n'était déclarée que sur la sous-classe SimpleXMLIterator.

Cette méthode lit le nom de la balise XML courante.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le nom de la balise XML dans l'objet courant de l'itéraeur SimpleXMLElement.

Erreurs / Exceptions

Lance une Error en cas d'échec.

Historique

Version | Description
8.1.0 | Une Error est maintenant lancée si SimpleXMLElement::key() est appelé sur un itérateur invalide. Auparavant, false était retourné.

Exemples

Exemple #1 Le nom de la balise XML courante

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP basics</book><book>XML basics</book></books>');

echo var_dump($xmlElement->key());
$xmlElement->rewind(); // retour au premier élément
echo var_dump($xmlElement->key());

?>

L'exemple ci-dessus va afficher :

bool(false)
string(4) "book"

User Contributed Notes

There are no user contributed notes for this page.


Se déplace sur l'élément suivant

  • « SimpleXMLElement::key
  • SimpleXMLElement::registerXPathNamespace »
  • PHP Manual
  • SimpleXMLElement
  • Se déplace sur l'élément suivant

SimpleXMLElement::next

(No version information available, might only be in Git)

SimpleXMLElement::next — Se déplace sur l'élément suivant

Description

public SimpleXMLElement::next(): void
Avertissement

Antérieur à PHP 8.0, SimpleXMLElement::next() n'était déclarée que sur la sous-classe SimpleXMLIterator.

Cette méthode déplace l'itérateur SimpleXMLElement à l'élément suivant.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Passe au prochain élément

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP Basics</book><book>XML basics</book></books>');
$xmlElement->rewind(); // rewind to the first element
$xmlElement->next();

var_dump($xmlElement->current());
?>

L'exemple ci-dessus va afficher :

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Crée un contexte préfixe/ns pour la prochaine requête XPath

  • « SimpleXMLElement::next
  • SimpleXMLElement::rewind »
  • PHP Manual
  • SimpleXMLElement
  • Crée un contexte préfixe/ns pour la prochaine requête XPath

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SimpleXMLElement::registerXPathNamespace — Crée un contexte préfixe/ns pour la prochaine requête XPath

Description

public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool

Crée un contexte préfixe/ns pour la prochaine requête XPath. En particulier, ceci est utile si le fournisseur du document XML donné modifie les préfixes d'espace de nom. registerXPathNamespace créera un préfixe pour l'espace de nom associé, autorisant l'accès aux nœuds dans cet espace de nom sans avoir besoin de changer le code pour autoriser les nouveaux préfixes dictés par le fournisseur.

Liste de paramètres

prefix

Le préfixe d'espace de nom à utiliser dans la requête XPath pour l'espace de nom donnée dans namespace.

namespace

L'espace de nom à utiliser pour la requête XPath. Ceci doit concorder avec un espace de nom qui est utilisé par le document XML, sinon la requête XPath qui utilise prefix ne retournera aucun résultat.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Fixe un préfixe d'espace de nom pour utiliser dans une requête XPath

<?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";
}

?>

L'exemple ci-dessus va afficher :

Chapter 1
Chapter 2

Notez comment le document XML montré dans cet exemple fixe un espace de nom avec le préfixe chap. Imaginez que ce document (ou un autre similaire) puisse avoir utilisé un préfixe c dans le passé pour le même espace de nom. Puisqu'il a changé, la requête XPath ne retournerait plus les résultats appropriés et la requête devrait être modifiée. L'utilisation de registerXPathNamespace évite les modifications futures de la requête même si le fournisseur change le préfixe d'espace de nom.

Voir aussi

  • SimpleXMLElement::xpath() - Exécute une requête Xpath sur des données XML
  • SimpleXMLElement::getDocNamespaces() - Retourne les espaces de noms déclarés dans un document
  • SimpleXMLElement::getNamespaces() - Retourne les espaces de noms utilisés dans un 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');
?>


Replace le pointeur au début

  • « SimpleXMLElement::registerXPathNamespace
  • SimpleXMLElement::saveXML »
  • PHP Manual
  • SimpleXMLElement
  • Replace le pointeur au début

SimpleXMLElement::rewind

(No version information available, might only be in Git)

SimpleXMLElement::rewind — Replace le pointeur au début

Description

public SimpleXMLElement::rewind(): void
Avertissement

Antérieur à PHP 8.0, SimpleXMLElement::rewind() n'était déclarée que sur la sous-classe SimpleXMLIterator.

Cette méthode remet l'itérateur SimpleXMLElement au premier élément.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Retour au premier élément

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP Basics</book><book>XML Basics</book></books>');
$xmlElement->rewind();

var_dump($xmlElement->current());
?>

L'exemple ci-dessus va afficher :

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Alias de SimpleXMLElement::asXML

  • « SimpleXMLElement::rewind
  • SimpleXMLElement::__toString »
  • PHP Manual
  • SimpleXMLElement
  • Alias de SimpleXMLElement::asXML

SimpleXMLElement::saveXML

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML()

Description

Cette méthode est un alias de: SimpleXMLElement::asXML()

User Contributed Notes

There are no user contributed notes for this page.


Retourne le contenu sous forme de chaine

  • « SimpleXMLElement::saveXML
  • SimpleXMLElement::valid »
  • PHP Manual
  • SimpleXMLElement
  • Retourne le contenu sous forme de chaine

SimpleXMLElement::__toString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SimpleXMLElement::__toString — Retourne le contenu sous forme de chaine

Description

public SimpleXMLElement::__toString(): string

Retourne le contenu texte stocké directement dans l'élément. Ne retourne pas le contenu texte stocké dans les éléments enfants.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le contenu sous forme de chaine de caractères, ou retourne une chaine vide en cas d'erreur.

Exemples

Exemple #1 Récupérer le contenu chaine

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

L'exemple ci-dessus va afficher :

1 3

Voir aussi

  • SimpleXMLElement::asXML() - Retourne une chaîne XML basée sur un élément SimpleXML

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.


Vérifie si l'élément actuel est valide

  • « SimpleXMLElement::__toString
  • SimpleXMLElement::xpath »
  • PHP Manual
  • SimpleXMLElement
  • Vérifie si l'élément actuel est valide

SimpleXMLElement::valid

(No version information available, might only be in Git)

SimpleXMLElement::valid — Vérifie si l'élément actuel est valide

Description

public SimpleXMLElement::valid(): bool
Avertissement

Antérieur à PHP 8.0, SimpleXMLElement::valid() n'était déclarée que sur la sous-classe SimpleXMLIterator.

Cette méthode vérifie si l'élément courant est valide, après un appel à SimpleXMLElement::rewind() ou SimpleXMLElement::next().

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne true si l'élément courant est valide, false sinon.

Exemples

Exemple #1 Vérifie si un élément est valide

<?php
$xmlElement = new SimpleXMLElement('<books><book>SQL Basics</book></books>');

$xmlElement->rewind(); // Retour au premier élément
echo var_dump($xmlElement->valid()); // bool(true)

$xmlElement->next(); // Avance au prochain élément
echo var_dump($xmlElement->valid()); // bool(false) car il y a un seul élément
?>

User Contributed Notes

There are no user contributed notes for this page.


Exécute une requête Xpath sur des données XML

  • « SimpleXMLElement::valid
  • SimpleXMLIterator »
  • PHP Manual
  • SimpleXMLElement
  • Exécute une requête Xpath sur des données XML

SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpath — Exécute une requête Xpath sur des données XML

Description

public SimpleXMLElement::xpath(string $expression): array|null|false

La méthode xpath cherche dans le nœud SimpleXML des enfants qui correspondent au expression Xpath.

Liste de paramètres

expression

Un chemin XPath

Valeurs de retour

Retourne un tableau d'objets SimpleXMLElement en cas de succès ou null ou false si une erreur survient.

Exemples

Exemple #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);

/* On cherche <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo '/a/b/c: ',$node,"\n";
}

/* Les chemins relatifs fonctionnent aussi... */
$result = $xml->xpath('b/c');

foreach ($result as $node) {
echo 'b/c: ',$node,"\n";
}
?>

L'exemple ci-dessus va afficher :

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notez que les deux résultats sont égaux.

Voir aussi

  • SimpleXMLElement::registerXPathNamespace() - Crée un contexte préfixe/ns pour la prochaine requête XPath
  • SimpleXMLElement::getDocNamespaces() - Retourne les espaces de noms déclarés dans un document
  • SimpleXMLElement::getNamespaces() - Retourne les espaces de noms utilisés dans un document
  • Utilisation de base SimpleXML

User Contributed Notes

Filippo Vicari 28-Sep-2022 09:56
You can also search for siblings with a condition. For example immagine to need the title for a desidered language which with the two siblings tags in this XML file

<?xml version="1.0" encoding="UTF-8"?>
<IDOC BEGIN="1">
...
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>E</LANG>
    <TITLE>Name</TITLE>
    <LANG_ISO>EN</LANG_ISO>
</PRODUCT>
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>I</LANG>
    <TITLE>Name I</TITLE>
    <LANG_ISO>IT</LANG_ISO>
</PRODUCT>
...
</IDOC>

Let's break it down
<?php
"//PRODUCT" // find product tag
"//PRODUCT/LANG[.='E']" // whithin it find lang == "E"
"//PRODUCT/LANG[.='E']/../"  // go up one step
"//PRODUCT/LANG[.='E']/../TITLE" // get the title Tag content

// Combined search and find siblings ----------------------------
$xml = simplexml_load_file("fname.xml");

// Search for the TITLE field which sibling is == "E" ----------
$title_E_array = $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE"); // By default gives back an array of  SimpleXmlElement
$title = (string) $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE")[0]; // in this way saves only the value as a string
?>
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"/>


La classe SimpleXMLIterator

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

Introduction

La classe SimpleXMLIterator fournit des itérations récursives sur tous les éléments d'un objet SimpleXMLElement.

Synopsis de la classe

class SimpleXMLIterator extends SimpleXMLElement {
/* Méthodes héritées */
public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)
public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement
public SimpleXMLElement::asXML(?string $filename = null): string|bool
public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public SimpleXMLElement::count(): int
public SimpleXMLElement::current(): SimpleXMLElement
public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false
public SimpleXMLElement::getName(): string
public SimpleXMLElement::getNamespaces(bool $recursive = false): array
public SimpleXMLElement::getChildren(): ?SimpleXMLElement
public SimpleXMLElement::hasChildren(): bool
public SimpleXMLElement::key(): string
public SimpleXMLElement::next(): void
public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool
public SimpleXMLElement::rewind(): void
public SimpleXMLElement::__toString(): string
public SimpleXMLElement::valid(): bool
public SimpleXMLElement::xpath(string $expression): array|null|false
}

Historique

Version | Description
8.0.0 | Les méthodes d'itération (SimpleXMLIterator::hasChildren(), SimpleXMLIterator::getChildren(), SimpleXMLIterator::current(), SimpleXMLIterator::key(), SimpleXMLIterator::next(),SimpleXMLIterator::rewind(), SimpleXMLIterator::valid()) ont été déplacées vers SimpleXMLElement.
8.0.0 | La classe SimpleXMLIterator implémente désormais Stringable.

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   )
    )
  )
)


Fonctions SimpleXML

Sommaire

  • simplexml_import_dom — Construit un objet SimpleXMLElement à partir d'un objet DOM
  • simplexml_load_file — Convertit un fichier XML en objet
  • simplexml_load_string — Convertit une chaîne XML en objet

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.


Construit un objet SimpleXMLElement à partir d'un objet DOM

  • « Fonctions SimpleXML
  • simplexml_load_file »
  • PHP Manual
  • Fonctions SimpleXML
  • Construit un objet SimpleXMLElement à partir d'un objet DOM

simplexml_import_dom

(PHP 5, PHP 7, PHP 8)

simplexml_import_dom — Construit un objet SimpleXMLElement à partir d'un objet DOM

Description

simplexml_import_dom(SimpleXMLElement|DOMNode $node, ?string $class_name = SimpleXMLElement::class): ?SimpleXMLElement

simplexml_import_dom() prend un nœud d'un document DOM et la transforme en nœud SimpleXML. Ce nouvel objet peut alors être utilisé comme un objet natif SimpleXML.

Liste de paramètres

node

Un élément DOM

class_name

Vous pouvez utiliser ce paramètre optionnel afin que simplexml_load_string() retourne un objet de la classe spécifiée. Cette classe doit étendre la classe SimpleXMLElement.

Valeurs de retour

Retourne un objet SimpleXMLElement ou null en cas d'échec.

Exemples

Exemple #1 Import DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Erreur durant l\'analyse du document';
exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

L'exemple ci-dessus va afficher :

blah

Voir aussi

  • dom_import_simplexml() - Transforme un objet SimpleXMLElement en un objet DOMElement
  • Utilisation de base SimpleXML

User Contributed Notes

paul dot allsopp at digital-pig dot com 06-Jun-2023 12:07
Why not just:
simplexml_import_dom(dom_import_simplexml($SimpleXmlNode))
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


Convertit un fichier XML en objet

  • « simplexml_import_dom
  • simplexml_load_string »
  • PHP Manual
  • Fonctions SimpleXML
  • Convertit un fichier XML en objet

simplexml_load_file

(PHP 5, PHP 7, PHP 8)

simplexml_load_file — Convertit un fichier XML en objet

Description

simplexml_load_file(
string $filename,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Convertit le document XML filename en un objet de type SimpleXMLElement.

Liste de paramètres

filename

Chemin vers le fichier XML

class_name

Vous pouvez utiliser ce paramètre optionnel et ainsi, la fonction simplexml_load_file() retournera un objet de la classe spécifiée. Cette classe doit étendre la classe SimpleXMLElement.

options

Opération de 'OU' logique des constantes d'option libxml.

namespace_or_prefix

Préfixe ou l'URI de l'espace de noms.

is_prefix

true si namespace_or_prefix est un préfixe, false si c'est l'URI ; par défaut, false.

Valeurs de retour

Retourne un objet de la classe SimpleXMLElement dont les propriétés contiennent les données du document XML, ou false si une erreur survient.

Avertissement

Cette fonction peut retourner false, mais elle peut aussi retourner une valeur équivalent à false. Veuillez lire la section sur les booléens pour plus d'informations. Utilisez l'opérateur === pour tester la valeur de retour exacte de cette fonction.

Erreurs / Exceptions

Produit un message d'erreur de niveau E_WARNING pour chaque erreur trouvée dans les données XML.

Astuce

Utilisez la fonction libxml_use_internal_errors() pour supprimer toutes les erreurs XML, et la fonction libxml_get_errors() pour les parcourir.

Exemples

Exemple #1 Interprétation d'un document XML

<?php
// Le fichier test.xml contient un document XML avec un élément racine
// et au moins un élément /[racine]/title.

if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');

print_r($xml);
} else {
exit('Echec lors de l\'ouverture du fichier test.xml.');
}
?>

Ce script affichera, en cas de succès :

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

À partir de là, vous pouvez utiliser $xml->title et tout autre élément.

Voir aussi

  • simplexml_load_string() - Convertit une chaîne XML en objet
  • SimpleXMLElement::__construct() - Crée un nouvel objet SimpleXMLElement
  • Traitement des erreurs XML
  • libxml_use_internal_errors() - Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure
  • Utilisation de base SimpleXML
  • libxml_set_streams_context() - Configure le contexte de flux pour la prochaine opération libxml

User Contributed Notes

siraic at gmail dot com 20-Jun-2023 08:47
LibXML typically uses ten times the file size in memory to read a file, and this memory usage falls largely outside the memory limit guarded by PHP.
tg at debian dot org 20-Feb-2022 09:36
This function does not accept all pathnames, in spite of its documentation.

$ php -r 'print_r( simplexml_load_file("%25.xml"));'
PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "%25.xml" in Command line code on line 1
visualmind at nospam dot php dot net 18-Jan-2022 02:49
This may sometimes get missed, but if your xml nodes are in the format:
<prefix:element />

You need to make sure to set the [namespace or prefix] argument and the [isPrefix] argument to true. Also when recalling elements you need to avoid adding the prefix if that is already set, so in the above example "prefix:element" should be added as "element" but when saved the prefix will be added automatically.

If prefix is not set during load or object construction, load will fail to get the nodes correctly and you will not be able to recall elements directly so $xml->{'prefix:element'} will not work either.
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 â€™ 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;
}
?>


Convertit une chaîne XML en objet

  • « simplexml_load_file
  • WDDX »
  • PHP Manual
  • Fonctions SimpleXML
  • Convertit une chaîne XML en objet

simplexml_load_string

(PHP 5, PHP 7, PHP 8)

simplexml_load_string — Convertit une chaîne XML en objet

Description

simplexml_load_string(
string $data,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Convertit la chaîne XML data et retourne un objet de la classe SimpleXMLElement.

Liste de paramètres

data

Une chaîne XML valide

class_name

Vous pouvez utiliser le paramètre optionnel et, ainsi, la fonction simplexml_load_string() retournera un objet de la classe spécifiée. Cette classe doit étendre la classe SimpleXMLElement.

options

Opération de 'OU' logique des constantes d'option libxml.

namespace_or_prefix

Préfixe ou URI de l'espace de noms.

is_prefix

true si namespace_or_prefix est un préfixe, false si c'est l'URI.

Valeurs de retour

Retourne un objet de la classe SimpleXMLElement dont les propriétés contiennent les données du document XML, ou false si une erreur survient.

Avertissement

Cette fonction peut retourner false, mais elle peut aussi retourner une valeur équivalent à false. Veuillez lire la section sur les booléens pour plus d'informations. Utilisez l'opérateur === pour tester la valeur de retour exacte de cette fonction.

Erreurs / Exceptions

Produit un message d'erreur de niveau E_WARNING pour chaque erreur trouvée dans les données XML.

Astuce

Utilisez la fonction libxml_use_internal_errors() pour supprimer toutes les erreurs XML, et la fonction libxml_get_errors() pour les parcourir.

Exemples

Exemple #1 Convertir une chaîne XML

<?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);
?>

L'exemple ci-dessus va afficher :

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

À partir de là, vous pouvez utiliser $xml->body et tout autre élément.

Voir aussi

  • simplexml_load_file() - Convertit un fichier XML en objet
  • SimpleXMLElement::__construct() - Crée un nouvel objet SimpleXMLElement
  • Traitement des erreurs XML
  • libxml_use_internal_errors() - Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure
  • Utilisation de base SimpleXML

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

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Exemples
    • Exemples wddx
  • WDDX Fonctions
    • wddx_add_vars — Ajoute des variables à un paquet WDDX
    • wddx_deserialize — Désérialise un paquet WDDX
    • wddx_packet_end — Clôt un paquet WDDX
    • wddx_packet_start — Commence un nouveau paquet WDDX avec une structure
    • wddx_serialize_value — Enregistre une valeur dans un paquet WDDX
    • wddx_serialize_vars — Enregistre plusieurs valeurs dans un paquet WDDX

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Avertissement

Cette extension est OBSOLÈTE et DÉGROUPÉ à partir de PHP 7.4.0.

Ces fonctions sont prévues pour fonctionner avec » WDDX.

Avertissement

Ne passez pas de données utilisateurs qui ne sont pas de confiance à la fonction wddx_deserialize(). La désérialisation peut conduire au chargement et à l'exécution des données lors de l'instansiation de l'objet et de son autochargement, aussi, un utilisateur malicieux peut être capable d'exploiter ce comportement. Utiliser donc des données sécurisées avec un format de données comme JSON (via la fonction json_decode() et la fonction json_encode()) si vous devez passer les données sérialisées à l'utilisateur.

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."


Pré-requis

Cette extension requière l'extension PHP libxml. Ceci signifie passer l'option de configuration --with-libxml, ou antérieur à PHP 7.4 l'option de configuration --enable-libxml, bien que ceci est accomplie implicitement car libxml est activé par défaut.

Afin d'utiliser WDDX, vous devez installer la bibliothèque expat (qui est fournie avec Apache 1.3.7 ou supérieur).

User Contributed Notes

There are no user contributed notes for this page.


Installation

PHP 7.4

Cette extension a été déplacée dans le module » PECL et ne sera plus intégrée dans PHP à partir de PHP 7.4.0

Des informations sur l'installation de ces extensions PECL peuvent être trouvées dans le chapitre du manuel intitulé Installation des extensions PECL. D'autres informations comme les notes sur les nouvelles versions, les téléchargements, les sources des fichiers, les informations concernant les mainteneurs ainsi qu'un CHANGELOG, peuvent être trouvées ici : » https://pecl.php.net/package/wddx.

PHP < 7.4

Après avoir installé Expat, compilez PHP avec --enable-wddx et utilisez --with-libexpat-dir pour Expat.

La version Windows de PHP dispose du support automatique de cette extension. Vous n'avez pas à ajouter de bibliothèque supplémentaire pour disposer de ces fonctions.

User Contributed Notes

There are no user contributed notes for this page.


Types de ressources

Cette extension définit un identifiant de paquet WDDX, retourné par la fonction wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Sommaire

  • Exemples wddx

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>


Exemples wddx

Toutes les fonctions qui sérialisent les variables utilisent le premier élément d'un tableau pour déterminer si le tableau doit être sérialisé dans un tableau ou dans une structure. Si le premier élément a une chaîne de caractères en tant que clé, alors, il sera sérialisé dans une structure, sinon, dans un tableau.

Exemple #1 Sérialisation d'une valeur simple avec WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

Cet exemple affichera :

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Exemple #2 Utilisation de paquets incrémentaux avec WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose que $cities provient d'une base de données */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

Cet exemple affichera :

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

Les chaînes de caractères doivent être encodées en UTF-8 ; pour gérer d'autres encodages, convertissez d'abord la chaîne de caractères en utilisant la mb_convert_encoding(), UConverter::transcode(), ou iconv().

User Contributed Notes

There are no user contributed notes for this page.


WDDX Fonctions

Sommaire

  • wddx_add_vars — Ajoute des variables à un paquet WDDX
  • wddx_deserialize — Désérialise un paquet WDDX
  • wddx_packet_end — Clôt un paquet WDDX
  • wddx_packet_start — Commence un nouveau paquet WDDX avec une structure
  • wddx_serialize_value — Enregistre une valeur dans un paquet WDDX
  • wddx_serialize_vars — Enregistre plusieurs valeurs dans un paquet WDDX

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>


Ajoute des variables à un paquet WDDX

  • « WDDX Fonctions
  • wddx_deserialize »
  • PHP Manual
  • WDDX Fonctions
  • Ajoute des variables à un paquet WDDX

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Ajoute des variables à un paquet WDDX

Avertissement

Cette fonction est a été SUPPRIMÉE à partir de PHP 7.4.0.

Description

wddx_add_vars(resource $packet_id, mixed $var_name, mixed ...$var_names): bool

Sert à enregistrer et à ajouter les variables passées en argument au paquet repéré par son identifiant packet_id.

Liste de paramètres

Cette fonction prend un nombre variable de paramètres.

packet_id

Un paquet WDDX, retourné par la fonction wddx_packet_start().

var_name

Peut être une chaîne de caractères nommant une variable ou un tableau contenant des noms de variables ou d'autres tableaux, etc..

var_names

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

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 !


Désérialise un paquet WDDX

  • « wddx_add_vars
  • wddx_packet_end »
  • PHP Manual
  • WDDX Fonctions
  • Désérialise un paquet WDDX

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Désérialise un paquet WDDX

Avertissement

Cette fonction est a été SUPPRIMÉE à partir de PHP 7.4.0.

Description

wddx_deserialize(string $packet): mixed

Désérialise un paquet packet WDDX.

Avertissement

Ne passez pas d'entrée utilisateur non vérifiée à wddx_deserialize(). La désérialisation peut faire que le code soit chargé, et exécuté lors de l'instanciation et l'autochargement de l'objet, et un utilisateur mal intentionné peut être capable d'y loger un exploit. Utilisez une format, sûr, d'échange de données standardisé comme JSON (à l'aide de json_decode() et json_encode()) si vous devez passer des données sérialisé à l'utilisateur.

Liste de paramètres

packet

Un paquet WDDX, sous la forme d'une chaîne de caractères ou d'un flux.

Valeurs de retour

Retourne la valeur désérialisée, pouvant être une chaîne de caractères, un nombre ou un tableau. Notez que les structures sont désérialisées dans des tableaux associatifs.

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>";
}
?>


Clôt un paquet WDDX

  • « wddx_deserialize
  • wddx_packet_start »
  • PHP Manual
  • WDDX Fonctions
  • Clôt un paquet WDDX

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Clôt un paquet WDDX

Avertissement

Cette fonction est a été SUPPRIMÉE à partir de PHP 7.4.0.

Description

wddx_packet_end(resource $packet_id): string

Clôt un paquet WDDX.

Liste de paramètres

packet_id

Un paquet WDDX, retourné par la fonction wddx_packet_start().

Valeurs de retour

Retourne une chaîne de caractères contenant le paquet WDDX.

User Contributed Notes

There are no user contributed notes for this page.


Commence un nouveau paquet WDDX avec une structure

  • « wddx_packet_end
  • wddx_serialize_value »
  • PHP Manual
  • WDDX Fonctions
  • Commence un nouveau paquet WDDX avec une structure

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Commence un nouveau paquet WDDX avec une structure

Avertissement

Cette fonction est a été SUPPRIMÉE à partir de PHP 7.4.0.

Description

wddx_packet_start(string $comment = ?): resource

wddx_packet_start() sert à créer un nouveau paquet WDDX, pour pouvoir y faire des ajouts incrémentaux de variables. Elle va automatiquement créer une définition de structure dans le paquet, pour accueillir des variables.

Liste de paramètres

comment

Une chaîne de caractères optionnelle contenant le commentaire.

Valeurs de retour

Retourne un identifiant de paquet pour utilisation ultérieure avec les fonctions WDDX, ou false si une erreur survient.

User Contributed Notes

There are no user contributed notes for this page.


Enregistre une valeur dans un paquet WDDX

  • « wddx_packet_start
  • wddx_serialize_vars »
  • PHP Manual
  • WDDX Fonctions
  • Enregistre une valeur dans un paquet WDDX

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Enregistre une valeur dans un paquet WDDX

Avertissement

Cette fonction est a été SUPPRIMÉE à partir de PHP 7.4.0.

Description

wddx_serialize_value(mixed $var, string $comment = ?): string

Enregistre une valeur donnée dans un paquet WDDX.

Liste de paramètres

var

La valeur à sérialiser.

comment

Une chaîne de caractères optionnelle contenant un commentaire qui apparaît dans l'en-tête du paquet.

Valeurs de retour

Retourne le paquet WDDX, ou false si une erreur survient.

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


Enregistre plusieurs valeurs dans un paquet WDDX

  • « wddx_serialize_value
  • XMLDiff »
  • PHP Manual
  • WDDX Fonctions
  • Enregistre plusieurs valeurs dans un paquet WDDX

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Enregistre plusieurs valeurs dans un paquet WDDX

Avertissement

Cette fonction est a été SUPPRIMÉE à partir de PHP 7.4.0.

Description

wddx_serialize_vars(mixed $var_name, mixed ...$var_names): string

Sert à créer un paquet WDDX avec une structure qui contient la représentation des variables passées en arguments.

Liste de paramètres

Cette fonction prend un nombre variable de paramètres.

var_name

Peut être soit une chaîne de caractères nommant une variable ou un tableau contenant des noms de variables ou d'autres tableaux, etc..

var_names

Valeurs de retour

Retourne le paquet WDDX, ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec wddx_serialize_vars()

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

L'exemple ci-dessus va afficher :

<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érence et fusion

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
  • XMLDiff\Base — La classe XMLDiff\Base
    • XMLDiff\Base::__construct — Constructeur
    • XMLDiff\Base::diff — Produit la différence de deux documents XML
    • XMLDiff\Base::merge — Produit un nouveau document XML basé sur une différence
  • XMLDiff\DOM — La classe XMLDiff\DOM
    • XMLDiff\DOM::diff — Trouve la différence de deux objets DOMDocument
    • XMLDiff\DOM::merge — Produit un DOMDocument fusionné
  • XMLDiff\Memory — La classe XMLDiff\Memory
    • XMLDiff\Memory::diff — Différence entre deux documents XML
    • XMLDiff\Memory::merge — Fusionne un document XML
  • XMLDiff\File — La classe XMLDiff\File
    • XMLDiff\File::diff — Effectue la différence entre deux documents XML
    • XMLDiff\File::merge — Fusionne un document XML

User Contributed Notes

There are no user contributed notes for this page.


Introduction

L'extension est capable de produire la différence de deux documents XML, puis d'appliquer la différence au document source. La différence est un document XML contenant les copies/insertions/suppressions dans un format humainement lisible. Les objets DOMDocument, les fichiers locaux, et les chaînes de caractères en mémoire peuvent être utilisés.

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

libdiffmark - version 0.10 est comprise dans l'extension. Si diffmark est disponible pour votre système de paquets, son utilisation est fortement encouragée.

extension libxml

extension DOM

User Contributed Notes

There are no user contributed notes for this page.


Installation

Cette extension » PECL n'est pas intégrée à PHP.

Des informations sur l'installation de ces extensions PECL peuvent être trouvées dans le chapitre du manuel intitulé Installation des extensions PECL. D'autres informations comme les notes sur les nouvelles versions, les téléchargements, les sources des fichiers, les informations concernant les mainteneurs ainsi qu'un CHANGELOG, peuvent être trouvées ici : » https://pecl.php.net/package/xmldiff.

Une bibliothèque DLL pour cette extension PECL est disponible sur » http://windows.php.net/downloads/pecl/releases/xmldiff/.

User Contributed Notes

There are no user contributed notes for this page.


La classe XMLDiff\Base

(PECL xmldiff >= 0.8.0)

Introduction

Classe abstraite de base pour toutes les classes de comparaison de cette extension.

Synopsis de la classe

class XMLDiff\Base {
/* Méthodes */
public __construct(string $nsname)
abstract public diff(mixed $from, mixed $to): mixed
abstract public merge(mixed $src, mixed $diff): mixed
}

Sommaire

  • XMLDiff\Base::__construct — Constructeur
  • XMLDiff\Base::diff — Produit la différence de deux documents XML
  • XMLDiff\Base::merge — Produit un nouveau document XML basé sur une différence

User Contributed Notes

There are no user contributed notes for this page.


Constructeur

  • « XMLDiff\Base
  • XMLDiff\Base::diff »
  • PHP Manual
  • XMLDiff\Base
  • Constructeur

XMLDiff\Base::__construct

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::__construct — Constructeur

Description

public XMLDiff\Base::__construct(string $nsname)

Constructeur de base pour toutes les classes de l'extension xmldiff.

Liste de paramètres

nsname

Espace de noms personnalisé pour le document de différence. L'espace de noms par défaut est http://www.locus.cz/diffmark et est suffisant pour éviter les conflits d'espaces de noms. Utilisez ce paramètre si vous voulez changer d'espace de noms.

User Contributed Notes

There are no user contributed notes for this page.


Produit la différence de deux documents XML

  • « XMLDiff\Base::__construct
  • XMLDiff\Base::merge »
  • PHP Manual
  • XMLDiff\Base
  • Produit la différence de deux documents XML

XMLDiff\Base::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::diff — Produit la différence de deux documents XML

Description

abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed

Méthode abstraire de création de différence à implémenter par héritage de la classe.

Le but premier de cette méthode est de produire la différence de deux documents. L'ordre des paramètres est important, et va produire une sortie différente.

Liste de paramètres

from

Document XML source.

to

Document XML cible.

Valeurs de retour

Dépend de l'implémentation.

User Contributed Notes

There are no user contributed notes for this page.


Produit un nouveau document XML basé sur une différence

  • « XMLDiff\Base::diff
  • XMLDiff\DOM »
  • PHP Manual
  • XMLDiff\Base
  • Produit un nouveau document XML basé sur une différence

XMLDiff\Base::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::merge — Produit un nouveau document XML basé sur une différence

Description

abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed

Méthode abstraite de fusion à implémenter par héritage de la classe.

Basiquement, le but de cette méthode est de produire un nouveau document XML basé sur les informations de différence.

Liste de paramètres

src

Document XML source.

diff

Document produit par la méthode de création de différence.

Valeurs de retour

Dépend de l'implémentation.

User Contributed Notes

There are no user contributed notes for this page.


La classe XMLDiff\DOM

(PECL xmldiff >= 0.8.0)

Introduction

Synopsis de la classe

class XMLDiff\DOM extends XMLDiff\Base {
/* Méthodes */
public diff(DOMDocument $from, DOMDocument $to): DOMDocument
public merge(DOMDocument $src, DOMDocument $diff): DOMDocument
/* Méthodes héritées */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Sommaire

  • XMLDiff\DOM::diff — Trouve la différence de deux objets DOMDocument
  • XMLDiff\DOM::merge — Produit un DOMDocument fusionné

User Contributed Notes

There are no user contributed notes for this page.


Trouve la différence de deux objets DOMDocument

  • « XMLDiff\DOM
  • XMLDiff\DOM::merge »
  • PHP Manual
  • XMLDiff\DOM
  • Trouve la différence de deux objets DOMDocument

XMLDiff\DOM::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::diff — Trouve la différence de deux objets DOMDocument

Description

public XMLDiff\DOM::diff(DOMDocument $from, DOMDocument $to): DOMDocument

Trouve la différence de deux instances DOMDocument et produit un nouvel objet DOMDocument contenant les informations de différence.

Liste de paramètres

from

Objet source DOMDocument.

to

Objet cible DOMDocument.

Valeurs de retour

Un nouvel objet DOMDocument contenant les informations de différence ou 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');

?>


Produit un DOMDocument fusionné

  • « XMLDiff\DOM::diff
  • XMLDiff\Memory »
  • PHP Manual
  • XMLDiff\DOM
  • Produit un DOMDocument fusionné

XMLDiff\DOM::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::merge — Produit un DOMDocument fusionné

Description

public XMLDiff\DOM::merge(DOMDocument $src, DOMDocument $diff): DOMDocument

Crée un nouveau DOMDocument basé sur une différence.

Liste de paramètres

src

Objet DOMDocument source.

diff

L'objet DOMDocument contenant les informations de différence.

Valeurs de retour

DOMDocument fusionné ou NULL.

User Contributed Notes

There are no user contributed notes for this page.


La classe XMLDiff\Memory

(PECL xmldiff >= 0.8.0)

Introduction

Synopsis de la classe

class XMLDiff\Memory extends XMLDiff\Base {
/* Méthodes */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Méthodes héritées */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Sommaire

  • XMLDiff\Memory::diff — Différence entre deux documents XML
  • XMLDiff\Memory::merge — Fusionne un document XML

User Contributed Notes

There are no user contributed notes for this page.


Différence entre deux documents XML

  • « XMLDiff\Memory
  • XMLDiff\Memory::merge »
  • PHP Manual
  • XMLDiff\Memory
  • Différence entre deux documents XML

XMLDiff\Memory::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::diff — Différence entre deux documents XML

Description

public XMLDiff\Memory::diff(string $from, string $to): string

Effectue la différence de deux chaînes contenant des documents XML et produit les informations de différence.

Liste de paramètres

from

Document XML source.

to

Document XML cible.

Valeurs de retour

Une chaîne contenant la différence entre les deux documents XML ou NULL.

User Contributed Notes

There are no user contributed notes for this page.


Fusionne un document XML

  • « XMLDiff\Memory::diff
  • XMLDiff\File »
  • PHP Manual
  • XMLDiff\Memory
  • Fusionne un document XML

XMLDiff\Memory::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::merge — Fusionne un document XML

Description

public XMLDiff\Memory::merge(string $src, string $diff): string

Crée un nouveau document XML basé sur les différences et le document source.

Liste de paramètres

src

Document XML source.

diff

Document XML contenant les informations de différence.

Valeurs de retour

Une chaîne contenant le nouveau document XML ou NULL.

User Contributed Notes

There are no user contributed notes for this page.


La classe XMLDiff\File

(PECL xmldiff >= 0.8.0)

Introduction

Synopsis de la classe

class XMLDiff\File extends XMLDiff\Base {
/* Méthodes */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Méthodes héritées */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Sommaire

  • XMLDiff\File::diff — Effectue la différence entre deux documents XML
  • XMLDiff\File::merge — Fusionne un document XML

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);
?>


Effectue la différence entre deux documents XML

  • « XMLDiff\File
  • XMLDiff\File::merge »
  • PHP Manual
  • XMLDiff\File
  • Effectue la différence entre deux documents XML

XMLDiff\File::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\File::diff — Effectue la différence entre deux documents XML

Description

public XMLDiff\File::diff(string $from, string $to): string

Effectue la différence entre deux documents XML locaux, et produit une chaîne contenant les informations de différence.

Liste de paramètres

from

Chemin vers le document source.

to

Chemin vers le document cible.

Valeurs de retour

Une chaîne contenant la différence des deux documents XML ou NULL.

User Contributed Notes

There are no user contributed notes for this page.


Fusionne un document XML

  • « XMLDiff\File::diff
  • Analyseur syntaxique XML »
  • PHP Manual
  • XMLDiff\File
  • Fusionne un document XML

XMLDiff\File::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\File::merge — Fusionne un document XML

Description

public XMLDiff\File::merge(string $src, string $diff): string

Crée un document XML basé sur des différences et sur le document source.

Liste de paramètres

src

Chemin vers le document XML source.

diff

Chemin vers le document XML contenant les informations de différence.

Valeurs de retour

Une chaîne de caractères représentant le nouveau document XML ou NULL.

User Contributed Notes

There are no user contributed notes for this page.


Analyseur syntaxique XML

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • gestionnaires d'événements
  • Problèmes de casse
  • Codes d'erreurs
  • Codage des caractères
  • Exemples
    • Exemple de structure XML
    • Transtypage XML -> HTML
    • Entité externe
  • Fonctions d'analyse de fichier XML
    • xml_error_string — Lit le message d'erreur de l'analyseur XML
    • xml_get_current_byte_index — Retourne l'index de l'octet courant d'un analyseur XML
    • xml_get_current_column_number — Retourne le numéro de colonne courant d'un analyseur XML
    • xml_get_current_line_number — Retourne le numéro de ligne courant d'un analyseur XML
    • xml_get_error_code — Récupère le code erreur de l'analyseur XML
    • xml_parse_into_struct — Analyse une structure XML
    • xml_parse — Commence l'analyse d'un document XML
    • xml_parser_create_ns — Crée un analyseur XML
    • xml_parser_create — Création d'un analyseur XML
    • xml_parser_free — Détruit un analyseur XML
    • xml_parser_get_option — Lit les options d'un analyseur XML
    • xml_parser_set_option — Affecte les options d'un analyseur XML
    • xml_set_character_data_handler — Affecte les gestionnaires de texte littéral
    • xml_set_default_handler — Affecte le gestionnaire XML par défaut
    • xml_set_element_handler — Affecte les gestionnaires de début et de fin de balise XML
    • xml_set_end_namespace_decl_handler — Configure le gestionnaire XML de données
    • xml_set_external_entity_ref_handler — Configure le gestionnaire XML de références externes
    • xml_set_notation_decl_handler — Configure le gestionnaire XML de notations
    • xml_set_object — Configure un objet comme analyseur XML
    • xml_set_processing_instruction_handler — Affecte les gestionnaires d'instructions de traitement
    • xml_set_start_namespace_decl_handler — Configure le gestionnaire de caractères
    • xml_set_unparsed_entity_decl_handler — Affecte les gestionnaires d'entités non déclarées
  • XMLParser — La classe XMLParser

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.


Introduction

Le langage XML (eXtensible Markup Language (Langage à Balises Extensible)) est un format structuré de données pour les échanges sur le web. C'est un standard défini par le consortium World Wide Web (W3C). Plus d'informations à propos du XML et des technologies afférentes sont accessibles (en anglais) » http://www.w3.org/XML/.

Cette extension PHP implémente la bibliothèque expat de James Clark sous PHP. Cela vous permettra d'analyser mais pas de valider les documents XML. Ce langage supporte trois types de jeux de caractères différents, disponibles aussi sous PHP : US-ASCII, ISO-8859-1 et UTF-8. UTF-16 n'est pas supporté.

Cette extension vous permet de créer des analyseurs XML puis de définir des gestionnaires pour chaque événement XML. Les analyseurs XML disposent de quelques paramètres que vous pouvez régler.

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

Cette extension requière l'extension PHP libxml. Ceci signifie passer l'option de configuration --with-libxml, ou antérieur à PHP 7.4 l'option de configuration --enable-libxml, bien que ceci est accomplie implicitement car libxml est activé par défaut.

Cette extension PHP utilise expat compat layer par défaut. Elle peut aussi utiliser expat, qui est disponible sur » http://www.jclark.com/xml/expat.html. Le fichier Makefile livré avec expat ne construit pas par défaut de bibliothèque : il faut utiliser la ligne suivante :

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
Un paquet RPM source de expat est disponible sur » http://sourceforge.net/projects/expat/.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Cette extension est activée par défaut. Elle peut être désactivée en utilisant l'option de configuration : --disable-xml

Ces fonctions sont activées par défaut, et utilisent la bibliothèque expat fournie avec la distribution. Vous pouvez désactiver le support de XML en utilisant l'option de compilation --disable-xml. Si vous compilez PHP comme module pour Apache 1.3.9 ou supérieur, PHP va automatiquement utiliser la bibliothèque expat fournie par Apache. Si vous ne souhaitez pas utiliser la bibliothèque expat intégrée, il faut que vous compiliez PHP avec l'option --with-expat-dir=DIR, où DIR est le dossier d'installation de votre bibliothèque expat.

La version Windows de PHP dispose du support automatique de cette extension. Vous n'avez pas à ajouter de bibliothèque supplémentaire pour disposer de ces fonctions.

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.


Types de ressources

Antérieur à PHP 8.0.0, la ressource xml est retournée par xml_parser_create() et xml_parser_create_ns(), et représente un analyseur XML à utiliser avec les autres fonctions de cette extension.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

XML_ERROR_NONE (int)
XML_ERROR_NO_MEMORY (int)
XML_ERROR_SYNTAX (int)
XML_ERROR_NO_ELEMENTS (int)
XML_ERROR_INVALID_TOKEN (int)
XML_ERROR_UNCLOSED_TOKEN (int)
XML_ERROR_PARTIAL_CHAR (int)
XML_ERROR_TAG_MISMATCH (int)
XML_ERROR_DUPLICATE_ATTRIBUTE (int)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (int)
XML_ERROR_PARAM_ENTITY_REF (int)
XML_ERROR_UNDEFINED_ENTITY (int)
XML_ERROR_RECURSIVE_ENTITY_REF (int)
XML_ERROR_ASYNC_ENTITY (int)
XML_ERROR_BAD_CHAR_REF (int)
XML_ERROR_BINARY_ENTITY_REF (int)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (int)
XML_ERROR_MISPLACED_XML_PI (int)
XML_ERROR_UNKNOWN_ENCODING (int)
XML_ERROR_INCORRECT_ENCODING (int)
XML_ERROR_UNCLOSED_CDATA_SECTION (int)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (int)
XML_OPTION_CASE_FOLDING (int)
XML_OPTION_TARGET_ENCODING (int)
XML_OPTION_SKIP_TAGSTART (int)
XML_OPTION_SKIP_WHITE (int)
XML_SAX_IMPL (string)
Précise la méthode d'implémentation de SAX. Peut être libxml ou expat.

User Contributed Notes

There are no user contributed notes for this page.


gestionnaires d'événements

Les gestionnaires d'événements XML sont :

Les gestionnaires d'événements XML supportés
Fonction PHP de configuration du gestionnaire | Description de l'événement
xml_set_element_handler() | Un événement est généré à chaque fois que l'analyseur XML rencontre une balise de début ou de fin. Deux gestionnaires sont disponibles : un pour le début, et un pour la fin.
xml_set_character_data_handler() | "Character data" correspond grosso modo à tout ce qui n'est pas une balise XML, y compris les espaces entre les balises. Notez bien que l'analyseur XML n'ajoute ou n'efface aucun espace, et que c'est à l'application (c'est-à-dire vous) de décider de la signification de ces espaces.
xml_set_processing_instruction_handler() | Les programmeurs PHP sont habitués aux instructions exécutables (processing instructions ou PIs). <?php ?> est une instruction exécutable où php est appelé programme cible. Ces instructions sont gérées de manière spécifique, (sauf le programme cible "XML" qui est réservé).
xml_set_default_handler() | Tout ce qui n'a pas trouvé de gestionnaire est transmis au gestionnaire par défaut. Vous retrouverez par exemple, les déclarations de type de document dans ce gestionnaire.
xml_set_unparsed_entity_decl_handler() | Ce gestionnaire est appelé pour gérer les déclaration des entités non analysées (NDATA).
xml_set_notation_decl_handler() | Ce gestionnaire est appelé pour déclarer les notations.
xml_set_external_entity_ref_handler() | Ce gestionnaire est appelé lorsque l'analyseur XML trouve une référence à une entité générale externe. Cela peut être une référence à un fichier ou à une URL. Reportez-vous à entité externe pour un exemple.
xml_set_start_namespace_decl_handler() | Ce gestionnaire est appelé pour le début de la déclaration d'un espace de noms.
xml_set_end_namespace_decl_handler() | Ce gestionnaire est appelé pour la déclaration de fin d'espace de noms. Notez que cet évennement n'est pas déclenché de LibXML.

User Contributed Notes

There are no user contributed notes for this page.


Problèmes de casse

Les fonctions de gestion des balises peuvent rencontrer des balises en minuscule, majuscule ou encore dans un mélange des deux. En XML, la procédure standard est d'"identifier les séquences de caractères qui ne sont pas reconnues comme majuscule, et de les remplacer par leur équivalent majuscule". C'est le case-folding, en anglais. En bref, XML met toutes les lettres en majuscules.

Par défaut, tous les noms des éléments qui sont transmis aux fonctions de gestion sont mis en majuscules. Ce comportement est contrôlé par l'analyseur XML, et peut être lu et modifié avec les fonctions respectives xml_parser_get_option() et xml_parser_set_option().

User Contributed Notes

There are no user contributed notes for this page.


Codes d'erreurs

Les constantes suivantes sont définies comme des codes d'erreurs XML : (retournées par 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
?>


Codage des caractères

L'extension XML de PHP supporte les caractères » Unicode grâce à différents codages. Il y a deux types de codages de caractères : le codage à la source et le codage à la cible. PHP utilise le UTF-8 comme représentation interne.

L'encodage à la source est effectué lors de l'analyse du fichier par XML. Lors de la création d'un analyseur XML), un type de codage à la source peut être spécifié (et il ne pourra plus être modifié jusqu'à la destruction de l'analyseur). Les codages supportés sont : ISO-8859-1, US-ASCII et UTF-8. Les deux derniers sont des codages à un seul octet, c'est-à-dire que les caractères sont représentés sur un seul octet. UTF-8 peut représenter des caractères composés par un nombre variable de bits (jusqu'à 21), allant de 1 à quatre octets. Le codage par défaut utilisé par PHP ISO-8859-1.

Le codage à la cible est effectué lorsque PHP transfert les données aux gestionnaires XML. Lorsqu'un analyseur est créé, le codage à la cible est spécifié de la même façon que le codage à la source, mais il peut être modifié à tout moment. Le codage à la cible affectera les balises, tout comme les données brutes, et les noms des instructions exécutables.

Si l'analyseur XML rencontre un caractère qu'il ne connaît pas (hors limite, par exemple), il retournera une erreur.

Si PHP rencontre un caractère dans le document XML analysé, qu'il ne peut pas représenter dans le codage à la cible choisi, le caractère sera remplacé par un point d'interrogation (cette attitude est susceptible de changer ultérieurement).

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Sommaire

  • Exemple de structure XML
  • Transtypage XML -> HTML
  • Entité externe

User Contributed Notes

There are no user contributed notes for this page.


Exemple de structure XML

Ce premier exemple affiche la structure de l'élément de début dans un document avec indentation.

Exemple #1 Afficher une structure XML

<?php
$file = "data.xml";
$depth = 0;

function startElement($parser, $name, $attrs)
{
global $depth;

global $depth;

for ($i = 0; $i < $depth; $i++) {
echo " ";
}
echo "$name\n";
$depth++;
}

function endElement($parser, $name)
{
global $depth;
$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);
?>

User Contributed Notes

Joachim Kruyswijk 27-Jun-2022 02:08
If you use strict_types=1, you'll get the warning "Notice: Resource ID#... used as offset, casting to integer".

Use

<?php $depth[(int) $parser]  ?>

instead of

<?php $depth[$parser]  ?>
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>";
?>


Transtypage XML -> HTML

Exemple #1 Transtypage XML -> HTML

Cet exemple remplace les balises XML d'un document par des balises HTML. Les éléments inconnus seront ignorés. Bien entendu, cet exemple sera appliqué à un type précis de fichiers 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();
// Utilisons la gestion de casse, de manière à être sûrs de trouver la balise dans $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("Erreur XML: %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.


Entité externe

Cet exemple exploite les références externes de XML : il est possible d'utiliser un gestionnaire d'entité externe pour inclure et analyser les documents, tous comme les instructions exécutables peuvent servir à inclure et analyser d'autres documents, et aussi fournir une indication de confiance (voir plus bas).

Le document XML qui est utilisé dans cet exemple est fourni plus loin dans l'exemple (xmltest.xml et xmltest2.xml).

Exemple #1 Entité externe

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
// faites seulement confiance aux fichiers locaux dont vous êtes le propriétaire
if (!preg_match("@^([a-z][a-z0-9+.-]*)\:\/\/@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;
// si le document analysé est de confiance, nous déclarons qu'il est sûr
// d'exécuter le code PHP qu'il contient. Si ce n'est pas le cas, le code est affiché
// à la place.
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);

?>

Exemple #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>

Ce fichier est inclus depuis xmltest.xml :

Exemple #3 xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "Ceci est du code PHP qui est exécuté."; ?>
</foo>

User Contributed Notes

There are no user contributed notes for this page.


Fonctions d'analyse de fichier XML

Sommaire

  • xml_error_string — Lit le message d'erreur de l'analyseur XML
  • xml_get_current_byte_index — Retourne l'index de l'octet courant d'un analyseur XML
  • xml_get_current_column_number — Retourne le numéro de colonne courant d'un analyseur XML
  • xml_get_current_line_number — Retourne le numéro de ligne courant d'un analyseur XML
  • xml_get_error_code — Récupère le code erreur de l'analyseur XML
  • xml_parse_into_struct — Analyse une structure XML
  • xml_parse — Commence l'analyse d'un document XML
  • xml_parser_create_ns — Crée un analyseur XML
  • xml_parser_create — Création d'un analyseur XML
  • xml_parser_free — Détruit un analyseur XML
  • xml_parser_get_option — Lit les options d'un analyseur XML
  • xml_parser_set_option — Affecte les options d'un analyseur XML
  • xml_set_character_data_handler — Affecte les gestionnaires de texte littéral
  • xml_set_default_handler — Affecte le gestionnaire XML par défaut
  • xml_set_element_handler — Affecte les gestionnaires de début et de fin de balise XML
  • xml_set_end_namespace_decl_handler — Configure le gestionnaire XML de données
  • xml_set_external_entity_ref_handler — Configure le gestionnaire XML de références externes
  • xml_set_notation_decl_handler — Configure le gestionnaire XML de notations
  • xml_set_object — Configure un objet comme analyseur XML
  • xml_set_processing_instruction_handler — Affecte les gestionnaires d'instructions de traitement
  • xml_set_start_namespace_decl_handler — Configure le gestionnaire de caractères
  • xml_set_unparsed_entity_decl_handler — Affecte les gestionnaires d'entités non déclarées

User Contributed Notes

biuro at dso dot biz dot pl 11-Jan-2022 08:40
A class proposition that can handle very large XML files

use
<?php
$domObj = new BigXMLToArray($fileData, true);
?>

<?php
class BigXMLToArray
{
    public $array;

    public function __construct($xml, $getRoot = false) {
        $use_errors = libxml_use_internal_errors(true);
        $xmlData = simplexml_load_string($xml);
        if (false === $xmlData) {
            $message = "Failed loading XML\r\n";

            foreach(libxml_get_errors() as $error) {
                $message = "\t" . $error->message . "\r\n";
            }
            // Do something about this error message , e.g.
            // DsoMultiImporterLog::setError(['message' => $message, 'xml' => $xml], 'GLOBAL', __METHOD__);
        } else {
            $this->array = $this->xml2array($xmlData, $getRoot);
        }
        libxml_clear_errors();
        libxml_use_internal_errors($use_errors);
    }

    private function getAttributesList($xmlObject, $out = [])
    {
        if (count($xmlObject) > 1) {
            foreach ($xmlObject as $index => $node) {
                if (is_object($node)) {
                    $out[$index] = $this->getAttributesList($xmlObject);
                } else {
                    $out[$index] = $node;
                }
            }
        } else {
            foreach ($xmlObject as $index => $node) {
                if (is_object($node)) {
                    $out = $this->getAttributesList($xmlObject);
                } else {
                    $out = $node;
                }
            }
        }

        return $out;
    }

    private function xml2array($xmlObject, $isRoot = false, $out = [])
    {
        if ($isRoot) {
            $out[$xmlObject->getName()] = $this->xml2array($xmlObject, false);
        } elseif (is_array($xmlObject) || (is_object($xmlObject) && $xmlObject->count() > 0)) {
            foreach ($xmlObject->children() as $index => $node) {
                $tmp = [];
                if (is_object($node)) {
                    foreach($node->attributes() as $a => $b) {
                        if (is_object($b) ||is_array($b)) {
                            $tmp['attrib'][$a] = $this->getAttributesList((array)$b);
                        } else {
                            $tmp['attrib'][$a] = $b;
                        }
                    }
                }

                if (empty($tmp['attrib'])) {
                    $tmp = $this->xml2array($node, false);
                } else {
                    $tmp['value'] = $this->xml2array($node, false);
                }

                if (!empty($out[$index])) {
                    if (is_string($out[$index])
                        || is_numeric($out[$index])
                        || (is_array($out[$index]) && $out[$index] !== array_values($out[$index]))
                    ) {
                        $out[$index] = [$out[$index]];
                    }

                    $out[$index][] = $tmp;
                } else {
                    $out[$index] = $tmp;
                }
            }
        }
        else{
            $out = json_decode($xmlObject);

            if ($out === null and !empty((string) $xmlObject)) {
                $out = (string) $xmlObject;
            }
        }
        return $out;
    }
}
?>
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.


Lit le message d'erreur de l'analyseur XML

  • « Fonctions d'analyse de fichier XML
  • xml_get_current_byte_index »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Lit le message d'erreur de l'analyseur XML

xml_error_string

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_error_string — Lit le message d'erreur de l'analyseur XML

Description

xml_error_string(int $error_code): ?string

Lit le message d'erreur de l'analyseur XML associé avec le code error_code donné.

Liste de paramètres

error_code

Un code erreur provenant de xml_get_error_code().

Valeurs de retour

Retourne une chaîne représentant la description de l'erreur error_code, ou null si aucune description n'est trouvée.

Voir aussi

  • xml_get_error_code() - Récupère le code erreur de l'analyseur 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;
?>


Retourne l'index de l'octet courant d'un analyseur XML

  • « xml_error_string
  • xml_get_current_column_number »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Retourne l'index de l'octet courant d'un analyseur XML

xml_get_current_byte_index

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_current_byte_index — Retourne l'index de l'octet courant d'un analyseur XML

Description

xml_get_current_byte_index(XMLParser $parser): int

Retourne l'index de l'octet courant de l'analyseur XML donné.

Liste de paramètres

parser

Une référence sur un analyseur XML valide.

Valeurs de retour

xml_get_current_byte_index() retourne l'index de l'octet d'analyse courante de l'analyseur XML (débute à 0).

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Notes

Avertissement

Cette fonction retourne l'index de l'octet en accord avec le texte encodé UTF-8 même si l'entrée est dans un autre encodage.

Voir aussi

  • xml_get_current_column_number() - Retourne le numéro de colonne courant d'un analyseur XML
  • xml_get_current_line_number() - Retourne le numéro de ligne courant d'un analyseur XML

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.


Retourne le numéro de colonne courant d'un analyseur XML

  • « xml_get_current_byte_index
  • xml_get_current_line_number »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Retourne le numéro de colonne courant d'un analyseur XML

xml_get_current_column_number

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_current_column_number — Retourne le numéro de colonne courant d'un analyseur XML

Description

xml_get_current_column_number(XMLParser $parser): int

Retourne le numéro de colonne courant de l'analyseur XML donné.

Liste de paramètres

parser

Une référence sur un analyseur XML valide.

Valeurs de retour

xml_get_current_column_number() retourne le numéro de colonne courante de la ligne courante de l'analyseur, qui correspond à la position d'analyse courante de l'analyseur XML (comme retourné par xml_get_current_line_number()).

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Voir aussi

  • xml_get_current_byte_index() - Retourne l'index de l'octet courant d'un analyseur XML
  • xml_get_current_line_number() - Retourne le numéro de ligne courant d'un analyseur XML

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.


Retourne le numéro de ligne courant d'un analyseur XML

  • « xml_get_current_column_number
  • xml_get_error_code »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Retourne le numéro de ligne courant d'un analyseur XML

xml_get_current_line_number

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_current_line_number — Retourne le numéro de ligne courant d'un analyseur XML

Description

xml_get_current_line_number(XMLParser $parser): int

Retourne le numéro de ligne courant de l'analyseur XML donné.

Liste de paramètres

parser

Une référence sur un analyseur XML valide.

Valeurs de retour

Retourne le numéro de la ligne en cours d'analyse.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Voir aussi

  • xml_get_current_column_number() - Retourne le numéro de colonne courant d'un analyseur XML
  • xml_get_current_byte_index() - Retourne l'index de l'octet courant d'un analyseur XML

User Contributed Notes

There are no user contributed notes for this page.


Récupère le code erreur de l'analyseur XML

  • « xml_get_current_line_number
  • xml_parse_into_struct »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Récupère le code erreur de l'analyseur XML

xml_get_error_code

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_get_error_code — Récupère le code erreur de l'analyseur XML

Description

xml_get_error_code(XMLParser $parser): int

Récupère le code erreur de l'analyseur XML.

Liste de paramètres

parser

Une référence sur un analyseur XML valide.

Valeurs de retour

xml_get_error_code() retourne un des codes erreur listés dans la section sur les codes erreur.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Voir aussi

  • xml_error_string() - Lit le message d'erreur de l'analyseur XML

User Contributed Notes

There are no user contributed notes for this page.


Analyse une structure XML

  • « xml_get_error_code
  • xml_parse »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Analyse une structure XML

xml_parse_into_struct

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parse_into_struct — Analyse une structure XML

Description

xml_parse_into_struct(
XMLParser $parser,
string $data,
array &$values,
array &$index = null
): int

Cette fonction analyse la chaîne XML data et le place dans deux tableaux : le premier index contient des pointeurs sur la position des valeurs correspondantes dans le tableau values. Ces deux paramètres sont passés par références.

Liste de paramètres

parser

Une référence à une analyseur XML.

data

Une chaîne de caractères contenant les données XML.

values

Un tableau contenant les valeurs des données XML.

index

Un tableau contenant les pointeurs vers les valeurs appropriées dans le paramètre $values.

Valeurs de retour

xml_parse_into_struct() retourne 0 si une erreur survient et 1 en cas de succès. Ce n'est pas la même chose que false et true, soyez prudent avec les opérateurs comme ===.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Exemples

Ci-dessous, vous trouverez un exemple qui illustre la structure des deux tableaux générés par la fonction. On utilise une balise simple note, placée dans une autre balise para. On analyse le tout, et on affiche la structure générée :

Exemple #1 Exemple avec 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);
?>

Affichera :

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
        )

)

L'analyse événementielle (comme celle de expat), peut se révéler complexe lorsque le document XML est complexe. xml_parse_into_struct() ne génère pas d'objet de type DOM, mais il génère plutôt des structures qui peuvent être parcourues à la façon d'un arbre. Considérons le fichier suivant, qui représente une petite base de données XML :

Exemple #2 moldb.xml - Petite base de données moléculaires

<?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>
Et maintenant, un code qui analyse le document, et génère les objets ad hoc :

Exemple #3 parsemoldb.php : Analyse moldb.xml et crée un tableau d'objets moléculaires

<?php

class AminoAcid {
var $name; // nom aa
var $symbol; // symbole à trois lettres
var $code; // code à une lettre
var $type; // hydrophobique, chargé ou neutre

function __construct ($aa) {
foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}

function readDatabase($filename) {
// lit la base de données xml des acides aminés
$data = file_get_contents($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);

// boucle à travers les structures
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 "** Base d'objets AminoAcid :\n";
print_r($db);

?>
Après exécution de parsemoldb.php, la variable $db contient un tableau d'objets AminoAcid, et l'affichage le confirme :
** Base d'objets AminoAcid :
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
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);
?>
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);

}
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
?>
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


Commence l'analyse d'un document XML

  • « xml_parse_into_struct
  • xml_parser_create_ns »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Commence l'analyse d'un document XML

xml_parse

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parse — Commence l'analyse d'un document XML

Description

xml_parse(XMLParser $parser, string $data, bool $is_final = false): int

xml_parse() analyse un document XML. Les gestionnaires pour les événements configurés sont appelés autant de fois que nécessaire.

Liste de paramètres

parser

Une référence sur l'analyseur XML à utiliser.

data

Une partie des données à analyser. Un document peut être analysé morceau par morceau par appels successifs à xml_parse() avec de nouvelles données, aussi longtemps que le paramètre is_final est défini et true lorsque les dernières données sont analysées.

is_final

Si défini et vaut true, data sera le dernier morceau de données envoyées à l'analyseur.

Valeurs de retour

Retourne 1 en cas de succès ou 0 en cas d'échec.

Lors d'un échec d'analyse, la cause de l'erreur peut être obtenue grâce
aux fonctions
xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() et
xml_get_current_byte_index().

Note:

Quelques erreurs (dont les erreurs d'entités) sont reportées à la fin des données, ceci uniquement si is_final vaut true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Exemples

Exemple #1 Analyse de gros documents XML par morceaux

Cet exemple montre comment les gros documents XML peuvent être lus et analysés en morceaux, permettant ainsi de ne pas conserver en mémoire la totalité du document. Aucun gestionnaire d'erreur n'a été positionné pour rendre l'exemple plus concis.

<?php
$stream = fopen('large.xml', 'r');
$parser = xml_parser_create();
// set up the handlers here
while (($data = fread($stream, 16384))) {
xml_parse($parser, $data); // analyse du morceau courant
}
xml_parse($parser, '', true); // finalisation de l'analyse
xml_parser_free($parser);
fclose($stream);

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 ;-)


Crée un analyseur XML

  • « xml_parse
  • xml_parser_create »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Crée un analyseur XML

xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

xml_parser_create_ns — Crée un analyseur XML

Description

xml_parser_create_ns(?string $encoding = null, string $separator = ":"): XMLParser

xml_parser_create_ns() crée un nouvel analyseur XML avec le support des espaces de noms, et retourne une instance de XMLParser à utiliser avec les autres fonctions XML.

Liste de paramètres

encoding

Ce jeu de caractères est automatiquement détecté et, donc, le paramètre encoding ne spécifie plus que la sortie. Le jeu de caractères de sortie par défaut est UTF-8. Les jeux de caractères supportés sont ISO-8859-1, UTF-8 et US-ASCII.

separator

Avec un analyseur qui supporte les espaces de noms, les balises qui sont passées aux différentes fonctions de gestion seront constituées du nom de l'espace et du nom de balise, séparé par la chaîne seperator.

Valeurs de retour

Retourne une nouvelle instance de XMLParser.

Historique

Version | Description
8.0.0 | Cette fonction retourne désormais une instance de XMLParser; auparavant, une resource était retournée, ou false si une erreur survient.
8.0.0 | encoding est désormais nullable.

Voir aussi

  • xml_parser_create() - Création d'un analyseur XML
  • xml_parser_free() - Détruit un analyseur XML

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.


Création d'un analyseur XML

  • « xml_parser_create_ns
  • xml_parser_free »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Création d'un analyseur XML

xml_parser_create

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_create — Création d'un analyseur XML

Description

xml_parser_create(?string $encoding = null): XMLParser

xml_parser_create() crée un analyseur XML et retourne une instance de XMLParser à utiliser avec les autres fonctions XML.

Liste de paramètres

encoding

L'encodage d'entrée est automatiquement détecté, ainsi le paramètre encoding ne spécifie que l'encodage de sortie. Si une chaîne vide est passée, l'analyseur tente d'identifier dans quel encodage le document est encodé en regardant les 3 ou 4 octets du haut. Le jeu de caractères de sortie par défaut est UTF-8. Les encodages supportées sont ISO-8859-1, UTF-8, et US-ASCII.

Valeurs de retour

Retourne une nouvelle instance de XMLParser.

Historique

Version | Description
8.0.0 | Cette fonction retourne désormais une instance de XMLParser; auparavant, une resource était retournée, ou false si une erreur survient.
8.0.0 | encoding est désormais nullable.

Voir aussi

  • xml_parser_create_ns() - Crée un analyseur XML
  • xml_parser_free() - Détruit un analyseur XML

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.


Détruit un analyseur XML

  • « xml_parser_create
  • xml_parser_get_option »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Détruit un analyseur XML

xml_parser_free

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_free — Détruit un analyseur XML

Description

xml_parser_free(XMLParser $parser): bool

Note:

Cette fonction n'a aucun effet. Antérieur à PHP 8.0.0, cette fonction était utilisé pour fermer une ressource.

Détruit l'analyseur XML parser.

Attention

Antérieur à PHP 8.0.0, en plus d'appeler la fonction xml_parser_free() à la fin de l'analyse, il était nécessaire de supprimer explicitement la référence au paramètre parser pour éviter les fuites mémoires, si la ressource analysé est référencé depuis un objet, et cet objet fait référence à la ressource analysé.

Liste de paramètres

parser
Une référence sur un analyseur XML.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

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!


Lit les options d'un analyseur XML

  • « xml_parser_free
  • xml_parser_set_option »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Lit les options d'un analyseur XML

xml_parser_get_option

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_get_option — Lit les options d'un analyseur XML

Description

xml_parser_get_option(XMLParser $parser, int $option): string|int|bool

Lit les options d'un analyseur XML.

Liste de paramètres

parser
Une référence sur un analyseur XML valide.
option
L'option demandée. XML_OPTION_CASE_FOLDING, XML_OPTION_SKIP_TAGSTART, XML_OPTION_SKIP_WHITE et XML_OPTION_TARGET_ENCODING sont disponibles. Reportez-vous à xml_parser_set_option() pour leurs descriptions.

Valeurs de retour

Renvoie la valeur de l'option

Erreurs / Exceptions

Lève une ValueError lorsque qu'une valeur invalide est passée à option.

Antérieur à PHP 8.0.0, passer une valeur invalide à option générait également un avertissement E_WARNING et faisait retourner à la fonction la valeur false.

Historique

Version | Description
8.3.0 | La fonction retourne désormais un booléen pour les options booléennes.
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.
8.0.0 | Une ValueError est désormais générée si option est invalide.
7.1.24, 7.2.12, 7.3.0 | options supporte désormais XML_OPTION_SKIP_TAGSTART et XML_OPTION_SKIP_WHITE.

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);
?>


Affecte les options d'un analyseur XML

  • « xml_parser_get_option
  • xml_set_character_data_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Affecte les options d'un analyseur XML

xml_parser_set_option

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_parser_set_option — Affecte les options d'un analyseur XML

Description

xml_parser_set_option(XMLParser $parser, int $option, string|int|bool $value): bool

Affecte les options d'un analyseur XML.

Liste de paramètres

parser

Une référence vers un analyseur XML.

option

L'option à modifier. Voir ci-dessous.

Les options suivantes sont disponibles :

Options de l'analyseur XML
Option | Type de données | Description
XML_OPTION_CASE_FOLDING | bool | Contrôle la gestion de la casse des balises de cet analyseur XML. Par défaut, activé.
XML_OPTION_SKIP_TAGSTART | bool | Spécifie combien de caractères doivent être éludés du début du nom de la balise.
XML_OPTION_SKIP_WHITE | entier | Élude ou non les valeurs contenant des caractères blancs.
XML_OPTION_TARGET_ENCODING | string | Modifie le codage à la cible utilisé par cet analyseur XML. Par défaut, c'est celui qui a été spécifié lors de l'appel de xml_parser_create(). Les codages supportés sont ISO-8859-1, US-ASCII et UTF-8.

value

La nouvelle valeur de l'option.

Valeurs de retour

Renvoie true en cas de succès ou false en cas d'échec.

Erreurs / Exceptions

Lève une ValueError lorsque qu'une valeur invalide est passée à option.

Antérieur à PHP 8.0.0, passer une valeur invalide à option générait un avertissement E_WARNING et faisait retourner à la fonction la valeur false.

Historique

Version | Description
8.3.0 | Le paramètre value accepte désormais également les booléens. Les options XML_OPTION_CASE_FOLDING et XML_OPTION_SKIP_WHITE sont désormais des options booléennes.
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.
8.0.0 | Une exception ValueError est désormais lancée si le option est invalide.

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.


Affecte les gestionnaires de texte littéral

  • « xml_parser_set_option
  • xml_set_default_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Affecte les gestionnaires de texte littéral

xml_set_character_data_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_character_data_handler — Affecte les gestionnaires de texte littéral

Description

xml_set_character_data_handler(XMLParser $parser, callable $handler): true

Affecte les gestionnaires de début et de fin de l'analyseur XML parser.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(XMLParser $parser, string $data): void
parser
Le parseur XML appelant le gestionnaire.
data
Character data comme chaîne de caractères.

Le gestionnaire des données est appelé pour chaque pièce du texte d'un document XML. Il peut être appelé plusieurs fois dans chaque fragment (par exemple pour les chaînes non-ASCII).

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

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.


Affecte le gestionnaire XML par défaut

  • « xml_set_character_data_handler
  • xml_set_element_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Affecte le gestionnaire XML par défaut

xml_set_default_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_default_handler — Affecte le gestionnaire XML par défaut

Description

xml_set_default_handler(XMLParser $parser, callable $handler): true

Affecte le gestionnaire par défaut de l'analyseur XML parser.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(XMLParser $parser, string $data): void
parser
Le parseur XML appelant le gestionnaire.
data
data contient les caractères sous la forme d'une chaîne. Cela peut être une déclaration XML, un type de document, une entité ou d'autres données pour lesquelles aucun gestionnaire n'est prévu.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

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.


Affecte les gestionnaires de début et de fin de balise XML

  • « xml_set_default_handler
  • xml_set_end_namespace_decl_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Affecte les gestionnaires de début et de fin de balise XML

xml_set_element_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_element_handler — Affecte les gestionnaires de début et de fin de balise XML

Description

xml_set_element_handler(XMLParser $parser, callable $start_handler, callable $end_handler): true

Affecte les gestionnaires de début et de fin de l'analyseur XML parser.

start_handler est appelé quand un nouvel élément XML est ouvert. end_handler est appelé quand un élément XML est fermé.

Liste de paramètres

parser

Le parseur XML.

start_handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

start_element_handler(XMLParser $parser, string $name, array $attributes): void
parser
Le parseur XML appelant le gestionnaire.
name
Contient le nom de l'élément qui a provoqué l'appel du gestionnaire. Si l'analyseur gère la casse, cet élément sera en majuscules.
attributes
Un tableau associatif avec les attributs de l'élément. Le tableau est vide s'il n'y a pas d'attributs. Les clés de ce tableau seront les noms des attributs, et les valeurs seront les valeurs correspondantes des attributs. Les noms des attributs seront mis en majuscules si l'analyseur gère la casse. Les valeurs des attributs seront inchangées. L'ordre dans lequel attributes est traversé est identique à l'ordre dans lequel les attributs ont été déclaré.

end_handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

end_element_handler(XMLParser $parser, string $name): void
parser
Le parseur XML appelant le gestionnaire.
name
Contient le nom de l'élément qui a provoqué l'appel du gestionnaire. Si l'analyseur gère la casse, cet élément sera en majuscules.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

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.


Configure le gestionnaire XML de données

  • « xml_set_element_handler
  • xml_set_external_entity_ref_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Configure le gestionnaire XML de données

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

xml_set_end_namespace_decl_handler — Configure le gestionnaire XML de données

Description

xml_set_end_namespace_decl_handler(XMLParser $parser, callable $handler): true

Définit un gestionnaire à appeler lorsque l'on quitte le contexte d'un espace de noms. Il peut être appelé, pour chaque déclaration de l'espace de noms, après le gestionnaire de la dernière balise de l'élément dont l'espace de noms a été déclaré.

Attention

Cet évènement n'est pas supporté sous libXML, aussi, un gestionnaire enregistré ne sera pas appelé.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(XMLParser $parser, string|false $prefix)
parser
Le parseur XML appelant le gestionnaire.
prefix
Le préfixe est une chaîne de caractères utilisée pour référencer l'espace de noms dans un objet. false si aucun préfixe existe.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Voir aussi

  • xml_set_start_namespace_decl_handler() - Configure le gestionnaire de caractères

User Contributed Notes

There are no user contributed notes for this page.


Configure le gestionnaire XML de références externes

  • « xml_set_end_namespace_decl_handler
  • xml_set_notation_decl_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Configure le gestionnaire XML de références externes

xml_set_external_entity_ref_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_external_entity_ref_handler — Configure le gestionnaire XML de références externes

Description

xml_set_external_entity_ref_handler(XMLParser $parser, callable $handler): true

Affecte le gestionnaire d'entité externe de l'analyseur XML parser.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(
XMLParser $parser,
string $open_entity_names,
string|false $base,
string $system_id,
string|false $public_id
): bool
parser
Le parseur XML appelant le gestionnaire.
open_entity_names
La liste de noms d'entités, séparés par des espaces. Ces entités sont accessibles à l'analyse par cette entité (y compris le nom de l'entité référencée).
base
La racine pour la résolution de l'identifiant système (system_id) de l'entité externe.
system_id
L'identifiant système tel que spécifié dans la déclaration d'entité
public_id
L'identifiant public tel que spécifié dans la déclaration d'entité, ou une chaîne vide, si aucune déclaration n'a été spécifiée. L'espace dans l'identifiant public sera normalisé comme spécifié dans les spécifications XML.

Le gestionnaire devrait retourner true si l'entité a été géré, sinon false. Quand false est retourné l'analyseur XML arrêtera l'analyse et xml_get_error_code() retournera XML_ERROR_EXTERNAL_ENTITY_HANDLING.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.
7.3.0 | La valeur de retour de handler n'est désormais plus ignoré quand l'extension a été compilé contre libxml. Auparavant, la valeur de retour était ignoré et l'analyse ne s'arrêtait jamais.

User Contributed Notes

There are no user contributed notes for this page.


Configure le gestionnaire XML de notations

  • « xml_set_external_entity_ref_handler
  • xml_set_object »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Configure le gestionnaire XML de notations

xml_set_notation_decl_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_notation_decl_handler — Configure le gestionnaire XML de notations

Description

xml_set_notation_decl_handler(XMLParser $parser, callable $handler): true

Affecte les gestionnaires de début et de fin de l'analyseur XML parser.

Une notation est une partie du DTD du document, qui a le format suivant :

<!NOTATION <parameter>name</parameter>
{ <parameter>systemId</parameter> | <parameter>publicId</parameter>?>
Reportez-vous à la section » des spécifications XML 1.0 pour connaître les notations des entités externes.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(
XMLParser $parser,
string $notation_name,
string|false $base,
string $system_id,
string|false $public_id
): void
parser
Le parseur XML appelant le gestionnaire.
notation_name
Le nom de la notation, comme précisé dans le format de notation ci-dessus.
base
La racine pour la résolution de l'identifiant système (system_id) de l'entité externe.
system_id
Identifiant système pour cette entité externe.
public_id
Identifiant public pour cette entité externe.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

User Contributed Notes

There are no user contributed notes for this page.


Configure un objet comme analyseur XML

  • « xml_set_notation_decl_handler
  • xml_set_processing_instruction_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Configure un objet comme analyseur XML

xml_set_object

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_object — Configure un objet comme analyseur XML

Description

xml_set_object(XMLParser $parser, object $object): true

Rend l'analyseur parser utilisable depuis un objet. Toutes les méthodes de rappel, affectées par xml_set_element_handler(), seront les méthodes de cet objet.

Liste de paramètres

parser

Une référence d'analyseur XML à utiliser dans l'objet.

object

L'objet dans lequel nous devons utiliser l'analyseur XML.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Exemples

Exemple #1 Exemple avec xml_set_object()

<?php
class CustomXMLParser
{
private $parser;

function __construct()
{
$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($tag, $attributes);
}

function cdata($parser, $cdata)
{
var_dump($cdata);
}

function tag_close($parser, $tag)
{
var_dump($tag);
}
}

$xml_parser = new CustomXMLParser();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

L'exemple ci-dessus va afficher :

string(1) "A"
array(1) {
  ["ID"]=>
  string(5) "hallo"
}
string(3) "PHP"
string(1) "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.


Affecte les gestionnaires d'instructions de traitement

  • « xml_set_object
  • xml_set_start_namespace_decl_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Affecte les gestionnaires d'instructions de traitement

xml_set_processing_instruction_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_processing_instruction_handler — Affecte les gestionnaires d'instructions de traitement

Description

xml_set_processing_instruction_handler(XMLParser $parser, callable $handler): true

Affecte le gestionnaire d'instructions exécutables de l'analyseur XML parser.

Une instruction de traitement a la forme suivante :

<?target
data
?>

Attention

Le code PHP code est délimité par l'instruction de traitement <?php. Ainsi, il est possible d'avoir du code PHP dans un document XML. Cependant, la balise de fin de l'instruction de traitement (?>) ne doit pas faire partie des données. Si une balise de fin de l'instruction de traitement existe dans le code PHP imbriqué, le reste du code PHP et la "vrai" balise de fin de l'instruction de traitement, seront traité comme des données de texte.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(XMLParser $parser, string $target, string $data): void
parser
Le parseur XML appelant le gestionnaire.
target
La cible de l'instruction de traitement.
data
Les données de l'instruction de traitement.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

User Contributed Notes

There are no user contributed notes for this page.


Configure le gestionnaire de caractères

  • « xml_set_processing_instruction_handler
  • xml_set_unparsed_entity_decl_handler »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Configure le gestionnaire de caractères

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

xml_set_start_namespace_decl_handler — Configure le gestionnaire de caractères

Description

xml_set_start_namespace_decl_handler(XMLParser $parser, callable $handler): true

Définit le gestionnaire à appeler lorsque l'espace de noms est déclaré. Les déclarations d'espace de noms surviennent dans les balises de départ. Mais le gestionnaire de départ, appelé lors de la déclaration de l'espace de noms, est appelé avant le gestionnaire de la balise de départ pour chaque espace de noms déclaré dans cette balise.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(XMLParser $parser, string|false $prefix, string $uri): void
parser
Le parseur XML appelant le gestionnaire.
prefix
Le préfixe est une chaîne de caractères utilisée pour référencer l'espace de noms d'un objet XML. false si aucun préfixe n'existe.
uri
Identifiant de ressource uniforme (URI) d'un espace de noms.

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

Voir aussi

  • xml_set_end_namespace_decl_handler() - Configure le gestionnaire XML de données

User Contributed Notes

There are no user contributed notes for this page.


Affecte les gestionnaires d'entités non déclarées

  • « xml_set_start_namespace_decl_handler
  • XMLParser »
  • PHP Manual
  • Fonctions d'analyse de fichier XML
  • Affecte les gestionnaires d'entités non déclarées

xml_set_unparsed_entity_decl_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_unparsed_entity_decl_handler — Affecte les gestionnaires d'entités non déclarées

Description

xml_set_unparsed_entity_decl_handler(XMLParser $parser, callable $handler): true

Affecte les gestionnaires d'entités non déclarées de l'analyseur XML parser.

Le gestionnaire parser sera appelé si l'analyseur XML rencontre une déclaration d'entité externe avec une déclaration de NDATA, comme suit :

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

Reportez-vous à la section » des spécifications XML 1.0 pour connaître les notations des entités externes.

Liste de paramètres

parser

Le parseur XML.

handler

Si null ou une chaîne vide est passée, le gestionnaire est réinitialisé à son état par défaut.

Si handler est un callable, l'appelable est défini comme le gestionnaire.

Si handler est une string, il peut s'agir du nom d'une méthode d'un objet défini avec xml_set_object().

La signature du gestionnaire doit être :

handler(
XMLParser $parser,
string $entity_name,
string|false $base,
string $system_id,
string|false $public_id,
string|false $notation_name
): void
parser
Le parseur XML appelant le gestionnaire.
entity_name
Le nom de l'entité qui va être définie.
base
La racine pour la résolution de l'identifiant système (system_id) de l'entité externe.
system_id
Identifiant système pour cette entité externe.
public_id
Identifiant public pour cette entité externe.
notation_name
Nom de la notation de cette entité. (Voir xml_set_notation_decl_handler()).

Valeurs de retour

Retourne toujours true.

Historique

Version | Description
8.0.0 | parser attend une instance de XMLParser désormais; auparavent, une resource xml était attendue.

User Contributed Notes

There are no user contributed notes for this page.


La classe XMLParser

(PHP 8)

Introduction

Une classe totalement opaque qui remplace les ressources xml à partir de PHP 8.0.0.

Synopsis de la classe

final class XMLParser {
}

User Contributed Notes

There are no user contributed notes for this page.


XMLReader

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • XMLReader — La classe XMLReader
    • XMLReader::close — Ferme l'entrée XMLReader
    • XMLReader::expand — Retourne une copie du nœud courant comme un nœud d'objet DOM
    • XMLReader::getAttribute — Récupère la valeur d'un attribut par nom
    • XMLReader::getAttributeNo — Récupère la valeur d'un attribut par index
    • XMLReader::getAttributeNs — Récupère la valeur d'un attribut par nom local et URI
    • XMLReader::getParserProperty — Indique si la propriété spécifiée a été fixée
    • XMLReader::isValid — Indique si le document analysé est valide
    • XMLReader::lookupNamespace — Consulte l'espace de nom pour un préfixe
    • XMLReader::moveToAttribute — Déplace un curseur à un attribut nommé
    • XMLReader::moveToAttributeNo — Déplace le curseur à un attribut par index
    • XMLReader::moveToAttributeNs — Déplace le curseur à un attribut d'espace de nom
    • XMLReader::moveToElement — Positionne le curseur sur l'élément parent de l'attribut courant
    • XMLReader::moveToFirstAttribute — Positionne le curseur sur le premier attribut
    • XMLReader::moveToNextAttribute — Positionne le curseur sur le prochain attribut
    • XMLReader::next — Déplace le curseur au prochain nœud en sautant tous les sous arbres
    • XMLReader::open — Fixe le URI contenant le XML à analyser
    • XMLReader::read — Déplace le curseur sur le prochain nœud du document
    • XMLReader::readInnerXml — Lit le code XML du nœud courant
    • XMLReader::readOuterXml — Lit le code XML du nœud courant, y compris lui-même
    • XMLReader::readString — Lit le contenu du nœud courant sous forme de chaîne
    • XMLReader::setParserProperty — Fixe des options pour l'analyseur
    • XMLReader::setRelaxNGSchema — Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG
    • XMLReader::setRelaxNGSchemaSource — Spécifie le schéma RelaxNG
    • XMLReader::setSchema — Valide le document avec XSD
    • XMLReader::XML — Fixe les données contenant le XML à analyser

User Contributed Notes

There are no user contributed notes for this page.


Introduction

L'extension XMLReader un analyseur XML Pull. Le lecteur fonctionne comme un curseur qui avance sur le flux du document et s'arrête à chaque nœud sur le chemin.

Encodage

Il est important de noter que, en interne, libxml utilise l'encodage UTF-8 et donc, l'encodage du contenu récupéré devra toujours être encodé UTF-8.

User Contributed Notes

There are no user contributed notes for this page.


Installation

L'extension XMLReader est inclut avec la source de PHP. Cette extension est activée par défaut. Elle peut être désactivée en utilisant l'option de configuration : --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.


La classe XMLReader

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Introduction

L'extension XMLReader est un analyseur XML. L'analyseur fonctionne comme un curseur qui parcourt le document et s'arrête sur chaque nœud.

Synopsis de la classe

class XMLReader {
/* Constantes */
public const int NONE;
public const int ELEMENT;
public const int ATTRIBUTE;
public const int TEXT;
public const int CDATA;
public const int ENTITY_REF;
public const int ENTITY;
public const int PI;
public const int COMMENT;
public const int DOC;
public const int DOC_TYPE;
public const int DOC_FRAGMENT;
public const int NOTATION;
public const int WHITESPACE;
public const int SIGNIFICANT_WHITESPACE;
public const int END_ELEMENT;
public const int END_ENTITY;
public const int XML_DECLARATION;
public const int LOADDTD;
public const int DEFAULTATTRS;
public const int VALIDATE;
public const int SUBST_ENTITIES;
/* Propriétés */
public int $attributeCount;
public string $baseURI;
public int $depth;
public bool $hasAttributes;
public bool $hasValue;
public bool $isDefault;
public bool $isEmptyElement;
public string $localName;
public string $name;
public string $namespaceURI;
public int $nodeType;
public string $prefix;
public string $value;
public string $xmlLang;
/* Méthodes */
public close(): true
public expand(?DOMNode $baseNode = null): DOMNode|false
public getAttribute(string $name): ?string
public getAttributeNo(int $index): ?string
public getAttributeNs(string $name, string $namespace): ?string
public getParserProperty(int $property): bool
public isValid(): bool
public lookupNamespace(string $prefix): ?string
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 $name = null): bool
public static open(string $uri, ?string $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 $filename): bool
public setRelaxNGSchemaSource(?string $source): bool
public setSchema(?string $filename): bool
public static XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader
}

Propriétés

attributeCount

Le nombre d'attributs dans le nœud

baseURI

La base URI du nœud

depth

Profondeur du nœud dans l'arbre démarrant à 0

hasAttributes

Indique si le nœud a des attributs

hasValue

Indique si le nœud a une valeur de texte

isDefault

Indique si l'attribut est par défaut à partir du DTD

isEmptyElement

Indique si le nœud est un élément vide

localName

Le nom local du nœud

name

Le nœud qualifié du nœud

namespaceURI

L'URI de l'espace de nom associé avec le nœud

nodeType

Le type de nœud pour le nœud

prefix

Le préfixe de l'espace de nom associé avec le nœud

value

La valeur du texte du nœud

xmlLang

La portée xml:lang dans lequel le nœud réside

Constantes pré-définies

Types de nœud XMLReader

XMLReader::NONE

Pas de type de nœud

XMLReader::ELEMENT

Élément de départ

XMLReader::ATTRIBUTE

Noeud Attribut

XMLReader::TEXT

Noeud texte

XMLReader::CDATA

Noeud CDATA

XMLReader::ENTITY_REF

Noeud de référence d'entité

XMLReader::ENTITY

Noeud de déclaration d'entité

XMLReader::PI

Noeud d'instruction de processus

XMLReader::COMMENT

Noeud de commentaire

XMLReader::DOC

Noeud document

XMLReader::DOC_TYPE

Noeud de type de document

XMLReader::DOC_FRAGMENT

Noeud de fragment de document

XMLReader::NOTATION

Noeud de notation

XMLReader::WHITESPACE

Noeud "espace"

XMLReader::SIGNIFICANT_WHITESPACE

Noeud "espace" significatif

XMLReader::END_ELEMENT

Élément de fin

XMLReader::END_ENTITY

Entité de fin

XMLReader::XML_DECLARATION

Noeud de déclaration XML

Options de l'analyseur XMLReader

XMLReader::LOADDTD

Charge une DTD mais ne la valide pas

XMLReader::DEFAULTATTRS

Charge une DTD et les attributs par défaut mais ne la valide pas

XMLReader::VALIDATE

Charge une DTD et valide le document au moment de l'analyse

XMLReader::SUBST_ENTITIES

Substitue les entités et étend les références

Sommaire

  • XMLReader::close — Ferme l'entrée XMLReader
  • XMLReader::expand — Retourne une copie du nœud courant comme un nœud d'objet DOM
  • XMLReader::getAttribute — Récupère la valeur d'un attribut par nom
  • XMLReader::getAttributeNo — Récupère la valeur d'un attribut par index
  • XMLReader::getAttributeNs — Récupère la valeur d'un attribut par nom local et URI
  • XMLReader::getParserProperty — Indique si la propriété spécifiée a été fixée
  • XMLReader::isValid — Indique si le document analysé est valide
  • XMLReader::lookupNamespace — Consulte l'espace de nom pour un préfixe
  • XMLReader::moveToAttribute — Déplace un curseur à un attribut nommé
  • XMLReader::moveToAttributeNo — Déplace le curseur à un attribut par index
  • XMLReader::moveToAttributeNs — Déplace le curseur à un attribut d'espace de nom
  • XMLReader::moveToElement — Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToFirstAttribute — Positionne le curseur sur le premier attribut
  • XMLReader::moveToNextAttribute — Positionne le curseur sur le prochain attribut
  • XMLReader::next — Déplace le curseur au prochain nœud en sautant tous les sous arbres
  • XMLReader::open — Fixe le URI contenant le XML à analyser
  • XMLReader::read — Déplace le curseur sur le prochain nœud du document
  • XMLReader::readInnerXml — Lit le code XML du nœud courant
  • XMLReader::readOuterXml — Lit le code XML du nœud courant, y compris lui-même
  • XMLReader::readString — Lit le contenu du nœud courant sous forme de chaîne
  • XMLReader::setParserProperty — Fixe des options pour l'analyseur
  • XMLReader::setRelaxNGSchema — Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG
  • XMLReader::setRelaxNGSchemaSource — Spécifie le schéma RelaxNG
  • XMLReader::setSchema — Valide le document avec XSD
  • XMLReader::XML — Fixe les données contenant le XML à analyser

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>


Ferme l'entrée XMLReader

  • « XMLReader
  • XMLReader::expand »
  • PHP Manual
  • XMLReader
  • Ferme l'entrée XMLReader

XMLReader::close

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::close — Ferme l'entrée XMLReader

Description

public XMLReader::close(): true

Ferme l'entrée de l'objet XMLReader qui est en train d'être analysé.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne toujours true.

Voir aussi

  • XMLReader::open() - Fixe le URI contenant le XML à analyser
  • XMLReader::xml() - Fixe les données contenant le XML à analyser

User Contributed Notes

There are no user contributed notes for this page.


Retourne une copie du nœud courant comme un nœud d'objet DOM

  • « XMLReader::close
  • XMLReader::getAttribute »
  • PHP Manual
  • XMLReader
  • Retourne une copie du nœud courant comme un nœud d'objet DOM

XMLReader::expand

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::expand — Retourne une copie du nœud courant comme un nœud d'objet DOM

Description

public XMLReader::expand(?DOMNode $baseNode = null): DOMNode|false

Cette méthode copie le nœud courant et retourne l'objet approprié DOM.

Liste de paramètres

baseNode

Un DOMNode définissant la cible DOMDocument pour l'objet DOM créé.

Valeurs de retour

L'objet DOMNode résultant ou false en cas d'erreur.

User Contributed Notes

Sbastien 02-Jan-2022 01:29
XMLReader::expand() expands the current subtree to DOM. SimpleXML is good too. To avoid a warning like "Imported Node must have associated Document" when using simplexml_import_dom(), we can do :

<?php

// Huge XML compressed file
$xml = XMLReader::open('compress.zlib:///path/to/my-data.xml.gz');

// Targeting a tiny subtree
while ($xml->name !== 'my-targeted-element') {
    $xml->read();
}

// The trick is here...
// Subtree is expanded in an empty document...
$dom = $xml->expand(new DOMDocument());

// ... which can be imported by SimpleXML
$sx = simplexml_import_dom($dom);

// We can now process our tiny subtree with SimpleXML $sx


Récupère la valeur d'un attribut par nom

  • « XMLReader::expand
  • XMLReader::getAttributeNo »
  • PHP Manual
  • XMLReader
  • Récupère la valeur d'un attribut par nom

XMLReader::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttribute — Récupère la valeur d'un attribut par nom

Description

public XMLReader::getAttribute(string $name): ?string

Retourne la valeur d'un attribut par nom ou null si l'attribut n'existe pas ou n'est pas positionné sur le nœud.

Liste de paramètres

name

Le nom de l'attribut.

Valeurs de retour

La valeur de l'attribut ou null si l'attribut avec le name donné n'existe pas ou n'est pas positionné sur le nœud d'un élément.

Historique

Version | Description
8.0.0 | Cette fonction ne peut plus retourner false.

Voir aussi

  • XMLReader::getAttributeNo() - Récupère la valeur d'un attribut par index
  • XMLReader::getAttributeNs() - Récupère la valeur d'un attribut par nom local et URI

User Contributed Notes

sven at e7o dot de 08-Nov-2023 02:44
To get all attributes and their names, use something like this:

<?php
function getAttributes($reader)
{
    $attributes = [];
    for ($i = 0; $i < $reader->attributeCount; $i++) {
        $reader->moveToAttributeNo($i);
        $attributes[$reader->name] = $reader->value;
    }
    return $attributes;
}
?>
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.


Récupère la valeur d'un attribut par index

  • « XMLReader::getAttribute
  • XMLReader::getAttributeNs »
  • PHP Manual
  • XMLReader
  • Récupère la valeur d'un attribut par index

XMLReader::getAttributeNo

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttributeNo — Récupère la valeur d'un attribut par index

Description

public XMLReader::getAttributeNo(int $index): ?string

Retourne la valeur d'un attribut basé sur sa position ou d'une chaîne de caractères vide si l'attribut n'existe pas ou n'est pas positionné sur le nœud.

Liste de paramètres

index

La position de l'attribut.

Valeurs de retour

La valeur de l'attribut, ou null si aucun attribut n'existe à index ou n'est pas positionné sur l'élément.

Voir aussi

  • XMLReader::getAttribute() - Récupère la valeur d'un attribut par nom
  • XMLReader::getAttributeNs() - Récupère la valeur d'un attribut par nom local et URI

User Contributed Notes

There are no user contributed notes for this page.


Récupère la valeur d'un attribut par nom local et URI

  • « XMLReader::getAttributeNo
  • XMLReader::getParserProperty »
  • PHP Manual
  • XMLReader
  • Récupère la valeur d'un attribut par nom local et URI

XMLReader::getAttributeNs

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttributeNs — Récupère la valeur d'un attribut par nom local et URI

Description

public XMLReader::getAttributeNs(string $name, string $namespace): ?string

Retourne la valeur d'un attribut par nom et espace de nom URI ou une chaîne de caractères vide si l'attribut n'existe pas ou n'est pas positionné sur le nœud.

Liste de paramètres

name

Le nom local.

namespace

L'espace de nom URI.

Valeurs de retour

La valeur de l'attribut, ou null si aucun attribut avec le name et namespace donnés n'est trouvé ou positionné sur l'élément.

Historique

Version | Description
8.0.0 | Cette fonction ne peut plus retourner false.

Voir aussi

  • XMLReader::getAttribute() - Récupère la valeur d'un attribut par nom
  • XMLReader::getAttributeNo() - Récupère la valeur d'un attribut par index

User Contributed Notes

There are no user contributed notes for this page.


Indique si la propriété spécifiée a été fixée

  • « XMLReader::getAttributeNs
  • XMLReader::isValid »
  • PHP Manual
  • XMLReader
  • Indique si la propriété spécifiée a été fixée

XMLReader::getParserProperty

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getParserProperty — Indique si la propriété spécifiée a été fixée

Description

public XMLReader::getParserProperty(int $property): bool

Indique si la propriété spécifiée a été fixée.

Liste de paramètres

property

Une des constantes d'analyseur.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::setParserProperty() - Fixe des options pour l'analyseur

User Contributed Notes

There are no user contributed notes for this page.


Indique si le document analysé est valide

  • « XMLReader::getParserProperty
  • XMLReader::lookupNamespace »
  • PHP Manual
  • XMLReader
  • Indique si le document analysé est valide

XMLReader::isValid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::isValid — Indique si le document analysé est valide

Description

public XMLReader::isValid(): bool

Retourne un booléen indiquant si le document qui est en train d'être analysé est valide.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Validation XML

<?php
$xml = XMLReader::open('test.xml');

// L'option de validation de l'analyseur doit être
// active pour que cette méthode fonctionne correctement
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Notes

Note: Cette méthode vérifie le nœud courant, et non le document complet.

Voir aussi

  • XMLReader::setParserProperty() - Fixe des options pour l'analyseur
  • XMLReader::setRelaxNGSchema() - Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG
  • XMLReader::setRelaxNGSchemaSource() - Spécifie le schéma RelaxNG
  • XMLReader::setSchema() - Valide le document avec XSD

User Contributed Notes

me at lubu dot ch 31-May-2022 09:54
Be aware that $xml->isValid() will return validity only for currently active node, so you have to loop trough the nodes.

Here is a example how to validate a entire XML file against a XSD schema:

<?php

$xmlReader = new \XMLReader();
$xmlReader->open('./example.xml');
$xmlReader->setParserProperty(\XMLReader::VALIDATE, true);
$xmlReader->setSchema('./schema.xsd');

\libxml_use_internal_errors(true);

$msgs = [];

while ($xmlReader->read()) {
    if (!$xmlReader->isValid()) {
        $err = \libxml_get_last_error();
        if ($err && $err instanceof \libXMLError) {
            $msgs[] = \trim($err->message) . ' on line ' . $err->line;
        }
    }
}

if ($msgs) {
    throw new \Exception("XML schema validation errors:\n - " . implode("\n - ", array_unique($msgs)));
}
?>
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).


Consulte l'espace de nom pour un préfixe

  • « XMLReader::isValid
  • XMLReader::moveToAttribute »
  • PHP Manual
  • XMLReader
  • Consulte l'espace de nom pour un préfixe

XMLReader::lookupNamespace

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::lookupNamespace — Consulte l'espace de nom pour un préfixe

Description

public XMLReader::lookupNamespace(string $prefix): ?string

Consulte dans la portée de l'espace de nom pour un préfixe donné.

Liste de paramètres

prefix

Chaînes de caractères contenant le préfixe.

Valeurs de retour

La valeur de l'espace de nom, ou null si aucun espace de nom existe.

Historique

Version | Description
8.0.0 | Cette fonction ne peut plus retourner false.

User Contributed Notes

There are no user contributed notes for this page.


Déplace un curseur à un attribut nommé

  • « XMLReader::lookupNamespace
  • XMLReader::moveToAttributeNo »
  • PHP Manual
  • XMLReader
  • Déplace un curseur à un attribut nommé

XMLReader::moveToAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttribute — Déplace un curseur à un attribut nommé

Description

public XMLReader::moveToAttribute(string $name): bool

Positionne le curseur sur l'attribut nommé.

Liste de paramètres

name

Le nom de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::moveToElement() - Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToAttributeNo() - Déplace le curseur à un attribut par index
  • XMLReader::moveToAttributeNs() - Déplace le curseur à un attribut d'espace de nom
  • XMLReader::moveToFirstAttribute() - Positionne le curseur sur le premier attribut

User Contributed Notes

There are no user contributed notes for this page.


Déplace le curseur à un attribut par index

  • « XMLReader::moveToAttribute
  • XMLReader::moveToAttributeNs »
  • PHP Manual
  • XMLReader
  • Déplace le curseur à un attribut par index

XMLReader::moveToAttributeNo

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttributeNo — Déplace le curseur à un attribut par index

Description

public XMLReader::moveToAttributeNo(int $index): bool

Positionne le curseur sur l'attribut basé sur sa position.

Liste de paramètres

index

La position de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::moveToElement() - Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToAttribute() - Déplace un curseur à un attribut nommé
  • XMLReader::moveToAttributeNs() - Déplace le curseur à un attribut d'espace de nom
  • XMLReader::moveToFirstAttribute() - Positionne le curseur sur le premier attribut

User Contributed Notes

There are no user contributed notes for this page.


Déplace le curseur à un attribut d'espace de nom

  • « XMLReader::moveToAttributeNo
  • XMLReader::moveToElement »
  • PHP Manual
  • XMLReader
  • Déplace le curseur à un attribut d'espace de nom

XMLReader::moveToAttributeNs

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttributeNs — Déplace le curseur à un attribut d'espace de nom

Description

public XMLReader::moveToAttributeNs(string $name, string $namespace): bool

Positionne le curseur sur le nom de l'attribut dans l'espace de nom spécifié.

Liste de paramètres

name

Le nom local.

namespace

L'espace de nom URI.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::moveToElement() - Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToAttribute() - Déplace un curseur à un attribut nommé
  • XMLReader::moveToAttributeNo() - Déplace le curseur à un attribut par index
  • XMLReader::moveToFirstAttribute() - Positionne le curseur sur le premier attribut

User Contributed Notes

There are no user contributed notes for this page.


Positionne le curseur sur l'élément parent de l'attribut courant

  • « XMLReader::moveToAttributeNs
  • XMLReader::moveToFirstAttribute »
  • PHP Manual
  • XMLReader
  • Positionne le curseur sur l'élément parent de l'attribut courant

XMLReader::moveToElement

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToElement — Positionne le curseur sur l'élément parent de l'attribut courant

Description

public XMLReader::moveToElement(): bool

Déplace le curseur de l'élément parent de l'attribut courant.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne true en cas de succès et false en cas d'échec ou non positionné sur un attribut lorsque cette méthode est appelée.

Voir aussi

  • XMLReader::moveToAttribute() - Déplace un curseur à un attribut nommé
  • XMLReader::moveToAttributeNo() - Déplace le curseur à un attribut par index
  • XMLReader::moveToAttributeNs() - Déplace le curseur à un attribut d'espace de nom
  • XMLReader::moveToFirstAttribute() - Positionne le curseur sur le premier attribut

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.


Positionne le curseur sur le premier attribut

  • « XMLReader::moveToElement
  • XMLReader::moveToNextAttribute »
  • PHP Manual
  • XMLReader
  • Positionne le curseur sur le premier attribut

XMLReader::moveToFirstAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToFirstAttribute — Positionne le curseur sur le premier attribut

Description

public XMLReader::moveToFirstAttribute(): bool

Déplace le curseur sur le premier attribut.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::moveToElement() - Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToAttribute() - Déplace un curseur à un attribut nommé
  • XMLReader::moveToAttributeNo() - Déplace le curseur à un attribut par index
  • XMLReader::moveToAttributeNs() - Déplace le curseur à un attribut d'espace de nom
  • XMLReader::moveToNextAttribute() - Positionne le curseur sur le prochain attribut

User Contributed Notes

There are no user contributed notes for this page.


Positionne le curseur sur le prochain attribut

  • « XMLReader::moveToFirstAttribute
  • XMLReader::next »
  • PHP Manual
  • XMLReader
  • Positionne le curseur sur le prochain attribut

XMLReader::moveToNextAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToNextAttribute — Positionne le curseur sur le prochain attribut

Description

public XMLReader::moveToNextAttribute(): bool

Déplace le curseur sur le prochain attribut si positionné sur un attribut ou déplace sur le premier attribut si positionné sur un élément.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::moveToElement() - Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToAttribute() - Déplace un curseur à un attribut nommé
  • XMLReader::moveToAttributeNo() - Déplace le curseur à un attribut par index
  • XMLReader::moveToAttributeNs() - Déplace le curseur à un attribut d'espace de nom
  • XMLReader::moveToFirstAttribute() - Positionne le curseur sur le premier attribut

User Contributed Notes

There are no user contributed notes for this page.


Déplace le curseur au prochain nœud en sautant tous les sous arbres

  • « XMLReader::moveToNextAttribute
  • XMLReader::open »
  • PHP Manual
  • XMLReader
  • Déplace le curseur au prochain nœud en sautant tous les sous arbres

XMLReader::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::next — Déplace le curseur au prochain nœud en sautant tous les sous arbres

Description

public XMLReader::next(?string $name = null): bool

Positionne le curseur sur le prochain nœud en sautant tous les sous arbres. Si aucun nœud existe, le curseur est déplacé à la fin du document.

Liste de paramètres

name

Le nom du prochaine nœud à se déplacer.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | name est désormais nullable.

Voir aussi

  • XMLReader::moveToNextAttribute() - Positionne le curseur sur le prochain attribut
  • XMLReader::moveToElement() - Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToAttribute() - Déplace un curseur à un attribut nommé

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();}


Fixe le URI contenant le XML à analyser

  • « XMLReader::next
  • XMLReader::read »
  • PHP Manual
  • XMLReader
  • Fixe le URI contenant le XML à analyser

XMLReader::open

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::open — Fixe le URI contenant le XML à analyser

Description

public static XMLReader::open(string $uri, ?string $encoding = null, int $flags = 0): bool|XMLReader

Fixe le URI contenant le document XML à être analysé.

Liste de paramètres

uri

URI pointant vers le document.

encoding

L'encodage du document, ou null.

flags

Un masque de constante LIBXML_*.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient. Si appelée statiquement, retourne un objet XMLReader ou false si une erreur survient.

Erreurs / Exceptions

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Historique

Version | Description
8.0.0 | XMLReader::open() est désormais déclaré comme méthode statique, mais peut toujours être appelé sur une instance de XMLReader.

Voir aussi

  • XMLReader::xml() - Fixe les données contenant le XML à analyser
  • XMLReader::close() - Ferme l'entrée XMLReader

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.


Déplace le curseur sur le prochain nœud du document

  • « XMLReader::open
  • XMLReader::readInnerXml »
  • PHP Manual
  • XMLReader
  • Déplace le curseur sur le prochain nœud du document

XMLReader::read

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::read — Déplace le curseur sur le prochain nœud du document

Description

public XMLReader::read(): bool

Déplace le curseur au prochain nœud texte du document.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::moveToElement() - Positionne le curseur sur l'élément parent de l'attribut courant
  • XMLReader::moveToAttribute() - Déplace un curseur à un attribut nommé
  • XMLReader::next() - Déplace le curseur au prochain nœud en sautant tous les sous arbres

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.


Lit le code XML du nœud courant

  • « XMLReader::read
  • XMLReader::readOuterXml »
  • PHP Manual
  • XMLReader
  • Lit le code XML du nœud courant

XMLReader::readInnerXml

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readInnerXml — Lit le code XML du nœud courant

Description

public XMLReader::readInnerXml(): string

Lit le contenu du nœud courant, incluant les enfants et le balisage.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le contenu du nœud courant sous forme de chaîne. Retourne une chaîne vide en cas d'échec.

Notes

Attention

Cette fonction n'est disponible que si PHP est compilé à l'aide de la librarie libxml 20620 ou ultérieure.

Voir aussi

  • XMLReader::readString() - Lit le contenu du nœud courant sous forme de chaîne
  • XMLReader::readOuterXml() - Lit le code XML du nœud courant, y compris lui-même
  • XMLReader::expand() - Retourne une copie du nœud courant comme un nœud d'objet DOM

User Contributed Notes

There are no user contributed notes for this page.


Lit le code XML du nœud courant, y compris lui-même

  • « XMLReader::readInnerXml
  • XMLReader::readString »
  • PHP Manual
  • XMLReader
  • Lit le code XML du nœud courant, y compris lui-même

XMLReader::readOuterXml

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readOuterXml — Lit le code XML du nœud courant, y compris lui-même

Description

public XMLReader::readOuterXml(): string

Lit le code XML du nœud courant, y compris lui-même.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Lit le code XML du nœud courant, y compris lui-même, sous forme de chaîne. Retourne une chaîne vide en cas d'erreur.

Notes

Attention

Cette fonction n'est disponible que si PHP est compilé à l'aide de la librarie libxml 20620 ou ultérieure.

Voir aussi

  • XMLReader::readString() - Lit le contenu du nœud courant sous forme de chaîne
  • XMLReader::readInnerXml() - Lit le code XML du nœud courant
  • XMLReader::expand() - Retourne une copie du nœud courant comme un nœud d'objet DOM

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.


Lit le contenu du nœud courant sous forme de chaîne

  • « XMLReader::readOuterXml
  • XMLReader::setParserProperty »
  • PHP Manual
  • XMLReader
  • Lit le contenu du nœud courant sous forme de chaîne

XMLReader::readString

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readString — Lit le contenu du nœud courant sous forme de chaîne

Description

public XMLReader::readString(): string

Lit le contenu du nœud courant sous forme de chaîne.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le contenu du nœud courant sous forme de chaîne ou une chaîne vide si une erreur survient.

Notes

Attention

Cette fonction n'est disponible que si PHP est compilé à l'aide de la librarie libxml 20620 ou ultérieure.

Voir aussi

  • XMLReader::readOuterXml() - Lit le code XML du nœud courant, y compris lui-même
  • XMLReader::readInnerXml() - Lit le code XML du nœud courant
  • XMLReader::expand() - Retourne une copie du nœud courant comme un nœud d'objet DOM

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>


Fixe des options pour l'analyseur

  • « XMLReader::readString
  • XMLReader::setRelaxNGSchema »
  • PHP Manual
  • XMLReader
  • Fixe des options pour l'analyseur

XMLReader::setParserProperty

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setParserProperty — Fixe des options pour l'analyseur

Description

public XMLReader::setParserProperty(int $property, bool $value): bool

Fixe des options pour l'analyseur. Les options doivent être fixées après l'appel de XMLReader::open() ou XMLReader::xml() et avant le premier appel de XMLReader::read().

Liste de paramètres

property

Une des constantes d'analyseur.

value

Si fixée à true, l'option sera activée sinon elle sera désactivée.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

User Contributed Notes

There are no user contributed notes for this page.


Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG

  • « XMLReader::setParserProperty
  • XMLReader::setRelaxNGSchemaSource »
  • PHP Manual
  • XMLReader
  • Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG

XMLReader::setRelaxNGSchema

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setRelaxNGSchema — Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG

Description

public XMLReader::setRelaxNGSchema(?string $filename): bool

Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG à utiliser pour validation.

Liste de paramètres

filename

Nom du fichier ou URI pointant vers le Schéma RelaxNG.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::setRelaxNGSchemaSource() - Spécifie le schéma RelaxNG
  • XMLReader::setSchema() - Valide le document avec XSD
  • XMLReader::isValid() - Indique si le document analysé est valide

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


Spécifie le schéma RelaxNG

  • « XMLReader::setRelaxNGSchema
  • XMLReader::setSchema »
  • PHP Manual
  • XMLReader
  • Spécifie le schéma RelaxNG

XMLReader::setRelaxNGSchemaSource

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setRelaxNGSchemaSource — Spécifie le schéma RelaxNG

Description

public XMLReader::setRelaxNGSchemaSource(?string $source): bool

Spécifie le schéma RelaxNG à utiliser pour validation.

Liste de paramètres

source

Chaîne de caractères contenant le schéma RelaxNG.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XMLReader::setRelaxNGSchema() - Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG
  • XMLReader::setSchema() - Valide le document avec XSD
  • XMLReader::isValid() - Indique si le document analysé est valide

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();
?>


Valide le document avec XSD

  • « XMLReader::setRelaxNGSchemaSource
  • XMLReader::XML »
  • PHP Manual
  • XMLReader
  • Valide le document avec XSD

XMLReader::setSchema

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::setSchema — Valide le document avec XSD

Description

public XMLReader::setSchema(?string $filename): bool

Utilise le schéma XSD W3C pour valider le contenu, tel qu'il est traité. L'activation n'est possible qu'avant le premier Read().

Liste de paramètres

filename

Le nom du fichier de schéma XSD.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Erreurs / Exceptions

Émet une alerte E_WARNING si libxml a été compilé sans le support des schémas, si le schéma contient des erreurs, ou si XMLReader::read() a déjà été appelé.

Notes

Attention

Cette fonction n'est disponible que si PHP est compilé à l'aide de la librarie libxml 20620 ou ultérieure.

Voir aussi

  • XMLReader::setRelaxNGSchema() - Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG
  • XMLReader::setRelaxNGSchemaSource() - Spécifie le schéma RelaxNG
  • XMLReader::isValid() - Indique si le document analysé est valide

User Contributed Notes

There are no user contributed notes for this page.


Fixe les données contenant le XML à analyser

  • « XMLReader::setSchema
  • XMLWriter »
  • PHP Manual
  • XMLReader
  • Fixe les données contenant le XML à analyser

XMLReader::XML

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::XML — Fixe les données contenant le XML à analyser

Description

public static XMLReader::XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader

Fixe les données contenant le XML à analyser.

Liste de paramètres

source

Chaîne de caractères contenant le XML à analyser.

encoding

L'encodage du document, ou null.

flags

Un masque de constantes LIBXML_*.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient. Si appelée statiquement, retourne un objet XMLReader ou false si une erreur survient.

Erreurs / Exceptions

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Historique

Version | Description
8.0.0 | XMLReader::xml() est désormais déclaré comme méthode statique, mais peut toujours être appelé sur une instance de XMLReader.

Voir aussi

  • XMLReader::open() - Fixe le URI contenant le XML à analyser
  • XMLReader::close() - Ferme l'entrée XMLReader

User Contributed Notes

There are no user contributed notes for this page.


XMLWriter

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Exemples
    • Créer un document XML basique
    • Travailler avec les espaces de noms XML
    • Travailler avec l'API OO
  • XMLWriter — La classe XMLWriter
    • XMLWriter::endAttribute — Termine un attribut
    • XMLWriter::endCdata — Termine un bloc CDATA
    • XMLWriter::endComment — Termine un commentaire
    • XMLWriter::endDocument — Termine le document courant
    • XMLWriter::endDtd — Termine la DTD courante
    • XMLWriter::endDtdAttlist — Termine la liste des attributs de la DTD courante
    • XMLWriter::endDtdElement — Termine l'élément de la DTD courante
    • XMLWriter::endDtdEntity — Termine l'entité de la DTD courante
    • XMLWriter::endElement — Termine l'élément courant
    • XMLWriter::endPi — Termine le PI courant
    • XMLWriter::flush — Affiche le buffer courant
    • XMLWriter::fullEndElement — Termine l'élément courant
    • XMLWriter::openMemory — Crée un nouveau xmlwriter en utilisant la mémoire pour l'affichage des chaînes
    • XMLWriter::openUri — Crée un nouveau xmlwriter, en utilisant l'URI source pour l'affichage
    • XMLWriter::outputMemory — Retourne le buffer courant
    • XMLWriter::setIndent — Active ou non l'indentation
    • XMLWriter::setIndentString — Définit la chaîne à utiliser pour l'indentation
    • XMLWriter::startAttribute — Crée un attribut
    • XMLWriter::startAttributeNs — Crée un attribut pour l'espace de noms
    • XMLWriter::startCdata — Crée une balise CDATA
    • XMLWriter::startComment — Crée un commentaire
    • XMLWriter::startDocument — Crée un document
    • XMLWriter::startDtd — Crée une DTD
    • XMLWriter::startDtdAttlist — Crée une liste d'attributs pour la DTD
    • XMLWriter::startDtdElement — Crée un élément DTD
    • XMLWriter::startDtdEntity — Crée une entité DTD
    • XMLWriter::startElement — Crée un élément
    • XMLWriter::startElementNs — Crée un élément d'un espace de noms
    • XMLWriter::startPi — Crée une balise PI
    • XMLWriter::text — Écrit du texte
    • XMLWriter::writeAttribute — Écrit un attribut
    • XMLWriter::writeAttributeNs — Écrit un attribut d'un espace de noms
    • XMLWriter::writeCdata — Écrit un bloc CDATA
    • XMLWriter::writeComment — Écrit un commentaire
    • XMLWriter::writeDtd — Écrit une DTD
    • XMLWriter::writeDtdAttlist — Écrit une liste d'attributs DTD
    • XMLWriter::writeDtdElement — Écrit un élément DTD
    • XMLWriter::writeDtdEntity — Écrit une entité DTD
    • XMLWriter::writeElement — Écrit un élément
    • XMLWriter::writeElementNs — Écrit un élément d'un espace de noms
    • XMLWriter::writePi — Écrit la balise PI
    • XMLWriter::writeRaw — Écrit un texte XML brut

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!


Introduction

Voici l'extension XMLWriter. Elle utilise l'API libxml xmlWriter.

Cette extension permet la génération de flux et de fichiers au format XML.

Cette extension peut être utilisée dans un style orienté objet ou un style procédural. Chaque méthode documentée décrit l'appel procédural équivalent.

User Contributed Notes

There are no user contributed notes for this page.


Installation

L'extension XMLWriter est inclut avec la source de PHP. Cette extension est activée par défaut. Elle peut être désactivée en utilisant l'option de configuration : --disable-xmlwriter

User Contributed Notes

There are no user contributed notes for this page.


Types de ressources

Antérieur à PHP 8.0.0, il y avait une ressource, utilisée par la version procédurale de l'extension XMLWriter : celle retournée par la fonction xmlwriter_open_memory() ou la fonction xmlwriter_open_uri().

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Sommaire

  • Créer un document XML basique
  • Travailler avec les espaces de noms XML
  • Travailler avec l'API OO

User Contributed Notes

There are no user contributed notes for this page.


Créer un document XML basique

Cet exemple montre comment utiliser XMLWriter pour créer un document XML en mémoire.

Exemple #1 Créer un document XML basique

<?php

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');

xmlwriter_start_document($xw, '1.0', 'UTF-8');

// Un premier élément
xmlwriter_start_element($xw, 'tag1');

// Attribut 'att1' pour élément 'tag1'
xmlwriter_start_attribute($xw, 'att1');
xmlwriter_text($xw, 'valueofatt1');
xmlwriter_end_attribute($xw);

xmlwriter_write_comment($xw, 'ceci est un commentaire.');

// Début d'un élément enfant
xmlwriter_start_element($xw, 'tag11');
xmlwriter_text($xw, 'Ceci est du texte, ä');
xmlwriter_end_element($xw); // tag11

xmlwriter_end_element($xw); // tag1

// CDATA
xmlwriter_start_element($xw, 'testc');
xmlwriter_write_cdata($xw, "Ceci est du contenu cdata");
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

// Une instruction de traitement
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);

L'exemple ci-dessus va afficher :

<?xml version="1.0" encoding="UTF-8"?>
<tag1 att1="valueofatt1">
 <!--ceci est un commentaire.-->
 <tag11>Ceci est du texte, ä</tag11>
</tag1>
<testc><![CDATA[Ceci est du contenu cdata]]></testc>
<testc><![CDATA[test cdata2]]></testc>
<?php $foo=2;echo $foo;?>

User Contributed Notes

There are no user contributed notes for this page.


Travailler avec les espaces de noms XML

Cet exemple montre comment créer des éléments dans des espaces de noms XML.

Exemple #1 Travailler avec les espaces de noms XML

<?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);

L'exemple ci-dessus va afficher :

<?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.


Travailler avec l'API OO

Cet exemple montre comment travailler avec l'API orienté objet de XMLWriter.

Exemple #1 Travailler avec l'API OO

<?php

$xw = new XMLWriter();
$xw->openMemory();
$xw->startDocument("1.0");
$xw->startElement("book");
$xw->text("example");
$xw->endElement();
$xw->endDocument();
echo $xw->outputMemory();

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<book>example</book>

User Contributed Notes

There are no user contributed notes for this page.


La classe XMLWriter

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

Introduction

Synopsis de la classe

class XMLWriter {
/* Méthodes */
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 $prefix, string $name, ?string $namespace): bool
public startCdata(): bool
public startComment(): bool
public startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool
public startDtd(string $qualifiedName, ?string $publicId = null, ?string $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 $prefix, string $name, ?string $namespace): bool
public startPi(string $target): bool
public text(string $content): bool
public writeAttribute(string $name, string $value): bool
public writeAttributeNs(
?string $prefix,
string $name,
?string $namespace,
string $value
): bool
public writeCdata(string $content): bool
public writeComment(string $content): bool
public writeDtd(
string $name,
?string $publicId = null,
?string $systemId = null,
?string $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 $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool
public writeElement(string $name, ?string $content = null): bool
public writeElementNs(
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool
public writePi(string $target, string $content): bool
public writeRaw(string $content): bool
}

Sommaire

  • XMLWriter::endAttribute — Termine un attribut
  • XMLWriter::endCdata — Termine un bloc CDATA
  • XMLWriter::endComment — Termine un commentaire
  • XMLWriter::endDocument — Termine le document courant
  • XMLWriter::endDtd — Termine la DTD courante
  • XMLWriter::endDtdAttlist — Termine la liste des attributs de la DTD courante
  • XMLWriter::endDtdElement — Termine l'élément de la DTD courante
  • XMLWriter::endDtdEntity — Termine l'entité de la DTD courante
  • XMLWriter::endElement — Termine l'élément courant
  • XMLWriter::endPi — Termine le PI courant
  • XMLWriter::flush — Affiche le buffer courant
  • XMLWriter::fullEndElement — Termine l'élément courant
  • XMLWriter::openMemory — Crée un nouveau xmlwriter en utilisant la mémoire pour l'affichage des chaînes
  • XMLWriter::openUri — Crée un nouveau xmlwriter, en utilisant l'URI source pour l'affichage
  • XMLWriter::outputMemory — Retourne le buffer courant
  • XMLWriter::setIndent — Active ou non l'indentation
  • XMLWriter::setIndentString — Définit la chaîne à utiliser pour l'indentation
  • XMLWriter::startAttribute — Crée un attribut
  • XMLWriter::startAttributeNs — Crée un attribut pour l'espace de noms
  • XMLWriter::startCdata — Crée une balise CDATA
  • XMLWriter::startComment — Crée un commentaire
  • XMLWriter::startDocument — Crée un document
  • XMLWriter::startDtd — Crée une DTD
  • XMLWriter::startDtdAttlist — Crée une liste d'attributs pour la DTD
  • XMLWriter::startDtdElement — Crée un élément DTD
  • XMLWriter::startDtdEntity — Crée une entité DTD
  • XMLWriter::startElement — Crée un élément
  • XMLWriter::startElementNs — Crée un élément d'un espace de noms
  • XMLWriter::startPi — Crée une balise PI
  • XMLWriter::text — Écrit du texte
  • XMLWriter::writeAttribute — Écrit un attribut
  • XMLWriter::writeAttributeNs — Écrit un attribut d'un espace de noms
  • XMLWriter::writeCdata — Écrit un bloc CDATA
  • XMLWriter::writeComment — Écrit un commentaire
  • XMLWriter::writeDtd — Écrit une DTD
  • XMLWriter::writeDtdAttlist — Écrit une liste d'attributs DTD
  • XMLWriter::writeDtdElement — Écrit un élément DTD
  • XMLWriter::writeDtdEntity — Écrit une entité DTD
  • XMLWriter::writeElement — Écrit un élément
  • XMLWriter::writeElementNs — Écrit un élément d'un espace de noms
  • XMLWriter::writePi — Écrit la balise PI
  • XMLWriter::writeRaw — Écrit un texte XML brut

User Contributed Notes

There are no user contributed notes for this page.


Termine un attribut

  • « XMLWriter
  • XMLWriter::endCdata »
  • PHP Manual
  • XMLWriter
  • Termine un attribut

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — Termine un attribut

Description

Style orienté objet

public XMLWriter::endAttribute(): bool

Style procédural

xmlwriter_end_attribute(XMLWriter $writer): bool

Termine l'attribut courant.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startAttribute() - Crée un attribut
  • XMLWriter::startAttributeNs() - Crée un attribut pour l'espace de noms
  • XMLWriter::writeAttribute() - Écrit un attribut
  • XMLWriter::writeAttributeNs() - Écrit un attribut d'un espace de noms

User Contributed Notes

There are no user contributed notes for this page.


Termine un bloc CDATA

  • « XMLWriter::endAttribute
  • XMLWriter::endComment »
  • PHP Manual
  • XMLWriter
  • Termine un bloc 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 — Termine un bloc CDATA

Description

Style orienté objet

public XMLWriter::endCdata(): bool

Style procédural

xmlwriter_end_cdata(XMLWriter $writer): bool

Termine la section CDATA courante.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startCdata() - Crée une balise CDATA
  • XMLWriter::writeCdata() - Écrit un bloc CDATA

User Contributed Notes

There are no user contributed notes for this page.


Termine un commentaire

  • « XMLWriter::endCdata
  • XMLWriter::endDocument »
  • PHP Manual
  • XMLWriter
  • Termine un commentaire

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Termine un commentaire

Description

Style orienté objet

public XMLWriter::endComment(): bool

Style procédural

xmlwriter_end_comment(XMLWriter $writer): bool

Termine le commentaire courant.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startComment() - Crée un commentaire
  • XMLWriter::writeComment() - Écrit un commentaire

User Contributed Notes

There are no user contributed notes for this page.


Termine le document courant

  • « XMLWriter::endComment
  • XMLWriter::endDtd »
  • PHP Manual
  • XMLWriter
  • Termine le document courant

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — Termine le document courant

Description

Style orienté objet

public XMLWriter::endDocument(): bool

Style procédural

xmlwriter_end_document(XMLWriter $writer): bool

Termine le document courant.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDocument() - Crée un document

User Contributed Notes

Sbastien 13-Mar-2022 09:44
XMLWriter::endDocument() closes properly all remaining elements not yet closed.

Without XMLWriter::endDocument() :

<?php
$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->startElement('a');
$xml->startElement('b');
$xml->startElement('c');
$xml->startAttribute('foo');
exit;

/*
Outputs :
<?xml version="1.0"?>
<a><b><c foo="
*/
?>

With XMLWriter::endDocument() :

<?php
$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->startElement('a');
$xml->startElement('b');
$xml->startElement('c');
$xml->startAttribute('foo');
$xml->endDocument();
exit;

/*
Outputs :
<?xml version="1.0"?>
<a><b><c foo=""/></b></a>
*/
?>


Termine la DTD courante

  • « XMLWriter::endDocument
  • XMLWriter::endDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Termine la DTD courante

XMLWriter::endDtd

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtd -- xmlwriter_end_dtd — Termine la DTD courante

Description

Style orienté objet

public XMLWriter::endDtd(): bool

Style procédural

xmlwriter_end_dtd(XMLWriter $writer): bool

Termine la DTD courante du document.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDtd() - Crée une DTD
  • XMLWriter::writeDtd() - Écrit une DTD

User Contributed Notes

There are no user contributed notes for this page.


Termine la liste des attributs de la DTD courante

  • « XMLWriter::endDtd
  • XMLWriter::endDtdElement »
  • PHP Manual
  • XMLWriter
  • Termine la liste des attributs de la DTD courante

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 — Termine la liste des attributs de la DTD courante

Description

Style orienté objet

public XMLWriter::endDtdAttlist(): bool

Style procédural

xmlwriter_end_dtd_attlist(XMLWriter $writer): bool

Termine la liste des attributs de la DTD courante.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDtdAttlist() - Crée une liste d'attributs pour la DTD
  • XMLWriter::writeDtdAttlist() - Écrit une liste d'attributs DTD

User Contributed Notes

There are no user contributed notes for this page.


Termine l'élément de la DTD courante

  • « XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity »
  • PHP Manual
  • XMLWriter
  • Termine l'élément de la DTD courante

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 — Termine l'élément de la DTD courante

Description

Style orienté objet

public XMLWriter::endDtdElement(): bool

Style procédural

xmlwriter_end_dtd_element(XMLWriter $writer): bool

Termine l'élément de la DTD courante.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDtdElement() - Crée un élément DTD
  • XMLWriter::writeDtdElement() - Écrit un élément DTD

User Contributed Notes

There are no user contributed notes for this page.


Termine l'entité de la DTD courante

  • « XMLWriter::endDtdElement
  • XMLWriter::endElement »
  • PHP Manual
  • XMLWriter
  • Termine l'entité de la DTD courante

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 — Termine l'entité de la DTD courante

Description

Style orienté objet

public XMLWriter::endDtdEntity(): bool

Style procédural

xmlwriter_end_dtd_entity(XMLWriter $writer): bool

Termine l'entité de la DTD courante.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDtdEntity() - Crée une entité DTD
  • XMLWriter::writeDtdEntity() - Écrit une entité DTD

User Contributed Notes

There are no user contributed notes for this page.


Termine l'élément courant

  • « XMLWriter::endDtdEntity
  • XMLWriter::endPi »
  • PHP Manual
  • XMLWriter
  • Termine l'élément courant

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — Termine l'élément courant

Description

Style orienté objet

public XMLWriter::endElement(): bool

Style procédural

xmlwriter_end_element(XMLWriter $writer): bool

Termine l'élément courant.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startElement() - Crée un élément
  • XMLWriter::writeElement() - Écrit un élément

User Contributed Notes

There are no user contributed notes for this page.


Termine le PI courant

  • « XMLWriter::endElement
  • XMLWriter::flush »
  • PHP Manual
  • XMLWriter
  • Termine le PI courant

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — Termine le PI courant

Description

Style orienté objet

public XMLWriter::endPi(): bool

Style procédural

xmlwriter_end_pi(XMLWriter $writer): bool

Termine l'instruction courante.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startPi() - Crée une balise PI
  • XMLWriter::writePi() - Écrit la balise PI

User Contributed Notes

There are no user contributed notes for this page.


Affiche le buffer courant

  • « XMLWriter::endPi
  • XMLWriter::fullEndElement »
  • PHP Manual
  • XMLWriter
  • Affiche le buffer courant

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Affiche le buffer courant

Description

Style orienté objet

public XMLWriter::flush(bool $empty = true): string|int

Style procédural

xmlwriter_flush(XMLWriter $writer, bool $empty = true): string|int

Affiche le buffer courant.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

empty

Si l'on doit vider le buffer ou non. Par défaut, ce paramètre vaut true.

Valeurs de retour

Si vous aviez ouvert le gestionnaire d'écriture en mémoire, cette fonction retourne le buffer XML généré. Si vous utilisez une URI, cette fonction écrira le buffer et retournera le nombre d'octets écrits.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.
8.0.0 | Cette fonction ne peut plus retourner false.

User Contributed Notes

Sbastien 13-Mar-2022 09:29
XMLWriter::flush() basic usage with XMLWriter::openMemory() :

<?php
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument();
$xml->writeElement('message', 'Hello World!');
$xml->endDocument();
echo $xml->flush();

/*
Produces :

<?xml version="1.0"?>
<message>Hello World!</message>
*/
?>


Termine l'élément courant

  • « XMLWriter::flush
  • XMLWriter::openMemory »
  • PHP Manual
  • XMLWriter
  • Termine l'élément courant

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 — Termine l'élément courant

Description

Style orienté objet

public XMLWriter::fullEndElement(): bool

Style procédural

xmlwriter_full_end_element(XMLWriter $writer): bool

Termine l'élément XML courant. Écrit une balise de fin même si l'élément est vide.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endElement() - Termine l'élément courant

User Contributed Notes

There are no user contributed notes for this page.


Crée un nouveau xmlwriter en utilisant la mémoire pour l'affichage des chaînes

  • « XMLWriter::fullEndElement
  • XMLWriter::openUri »
  • PHP Manual
  • XMLWriter
  • Crée un nouveau xmlwriter en utilisant la mémoire pour l'affichage des chaînes

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Crée un nouveau xmlwriter en utilisant la mémoire pour l'affichage des chaînes

Description

Style orienté objet

public XMLWriter::openMemory(): bool

Style procédural

xmlwriter_open_memory(): XMLWriter|false

Crée un nouvel objet XMLWriter, en utilisant la mémoire pour l'affichage des chaînes.

Liste de paramètres

Valeurs de retour

Style orienté objet : Cette fonction retourne true en cas de succès ou false si une erreur survient.

Style procédural : Retourne une nouvelle instance de XMLWriter pour une utilisation future avec les fonctions xmlwriter en cas de succès, ou false si une erreur survient.

Historique

Version | Description
8.0.0 | Cette fonction retourne désormais une instance de XMLWriter en cas de succès. Auparavant, une ressource était retournée dans ce cas.

Voir aussi

  • XMLWriter::openUri() - Crée un nouveau xmlwriter, en utilisant l'URI source pour l'affichage

User Contributed Notes

There are no user contributed notes for this page.


Crée un nouveau xmlwriter, en utilisant l'URI source pour l'affichage

  • « XMLWriter::openMemory
  • XMLWriter::outputMemory »
  • PHP Manual
  • XMLWriter
  • Crée un nouveau xmlwriter, en utilisant l'URI source pour l'affichage

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Crée un nouveau xmlwriter, en utilisant l'URI source pour l'affichage

Description

Style orienté objet

public XMLWriter::openUri(string $uri): bool

Style procédural

xmlwriter_open_uri(string $uri): XMLWriter|false

Crée un nouveau XMLWriter, en utilisant l'uri pour l'affichage.

Liste de paramètres

uri

L'URI de la ressource pour l'affichage.

Valeurs de retour

Style orienté objet : Cette fonction retourne true en cas de succès ou false si une erreur survient.

Style procédural : Retourne une nouvelle instance de XMLWriter pour une utilisation future avec les fonctions xmlwriter en cas de succès, ou false si une erreur survient.

Historique

Version | Description
8.0.0 | Cette fonction retourne désormais une instance de XMLWriter en cas de succès. Auparavant, une ressource était retournée dans ce cas.

Exemples

Exemple #1 Écrire directement de l'XML

Il est possible d'écrire directement de l'XML en utilisant l' enveloppe de flux php://output.

<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>

Notes

Note:

Sur Windows, les fichiers ouvert avec cette fonction sont vérouiller jusqu'à ce que l'objet XMLWriter est libéré.

Voir aussi

  • XMLWriter::openMemory() - Crée un nouveau xmlwriter en utilisant la mémoire pour l'affichage des chaînes

User Contributed Notes

There are no user contributed notes for this page.


Retourne le buffer courant

  • « XMLWriter::openUri
  • XMLWriter::setIndent »
  • PHP Manual
  • XMLWriter
  • Retourne le buffer courant

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Retourne le buffer courant

Description

Style orienté objet

public XMLWriter::outputMemory(bool $flush = true): string

Style procédural

xmlwriter_output_memory(XMLWriter $writer, bool $flush = true): string

Retourne le buffer courant.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

flush

Si l'on doit afficher le buffer ou non. Par défaut, ce paramètre vaut true.

Valeurs de retour

Retourne le buffer courant sous la forme d'une chaîne de caractères.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::flush() - Affiche le buffer courant

User Contributed Notes

There are no user contributed notes for this page.


Active ou non l'indentation

  • « XMLWriter::outputMemory
  • XMLWriter::setIndentString »
  • PHP Manual
  • XMLWriter
  • Active ou non l'indentation

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Active ou non l'indentation

Description

Style orienté objet

public XMLWriter::setIndent(bool $enable): bool

Style procédural

xmlwriter_set_indent(XMLWriter $writer, bool $enable): bool

Active ou non l'indentation.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

enable

Si l'on doit activer l'indentation ou non.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Exemples

Exemple #1 XMLWriter::setIndent() et divers contenus

L'activation de l'indentation n'est pas conseillé pour le contenu diverse, car le caractère d'indentation sera aussi inséré avant les éléments en ligne.

<?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();
?>

L'exemple ci-dessus va afficher :

<?xml version="1.0"?>
<p>before <a>element</a>
after</p>

Notes

Note:

L'indentation est réinitialisé quand un XMLWriter est ouvert.

Voir aussi

  • XMLWriter::setIndentString() - Définit la chaîne à utiliser pour l'indentation

User Contributed Notes

info at ensostudio dot ru 04-Apr-2021 01:04
NOTE: $enable can be integer as in example, or boolean.


Définit la chaîne à utiliser pour l'indentation

  • « XMLWriter::setIndent
  • XMLWriter::startAttribute »
  • PHP Manual
  • XMLWriter
  • Définit la chaîne à utiliser pour l'indentation

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 — Définit la chaîne à utiliser pour l'indentation

Description

Style orienté objet

public XMLWriter::setIndentString(string $indentation): bool

Style procédural

xmlwriter_set_indent_string(XMLWriter $writer, string $indentation): bool

Définit la chaîne qui sera utilisée pour indenter chaque élément/attribut d'un document XML.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

indentation

La chaîne pour l'indentation.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Notes

Note:

L'indentation est réinitialisé quand un XMLWriter est ouvert.

Voir aussi

  • XMLWriter::setIndent() - Active ou non l'indentation

User Contributed Notes

There are no user contributed notes for this page.


Crée un attribut

  • « XMLWriter::setIndentString
  • XMLWriter::startAttributeNs »
  • PHP Manual
  • XMLWriter
  • Crée un attribut

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Crée un attribut

Description

Style orienté objet

public XMLWriter::startAttribute(string $name): bool

Style procédural

xmlwriter_start_attribute(XMLWriter $writer, string $name): bool

Commence un attribut.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Exemples

Exemple #1 Utilisation Basique de XMLWriter::startAttribute()

<?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();

Résultat de l'exemple ci-dessus est similaire à :

<?xml version="1.0" encoding="UTF-8"?>
<element attribute="value"/>

Voir aussi

  • XMLWriter::startAttributeNs() - Crée un attribut pour l'espace de noms
  • XMLWriter::endAttribute() - Termine un attribut
  • XMLWriter::writeAttribute() - Écrit un attribut
  • XMLWriter::writeAttributeNs() - Écrit un attribut d'un espace de noms

User Contributed Notes

There are no user contributed notes for this page.


Crée un attribut pour l'espace de noms

  • « XMLWriter::startAttribute
  • XMLWriter::startCdata »
  • PHP Manual
  • XMLWriter
  • Crée un attribut pour l'espace de noms

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 — Crée un attribut pour l'espace de noms

Description

Style orienté objet

public XMLWriter::startAttributeNs(?string $prefix, string $name, ?string $namespace): bool

Style procédural

xmlwriter_start_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Crée un attribut pour l'espace de noms.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

Le préfixe pour l'espace de noms.

name

Le nom de l'attribut.

namespace

L'URI de l'espace de noms. Si le namespace vaut null, la déclaration de l'espace de noms sera omise.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.
8.0.0 | prefix est désormais nullable.

Voir aussi

  • XMLWriter::startAttribute() - Crée un attribut
  • XMLWriter::endAttribute() - Termine un attribut
  • XMLWriter::writeAttribute() - Écrit un attribut
  • XMLWriter::writeAttributeNs() - Écrit un attribut d'un espace de noms

User Contributed Notes

There are no user contributed notes for this page.


Crée une balise CDATA

  • « XMLWriter::startAttributeNs
  • XMLWriter::startComment »
  • PHP Manual
  • XMLWriter
  • Crée une balise CDATA

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — Crée une balise CDATA

Description

Style orienté objet

public XMLWriter::startCdata(): bool

Style procédural

xmlwriter_start_cdata(XMLWriter $writer): bool

Commence un bloc CDATA.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endCdata() - Termine un bloc CDATA
  • XMLWriter::writeCdata() - Écrit un bloc CDATA

User Contributed Notes

There are no user contributed notes for this page.


Crée un commentaire

  • « XMLWriter::startCdata
  • XMLWriter::startDocument »
  • PHP Manual
  • XMLWriter
  • Crée un commentaire

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Crée un commentaire

Description

Style orienté objet

public XMLWriter::startComment(): bool

Style procédural

xmlwriter_start_comment(XMLWriter $writer): bool

Commence un commentaire.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endComment() - Termine un commentaire
  • XMLWriter::writeComment() - Écrit un commentaire

User Contributed Notes

There are no user contributed notes for this page.


Crée un document

  • « XMLWriter::startComment
  • XMLWriter::startDtd »
  • PHP Manual
  • XMLWriter
  • Crée un document

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Crée un document

Description

Style orienté objet

public XMLWriter::startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool

Style procédural

xmlwriter_start_document(
XMLWriter $writer,
?string $version = "1.0",
?string $encoding = null,
?string $standalone = null
): bool

Commence un document.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

version

Le numéro de version du document dans la déclaration XML.

encoding

L'encodage du document dans la déclaration XML.

standalone

yes ou no.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endDocument() - Termine le document courant

User Contributed Notes

Sbastien 13-Mar-2022 09:52
XMLWriter::startDocument() writes the XML declaration.

Without XMLWriter::startDocument() :

<?php

$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->writeElement('message', 'Hello World!');
exit;

/*
Outputs :
<message>Hello World!</message>
*/
?>

With XMLWriter::startDocument() :

<?php

$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->writeElement('message', 'Hello World!');
exit;

/*
Outputs :
<?xml version="1.0"?>
<message>Hello World!</message>
*/
?>


Crée une DTD

  • « XMLWriter::startDocument
  • XMLWriter::startDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Crée une DTD

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — Crée une DTD

Description

Style orienté objet

public XMLWriter::startDtd(string $qualifiedName, ?string $publicId = null, ?string $systemId = null): bool

Style procédural

xmlwriter_start_dtd(
XMLWriter $writer,
string $qualifiedName,
?string $publicId = null,
?string $systemId = null
): bool

Commence une DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

qualifiedName

Le nom qualifié du type de document à créer.

publicId

L'identifiant publique externe.

systemId

L'identifiant système externe.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endDtd() - Termine la DTD courante
  • XMLWriter::writeDtd() - Écrit une DTD

User Contributed Notes

There are no user contributed notes for this page.


Crée une liste d'attributs pour la DTD

  • « XMLWriter::startDtd
  • XMLWriter::startDtdElement »
  • PHP Manual
  • XMLWriter
  • Crée une liste d'attributs pour la DTD

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 — Crée une liste d'attributs pour la DTD

Description

Style orienté objet

public XMLWriter::startDtdAttlist(string $name): bool

Style procédural

xmlwriter_start_dtd_attlist(XMLWriter $writer, string $name): bool

Crée une liste d'attributs pour la DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de la liste d'attributs.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endDtdAttlist() - Termine la liste des attributs de la DTD courante
  • XMLWriter::writeDtdAttlist() - Écrit une liste d'attributs DTD

User Contributed Notes

There are no user contributed notes for this page.


Crée un élément DTD

  • « XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity »
  • PHP Manual
  • XMLWriter
  • Crée un élément DTD

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 — Crée un élément DTD

Description

Style orienté objet

public XMLWriter::startDtdElement(string $qualifiedName): bool

Style procédural

xmlwriter_start_dtd_element(XMLWriter $writer, string $qualifiedName): bool

Commence un élément DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

qualifiedName

Le nom qualifié du type de document à créer.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endDtdElement() - Termine l'élément de la DTD courante
  • XMLWriter::writeDtdElement() - Écrit un élément DTD

User Contributed Notes

There are no user contributed notes for this page.


Crée une entité DTD

  • « XMLWriter::startDtdElement
  • XMLWriter::startElement »
  • PHP Manual
  • XMLWriter
  • Crée une entité DTD

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 — Crée une entité DTD

Description

Style orienté objet

public XMLWriter::startDtdEntity(string $name, bool $isParam): bool

Style procédural

xmlwriter_start_dtd_entity(XMLWriter $writer, string $name, bool $isParam): bool

Commence une entité DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de l'entité.

isParam

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endDtdEntity() - Termine l'entité de la DTD courante
  • XMLWriter::writeDtdEntity() - Écrit une entité DTD

User Contributed Notes

There are no user contributed notes for this page.


Crée un élément

  • « XMLWriter::startDtdEntity
  • XMLWriter::startElementNs »
  • PHP Manual
  • XMLWriter
  • Crée un élément

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Crée un élément

Description

Style orienté objet

public XMLWriter::startElement(string $name): bool

Style procédural

xmlwriter_start_element(XMLWriter $writer, string $name): bool

Commence un élément.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de l'élément.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endElement() - Termine l'élément courant
  • XMLWriter::writeElement() - Écrit un élément

User Contributed Notes

There are no user contributed notes for this page.


Crée un élément d'un espace de noms

  • « XMLWriter::startElement
  • XMLWriter::startPi »
  • PHP Manual
  • XMLWriter
  • Crée un élément d'un espace de noms

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 — Crée un élément d'un espace de noms

Description

Style orienté objet

public XMLWriter::startElementNs(?string $prefix, string $name, ?string $namespace): bool

Style procédural

xmlwriter_start_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Crée un élément d'un espace de noms.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

Le préfixe de l'espace de noms. Si le paramètre prefix vaut null, l'espace de noms sera omis.

name

Le nom de l'élément.

namespace

L'URI de l'espace de noms. Si le namespace vaut null, la déclaration de l'espace de noms sera omise.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endElement() - Termine l'élément courant
  • XMLWriter::writeElementNs() - Écrit un élément d'un espace de noms

User Contributed Notes

There are no user contributed notes for this page.


Crée une balise PI

  • « XMLWriter::startElementNs
  • XMLWriter::text »
  • PHP Manual
  • XMLWriter
  • Crée une balise PI

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Crée une balise PI

Description

Style orienté objet

public XMLWriter::startPi(string $target): bool

Style procédural

xmlwriter_start_pi(XMLWriter $writer, string $target): bool

Commence une balise d'instruction.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

target

La cible de l'instruction.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::endPi() - Termine le PI courant
  • XMLWriter::writePi() - Écrit la balise PI

User Contributed Notes

There are no user contributed notes for this page.


Écrit du texte

  • « XMLWriter::startPi
  • XMLWriter::writeAttribute »
  • PHP Manual
  • XMLWriter
  • Écrit du texte

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Écrit du texte

Description

Style orienté objet

public XMLWriter::text(string $content): bool

Style procédural

xmlwriter_text(XMLWriter $writer, string $content): bool

Écrit du texte.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

content

Le contenu du texte. Les caractères <, >, & et " sont écrit en tant que références d'entités (c.à.d. &lt;, &gt;, &amp; et &quot;, respectivement). Tous les autres caractères ' inclus sont écrit littéralement. Pour écrire les caractères XML spéciaux littéralement, ou pour écrire des références d'entités litérales, xmlwriter_write_raw() doit être utilisé.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

User Contributed Notes

There are no user contributed notes for this page.


Écrit un attribut

  • « XMLWriter::text
  • XMLWriter::writeAttributeNs »
  • PHP Manual
  • XMLWriter
  • Écrit un attribut

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Écrit un attribut

Description

Style orienté objet

public XMLWriter::writeAttribute(string $name, string $value): bool

Style procédural

xmlwriter_write_attribute(XMLWriter $writer, string $name, string $value): bool

Écrit un attribut.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de l'attribut.

value

La valeur de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Exemples

Exemple #1 Mélanger des Sous-éléments et Attributs

Lors de l'écriture de sous-éléments avec des attributs mélangé, toute tentative d'écrires des attributs après le premier sous-élément échouera et retournera 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();
?>

L'exemple ci-dessus va afficher :

bool(false)
<element attr1="0"><subelem>0</subelem></element>

Voir aussi

  • XMLWriter::writeAttributeNs() - Écrit un attribut d'un espace de noms
  • XMLWriter::startAttribute() - Crée un attribut
  • XMLWriter::startAttributeNs() - Crée un attribut pour l'espace de noms
  • XMLWriter::endAttribute() - Termine un attribut

User Contributed Notes

There are no user contributed notes for this page.


Écrit un attribut d'un espace de noms

  • « XMLWriter::writeAttribute
  • XMLWriter::writeCdata »
  • PHP Manual
  • XMLWriter
  • Écrit un attribut d'un espace de noms

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 — Écrit un attribut d'un espace de noms

Description

Style orienté objet

public XMLWriter::writeAttributeNs(
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Style procédural

xmlwriter_write_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Écrit un attribut d'un espace de noms.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

Le préfixe de l'espace de noms. Si le paramètre prefix vaut null, l'espace de noms sera omis.

name

Le nom de l'attribut.

namespace

L'URI de l'espace de noms. Si le namespace vaut null, la déclaration de l'espace de noms sera omise.

value

La valeur de l'attribut.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::writeAttribute() - Écrit un attribut
  • XMLWriter::startAttribute() - Crée un attribut
  • XMLWriter::startAttributeNs() - Crée un attribut pour l'espace de noms
  • XMLWriter::endAttribute() - Termine un attribut

User Contributed Notes

There are no user contributed notes for this page.


Écrit un bloc CDATA

  • « XMLWriter::writeAttributeNs
  • XMLWriter::writeComment »
  • PHP Manual
  • XMLWriter
  • Écrit un bloc CDATA

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Écrit un bloc CDATA

Description

Style orienté objet

public XMLWriter::writeCdata(string $content): bool

Style procédural

xmlwriter_write_cdata(XMLWriter $writer, string $content): bool

Écrit un bloc CDATA.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

content

Le contenu du bloc CDATA.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Exemples

Exemple #1 Utilisation Basique de xmlwriter_write_cdata()

<?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);
?>

L'exemple ci-dessus va afficher :

<mydoc>
 <myele>
  <mycdataelement><![CDATA[text for inclusion as CData]?]></mycdataelement>
 </myele>
</mydoc>

Voir aussi

  • XMLWriter::startCdata() - Crée une balise CDATA
  • XMLWriter::endCdata() - Termine un bloc CDATA

User Contributed Notes

There are no user contributed notes for this page.


Écrit un commentaire

  • « XMLWriter::writeCdata
  • XMLWriter::writeDtd »
  • PHP Manual
  • XMLWriter
  • Écrit un commentaire

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Écrit un commentaire

Description

Style orienté objet

public XMLWriter::writeComment(string $content): bool

Style procédural

xmlwriter_write_comment(XMLWriter $writer, string $content): bool

Écrit un commentaire.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

content

Le contenu du commentaire.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startComment() - Crée un commentaire
  • XMLWriter::endComment() - Termine un commentaire

User Contributed Notes

There are no user contributed notes for this page.


Écrit une DTD

  • « XMLWriter::writeComment
  • XMLWriter::writeDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Écrit une DTD

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Écrit une DTD

Description

Style orienté objet

public XMLWriter::writeDtd(
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Style procédural

xmlwriter_write_dtd(
XMLWriter $writer,
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Écrit une DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de la DTD.

publicId

L'identifiant publique externe.

systemId

L'identifiant système externe.

content

Le contenu de la DTD.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDtd() - Crée une DTD
  • XMLWriter::endDtd() - Termine la DTD courante

User Contributed Notes

There are no user contributed notes for this page.


Écrit une liste d'attributs DTD

  • « XMLWriter::writeDtd
  • XMLWriter::writeDtdElement »
  • PHP Manual
  • XMLWriter
  • Écrit une liste d'attributs DTD

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 — Écrit une liste d'attributs DTD

Description

Style orienté objet

public XMLWriter::writeDtdAttlist(string $name, string $content): bool

Style procédural

xmlwriter_write_dtd_attlist(XMLWriter $writer, string $name, string $content): bool

Écrit une liste d'attribut DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de la liste d'attributs DTD.

content

Le contenu de la liste d'attributs DTD.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDtdAttlist() - Crée une liste d'attributs pour la DTD
  • XMLWriter::endDtdAttlist() - Termine la liste des attributs de la DTD courante

User Contributed Notes

There are no user contributed notes for this page.


Écrit un élément DTD

  • « XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity »
  • PHP Manual
  • XMLWriter
  • Écrit un élément DTD

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 — Écrit un élément DTD

Description

Style orienté objet

public XMLWriter::writeDtdElement(string $name, string $content): bool

Style procédural

xmlwriter_write_dtd_element(XMLWriter $writer, string $name, string $content): bool

Écrit un élément DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de l'élément DTD.

content

Le contenu de l'élément.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startDtdElement() - Crée un élément DTD
  • XMLWriter::endDtdElement() - Termine l'élément de la DTD courante

User Contributed Notes

There are no user contributed notes for this page.


Écrit une entité DTD

  • « XMLWriter::writeDtdElement
  • XMLWriter::writeElement »
  • PHP Manual
  • XMLWriter
  • Écrit une entité DTD

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 — Écrit une entité DTD

Description

Style orienté objet

public XMLWriter::writeDtdEntity(
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Style procédural

xmlwriter_write_dtd_entity(
XMLWriter $writer,
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Écrit une entité DTD.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de l'entité.

content

Le contenu de l'entité.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.
8.0.0 | publicId, systemId et notationData sont désormais nullable.

Voir aussi

  • XMLWriter::startDtdEntity() - Crée une entité DTD
  • XMLWriter::endDtdEntity() - Termine l'entité de la DTD courante

User Contributed Notes

There are no user contributed notes for this page.


Écrit un élément

  • « XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs »
  • PHP Manual
  • XMLWriter
  • Écrit un élément

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Écrit un élément

Description

Style orienté objet

public XMLWriter::writeElement(string $name, ?string $content = null): bool

Style procédural

xmlwriter_write_element(XMLWriter $writer, string $name, ?string $content = null): bool

Écrit un élément.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

name

Le nom de l'élément.

content

Le contenu de l'élément.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startElement() - Crée un élément
  • XMLWriter::endElement() - Termine l'élément courant
  • XMLWriter::writeElementNs() - Écrit un élément d'un espace de noms

User Contributed Notes

There are no user contributed notes for this page.


Écrit un élément d'un espace de noms

  • « XMLWriter::writeElement
  • XMLWriter::writePi »
  • PHP Manual
  • XMLWriter
  • Écrit un élément d'un espace de noms

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 — Écrit un élément d'un espace de noms

Description

Style orienté objet

public XMLWriter::writeElementNs(
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Style procédural

xmlwriter_write_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Écrit un élément d'un espace de noms.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

Le préfixe de l'espace de noms. Si le paramètre prefix vaut null, l'espace de noms sera omis.

name

Le nom de l'élément.

namespace

L'URI de l'espace de noms. Si le namespace vaut null, la déclaration de l'espace de noms sera omise.

content

Le contenu de l'élément.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startElementNs() - Crée un élément d'un espace de noms
  • XMLWriter::endElement() - Termine l'élément courant
  • XMLWriter::writeElement() - Écrit un élément

User Contributed Notes

There are no user contributed notes for this page.


Écrit la balise PI

  • « XMLWriter::writeElementNs
  • XMLWriter::writeRaw »
  • PHP Manual
  • XMLWriter
  • Écrit la balise 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 — Écrit la balise PI

Description

Style orienté objet

public XMLWriter::writePi(string $target, string $content): bool

Style procédural

xmlwriter_write_pi(XMLWriter $writer, string $target, string $content): bool

Écrit la balise PI.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

target

La cible de l'instruction.

content

Le contenu de l'instruction.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::startPi() - Crée une balise PI
  • XMLWriter::endPi() - Termine le PI courant

User Contributed Notes

There are no user contributed notes for this page.


Écrit un texte XML brut

  • « XMLWriter::writePi
  • XSL »
  • PHP Manual
  • XMLWriter
  • Écrit un texte XML brut

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Écrit un texte XML brut

Description

Style orienté objet

public XMLWriter::writeRaw(string $content): bool

Style procédural

xmlwriter_write_raw(XMLWriter $writer, string $content): bool

Écrit un texte XML brut.

Liste de paramètres

writer

Uniquement pour les appels procéduraux. L'instance XMLWriter qui est modifiée. Cet objet provient d'un appel à xmlwriter_open_uri() ou xmlwriter_open_memory().

content

Le texte à écrire.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version | Description
8.0.0 | writer attend une instance de XMLWriter désormais; auparavant, une resource était attendu.

Voir aussi

  • XMLWriter::text() - Écrit du texte

User Contributed Notes

There are no user contributed notes for this page.


XSL

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
    • Configuration à l'exécution
    • Types de ressources
  • Constantes pré-définies
  • Exemples
    • Exemple de fichiers collection.xml et collection.xsl
    • Gestion des erreurs avec les fonctions de gestion d'erreur libxml
  • XSLTProcessor — La classe XSLTProcessor
    • XSLTProcessor::__construct — Crée un nouvel objet XSLTProcessor
    • XSLTProcessor::getParameter — Récupère la valeur d'un paramètre
    • XSLTProcessor::getSecurityPrefs — Récupère les préférences de sécurité
    • XSLTProcessor::hasExsltSupport — Indique si PHP utilise EXSLT
    • XSLTProcessor::importStylesheet — Importe une feuille de style
    • XSLTProcessor::registerPHPFunctions — Active l'utilisation de PHP dans les feuilles de styles XSLT
    • XSLTProcessor::removeParameter — Efface un paramètre
    • XSLTProcessor::setParameter — Définit la valeur d'un paramètre
    • XSLTProcessor::setProfiling — Spécifie le fichier de profilage
    • XSLTProcessor::setSecurityPrefs — Définit les préférences de sécurité
    • XSLTProcessor::transformToDoc — Transforme en un document
    • XSLTProcessor::transformToUri — Transforme en URI
    • XSLTProcessor::transformToXml — Transformer en 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));
?>


Introduction

L'extension XSL implémente le standard XSL, et effectue des » transformations XSLT en utilisant la » bibliothèque libxslt

User Contributed Notes

There are no user contributed notes for this page.


Pré-requis

Cette extension requière l'extension PHP libxml. Ceci signifie passer l'option de configuration --with-libxml, ou antérieur à PHP 7.4 l'option de configuration --enable-libxml, bien que ceci est accomplie implicitement car libxml est activé par défaut.

Cette extension utilise libxslt qui peut être trouvée sur » http://xmlsoft.org/XSLT/. libxslt en version 1.1.0 ou ultérieure est requise.

User Contributed Notes

There are no user contributed notes for this page.


Installation

PHP inclut l'extension XSL par défaut et peut être activée en ajoutant l'argument --with-xsl[=DIR] à votre ligne de configuration. DIR est le dossier d'installation de la bibliothèque libxslt.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

XSL_CLONE_AUTO (int)
XSL_CLONE_NEVER (int)
XSL_CLONE_ALWAYS (int)
LIBXSLT_VERSION (int)
Version libxslt, par exemple : 10117.
LIBXSLT_DOTTED_VERSION (string)
Version libxslt, par exemple : 1.1.17.
LIBEXSLT_VERSION (int)
Version libexslt, par exemple : 813.
LIBEXSLT_DOTTED_VERSION (string)
Version libexslt, par exemple : 1.1.17.
XSL_SECPREF_NONE (int)
Désactive toutes les restrictions de sécurité.
XSL_SECPREF_READ_FILE (int)
Interdit la lecture de fichiers.
XSL_SECPREF_WRITE_FILE (int)
Interdit l'écriture de fichiers.
XSL_SECPREF_CREATE_DIRECTORY (int)
Interdit la création de répertoires.
XSL_SECPREF_READ_NETWORK (int)
Interdit la lecture de fichiers via le réseau.
XSL_SECPREF_WRITE_NETWORK (int)
Interdit l'écriture de fichiers via le réseau.
XSL_SECPREF_DEFAULT (int)
Interdit tous les accès en écriture, i.e. un masque XSL_SECPREF_WRITE_NETWORK | XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE.

User Contributed Notes

There are no user contributed notes for this page.


Exemples

Sommaire

  • Exemple de fichiers collection.xml et collection.xsl
  • Gestion des erreurs avec les fonctions de gestion d'erreur libxml

User Contributed Notes

There are no user contributed notes for this page.


Exemple de fichiers collection.xml et collection.xsl

De nombreux exemples de ce chapitre nécessitent à la fois un fichier XML et un fichier XSL. Nous utiliserons collection.xml et collection.xsl qui contiennent respectivement :

Exemple #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>

Exemple #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.


Gestion des erreurs avec les fonctions de gestion d'erreur libxml

libxml fournit des fonctions pour gérer les erreurs qui peuvent être utilisées pour capturer et gérér celles ci lors du traitement XSLT.

Exemple #1 fruits.xml

Un fichier XML valide.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Exemple #2 fruits.xsl

Contient une expression select invalide.

<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>

Exemple #3 Collating and printing errors

L'exemple ci dessous capture et affiche les erreurs libxml levées lors de l'appel XSLTProcessor::importStyleSheet() avec une feuille de style contenant une erreur.

<?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);
}

?>

Résultat de l'exemple ci-dessus est similaire à :

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.


La classe XSLTProcessor

(PHP 5, PHP 7, PHP 8)

Introduction

Synopsis de la classe

class XSLTProcessor {
/* Méthodes */
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 setParameter(string $namespace, array $options): bool
public setProfiling(?string $filename): true
public setSecurityPrefs(int $preferences): int
public transformToDoc(object $document, ?string $returnClass = null): object|false
public transformToUri(object $document, string $uri): int
public transformToXml(object $document): string|null|false
}

Sommaire

  • XSLTProcessor::__construct — Crée un nouvel objet XSLTProcessor
  • XSLTProcessor::getParameter — Récupère la valeur d'un paramètre
  • XSLTProcessor::getSecurityPrefs — Récupère les préférences de sécurité
  • XSLTProcessor::hasExsltSupport — Indique si PHP utilise EXSLT
  • XSLTProcessor::importStylesheet — Importe une feuille de style
  • XSLTProcessor::registerPHPFunctions — Active l'utilisation de PHP dans les feuilles de styles XSLT
  • XSLTProcessor::removeParameter — Efface un paramètre
  • XSLTProcessor::setParameter — Définit la valeur d'un paramètre
  • XSLTProcessor::setProfiling — Spécifie le fichier de profilage
  • XSLTProcessor::setSecurityPrefs — Définit les préférences de sécurité
  • XSLTProcessor::transformToDoc — Transforme en un document
  • XSLTProcessor::transformToUri — Transforme en URI
  • XSLTProcessor::transformToXml — Transformer en 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


Crée un nouvel objet XSLTProcessor

  • « XSLTProcessor
  • XSLTProcessor::getParameter »
  • PHP Manual
  • XSLTProcessor
  • Crée un nouvel objet XSLTProcessor

XSLTProcessor::__construct

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::__construct — Crée un nouvel objet XSLTProcessor

Description

XSLTProcessor::__construct()

Crée un nouvel objet XSLTProcessor.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Exemples

Exemple #1 Exemple avec 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.


Récupère la valeur d'un paramètre

  • « XSLTProcessor::__construct
  • XSLTProcessor::getSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Récupère la valeur d'un paramètre

XSLTProcessor::getParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::getParameter — Récupère la valeur d'un paramètre

Description

public XSLTProcessor::getParameter(string $namespace, string $name): string|false

Récupère la valeur d'un paramètre s'il a été défini précédemment par la fonction XSLTProcessor::setParameter().

Liste de paramètres

namespace

L'URI de l'espace de noms du paramètre XSLT.

name

Le nom local du paramètre XSLT.

Valeurs de retour

La valeur du paramètre (sous la forme d'une chaîne de caractères), ou false s'il n'est pas défini.

Voir aussi

  • XSLTProcessor::setParameter() - Définit la valeur d'un paramètre
  • XSLTProcessor::removeParameter() - Efface un paramètre

User Contributed Notes

There are no user contributed notes for this page.


Récupère les préférences de sécurité

  • « XSLTProcessor::getParameter
  • XSLTProcessor::hasExsltSupport »
  • PHP Manual
  • XSLTProcessor
  • Récupère les préférences de sécurité

XSLTProcessor::getSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::getSecurityPrefs — Récupère les préférences de sécurité

Description

public XSLTProcessor::getSecurityPrefs(): int

Récupère les préférences de sécurité.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Un masque de constantes 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.


Indique si PHP utilise EXSLT

  • « XSLTProcessor::getSecurityPrefs
  • XSLTProcessor::importStylesheet »
  • PHP Manual
  • XSLTProcessor
  • Indique si PHP utilise EXSLT

XSLTProcessor::hasExsltSupport

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

XSLTProcessor::hasExsltSupport — Indique si PHP utilise EXSLT

Description

public XSLTProcessor::hasExsltSupport(): bool

Cette méthode détermine si PHP a été compilé avec la bibliothèque » EXSLT.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Test du support EXSLT

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
die('Le support d\'EXSLT n\'est pas disponible');
}

// Travaux avec EXSLT

?>

User Contributed Notes

There are no user contributed notes for this page.


Importe une feuille de style

  • « XSLTProcessor::hasExsltSupport
  • XSLTProcessor::registerPHPFunctions »
  • PHP Manual
  • XSLTProcessor
  • Importe une feuille de style

XSLTProcessor::importStylesheet

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::importStylesheet — Importe une feuille de style

Description

public XSLTProcessor::importStylesheet(object $stylesheet): bool

Cette méthode importe une feuille de style dans le XSLTProcessor pour transformations.

Liste de paramètres

stylesheet

La feuille de style importée en tant qu'objet DOMDocument ou objet SimpleXMLElement.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

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!


Active l'utilisation de PHP dans les feuilles de styles XSLT

  • « XSLTProcessor::importStylesheet
  • XSLTProcessor::removeParameter »
  • PHP Manual
  • XSLTProcessor
  • Active l'utilisation de PHP dans les feuilles de styles XSLT

XSLTProcessor::registerPHPFunctions

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

XSLTProcessor::registerPHPFunctions — Active l'utilisation de PHP dans les feuilles de styles XSLT

Description

public XSLTProcessor::registerPHPFunctions(array|string|null $functions = null): void

Cette méthode permet d'utiliser les fonctions PHP en tant que fonctions XSLT dans les feuilles de style XSL.

Liste de paramètres

functions

Utilisez ce paramètre pour restreindre les fonctions PHP accessibles depuis XSLT.

Ce paramètre peut être une chaîne (le nom d'une fonction) ou un tableau de noms de fonctions.

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Appel d'une fonction PHP depuis une feuille de style

<?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 = new DOMDocument();
$xmldoc->loadXML($xml);
$xsldoc = new DOMDocument();
$xsldoc->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=Windows-1252;" );
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


Efface un paramètre

  • « XSLTProcessor::registerPHPFunctions
  • XSLTProcessor::setParameter »
  • PHP Manual
  • XSLTProcessor
  • Efface un paramètre

XSLTProcessor::removeParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::removeParameter — Efface un paramètre

Description

public XSLTProcessor::removeParameter(string $namespace, string $name): bool

Efface un paramètre, s'il est défini. Ceci fera que le processeur utilisera la valeur par défaut pour le paramètre comme défini dans la feuille de style.

Liste de paramètres

namespace

L'URI de l'espace de noms du paramètre XSLT.

name

Le nom local du paramètre XSLT.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Voir aussi

  • XSLTProcessor::setParameter() - Définit la valeur d'un paramètre
  • XSLTProcessor::getParameter() - Récupère la valeur d'un paramètre

User Contributed Notes

There are no user contributed notes for this page.


Définit la valeur d'un paramètre

  • « XSLTProcessor::removeParameter
  • XSLTProcessor::setProfiling »
  • PHP Manual
  • XSLTProcessor
  • Définit la valeur d'un paramètre

XSLTProcessor::setParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::setParameter — Définit la valeur d'un paramètre

Description

public XSLTProcessor::setParameter(string $namespace, string $name, string $value): bool
public XSLTProcessor::setParameter(string $namespace, array $options): bool

Spécifie la valeur d'un ou plusieurs paramètres pour être utilisés dans une sous-séquence de transformation avec XSLTProcessor. Si le paramètre n'existe pas dans la feuille de style, il sera ignoré.

Liste de paramètres

namespace

L'URI de l'espace de noms du paramètre XSLT.

name

Le nom local du paramètre XSLT.

value

La nouvelle valeur du paramètre XSLT.

options

Un tableau de paire nom => valeur.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Modification du propriétaire avant la transformation

<?php

$collections = array(
'Marc Rutkowski' => 'marc',
'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure le transformateur
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attachement des règles xsl

foreach ($collections as $name => $file) {
// Chargement de la source XML
$xml = new DOMDocument;
$xml->load('collection_' . $file . '.xml');

$proc->setParameter('', 'owner', $name);
$proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

Voir aussi

  • XSLTProcessor::getParameter() - Récupère la valeur d'un paramètre
  • XSLTProcessor::removeParameter() - Efface un paramètre

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.


Spécifie le fichier de profilage

  • « XSLTProcessor::setParameter
  • XSLTProcessor::setSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Spécifie le fichier de profilage

XSLTProcessor::setProfiling

(PHP >= 5.3.0, PHP 7, PHP 8)

XSLTProcessor::setProfiling — Spécifie le fichier de profilage

Description

public XSLTProcessor::setProfiling(?string $filename): true

Spécifie le fichier de sortie contenant les informations de profilage lors de l'exécution d'une feuille de style.

Liste de paramètres

filename

Chemin vers le fichier pour décharger les informations de profilage.

Valeurs de retour

Retourne toujours true.

Exemples

Exemple #1 Exemple d'utilisation du profilage

<?php
// Chargement de la source XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configuration du transformateur
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // attachement des règles xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

Le code ci-dessus produira les informations suivantes dans le fichier de profilage :

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.


Définit les préférences de sécurité

  • « XSLTProcessor::setProfiling
  • XSLTProcessor::transformToDoc »
  • PHP Manual
  • XSLTProcessor
  • Définit les préférences de sécurité

XSLTProcessor::setSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::setSecurityPrefs — Définit les préférences de sécurité

Description

public XSLTProcessor::setSecurityPrefs(int $preferences): int

Définit les préférences de sécurité.

Liste de paramètres

preferences

Les nouvelles préférences de sécurité. Les constantes suivantes peuvent être combinées : 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.

Valeurs de retour

Retourne les anciennes préférences de sécurité

User Contributed Notes

There are no user contributed notes for this page.


Transforme en un document

  • « XSLTProcessor::setSecurityPrefs
  • XSLTProcessor::transformToUri »
  • PHP Manual
  • XSLTProcessor
  • Transforme en un document

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDoc — Transforme en un document

Description

public XSLTProcessor::transformToDoc(object $document, ?string $returnClass = null): object|false

Transforme le nœud source en un document (par ex. DOMDocument) en y appliquant la feuille de style donnée par la méthode XSLTProcessor::importStylesheet().

Liste de paramètres

document

L'objet DOMDocument ou SimpleXMLElement ou un objet libxml-compatible à transformer.

returnClass

Ce paramètre facultatif peut être utilisé afin que XSLTProcessor::transformToDoc() renvoie un objet de la classe spécifiée. Cette classe doit soit étendre la classe de document, soit être la même classe que celle de document.

Valeurs de retour

Le document résultant ou false si une erreur survient.

Exemples

Exemple #1 Transformation en un document DOM

<?php

// Chargement de la source XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configuration du transformateur
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attachement des règles xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

L'exemple ci-dessus va afficher :

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

Voir aussi

  • XSLTProcessor::transformToUri() - Transforme en URI
  • XSLTProcessor::transformToXml() - Transformer en 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.


Transforme en URI

  • « XSLTProcessor::transformToDoc
  • XSLTProcessor::transformToXml »
  • PHP Manual
  • XSLTProcessor
  • Transforme en URI

XSLTProcessor::transformToUri

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToUri — Transforme en URI

Description

public XSLTProcessor::transformToUri(object $document, string $uri): int

Transforme le nœud source en une URI en y appliquant la feuille de style donnée par la méthode XSLTProcessor::importStylesheet().

Liste de paramètres

document

L'objet DOMDocument ou SimpleXMLElement à transformer.

uri

L'URL pour la transformation.

Valeurs de retour

Retourne le nombre d'octets écrits ou false si une erreur survient.

Exemples

Exemple #1 Transformation en un fichier HTML

<?php

// Chargement du source XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configuration du transformateur
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attachement des règles xsl

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

Voir aussi

  • XSLTProcessor::transformToDoc() - Transforme en un document
  • XSLTProcessor::transformToXml() - Transformer en 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();
?>


Transformer en XML

  • « XSLTProcessor::transformToUri
  • Extensions GUI »
  • PHP Manual
  • XSLTProcessor
  • Transformer en XML

XSLTProcessor::transformToXml

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToXml — Transformer en XML

Description

public XSLTProcessor::transformToXml(object $document): string|null|false

Transforme le nœud source en une chaîne en y appliquant une feuille de style donnée par la méthode xsltprocessor::importStylesheet().

Liste de paramètres

document

L'objet DOMDocument ou SimpleXMLElement à transformer.

Valeurs de retour

Le résultat de la transformation en tant que chaîne de caractères ou false si une erreur survient.

Exemples

Exemple #1 Transformation en une chaîne

<?php

// CHargement du source XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configuration du transformateur
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attachement des règles xsl

echo $proc->transformToXML($xml);

?>

L'exemple ci-dessus va afficher :

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>

Voir aussi

  • XSLTProcessor::transformToDoc() - Transforme en un document
  • XSLTProcessor::transformToUri() - Transforme en 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=Windows-1252">

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.


Extensions GUI

  • UI
    • Introduction
    • Installation/Configuration
    • UI\Point — Represents a position (x,y)
    • UI\Size — Represents dimensions (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 Fonctions
    • 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

  • Introduction
  • Installation/Configuration
    • Pré-requis
    • Installation
  • 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 dimensions (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 — Affiche un message d'erreur
    • 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 Fonctions
    • UI\Draw\Text\Font\fontFamilies — Récupére les familles de polices
    • UI\quit — Quitte la boucle UI
    • UI\run — Entre dans la boucle 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.


Introduction

Cette extension encapsule libui afin de fournir une API OO pour le développement multi-plateforme d’interfaces utilisateur ayant un aspect natif.

User Contributed Notes

There are no user contributed notes for this page.


Installation/Configuration

Sommaire

  • Pré-requis
  • Installation

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


Pré-requis

L'installation nécessite la bibliothèque libui et PHP 7 ou une version plus récente.

Cette extension nécessite l'installation de » la bibliothèque libui version 0.1.0 ou une version plus récente. Consultez la documentation libui pour obtenir une liste des prérequis.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Cette extension » PECL n'est pas intégrée à PHP.

Des informations sur l'installation de ces extensions PECL peuvent être trouvées dans le chapitre du manuel intitulé Installation des extensions PECL. D'autres informations comme les notes sur les nouvelles versions, les téléchargements, les sources des fichiers, les informations concernant les mainteneurs ainsi qu'un CHANGELOG, peuvent être trouvées ici : » https://pecl.php.net/package/ui.

Les binaires Windows (les fichiers DLL) pour cette extension PECL sont disponibles sur le site web PECL.

User Contributed Notes

There are no user contributed notes for this page.


Represents a position (x,y)

(UI 0.9.9)

Introduction

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

Synopsis de la classe

final class UI\Point {
/* Propriétés */
public $x;
public $y;
/* Constructor */
public __construct(float $x, float $y)
/* Méthodes */
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)
}

Propriétés

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Sommaire

  • 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

Description

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

Liste de paramètres

point

The value for x and y

size

The Size to convert

Valeurs de retour

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

Description

public UI\Point::__construct(float $x, float $y)

Construct a new Point using new co-ordinates

Liste de paramètres

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

Description

public UI\Point::getX(): float

Retrieves the X co-ordinate

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Point::getY(): float

Retrieves the Y co-ordinate

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Point::setX(float $point)

Set the X co-ordinate

Liste de paramètres

point

The new X co-ordinate

Valeurs de retour

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

Description

public UI\Point::setY(float $point)

Set the Y co-ordinate

Liste de paramètres

point

The new Y co-ordinate

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Represents dimensions (width, height)

(UI 0.9.9)

Introduction

Sizes are used throughout UI to represent the size of a screen, control, or area.

Synopsis de la classe

final class UI\Size {
/* Propriétés */
public $width;
public $height;
/* Constructor */
public __construct(float $width, float $height)
/* Méthodes */
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)
}

Propriétés

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Sommaire

  • 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

Description

public UI\Size::__construct(float $width, float $height)

Construct a new Size using new width and height

Liste de paramètres

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

Description

public UI\Size::getHeight(): float

Retrieves the Height

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Size::getWidth(): float

Retrieves the Width

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

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

Liste de paramètres

size

The value for width and height

point

The Point to convert

Valeurs de retour

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

Description

public UI\Size::setHeight(float $size)

Set new Height

Liste de paramètres

size

The new Height

Valeurs de retour

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

Description

public UI\Size::setWidth(float $size)

Set new Width

Liste de paramètres

size

The new Width

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Window

(UI 0.9.9)

Introduction

Represents a UI Window

Synopsis de la classe

class UI\Window extends UI\Control {
/* Propriétés */
protected $controls;
/* Constructor */
public __construct(string $title, Size $size, bool $menu = false)
/* Méthodes */
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)
/* Méthodes héritées */
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()
}

Propriétés

controls

Contains controls, should not be manipulated directly

Sommaire

  • UI\Window::add — Add a Control
  • UI\Window::__construct — Construct a new Window
  • UI\Window::error — Affiche un message d'erreur
  • 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

Description

public UI\Window::add(UI\Control $control)

Shall add a Control to this Window

Liste de paramètres

control

The Control to add

Valeurs de retour

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

Description

public UI\Window::__construct(string $title, Size $size, bool $menu = false)

Shall construct a new Window

Liste de paramètres

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.


Affiche un message d'erreur

  • « UI\Window::__construct
  • UI\Window::getSize »
  • PHP Manual
  • UI\Window
  • Affiche un message d'erreur

UI\Window::error

(UI 0.9.9)

UI\Window::error — Affiche un message d'erreur

Description

public UI\Window::error(string $title, string $msg)

Devrait montrer un message d'erreur

Liste de paramètres

title

Titre du message d'erreur

msg

Message d'erreur

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

Description

public UI\Window::getSize(): UI\Size

Shall return the size of this Window

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::getTitle(): string

Shall retrieve the title of this Window

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::hasBorders(): bool

Shall detect if borders are used on this Window

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::hasMargin(): bool

Shall detect if margins are used on this Window

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::isFullScreen(): bool

Shall detect if this Window us using the whole screen

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::msg(string $title, string $msg)

Shall show a message box

Liste de paramètres

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

Description

protected UI\Window::onClosing(): int

Should gracefully destroy this Window

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::open(): string

Shall show an open file dialog

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::save(): string

Shall show a save dialog

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Window::setBorders(bool $borders)

Shall enable or disable the use of borders on this Window

Liste de paramètres

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

Description

public UI\Window::setFullScreen(bool $full)

Shall enable or disable the use of the full screen for this Window

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

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

Description

public UI\Window::setMargin(bool $margin)

Shall enable or disable the use of margins for this Window

Liste de paramètres

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

Description

public UI\Window::setSize(UI\Size $size)

Shall set the size of this Window

Liste de paramètres

size

Valeurs de retour

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

Description

public UI\Window::setTitle(string $title)

Shall set the title for this Window

Liste de paramètres

title

The new title

User Contributed Notes

There are no user contributed notes for this page.


Control

(UI 0.9.9)

Introduction

This is the closed base class for all UI Controls.

Synopsis de la classe

final class UI\Control {
/* Méthodes */
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()
}

Sommaire

  • 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

Description

public UI\Control::destroy()

Shall destroy this Control

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::disable()

Shall disable this Control

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::enable()

Shall enable this Control

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::getParent(): UI\Control

Shall return the parent Control

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::getTopLevel(): int

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::hide()

Shall hide this Control

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::isEnabled(): bool

Shall detect if this Control is enabled

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::isVisible(): bool

Shall detect if this Control is visible

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Control::setParent(UI\Control $parent)

Shall set the parent Control of this Control

Liste de paramètres

parent

The parent Control

Valeurs de retour

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

Description

public UI\Control::show()

Shall show this Control

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Menu

(UI 0.9.9)

Introduction

Menus must be constructed before the first Window, and can be shown on any Window

Synopsis de la classe

class UI\Menu {
/* Constructor */
public __construct(string $name)
/* Méthodes */
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()
}

Sommaire

  • 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

Description

public UI\Menu::append(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a new Menu Item

Liste de paramètres

name

The name (text) for the new item

type

The type for the new item

Valeurs de retour

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

Description

public UI\Menu::appendAbout(string $type = UI\MenuItem::class): UI\MenuItem

Shall append an About menu item

Liste de paramètres

type

The type for the new item

Valeurs de retour

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

Description

public UI\Menu::appendCheck(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a checkable menu item

Liste de paramètres

name

The name (text) for the new item

type

The type for the new item

Valeurs de retour

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

Description

public UI\Menu::appendPreferences(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Preferences menu item

Liste de paramètres

type

The type for the new item

Valeurs de retour

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

Description

public UI\Menu::appendQuit(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Quit menu item

Liste de paramètres

type

The type for the new item

Valeurs de retour

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

Description

public UI\Menu::appendSeparator()

Shall append a separator

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Menu::__construct(string $name)

Shall construct a new Menu

Liste de paramètres

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)

Introduction

Menu Items should only be created by the Menu

Synopsis de la classe

class UI\MenuItem {
/* Méthodes */
public disable()
public enable()
public isChecked(): bool
protected onClick()
public setChecked(bool $checked)
}

Sommaire

  • 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

Description

public UI\MenuItem::disable()

Shall disable this Menu Item

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\MenuItem::enable()

Shall enable this Menu Item

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\MenuItem::isChecked(): bool

Shall detect if this Menu Item is checked

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\MenuItem::onClick()

Shall be executed when this Menu Item is clicked

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\MenuItem::setChecked(bool $checked)

Shall set the checked status of this Menu Item

Liste de paramètres

checked

The new status

User Contributed Notes

There are no user contributed notes for this page.


Area

(UI 0.9.9)

Introduction

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

Synopsis de la classe

class UI\Area extends UI\Control {
/* Constantes */
const int Ctrl;
const int Alt;
const int Shift;
const int Super;
const int Down;
const int Up;
/* Méthodes */
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)
/* Méthodes héritées */
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()
}

Constantes pré-définies

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

Sommaire

  • 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

Description

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

Liste de paramètres

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

Description

protected UI\Area::onKey(string $key, int $ext, int $flags)

Shall be executed on key events

Liste de paramètres

key

The key pressed

ext

The extended key pressed

flags

Event modifiers

Valeurs de retour

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

Description

protected UI\Area::onMouse(UI\Point $areaPoint, UI\Size $areaSize, int $flags)

Shall be executed on mouse events

Liste de paramètres

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

Description

public UI\Area::redraw()

Requests that this Area is redrawn

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Area::scrollTo(UI\Point $point, UI\Size $size)

Scroll this Area

Liste de paramètres

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

Description

public UI\Area::setSize(UI\Size $size)

Sets the size of this Area

Liste de paramètres

size

The new size

User Contributed Notes

There are no user contributed notes for this page.


Execution Scheduler

(UI 2.0.0)

Introduction

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

Synopsis de la classe

abstract class UI\Executor {
/* Constructor */
public __construct()
public __construct(int $microseconds)
public __construct(int $seconds, int $microseconds)
/* Méthodes */
public kill(): void
abstract protected onExecute(): void
public setInterval(int $microseconds): bool
public setInterval(int $seconds, int $microseconds): bool
}

Sommaire

  • 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

Description

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

Liste de paramètres

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

Description

public UI\Executor::kill(): void

Shall stop an executor, the executor cannot be restarted

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

abstract protected UI\Executor::onExecute(): void

Shall be repetitively queued for execution in the main thread

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

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

Liste de paramètres

seconds

microseconds

Valeurs de retour

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Tab Control

(UI 0.9.9)

Introduction

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

Synopsis de la classe

class UI\Controls\Tab extends UI\Control {
/* Propriétés */
protected $controls;
/* Méthodes */
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)
/* Méthodes héritées */
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()
}

Propriétés

controls

Contains controls, should not be manipulated directly

Sommaire

  • 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

Description

public UI\Controls\Tab::append(string $name, UI\Control $control): int

Append a new page to this Tab

Liste de paramètres

name

The name for the new page

control

The control for the new page

Valeurs de retour

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

Description

public UI\Controls\Tab::delete(int $index): bool

Shall remove the selected page from this Tab

Liste de paramètres

index

The index of the page to remove

Valeurs de retour

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

Description

public UI\Controls\Tab::hasMargin(int $page): bool

Shall detect if the given page has a margin.

Liste de paramètres

page

The index of the page

Valeurs de retour

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

Description

public UI\Controls\Tab::insertAt(string $name, int $page, UI\Control $control)

Shall insert a new page into this Tab

Liste de paramètres

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

Description

public UI\Controls\Tab::pages(): int

Shall return the number of pages in this Tab

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Controls\Tab::setMargin(int $page, bool $margin)

Shall enable or disable margins on the selected page

Liste de paramètres

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)

Introduction

A Check is a labelled checkable box

Synopsis de la classe

class UI\Controls\Check extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Méthodes */
public getText(): string
public isChecked(): bool
protected onToggle()
public setChecked(bool $checked)
public setText(string $text)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Check::__construct(string $text)

Shall construct a new Check

Liste de paramètres

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

Description

public UI\Controls\Check::getText(): string

Shall return the text (label) for this Check

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Controls\Check::isChecked(): bool

Shall detect the status of this Check

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\Controls\Check::onToggle()

Shall be executed when the status of this Check is changed

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Check::setChecked(bool $checked)

Shall change the status of this Check

Liste de paramètres

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

Description

public UI\Controls\Check::setText(string $text)

Shall set the text (label) for this Check

Liste de paramètres

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


Button Control

(UI 0.9.9)

Introduction

Represents a labelled clickable button

Synopsis de la classe

class UI\Controls\Button extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Méthodes */
public getText(): string
protected onClick()
public setText(string $text)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Button::__construct(string $text)

Shall construct a new Button

Liste de paramètres

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

Description

public UI\Controls\Button::getText(): string

Shall retrieve the text (label) for this Button

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

protected UI\Controls\Button::onClick()

Shall be executed when this Button is clicked

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Button::setText(string $text)

Shall set the text (label) for this Button

Liste de paramètres

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


ColorButton Control

(UI 0.9.9)

Introduction

A Color Button is a button which displays a color picker when clicked

Synopsis de la classe

class UI\Controls\ColorButton extends UI\Control {
/* Méthodes */
public getColor(): UI\Color
protected onChange()
public setColor(UI\Draw\Color $color)
public setColor(int $color)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\ColorButton::getColor(): UI\Color

Shall retrieve the currently selected Color

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

protected UI\Controls\ColorButton::onChange()

Shall be executed when the selected Color is changed

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\ColorButton::setColor(UI\Draw\Color $color)
public UI\Controls\ColorButton::setColor(int $color)

Shall set the currently selected Color

Liste de paramètres

color

The new color

User Contributed Notes

There are no user contributed notes for this page.


Label Control

(UI 0.9.9)

Introduction

A Label is a single line of text, meant to identify, for the user, some element of the interface.

Synopsis de la classe

class UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Méthodes */
public getText(): string
public setText(string $text)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Label::__construct(string $text)

Shall construct a new Label

Liste de paramètres

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

Description

public UI\Controls\Label::getText(): string

Shall return the current text for this Label

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Controls\Label::setText(string $text)

Shall set the text for this Label

Liste de paramètres

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Entry Control

(UI 0.9.9)

Introduction

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

Synopsis de la classe

class UI\Controls\Entry extends UI\Control {
/* Constantes */
const int Normal;
const int Password;
const int Search;
/* Constructor */
public __construct(int $type = UI\Controls\Entry::Normal)
/* Méthodes */
public getText(): string
public isReadOnly(): bool
protected onChange()
public setReadOnly(bool $readOnly)
public setText(string $text)
/* Méthodes héritées */
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()
}

Constantes pré-définies

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Sommaire

  • 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

Description

public UI\Controls\Entry::__construct(int $type = UI\Controls\Entry::Normal)

Construct a new entry of the given type

Liste de paramètres

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

Description

public UI\Controls\Entry::getText(): string

Shall return the current text from this Entry

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Controls\Entry::isReadOnly(): bool

Shall detect if this Entry is read only

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

protected UI\Controls\Entry::onChange()

Shall be executed when the text in this Entry changes

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Entry::setReadOnly(bool $readOnly)

Shall enable or disable read only for this Entry

Liste de paramètres

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

Description

public UI\Controls\Entry::setText(string $text)

Shall set the text for this Entry

Liste de paramètres

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


MultilineEntry Control

(UI 0.9.9)

Introduction

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

Synopsis de la classe

class UI\Controls\MultilineEntry extends UI\Control {
/* Constantes */
const int Wrap;
const int NoWrap;
/* Constructor */
public __construct(int $type = ?)
/* Méthodes */
public append(string $text)
public getText(): string
public isReadOnly(): bool
protected onChange()
public setReadOnly(bool $readOnly)
public setText(string $text)
/* Méthodes héritées */
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()
}

Constantes pré-définies

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Sommaire

  • 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

Description

public UI\Controls\MultilineEntry::append(string $text)

Shall append the given text to the text in this Multiline Entry

Liste de paramètres

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

Description

public UI\Controls\MultilineEntry::__construct(int $type = ?)

Shall construct a new Multiline Entry of the given type

Liste de paramètres

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

Description

public UI\Controls\MultilineEntry::getText(): string

Shall return the text in this Multiline Entry

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\MultilineEntry::isReadOnly(): bool

Shall detect if this Multiline Entry is read only

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\Controls\MultilineEntry::onChange()

Shall be executed when the text in this Multiline Entry is changed

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\MultilineEntry::setReadOnly(bool $readOnly)

Shall enable or disable read only on this Multiline Entry

Liste de paramètres

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

Description

public UI\Controls\MultilineEntry::setText(string $text)

Shall set the text in this Multiline Entry

Liste de paramètres

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Spin Control

(UI 0.9.9)

Introduction

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

Synopsis de la classe

class UI\Controls\Spin extends UI\Control {
/* Constructor */
public __construct(int $min, int $max)
/* Méthodes */
public getValue(): int
protected onChange()
public setValue(int $value)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Spin::__construct(int $min, int $max)

Constructs a new Spin with the given range

Liste de paramètres

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

Description

public UI\Controls\Spin::getValue(): int

Get the value in this Spin

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\Controls\Spin::onChange()

Shall be executed when the value in this Spin changes

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Spin::setValue(int $value)

Set the value in this Spin

Liste de paramètres

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Slider Control

(UI 0.9.9)

Introduction

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.

Synopsis de la classe

class UI\Controls\Slider extends UI\Control {
/* Constructor */
public __construct(int $min, int $max)
/* Méthodes */
public getValue(): int
protected onChange()
public setValue(int $value)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Slider::__construct(int $min, int $max)

Construct a new Slider with the given range

Liste de paramètres

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

Description

public UI\Controls\Slider::getValue(): int

Get the value from this Slider

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\Controls\Slider::onChange()

Shall be executed when the value of this Slider changes

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Slider::setValue(int $value)

Shall set the value for this Slider

Liste de paramètres

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Progress Control

(UI 0.9.9)

Introduction

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

Synopsis de la classe

class UI\Controls\Progress extends UI\Control {
/* Méthodes */
public getValue(): int
public setValue(int $value)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Progress::getValue(): int

Shall retrieve the current value of this Progress bar

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Progress::setValue(int $value)

Shall set the value for this Progress bar

Liste de paramètres

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)

Introduction

A Separator represents a control separator, it has no other function.

Synopsis de la classe

class UI\Controls\Separator extends UI\Control {
/* Constantes */
const int Horizontal;
const int Vertical;
/* Constructor */
public __construct(int $type = UI\Controls\Separator::Horizontal)
/* Méthodes héritées */
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()
}

Constantes pré-définies

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Sommaire

  • 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

Description

public UI\Controls\Separator::__construct(int $type = UI\Controls\Separator::Horizontal)

Shall construct a new Separator of the given type

Liste de paramètres

type

Separator::Horizonal or Separator::Vertical

User Contributed Notes

There are no user contributed notes for this page.


Combo Control

(UI 0.9.9)

Introduction

A Combo control represents a list of options, like the familiar select HTML element.

Synopsis de la classe

class UI\Controls\Combo extends UI\Control {
/* Méthodes */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Combo::append(string $text)

Append an option to this Combo

Liste de paramètres

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

Description

public UI\Controls\Combo::getSelected(): int

Shall retrieve the index of the option selected in this Combo

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\Controls\Combo::onSelected()

Shall be executed when an option is selected in this Combo

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Combo::setSelected(int $index)

Shall set the currently selected option in this Combo

Liste de paramètres

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)

Introduction

An Editable Combo is a Combo which allows the user to enter custom options

Synopsis de la classe

class UI\Controls\EditableCombo extends UI\Control {
/* Méthodes */
public append(string $text)
public getText(): string
protected onChange()
public setText(string $text)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\EditableCombo::append(string $text)

Shall append a new option to this Editable Combo

Liste de paramètres

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

Description

public UI\Controls\EditableCombo::getText(): string

Get the value of the currently selected option in this Editable Combo

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\Controls\EditableCombo::onChange()

Shall be executed when the value of this Editable Combobox changes

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\EditableCombo::setText(string $text)

Shall set the text of the currently selected option in this Editable Combo

Liste de paramètres

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Radio Control

(UI 0.9.9)

Introduction

A Radio is similar to the radio input type familiar from HTML

Synopsis de la classe

class UI\Controls\Radio extends UI\Control {
/* Méthodes */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Méthodes héritées */
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()
}

Sommaire

  • 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

Description

public UI\Controls\Radio::append(string $text)

Shall append a new option to this Radio

Liste de paramètres

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

Description

public UI\Controls\Radio::getSelected(): int

Shall retrieve the index of the currently selected option in this Radio

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

protected UI\Controls\Radio::onSelected()

Shall be executed when the option selected in this Radio changes

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Radio::setSelected(int $index)

Shall set the currently selected option in this Radio

Liste de paramètres

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)

Introduction

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

Synopsis de la classe

class UI\Controls\Picker extends UI\Control {
/* Constantes */
const int Date;
const int Time;
const int DateTime;
/* Constructor */
public __construct(int $type = UI\Controls\Picker::Date)
/* Méthodes héritées */
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()
}

Constantes pré-définies

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Sommaire

  • 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

Description

public UI\Controls\Picker::__construct(int $type = UI\Controls\Picker::Date)

Construct a new Picker of the given type

Liste de paramètres

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)

Introduction

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

Synopsis de la classe

class UI\Controls\Form extends UI\Control {
/* Propriétés */
protected $controls;
/* Méthodes */
public append(string $label, UI\Control $control, bool $stretchy = false): int
public delete(int $index): bool
public isPadded(): bool
public setPadded(bool $padded)
/* Méthodes héritées */
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()
}

Propriétés

controls

Contains controls, should not be manipulated directly

Sommaire

  • 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

Description

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

Liste de paramètres

label

The text for the label

control

A control

stretchy

Should be set true to stretch the control

Valeurs de retour

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

Description

public UI\Controls\Form::delete(int $index): bool

Shall delete the control at the given index in this Form

Liste de paramètres

index

The index of the control to remove

Valeurs de retour

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

Description

public UI\Controls\Form::isPadded(): bool

Shall detect if padding is enabled on this Form

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Form::setPadded(bool $padded)

Shall enable or disable padding on this Form

Liste de paramètres

padded

User Contributed Notes

There are no user contributed notes for this page.


Control Grid (Arrangement)

(UI 0.9.9)

Introduction

A Grid is a control which is allows the arrangement of children into a grid

Synopsis de la classe

class UI\Controls\Grid extends UI\Control {
/* Constantes */
const int Fill;
const int Start;
const int Center;
const int End;
const int Leading;
const int Top;
const int Trailing;
const int Bottom;
/* Propriétés */
protected $controls;
/* Méthodes */
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)
/* Méthodes héritées */
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()
}

Constantes pré-définies

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

Propriétés

controls

Contains controls, should not be manipulated directly

Sommaire

  • 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

Description

public UI\Controls\Grid::append(
UI\Control $control,
int $left,
int $top,
int $xspan,
int $yspan,
bool $hexpand,
int $halign,
bool $vexpand,
int $valign
)

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

Valeurs de retour

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

Description

public UI\Controls\Grid::isPadded(): bool

Shall detect if padding is enabled on this Grid

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Grid::setPadded(bool $padding)

Shall enable or disable padding for this Grid

Liste de paramètres

padding

User Contributed Notes

There are no user contributed notes for this page.


Control Group (Arrangement)

(UI 0.9.9)

Introduction

A Group is a titled container for child controls

Synopsis de la classe

class UI\Controls\Group extends UI\Control {
/* Propriétés */
protected $controls;
/* Constructor */
public __construct(string $title)
/* Méthodes */
public append(UI\Control $control)
public getTitle(): string
public hasMargin(): bool
public setMargin(bool $margin)
public setTitle(string $title)
/* Méthodes héritées */
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()
}

Propriétés

controls

Contains controls, should not be manipulated directly

Sommaire

  • 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

Description

public UI\Controls\Group::append(UI\Control $control)

Shall append a control to this Group

Liste de paramètres

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

Description

public UI\Controls\Group::__construct(string $title)

Shall construct a new Group with the given title

Liste de paramètres

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

Description

public UI\Controls\Group::getTitle(): string

Shall return the current title for this Group

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Controls\Group::hasMargin(): bool

Shall detect if this Group has a margin

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Group::setMargin(bool $margin)

Shall enable or disable margins for this Group

Liste de paramètres

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

Description

public UI\Controls\Group::setTitle(string $title)

Shall set the title for this Group

Liste de paramètres

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)

Introduction

A Box allows the arrangement of other controls

Synopsis de la classe

class UI\Controls\Box extends UI\Control {
/* Constantes */
const int Vertical;
const int Horizontal;
/* Propriétés */
protected $controls;
/* Constructor */
public __construct(int $orientation = UI\Controls\Box::Horizontal)
/* Méthodes */
public append(Control $control, bool $stretchy = false): int
public delete(int $index): bool
public getOrientation(): int
public isPadded(): bool
public setPadded(bool $padded)
/* Méthodes héritées */
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()
}

Propriétés

controls

Contains controls, should not be manipulated directly

Constantes pré-définies

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Sommaire

  • 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

Description

public UI\Controls\Box::append(Control $control, bool $stretchy = false): int

Shall append the given control to this Box

Liste de paramètres

control

The control to append

stretchy

Set true to stretch the control

Valeurs de retour

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

Description

public UI\Controls\Box::__construct(int $orientation = UI\Controls\Box::Horizontal)

Shall construct a new box

Liste de paramètres

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

Description

public UI\Controls\Box::delete(int $index): bool

Shall delete the control at the given index from this Box

Liste de paramètres

index

The index of the control to delete

Valeurs de retour

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

Description

public UI\Controls\Box::getOrientation(): int

Shall retrieve the orientation of this Box

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Box::isPadded(): bool

Shall detect if padding is enabled on this Box

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Controls\Box::setPadded(bool $padded)

Shall enable or disable padding on this Box

Liste de paramètres

padded

User Contributed Notes

There are no user contributed notes for this page.


Draw Pen

(UI 0.9.9)

Introduction

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

Synopsis de la classe

final class UI\Draw\Pen {
/* Méthodes */
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)
}

Sommaire

  • 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

Description

public UI\Draw\Pen::clip(UI\Draw\Path $path)

Shall clip the given Path

Liste de paramètres

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

Description

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

Liste de paramètres

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

Description

public UI\Draw\Pen::restore()

Shall restore a previously saved Pen

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Draw\Pen::save()

Shall save the Pen

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

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

Liste de paramètres

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

Description

public UI\Draw\Pen::transform(UI\Draw\Matrix $matrix)

Shall perform matrix transformation

Liste de paramètres

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

Description

public UI\Draw\Pen::write(UI\Point $point, UI\Draw\Text\Layout $layout)

Shall draw the given text layout at the given point

Liste de paramètres

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)

Introduction

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

Synopsis de la classe

class UI\Draw\Path {
/* Constantes */
const int Winding;
const int Alternate;
/* Constructor */
public __construct(int $mode = UI\Draw\Path::Winding)
/* Méthodes */
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
)
}

Constantes pré-définies

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Sommaire

  • 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

Description

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

Liste de paramètres

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

Description

public UI\Draw\Path::arcTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for an arc

Liste de paramètres

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

Valeurs de retour

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

Description

public UI\Draw\Path::bezierTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall draw a bezier curve

Liste de paramètres

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

Description

public UI\Draw\Path::closeFigure()

Shall close the current figure

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Draw\Path::__construct(int $mode = UI\Draw\Path::Winding)

Shall construct a new path in the given mode

Liste de paramètres

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

Description

public UI\Draw\Path::end()

Shall finalize this Path

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Draw\Path::lineTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for a line

Liste de paramètres

point

The point to begin mapping

radius

angle

sweep

negative

Valeurs de retour

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

Description

public UI\Draw\Path::newFigure(UI\Point $point)

Shall map a new figure at the given point

Liste de paramètres

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

Description

public UI\Draw\Path::newFigureWithArc(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Liste de paramètres

point

radius

angle

sweep

negative

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Draw Matrix

(UI 0.9.9)

Introduction

Synopsis de la classe

class UI\Draw\Matrix {
/* Méthodes */
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)
}

Sommaire

  • 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

Description

public UI\Draw\Matrix::invert()

Shall invert this matrix

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Draw\Matrix::isInvertible(): bool

Shall detect if this Matrix may be inverted

Liste de paramètres

Cette fonction ne contient aucun paramètre.

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

Description

public UI\Draw\Matrix::multiply(UI\Draw\Matrix $matrix): UI\Draw\Matrix

Shall multiply this matrix with the given matrix

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Matrix::rotate(UI\Point $point, float $amount)

Shall rotate this Matrix

Liste de paramètres

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

Description

public UI\Draw\Matrix::scale(UI\Point $center, UI\Point $point)

Shall scale this Matrix

Liste de paramètres

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

Description

public UI\Draw\Matrix::skew(UI\Point $point, UI\Point $amount)

Shall skew this Matrix

Liste de paramètres

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

Description

public UI\Draw\Matrix::translate(UI\Point $point)

Shall translate this Matrix

Liste de paramètres

point

User Contributed Notes

There are no user contributed notes for this page.


Color Representation

(UI 0.9.9)

Introduction

Represents RGBA colours, individual channels are accessible via public properties.

Synopsis de la classe

class UI\Draw\Color {
/* Constantes */
const int Red;
const int Green;
const int Blue;
const int Alpha;
/* Propriétés */
public $r;
public $g;
public $b;
public $a;
/* Constructor */
public __construct(UI\Draw\Color $color = ?)
public __construct(int $color = ?)
/* Méthodes */
public getChannel(int $channel): float
public setChannel(int $channel, float $value): void
}

Propriétés

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

Constantes pré-définies

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

Sommaire

  • 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

Description

public UI\Draw\Color::__construct(UI\Draw\Color $color = ?)
public UI\Draw\Color::__construct(int $color = ?)

Shall construct a new color

Liste de paramètres

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

Description

public UI\Draw\Color::getChannel(int $channel): float

Shall retrieve the value for a channel

Liste de paramètres

channel

Constant channel identity

Valeurs de retour

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

Description

public UI\Draw\Color::setChannel(int $channel, float $value): void

Shall set the selected channel to the given value

Liste de paramètres

channel

Constant channel identity

value

The new value for the selected channel

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Draw Stroke

(UI 0.9.9)

Introduction

Holds the configuration for the Pen to perform a stroke

Synopsis de la classe

class 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
)
/* Méthodes */
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)
}

Sommaire

  • 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

Description

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

Liste de paramètres

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

Description

public UI\Draw\Stroke::getCap(): int

Shall retrieve the line cap setting of this Stroke

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Stroke::getJoin(): int

Shall retrieve the line join setting of this Stroke

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Stroke::getMiterLimit(): float

Shall retrieve the miter limit of this Stroke

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Stroke::getThickness(): float

Shall retrieve the thickness of this Stroke

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Stroke::setCap(int $cap)

Shall set the line cap setting for this Stroke

Liste de paramètres

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

Description

public UI\Draw\Stroke::setJoin(int $join)

Shall set the line join setting for this Stroke

Liste de paramètres

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

Valeurs de retour

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

Description

public UI\Draw\Stroke::setMiterLimit(float $limit)

Set the miter limit for this Stroke

Liste de paramètres

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

Description

public UI\Draw\Stroke::setThickness(float $thickness)

Shall set the thickness for this Stroke

Liste de paramètres

thickness

The new thickness

User Contributed Notes

There are no user contributed notes for this page.


Brushes

(UI 0.9.9)

Introduction

Represents a solid color brush

Synopsis de la classe

class UI\Draw\Brush {
/* Constructor */
public __construct(UI\Draw\Color $color)
public __construct(int $color)
/* Méthodes */
public getColor(): UI\Draw\Color
public setColor(UI\Draw\Color $color): void
public setColor(int $color): void
}

Sommaire

  • 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

Description

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

Liste de paramètres

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

Description

public UI\Draw\Brush::getColor(): UI\Draw\Color

Shall return a UI\Draw\Color for this brush

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

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

Liste de paramètres

color

Can be a UI\Draw\Color or RRGGBBAA

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Gradient Brushes

(UI 2.0.0)

Introduction

Abstract for gradient brushes

Synopsis de la classe

abstract class UI\Draw\Brush\Gradient extends UI\Draw\Brush {
/* Méthodes */
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
/* Méthodes héritées */
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
}

Sommaire

  • 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

Description

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

Liste de paramètres

position

The position for the new stop

color

The color for the new stop, may be UI\Draw\Color or RRGGBBAA

Valeurs de retour

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

Description

public UI\Draw\Brush\Gradient::delStop(int $index): int

Avertissement

Cette fonction est actuellement non documentée ; seule la liste des arguments est disponible.

Liste de paramètres

index

Valeurs de retour

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

Description

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

Liste de paramètres

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

Valeurs de retour

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Linear Gradient

(UI 2.0.0)

Introduction

Synopsis de la classe

class UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $end)
/* Méthodes héritées */
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
}

Sommaire

  • 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

Description

public UI\Draw\Brush\LinearGradient::__construct(UI\Point $start, UI\Point $end)

Shall construct a new linear gradient

Liste de paramètres

start

end

User Contributed Notes

There are no user contributed notes for this page.


Radial Gradient

(UI 2.0.0)

Introduction

Synopsis de la classe

class UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $outer, float $radius)
/* Méthodes héritées */
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
}

Sommaire

  • 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

Description

public UI\Draw\Brush\RadialGradient::__construct(UI\Point $start, UI\Point $outer, float $radius)

Shall construct a new radial gradient

Liste de paramètres

start

outer

radius

User Contributed Notes

There are no user contributed notes for this page.


Represents Text Layout

(UI 0.9.9)

Introduction

A Text Layout represents the layout of text which will be drawn by the Pen

Synopsis de la classe

class UI\Draw\Text\Layout {
/* Constructor */
public __construct(string $text, UI\Draw\Text\Font $font, float $width)
/* Méthodes */
public setColor(UI\Draw\Color $color, int $start = 0, int $end = ?)
public setColor(int $color, int $start = 0, int $end = ?)
public setWidth(float $width)
}

Sommaire

  • 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

Description

public UI\Draw\Text\Layout::__construct(string $text, UI\Draw\Text\Font $font, float $width)

Shall construct a new Text Layout

Liste de paramètres

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

Description

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

Liste de paramètres

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

Description

public UI\Draw\Text\Layout::setWidth(float $width)

Shall set the width of this Text Layout

Liste de paramètres

width

The new width

User Contributed Notes

There are no user contributed notes for this page.


Represents a Font

(UI 0.9.9)

Introduction

Loads a described font

Synopsis de la classe

class UI\Draw\Text\Font {
/* Constructor */
public __construct(UI\Draw\Text\Font\Descriptor $descriptor)
/* Méthodes */
public getAscent(): float
public getDescent(): float
public getLeading(): float
public getUnderlinePosition(): float
public getUnderlineThickness(): float
}

Sommaire

  • 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

Description

public UI\Draw\Text\Font::__construct(UI\Draw\Text\Font\Descriptor $descriptor)

Shall construct a new Font using the given descriptor

Liste de paramètres

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

Description

public UI\Draw\Text\Font::getAscent(): float

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Text\Font::getDescent(): float

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Text\Font::getLeading(): float

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Text\Font::getUnderlinePosition(): float

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Text\Font::getUnderlineThickness(): float

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Font Descriptor

(UI 0.9.9)

Introduction

Describes a font

Synopsis de la classe

class 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
)
/* Méthodes */
public getFamily(): string
public getItalic(): int
public getSize(): float
public getStretch(): int
public getWeight(): int
}

Sommaire

  • 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

Description

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

Liste de paramètres

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

Description

public UI\Draw\Text\Font\Descriptor::getFamily(): string

Shall return the requested font family

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Text\Font\Descriptor::getItalic(): int

Shall return constant setting

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Text\Font\Descriptor::getSize(): float

Shall return the requested size

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

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

Description

public UI\Draw\Text\Font\Descriptor::getStretch(): int

Shall return requested stretch

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Weight Detection

  • « UI\Draw\Text\Font\Descriptor::getStretch
  • UI Fonctions »
  • 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

Description

public UI\Draw\Text\Font\Descriptor::getWeight(): int

Shall return requested weight

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


UI Fonctions

Sommaire

  • UI\Draw\Text\Font\fontFamilies — Récupére les familles de polices
  • UI\quit — Quitte la boucle UI
  • UI\run — Entre dans la boucle UI

User Contributed Notes

There are no user contributed notes for this page.


Récupére les familles de polices

  • « UI Fonctions
  • UI\quit »
  • PHP Manual
  • UI Fonctions
  • Récupére les familles de polices

UI\Draw\Text\Font\fontFamilies

(UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Récupére les familles de polices

Description

UI\Draw\Text\Font\fontFamilies(): array

Retourne un tableau des familles de polices valide pour le système actuel

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne un tableau des familles de polices valide pour le système actuel.

User Contributed Notes

There are no user contributed notes for this page.


Quitte la boucle UI

  • « UI\Draw\Text\Font\fontFamilies
  • UI\run »
  • PHP Manual
  • UI Fonctions
  • Quitte la boucle UI

UI\quit

(UI 2.0.0)

UI\quit — Quitte la boucle UI

Description

UI\quit(): void

Doit faire arrêter la boucle principale

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Entre dans la boucle UI

  • « UI\quit
  • UI\Draw\Text\Font\Weight »
  • PHP Manual
  • UI Fonctions
  • Entre dans la boucle UI

UI\run

(UI 2.0.0)

UI\run — Entre dans la boucle UI

Description

UI\run(int $flags = ?): void

Doit pousser PHP à entrer dans la boucle principale. Par défaut, le contrôle ne sera pas retourné à la fonction appelante.

Liste de paramètres

flags

Mettre UI\Loop pour retourner le contrôle et UI\Wait pour retourner le contrôle après l'attente.

Valeurs de retour

User Contributed Notes

There are no user contributed notes for this page.


Font Weight Settings

(UI 0.9.9)

Introduction

Synopsis de la classe

final class UI\Draw\Text\Font\Weight {
/* Constantes */
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)

Introduction

Synopsis de la classe

final class UI\Draw\Text\Font\Italic {
/* Constantes */
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)

Introduction

Synopsis de la classe

final class UI\Draw\Text\Font\Stretch {
/* Constantes */
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)

Introduction

Synopsis de la classe

final class UI\Draw\Line\Cap {
/* Constantes */
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)

Introduction

Synopsis de la classe

final class UI\Draw\Line\Join {
/* Constantes */
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)

Introduction

Synopsis de la classe

final class UI\Key {
/* Constantes */
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)

Introduction

Synopsis de la classe

class UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes héritées */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


RuntimeException

(UI 1.0.3)

Introduction

Synopsis de la classe

class UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Propriétés héritées */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Méthodes héritées */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


FAQ : foire Aux Questions

  • Informations générales
  • Listes de diffusion — Listes de diffusions
  • Obtenir PHP
  • Considérations sur les bases de données
  • Installation
  • Problèmes de compilation
  • Utiliser PHP
  • Hachage de mots de passe — Hachage de mots de passe sûr
  • PHP et HTML
  • PHP et COM
  • Questions diverses

User Contributed Notes

There are no user contributed notes for this page.


Informations générales

Cette section présente les questions les plus fréquentes à propos de PHP : ce qu'est PHP et ce qu'il fait.

  1. Qu'est-ce que PHP ?
  2. Que représente l'acronyme PHP ?
  3. Quelle est la relation entre les versions ?
  4. Puis-je utiliser plusieurs versions de PHP en même temps ?
  5. Je pense avoir trouvé un bogue ! Qui dois-je contacter ?
Qu'est-ce que PHP ?

Depuis la préface de ce manuel :

PHP est un langage de script HTML, exécuté coté serveur. Sa syntaxe est empruntée aux langages C, Java et Perl, et est facile à apprendre. Le but de ce langage est de permettre aux développeurs web d'écrire des pages dynamiques rapidement, mais vous pouvez faire beaucoup plus avec PHP.

Que représente l'acronyme PHP ?

PHP signifie PHP: Hypertext Preprocessor. La confusion vient du fait que la première lettre de l'acronyme représente l'acronyme lui-même. Ce type d'acronyme est appelé un acronyme récursif. Pour plus d'informations, les plus curieux peuvent visiter "» Free On-Line Dictionary of Computing" ou l'» entrée Wikipedia sur les acronymes récursifs.

Quelle est la relation entre les versions ?

PHP/FI 2.0 est une des premières versions de PHP et elle n'est plus supportée. PHP 3 en est son successeur et est beaucoup plus convivial. PHP 8 est la génération actuelle de PHP, qui utilise le moteur Zend 4 qui apporte, entre autres, beaucoup de nouveautés dans le modèle objet.

Puis-je utiliser plusieurs versions de PHP en même temps ?

Oui. Voir le fichier INSTALL inclus dans les sources de PHP.

Je pense avoir trouvé un bogue ! Qui dois-je contacter ?

Vous devriez aller sur la base de données de bogues PHP afin de vous assurer qu'il n'est pas déjà connu. Si vous ne le trouvez pas, utilisez le formulaire de rapport de bogues pour le faire connaître. Il est important d'utiliser la base de données de bogues au lieu d'envoyer simplement un courriel à une des listes de diffusion car le bogue se verra assigner un numéro qui vous sera utile pour suivre son évolution. La base de données de bogues peut être trouvée à » https://github.com/php/php-src/issues.

User Contributed Notes

There are no user contributed notes for this page.


Listes de diffusions

Cette section traite des questions à propos de la communication avec la communauté PHP. Le meilleur moyen est l'utilisation des listes de diffusion.

  1. Existe-t-il des listes de diffusion PHP ?
  2. Y a-t-il d'autres communautés ?
  3. Puis-je mettre en place ma propre liste de diffusion PHP ?
  4. Aidez-moi ! Je ne peux visiblement pas m'inscrire à une / me désinscrire d'une des listes de diffusion !
  5. Y a-t-il une archive des listes de diffusion quelque part ?
  6. Que puis-je demander sur les listes de diffusion ?
  7. Quelle information devrais-je inclure lors de l'écriture de mon message à la liste de diffusion ?
Existe-t-il des listes de diffusion PHP ?

Bien sûr ! Il y a beaucoup de listes de diffusion traitant de beaucoup de sujets. Une liste des listes de diffusion les plus communes peut être trouvée sur cette » page.

La liste de diffusion la plus générale est la liste php-general. Pour s'y inscrire, envoyez un courriel vide à » php-general-subscribe@lists.php.net. Pour se déinscrire, envoyez un courriel vide à » php-general-unsubscribe@lists.php.net.

Vous pouvez également vous inscrire et vous désinscrire en utilisant l'interface web sur cette » page; les instructions pour se désinscrire sont également présentes en bas de chaque courriel de la liste.

Y a-t-il d'autres communautés ?

Il y a énormément de communautés PHP à travers le monde, et nous avons une liste de la plupart des ressources (ainsi que des informations pour en connaître d'autres) sur notre page de » support.

Puis-je mettre en place ma propre liste de diffusion PHP ?

Absolument ! En fait, nous ne faisons pas que l'autoriser, mais nous l'encourageons ! Le fait d'aider les autres en partageant ses compétences et son expérience de PHP aide dans le développement de la communauté PHP mais aussi dans le language en tant que tel.

Aidez-moi ! Je ne peux visiblement pas m'inscrire à une / me désinscrire d'une des listes de diffusion !

Si vous avez des problèmes pour l'inscription/la désinscription depuis la liste de diffusion php-general, cela peut être dû au fait que le logiciel de listes de diffusion n'arrive pas à traiter correctement la liste de diffusion à utiliser. Si votre adresse e-mail est joeblow@example.com, vous pouvez envoyer une requête d'inscription à php-general-subscribe-joeblow=example.com@lists.php.net, ou une requête de désinscription à php-general-unsubscribe-joeblow=example.com@lists.php.net. Utilisez la même méthode avec les autres listes de diffusion.

La plupart du temps, lorsque les utilisateurs rencontrent des problèmes pour se désinscrire d'une liste de diffusion PHP, c'est à cause des courriels redirigés. Par exemple, si votre adresse est danbrown@example.com, mais que vous vous êtes inscrit en utilisant la redirection php-lists@example.com et ensuite, vous redirigez la liste vers danbrown@example.com, le fait de tenter de se désinscrire en utilisant danbrown@example.com ne fonctionnera pas. À la place, vous devez vous désinscrire en utilisant l'adresse recevant les courriels de la liste - dans notre exemple, php-lists@example.com.

Y a-t-il une archive des listes de diffusion quelque part ?

Oui, vous pouvez trouver la liste des sites proposant des archives sur la page des » listes de diffusion. Vous pouvez également trouver plusieurs sites qui archivent ou publient le contenu de nos listes de diffusion en utilisant votre moteur de recherche Internet préféré, en cherchant, par exemple, la chaîne "php mailing list archives".

Tous les messages de nos listes de diffusion sont également archivés dans des newsgroup. Vous pouvez accéder à ces serveurs sur » news://news.php.net/ avec un client adapté. Il y a également une interface web expérimentale pour ces serveurs à l'adresse » http://news.php.net/

Que puis-je demander sur les listes de diffusion ?

PHP devient de plus en plus populaire chaque jour, augmentant ainsi le trafic sur la liste de diffusion php-general qui accueille de 75 à 200 messages chaque jour. Aussi, c'est dans l'intérêt de tous que d'utiliser la liste de diffusion en dernier ressort, lorsque vous avez déjà épuisé toutes les autres voies.

Avant de poster sur cette liste, merci de lire la FAQ (Foire Aux Questions) afin de voir si vous n'y trouvez pas de l'aide. S'il n'y a rien concernant votre problème, essayez dans les archives de la liste de diffusion (voir précédemment). Si vous avez des problèmes pour l'installation ou la configuration de PHP, lisez toute la documentation s'y rapportant, ainsi que les fichiers README. Si vous ne trouvez toujours pas de réponse à votre problème, vous êtes le bienvenu sur la liste de diffusion.

Afin d'avoir la meilleure réponse à votre question (et pour éviter d'agacer les développeurs), assurez-vous de poser votre question sur la liste de diffusion appropriée. Par exemple, si vous avez des difficultés à installer PHP, vous devez poser votre question sur la liste de diffusion php-install. Attention : certaines listes ont des noms similaires, mais des usages totalement différents ; une question vis à vis des scripts PHP sous Windows doit être dirigée vers la liste des utilisateurs PHP sous Windows, et non vers la liste interne Windows.

Avant de poser une question, vous devriez lire l'article intitulé "» Comment poser une question de la meilleur façon" ; c'est une bonne idée, pour tout le monde.

Quelle information devrais-je inclure lors de l'écriture de mon message à la liste de diffusion ?

Les messages comme "Je n'arrive pas à faire fonctionner PHP !! Aidez-moi !! Qu'est-ce qu'il ne va pas ??" sont totalement inutiles, pour tous. Si vous avez des problèmes pour faire fonctionner PHP, vous devez inclure le système sur lequel le problème survient, quelle version de PHP vous tentez de faire fonctionner, sous quelle forme vous l'avez installée (précompilé, Git, RPMs, etc.), qu'est-ce que vous avez fait pour le moment, l'endroit où vous êtes coincé et quel est le message d'erreur.

Cela est valable pour n'importe quel type de problème. Vous devez inclure les informations sur ce que vous avez fait, où vous êtes coincé, ce que vous cherché à faire et, si possible, le message d'erreur obtenu. Si vous avez un problème avec votre code source, vous devez également inclure la portion de code qui ne fonctionne pas. N'incluez que le code nécessaire à la compréhension du problème ! Si vous incluez tout le code, votre message sera difficile à lire et, à cause de cela, beaucoup de personnes passeront sans même le lire. Si vous n'êtes pas sûr sur la quantité d'informations à inclure à votre message, il est préférable d'en mettre trop que pas assez et préparez-vous à fournir d'autres informations.

Un autre point important à ne pas oublier est de résumer votre problème dans l'objet du message. Un objet qui ressemble à "Aidez-moi !!!!" ou "Quel est le souci ici ?" sera ignoré par la majorité des lecteurs.

Et pour finir, vous êtes encouragé à lire l'article sur "» Comment poser une question de la meilleur façon", ce qui sera une aide énorme pour tous, et tout spécialement pour vous.

User Contributed Notes

There are no user contributed notes for this page.


Obtenir PHP

Cette section traite du téléchargement de PHP et les problèmes liés aux systèmes d'exploitation.

  1. Où puis-je obtenir PHP ?
  2. Est-ce que les versions binaires pré-compilées sont disponibles ?
  3. Où puis-je obtenir les bibliothèques dont j'ai besoin pour compiler les extensions optionnelles de PHP ?
  4. Comment faire fonctionner ces bibliothèques ?
  5. J'ai la dernière version du code source de PHP, téléchargée à partir de Git. De quoi ai-je besoin pour le compiler sous Windows ?
  6. Où puis-je trouver le fichier Browser Capabilities ?
  7. Que signifie thread safety lors du téléchargement de PHP?
Où puis-je obtenir PHP ?

Vous pouvez télécharger PHP à partir d'un des membres du réseau de sites PHP. Vous pouvez les trouver sur » https://www.php.net/. Vous pouvez aussi utiliser Git pour obtenir la toute dernière version des sources. Pour plus d'informations, allez sur » https://www.php.net/git.php.

Est-ce que les versions binaires pré-compilées sont disponibles ?

Nous ne les distribuons que pour le système Windows, car nous ne pouvons compiler PHP pour chaque plate-forme Linux/Unix avec toutes les combinaisons d'extensions. Notez aussi que plusieurs distributions Linux fournissent PHP d'office de nos jours. Les binaires Windows peuvent être téléchargés à partir de notre page de » Téléchargement, pour les binaires Linux, visitez le site de votre distribution.

Où puis-je obtenir les bibliothèques dont j'ai besoin pour compiler les extensions optionnelles de PHP ?

Note: Celles marquées d'une étoile (*) ne sont pas thread safe ; nous vous recommandons de ne pas les utiliser en environnement multithreadé.

  • » LDAP (Unix).
  • » LDAP (Unix/Win) : Mozilla Directory (LDAP) SDK
  • » free LDAP server.
  • » Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
  • » SNMP* (Unix): .
  • » GD (Unix/Win).
  • » mSQL* (Unix).
  • » PostgreSQL (Unix).
  • » IMAP* (Win/Unix).
  • » Sybase-CT* (Linux, libc5) : Disponible localement.
  • » FreeType (libttf):.
  • » ZLib (Unix/Win32).
  • » expat XML parser (Unix/Win32).
  • » PDFLib.
  • » mcrypt.
  • » mhash.
  • » t1lib.
  • » dmalloc.
  • » aspell.
  • » readline.

Comment faire fonctionner ces bibliothèques ?

Vous devrez suivre les instructions fournies avec les bibliothèques. Quelques une d'entre elles sont détectées automatiquement lorsque vous exécutez le script 'configure' de PHP (comme la bibliothèque GD), pour les autres, vous devrez les activer en utilisant l'option '--with-EXTENSION' de 'configure'. Exécutez 'configure --help' pour en avoir la liste complète.

J'ai la dernière version du code source de PHP, téléchargée à partir de Git. De quoi ai-je besoin pour le compiler sous Windows ?

Voir le wiki PHP pour les dernières instructions : » Instructions de compilation étape par étape

Où puis-je trouver le fichier Browser Capabilities ?

Vous pouvez trouver un fichier browscap.ini sur » http://browscap.org/.

Que signifie thread safety lors du téléchargement de PHP?

Thread Safety signifie que le binaire peut fonctionner sur des serveurs à contexte multithread comme Apache 2 sous Windows. La sécurité des threads (Thread Safety) fonctionne en créant un espace de stockage local pour chaque thread de telle sorte que les données n'entrent pas en collision entre les threads.

Donc, que choisir? Si vous utilisez PHP comme CGI, alors vous n'avez pas besoin de la sécurité des threads car le binaire est invoqué à chaque requête. Concernant les serveurs multithreads, comme IIS5 et IIS6, vous devriez utiliser la version threadée de PHP.

User Contributed Notes

There are no user contributed notes for this page.


Considérations sur les bases de données

Cette section traite de questions relatives aux relations entre PHP et les bases de données. Oui, PHP peut accéder virtuellement à n'importe quelle base de données disponible aujourd'hui.

  1. J'ai entendu dire qu'il était possible d'accéder à Microsoft SQL Server à partir de PHP. Comment est-ce possible ?
  2. Puis-je accéder à des bases Microsoft Access ?
J'ai entendu dire qu'il était possible d'accéder à Microsoft SQL Server à partir de PHP. Comment est-ce possible ?

Sur les machines UNIX, vous pouvez utiliser PDO_ODBC ou Unified ODBC API.

Sur les machines Windows, vous pouvez également utiliser PDO_SQLSRV ou SQLSRV.

Jetez aussi un oeil à la réponse à la question suivante.

Puis-je accéder à des bases Microsoft Access ?

Si vous utilisez PHP sur une machine Unix et que vous voulez vous connecter à une base Access sur une machine Windows, vous aurez besoin des pilotes ODBC Unix. » OpenLink Software fournit des pilotes ODBC pour Unix qui peuvent le faire.

Une autre solution consiste à utiliser un serveur SQL qui a des pilotes ODBC Windows et l'utiliser pour stocker les données, que vous pouvez utiliser à partir de Microsoft Access (en utilisant ODBC) et PHP (en utilisant les pilotes inclus), ou bien utiliser un format de fichier intermédiaire que Access et PHP peuvent traiter tous les deux, comme des fichier bruts ou des bases de données dBase. À ce sujet, Tim Hayes de Openlink software écrit :

Utiliser une autre base de données comme intermédiaire n'est pas une bonne idée lorsque vous pouvez utiliser ODBC de PHP directement vers vos bases de données - par exemple avec les pilotes Openlink. Si vous avez besoin d'un format de fichier intermédiaire, Openlink a publié Virtuoso (un moteur de base de données virtuel) pour NT, Linux et d'autres plates-formes Unix. Visitez notre » site pour un téléchargement gratuit.

Une solution qui a fait ses preuves est d'utiliser MySQL et ses pilotes ODBC sous Windows et de synchroniser les bases de données. Steve Lawrence écrit :

  • Installez MySQL sur votre plate-forme conformément aux instructions de MySQL. Vous pouvez l'obtenir sur » http://www.mysql.com/. Aucune configuration particulière n'est nécessaire, mis à part que lorsque vous configurez une base de données et un compte utilisateur, il faille spécifier % dans le champ host, ou bien le nom de la machine Windows avec laquelle vous voulez accéder à MySQL. Notez bien votre nom de serveur, d'utilisateur et votre mot de passe.
  • Téléchargez les pilotes MyODBC pour Windows à partir du site de MySQL. Installez les sur votre machine Windows. Vous pouvez tester votre installation avec les utilitaires fournis avec les pilotes.
  • Créez un utilisateur ou une source de données système dans votre administration ODBC, dans le panneau de configuration. Donnez un nom de source de données dsn, entrez votre nom d'hôte, identifiant, mot de passe, port, etc. pour la base de données configurée à l'étape 1.
  • Installez Access avec une installation complète pour être sûr d'avoir tous les composants nécessaires... Vous aurez besoin d'au moins le support ODBC et le gestionnaire de tables liées.
  • Maintenant, la partie amusante ! Créez un accès à une base de données. Dans la fenêtre de la table, cliquez droit et sélectionner Lier les Tables, ou, dans le menu Fichier, sélectionnez Obtenir des données externes et alors Lier les Tables. Quand la fenêtre de gestion de fichiers apparaît, sélectionnez les fichiers de type : ODBC. Sélectionnez dsn Système et le nom de votre dsn créée à l'étape 3. Sélectionnez la table à lier, cliquez sur OK, et voilà ! Vous pouvez maintenant ouvrir la table et ajouter/supprimer/éditer des données sur votre serveur MySQL ! Vous pouvez ainsi exécuter des requêtes, importer/exporter des tables vers MySQL, construire des formulaires et des rapports, etc.

Trucs et astuces :

  • Vous pouvez construire vos tables dans Access et les exporter dans MySQL, puis les lier de nouveau. Cela rend la création de table très rapide.
  • Lorsque vous créez des tables dans Access, vous devez avoir une clé primaire définie pour avoir accès en écriture à la table. Assurez-vous que vous avez bien créé une clé primaire dans MySQL avant de lier le tout à Access.
  • Si vous changez une table dans MySQL, vous devez la lier de nouveau à Access. Allez dans Outils>suppléments>gestionnaire de tables liées, cherchez votre DSN ODBC, et sélectionnez la table à lier de nouveau. Vous pouvez aussi changer votre source dsn à partir de là, en cliquant sur l'option toujours demander pour un nouvel emplacement avant de presser OK.

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.


Installation

Cette section traite de questions courantes sur la façon d'installer PHP. PHP est disponible sur la plupart des systèmes d'exploitation et pour quasiment n'importe quel serveur web.

Pour installer PHP, suivez les instructions présentes dans Installation et configuration.

  1. Pourquoi ne doit-on pas utiliser Apache 2 dans un environnement threadé multiprocesseur de production ?
  2. Unix/Windows : où doit être placé mon fichier php.ini ?
  3. Unix : j'ai installé PHP, mais à chaque fois que je charge un document, j'obtiens l'erreur 'Document Contains No Data' ! Que se passe-t-il ?
  4. Unix : J'ai installé PHP en utilisant des fichiers sources RPM, mais apache ne traite pas les pages PHP. Que se passe-t-il ?
  5. Unix : J'ai patché Apache avec l'extension FrontPage et subitement, PHP ne fonctionne plus. Est-ce que PHP est incompatible avec l'extension FrontPage pour Apache ?
  6. Unix/Windows : J'ai installé PHP, mais lorsque je tente d'accéder à un fichier contenant un script PHP via mon navigateur, j'obtiens un écran vide.
  7. Unix/Windows : J'ai installé PHP, mais lorsque je tente d'accéder à un fichier contenant un script PHP via mon navigateur, j'obtiens une erreur de type 'server 500 error'.
  8. Quelques systèmes d'exploitations : J'ai installé PHP sans erreur, mais lorsque je tente de démarrer Apache, j'obtiens une erreur du type 'Undefined symbols' : [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows : J'ai installé PHP, mais lorsque je tente d'accèder à un fichier contenant un script PHP via mon navigateur, j'obtiens l'erreur : cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows : J'ai suivi toutes les instructions, mais je n'arrive toujours pas à faire fonctionner PHP et IIS ensemble !
  11. Lorsque vous exécutez PHP comme CGI avec IIS, PWS, OmniHTTPD ou Xitami, j'obtiens l'erreur suivante : Security Alert! PHP CGI cannot be accessed directly..
  12. Comment puis-je savoir si mon php.ini a bien été trouvé et lu ? Cela semble être le cas mais aucun de mes changements n'ont eu d'effet.
  13. Où dois-je ajouter mon répertoire PHP à la variable PATH sous Windows ?
  14. Comment rendre le fichier php.ini disponible à PHP sous Windows ?
  15. Est-il possible d'utiliser la négociation sur le contenu fournie par Apache (option MultiViews) avec PHP ?
  16. Est-ce que PHP est limité au traitement des méthodes GET et POST ?
Pourquoi ne doit-on pas utiliser Apache 2 dans un environnement threadé multiprocesseur de production ?

PHP est un mortier. C'est un mortier utilisé pour construire de belles applications web en utilisant beaucoup de bibliothèques ensemble, apparaissant comme une seule entité à travers un langage intuitif et facile à apprendre. La flexibilité et la puissance de PHP se fondent sur la stabilité et la robustesse de la plate-forme fondamentale. Il a besoin d'un OS qui fonctionne, d'un serveur web qui fonctionne et de bibliothèques externes pour coller le tout. Lorsqu'un seul de ces éléments arrêtent subitement de fonctionner, PHP doit identifier le problème et le réparer au plus vite. En rendant le cadre fondamental plus complexe en ne séparant pas les exécutions des threads, ni les segments mémoires, ni un endroit clos pour traiter chaque requête entrante, de nouvelles faiblesses sont introduites dans le système PHP.

Si vous voulez utiliser un MPM threadé, regardez du côté d'une configuration FastCGI dans lequel PHP s'exécute dans son propre espace mémoire.

Unix/Windows : où doit être placé mon fichier php.ini ?

Par défaut sous Unix, il doit être placé dans /usr/local/lib qui est en fait <install-path>/lib. La plupart des personnes voudront changer ceci lors de la compilation avec l'option --with-config-file-path. Vous pouvez par exemple le régler de cette façon :

--with-config-file-path=/etc
Et alors vous copierez le fichier php.ini-development livré avec les sources vers /etc/php.ini et l'éditer pour l'adapter à vos besoins.

--with-config-file-scan-dir=PATH

Sous Windows, le chemin par défaut de php.ini est le répertoire de Windows. Si vous utilisez le serveur web Apache, php.ini est tout d'abord cherché dans le répertoire d'installation de Apache, c'est-à-dire c:\program files\apache group\apache. De cette façon, vous pouvez avoir un php.ini différent pour chaque version de Apache installée.

Consultez aussi le chapitre sur le fichier de configuration.

Unix : j'ai installé PHP, mais à chaque fois que je charge un document, j'obtiens l'erreur 'Document Contains No Data' ! Que se passe-t-il ?

Cela signifie probablement que PHP rencontre un problème et génère un fichier core. Consultez vos fichiers de logs de votre serveur pour voir si c'est le cas, et tentez de reproduire le problème avec un test simple. Si vous savez utiliser 'gdb', il serait très utile de fournir un backtrace avec votre rapport de bogue, afin d'aider les développeurs à cerner le problème. Si vous utilisez PHP en module Apache, essayez ceci :

  • Stoppez vos processus httpd

  • gdb httpd

  • Stoppez vos processus httpd

  • > run -X -f /path/to/httpd.conf

  • Pointez alors avec votre navigateur vers l'URL posant problème.

  • > run -X -f /path/to/httpd.conf

  • Si vous obtenez un fichier core, gdb doit alors vous en informer.

  • tapez : bt

  • Vous devriez inclure votre backtrace dans votre rapport de bogue. Celui-ci doit être posté sur » https://github.com/php/php-src/issues.

Si votre script utilise les expressions régulières (preg_match() et consorts), assurez-vous que PHP et Apache ont été compilés avec les même outils d'expression régulières. Cela doit être automatiquement le cas avec PHP et Apache 1.3.x.

Unix : J'ai installé PHP en utilisant des fichiers sources RPM, mais apache ne traite pas les pages PHP. Que se passe-t-il ?

En supposant que vous avez installé à la fois Apache et PHP à partir de fichiers RPM, vous devrez commenter ou ajouter au moins quelques unes des lignes suivantes dans votre fichier httpd.conf :

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so
Et ajouter :
AddType application/x-httpd-php .php
... aux propriétés globales ou aux propriétés du VirtualDomain ou vous voulez que PHP officie.

Unix : J'ai patché Apache avec l'extension FrontPage et subitement, PHP ne fonctionne plus. Est-ce que PHP est incompatible avec l'extension FrontPage pour Apache ?

Non, PHP fonctionne très bien avec l'extension FrontPage. Le souci vient du fait que le patch pour l'installation de FrontPage modifie la structure d'Apache, qui est relié à PHP. Recompiler PHP (en utilisant 'make clean ; make') après avoir patché Apache avec l'extension FrontPage devrait résoudre ce problème.

Unix/Windows : J'ai installé PHP, mais lorsque je tente d'accéder à un fichier contenant un script PHP via mon navigateur, j'obtiens un écran vide.

Affichez le code source du document dans votre navigateur et vous devriez probablement trouver le code source de votre script PHP. Cela signifie que le serveur web n'a pas envoyé le script à PHP pour interprétation. Quelque chose est donc incorrecte dans le fichier de configuration de votre serveur web - re-vérifiez la configuration du serveur web en vous référant aux instructions d'installations de PHP.

Unix/Windows : J'ai installé PHP, mais lorsque je tente d'accéder à un fichier contenant un script PHP via mon navigateur, j'obtiens une erreur de type 'server 500 error'.

Quelque chose se passe mal lorsque le serveur tente d'utiliser PHP. Pour tenter de récupérer un message d'erreur, depuis la ligne de commande, placez-vous dans le répertoire contenant l'exécutable PHP (php.exe sous Windows) et exécutez la commande php -i. Si PHP a un problème quelconque l'empêchant de fonctionner, un message d'erreur devrait s'afficher qui devrait expliquer comment résoudre ce souci. Si un écran de code HTML apparaît (la sortie de la fonction phpinfo()), cela signifie que PHP fonctionne correctement et que le problème doit certainement venir de la configuration de votre serveur web que vous devriez re-vérifier.

Quelques systèmes d'exploitations : J'ai installé PHP sans erreur, mais lorsque je tente de démarrer Apache, j'obtiens une erreur du type 'Undefined symbols' :
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

Cela n'a actuellement rien à voir avec PHP mais avec la bibliothèque cliente MySQL. Suivant les versions, elle a besoin que PHP soit compilé avec l'option --with-zlib, d'autre non. Ce problème est également traité dans la FAQ de MySQL.

Windows : J'ai installé PHP, mais lorsque je tente d'accèder à un fichier contenant un script PHP via mon navigateur, j'obtiens l'erreur :
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Ce message d'erreur signifie que PHP a échoué lors de l'affichage. Pour tenter de récupérer un message d'erreur, depuis la ligne de commande, placez-vous dans le répertoire contenant l'exécutable PHP (php.exe sous Windows) et exécutez la commande php -i. Si PHP a un quelconque souci de fonctionnement, alors un message d'erreur le décrivant s'affichera. Si vous obtenez un écran de code HTML (le contenu du résultat de la fonction phpinfo()), alors PHP fonctionne correctement.

Si PHP fonctionne depuis la ligne de commande, tentez d'accéder à votre script encore une fois via votre navigateur. S'il échoue toujours, alors, il se peut que ce soit l'un des soucis suivants :

  • Les permissions de votre script PHP des fichiers php.exe, php5ts.dll, php.ini ou de toute extension nécessaire à PHP que vous tentez de charger, sont telles que l'utilisateur internet anonyme de votre système ISUR_<machinename> ne peut pas y accéder.
  • Le script PHP n'existe pas (ou n'est pas à l'endroit que vous pensez, relativement au répertoire racine de votre serveur web). Notez que pour le serveur web IIS, vous pouvez vérifier cela en cochant la case 'vérifier si le fichier existe' lors de la configuration de l'exécution des scripts dans le gestionnaire de services Internet. Si un fichier de script n'existe pas, le serveur web retournera une erreur 404. IIS a également l'avantage d'effectuer toutes les identifications requises à votre place, basés sur les permissions NTLanMan, sur votre fichier de script.
Windows : J'ai suivi toutes les instructions, mais je n'arrive toujours pas à faire fonctionner PHP et IIS ensemble !

Assurez-vous que chaque utilisateur qui a besoin d'exécuter un script PHP possède les droits requis pour exécuter le fichier php.exe ! IIS utilise un utilisateur anonyme qui est ajouté lors de l'installation de IIS. Cet utilisateur doit avoir les droits suffisant sur le fichier php.exe. De même, tous les utilisateurs enregistrés doivent posséder les droits requis pour exécuter le fichier php.exe. Pour IIS4, vous devez lui dire que PHP est un moteur de script. De plus, vous devriez lire cette FAQ.

Lorsque vous exécutez PHP comme CGI avec IIS, PWS, OmniHTTPD ou Xitami, j'obtiens l'erreur suivante : Security Alert! PHP CGI cannot be accessed directly..

Vous devez définir la directive cgi.force_redirect à 0. Par défaut, elle vaut 1, donc, soyez sûrs que cette directive n'est pas commentée (précédée d'un point virgule). Comme toutes les directives, elles sont définies dans le php.ini.

Comme la valeur par défaut vaut 1, il est impératif que vous soyez sûrs à 100% que le bon fichier php.ini a été lu. Lisez cette FAQ pour plus de détails.

Comment puis-je savoir si mon php.ini a bien été trouvé et lu ? Cela semble être le cas mais aucun de mes changements n'ont eu d'effet.

Pour être sûr que votre php.ini a été lu par PHP, effectuez un appel à la fonction phpinfo(). Vers le haut du document résultant, il devrait figurer une liste appelée Configuration File (php.ini). Cela vous indiquera où PHP a cherché le php.ini et si oui ou non il l'a lu. Si seul un dossier PATH existe et qu'il est accessible en lecture, vous devez copier votre php.ini dans ce dossier. Si le php.ini est présent dans le chemin, cela signifie qu'il a bien été lu.

Si le php.ini a bien été lu et que vous exécutez PHP comme module, alors assurez-vous de redémarrer le serveur web après avoir effectué les modifications à votre php.ini.

Voir aussi la fonction php_ini_loaded_file().

Où dois-je ajouter mon répertoire PHP à la variable PATH sous Windows ?

Sous Windows :

  • Allez dans le centre de contrôle et ouvrez l'icône système (Démarrer ? Paramètres ? Panneau de configuration ? Système ou juste Démarrer ? centre de contrôle ? Système pour Windows XP/2003+)

  • Allez à l'onglet "Avancé"

  • Cliquez sur le bouton "Variables d'environnements"

  • Regardez dans le panneau "Variables systèmes"

  • Trouvez l'entrée Path (vous devriez avoir à faire descendre l'ascenseur pour le trouver)

  • Double cliquez sur l'entrée Path

  • Entrez votre répertoire PHP à la fin, sans oublier le point virgule (;) avant (par exemple ;C:\php)

  • Confirmez en cliquant sur OK

Note: Assurez-vous de redémarrer l'ordinateur après avoir suivi cette procédure afin que les modifications sur la variable PATH soient bien prises en compte.

Comment rendre le fichier php.ini disponible à PHP sous Windows ?

Il y a plusieurs façons de faire cela. Si vous utilisez Apache, référez vous à la documentation d'Apache, sinon vous devez définir la variable d'environnement PHPRC.

Est-il possible d'utiliser la négociation sur le contenu fournie par Apache (option MultiViews) avec PHP ?

Si les liens vers les fichiers PHP incluent l'extension, tout fonctionne parfaitement. Cette entrée de la FAQ traite uniquement du cas où les liens vers les fichiers PHP n'incluent pas l'extension et que vous voulez utiliser la négociation sur le contenu fourni par Apache pour choisir les fichiers PHP depuis une URL qui ne contient pas d'extension. Dans ce cas, remplacez la ligne AddType application/x-httpd-php .php par :

AddHandler php5-script php
AddType text/html php
Cette solution ne fonctionne pas pour Apache 1 car le module PHP ne captura pas le php-script.

Est-ce que PHP est limité au traitement des méthodes GET et POST ?

Non, il est possible de gérer tout type de méthode, comme CONNECT. Les bons en-têtes de réponse peuvent être envoyés avec la fonction header(). Si seules les méthodes POST et GET doivent être gérées, vous pouvez configurer Apache comme ce qui suit :

<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


Problèmes de compilation

Cette section couvre les erreurs les plus communes pouvant se produire lors de la compilation de PHP.

  1. J'ai téléchargé la dernière version des sources de PHP en utilisant Git, mais il n'y a pas de script configure !
  2. J'ai des problèmes pour configurer PHP avec Apache. On m'indique que httpd.h n'est pas trouvé, mais il est bien là ou je l'ai spécifié !
  3. Pendant la configuration de PHP (./configure), vous rencontrez une erreur semblable à celle-ci : checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. Quand je lance Apache, j'obtiens le message suivant : fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. Quand je lance le ./configure, on me dit que les fichiers d'en-tête de GD, gdbm, ... ne sont pas trouvés !
  6. Quand le fichier language-parser.tab.c est compilé, j'obtiens un message yytname undeclared.
  7. Quand je lance make, tout semble bien se passer, mais ça échoue quand il essaie de lier l'application finale, en prétendant qu'il manque des fichiers.
  8. Au moment de lier PHP, il y a des références indéfinies.
  9. J'ai suivi toutes les étapes pour installer le module Apache sous Unix, mais malgré tout, mes scripts PHP s'affichent en clair dans mon navigateur ou celui-ci me demande de sauver le fichier.
  10. Il est dit d'utiliser --activate-module=src/modules/php4/libphp4.a, mais ce fichier n'existe pas, alors je l'ai changé pour --activate-module=src/modules/php4/libmodphp4.a et ça ne fonctionne pas. Qu'est ce qui se passe ?
  11. Quand j'essaie de compiler Apache avec PHP en module statique en utilisant --activate-module=src/modules/php4/libphp4.a on me répond que mon compilateur n'est pas conforme aux normes ANSI.
  12. Quand j'esaie de compiler PHP avec --with-apxs, j'obtiens des messages d'erreur étranges.
  13. Pendant le make, j'ai des erreurs concernant microtime et beaucoup de RUSAGE_.
  14. Quand je compile PHP avec le support MySQL, le configure se passe bien, mais pendant le make, j'obtiens une erreur de ce style : 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', qu'est ce qui ne va pas ?
  15. Je veux mettre à jour mon PHP. Où puis-je trouver la ligne ./configure qui a été utilisée pour mon installation actuelle de PHP?
  16. Quand je compile PHP avec le support de la bibliothèque GD, j'obtiens des erreurs de compilation étrange, voire même des erreurs de segmentation.
  17. Quand je compile PHP, j'obtiens des erreurs aléatoires, voire même tout s'arrête. J'utilise Solaris.
J'ai téléchargé la dernière version des sources de PHP en utilisant Git, mais il n'y a pas de script configure !

Vous devez avoir le logiciel GNU autoconf d'installé pour générer le script configure à partir de configure.in. Lancez juste ./buildconf à la racine du répertoire des sources après avoir récupéré celles-ci à partir du serveur Git. (De plus, à moins que vous ne lanciez configure avec l'option --enable-maintainer-mode, le script configure ne sera pas automatiquement reconstruit si configure.in est mis à jour, vous obligeant à le faire à la main quand vous remarquez que configure.in est mis à jour. Une conséquence de ceci est que l'on trouve des choses telles que @VARIABLE@ dans votre Makefile après que configure ou config.status soit lancé.)

J'ai des problèmes pour configurer PHP avec Apache. On m'indique que httpd.h n'est pas trouvé, mais il est bien là ou je l'ai spécifié !

Vous devez spécifier au script de configuration (configure) l'emplacement du répertoire ou sont les sources de Apache. Cela signifie que vous devez spécifier --with-apache=/chemin/vers/apache et pas --with-apache=/chemin/vers/apache/src.

Pendant la configuration de PHP (./configure), vous rencontrez une erreur semblable à celle-ci :

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Assurez-vous de bien avoir lu les instructions d'installation et d'avoir flex et bison d'installés pour compiler PHP. Selon votre système, vous devrez installer bison et flex à partir de sources ou bien de paquets, tel qu'un RPM.

Quand je lance Apache, j'obtiens le message suivant :

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

Cette erreur survient généralement quand quelqu'un compile le cœur Apache comme bibliothèque partagée DSO. Essayez de reconfigurer Apache, en vous assurant d'utiliser les options suivantes :

--enable-shared=max --enable-rule=SHARED_CORE

Pour davantage d'informations, lisez le fichier INSTALL à la racine de votre répertoire source Apache ou bien » le manuel des bibliothèques DSO.

Quand je lance le ./configure, on me dit que les fichiers d'en-tête de GD, gdbm, ... ne sont pas trouvés !

Vous pouvez forcer le script configure à chercher les fichiers d'en-tête à des endroits non-standard en passant des options supplémentaires au préprocesseur C et à l'éditeur de liens, par exemple :

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
Si vous utilisez une variante de csh, utilisez plutôt :
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

Quand le fichier language-parser.tab.c est compilé, j'obtiens un message yytname undeclared.

Vous devez mettre à jour votre version de bison. Vous pourrez trouver la dernière version sur » http://www.gnu.org/software/bison/bison.html.

Quand je lance make, tout semble bien se passer, mais ça échoue quand il essaie de lier l'application finale, en prétendant qu'il manque des fichiers.

Certaines anciennes versions de make ne déplacent pas correctement les versions compilées des fichiers dans le répertoire functions. Essayez de lancer cp *.o functions et de relancer make pour voir si le problème est résolu. Si tel est le cas, vous devriez vraiment mettre à jour votre version de GNU make.

Au moment de lier PHP, il y a des références indéfinies.

Jetez un oeil à la ligne de lien et assurez-vous que toutes les bibliothèques nécessaires ont été incluses à la fin. Celles qui manquent probablement sont '-ldl' et les bibliothèques relatives aux bases de données dont vous voulez le support.

Des personnes nous ont rapporté qu'elle devaient ajouter '-ldl' immédiatement après libphp4.a lors de la compilation avec Apache.

J'ai suivi toutes les étapes pour installer le module Apache sous Unix, mais malgré tout, mes scripts PHP s'affichent en clair dans mon navigateur ou celui-ci me demande de sauver le fichier.

Cela signifie que le module PHP n'est pas chargé, pour une raison ou pour une autre. Avant de chercher de l'aide ailleurs, veuillez vérifier ces quelques points :

  • Assurez-vous que le binaire httpd que vous exécutez est bien le nouveau binaire que vous avez compilé. Pour cela, essayez de lancer : /chemin/vers/le/binaire/httpd -l Si vous ne voyez pas mod_php4.c dans la liste, c'est que vous n'utilisez pas le bon binaire. Trouvez et installez correctement le bon binaire.
  • Assurez-vous que vous avez bien ajouté le bon type Mime à un de vos fichiers Apache .conf. Ce devrait être : AddType application/x-httpd-php .php Assurez-vous aussi que cette ligne Addtype n'est pas dissimulée dans un contexte de <Virtualhost> ou <Directory> qui l'empêcherait de s'appliquer à l'emplacement de vos scripts.
  • Enfin, l'emplacement par défaut des fichiers de configuration Apache a changé entre Apache 1.2 et Apache 1.3. Vous devriez vérifier que les fichiers de configuration auxquels vous ajoutez la ligne Addtype sont bien ceux qui sont pris en compte. Vous pouvez introduire une erreur de syntaxe dans votre httpd.conf (ou bien tout autre changement incorrect) pour vous assurer que c'est bien ce fichier qui est pris en compte.

Il est dit d'utiliser --activate-module=src/modules/php4/libphp4.a, mais ce fichier n'existe pas, alors je l'ai changé pour --activate-module=src/modules/php4/libmodphp4.a et ça ne fonctionne pas. Qu'est ce qui se passe ?

Notez que le fichier libphp4.a n'est pas supposé exister. Le processus apache le créera !

Quand j'essaie de compiler Apache avec PHP en module statique en utilisant --activate-module=src/modules/php4/libphp4.a on me répond que mon compilateur n'est pas conforme aux normes ANSI.

C'est un mauvais message d'erreur de Apache qui n'apparaît plus dans des versions plus récentes.

Quand j'esaie de compiler PHP avec --with-apxs, j'obtiens des messages d'erreur étranges.

Il y a trois choses à vérifier ici. Tout d'abord, quand Apache crée le script Perl apxs, il s'interrompt parfois en étant compilé sans le bon compilateur ou les bonnes options. Trouvez votre script apxs (lancez la commande which apxs), qui se trouve souvent à /usr/local/apache/bin/apxs ou bien /usr/sbin/apxs. Éditez-le et vérifiez que des lignes similaires sont présentes :

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
Si c'est ce que vous voyez, vous avez trouvé votre problème. Elles peuvent contenir juste des espaces ou d'autres valeurs incorrectes, comme 'q()'. Changez ces lignes pour obtenir :
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
Le deuxième problème potentiel est uniquement relatif aux distributions Red Hat 6.1 et 6.2. The scripts apxs de Red Hat est défectueux. Cherchez cette ligne :
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
Si vous la voyez telle quelle, changez-la en :
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Enfin, si vous reconfigurez/réinstallez Apache, lancez un make clean entre votre ./configure et votre make.

Pendant le make, j'ai des erreurs concernant microtime et beaucoup de RUSAGE_.

Pendant le make, si vous rencontrez des problèmes identiques à celui-ci :

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

Votre système est défectueux. Vous devez corriger vos fichiers /usr/include en instalant un paquet glibc-devel qui correspond à votre version de la glibc. Cela n'a rien à voir avec PHP. Pour vous en convaincre, essayez ceci :

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
Si vous obtenez des erreurs, c'est que vos fichiers d'en-tête sont mauvais.

Quand je compile PHP avec le support MySQL, le configure se passe bien, mais pendant le make, j'obtiens une erreur de ce style : 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', qu'est ce qui ne va pas ?

Tout d'abord, il est important de savoir que ce n'est qu'un Warning et pas une erreur fatale. Comme c'est souvent la dernière erreur vu lors du make, ça a l'air d'une erreur fatale, mais ça n'en est pas une. Bien sûr, si vous demandez à votre compilateur de stopper à chaque Warning, ça en deviendra une. Notez aussi que le support de MySQL est activé par défaut.

Note:

Depuis PHP 4.3.2, vous verrez le texte suivant après la compilation (make) :

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).

Je veux mettre à jour mon PHP. Où puis-je trouver la ligne ./configure qui a été utilisée pour mon installation actuelle de PHP?

Vous pouvez jetez un oeil au fichier config.nice dans votre répertoire source ou sinon simplement exécuter un script

<?php phpinfo(); ?>
Au début du résultat affiché figure la ligne ./configure qui fût utilisée lors de la configuration de votre PHP actuel.

Quand je compile PHP avec le support de la bibliothèque GD, j'obtiens des erreurs de compilation étrange, voire même des erreurs de segmentation.

Assurez-vous que votre bibliothèque GD et PHP sont liés aux mêmes bibliothèques (libpng, par exemple).

Quand je compile PHP, j'obtiens des erreurs aléatoires, voire même tout s'arrête. J'utilise Solaris.

L'utilisation d'utilitaires non-GNU pour compiler PHP peut poser problème. Assurez-vous de bien utiliser des outils GNU pour être certain que votre compilation arrive à terme. Par exemple, sous Solaris, utiliser les version SunOS BSD-compatible ou Solaris de sed ne fonctionnera pas, mais utiliser les versions GNU ou Sun POSIX (xpg4) de sed fonctionnera. Liens : » GNU sed, » GNU flex et » GNU bison.

User Contributed Notes

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.


Utiliser PHP

Cette section regroupe plusieurs erreurs que vous pouvez rencontrer lors de l'écriture de vos scripts PHP.

  1. Je ne me rappelle par de l'ordre des paramètres dans les fonctions PHP, sont-ils aléatoires ?
  2. J'aimerais écrire un script PHP générique qui pourrait traiter les données provenant de tout formulaire. Comment savoir quelles variables de la méthode POST sont disponibles ?
  3. Il faut que je convertisse tous les guillemets simples (') en un antislash suivi d'un guillemet simple (\'). Comment le faire avec une expression régulière ? J'aimerais aussi convertir " en \" et \ en \\.
  4.       Quand je fais ce qui suit, l'affichage se fait dans le mauvais ordre :

<?php
function mafonction($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "mafonction($variable) = " . mafonction($variable);
?>

     que se passe-t-il ?
  5. Hey, où sont mes nouvelles lignes ? <pre> <?php echo "Ceci est ma première ligne."; ?> <?php echo "Celle-ci devrait s'afficher en dessous de la première."; ?> </pre>
  6. J'obtiens le message 'Warning: Cannot send session cookie - headers already sent...' ou 'Cannot add header information - headers already sent...'.
  7. J'ai besoin d'accéder à des informations dans l'en-tête de requête directement. Comment puis-je le faire ?
  8. Quand j'essaye d'utiliser l'identification avec IIS j'obtiens 'No Input file specified'.
  9. Windows: Je ne peux pas accéder aux fichiers partagés sur un autre ordinateur utilisant IIS
  10. Comment mélanger XML et PHP ? PHP se plaint de mes balises <?xml !
  11. Où puis-je trouver une liste complète des variables prédéfinies que je peux utiliser dans mes scripts PHP ?
  12. Comment puis-je générer des fichiers PDF sans utiliser les bibliothèques non libres PDFLib ? J'aimerais une façon gratuite et qui ne requiert pas de bibliothèques PDF externes.
  13. Certaines directives PHP peuvent prendre des noms littéraux, et pas seulement des valeurs entier. Quelles sont tous les raccourcis disponibles?
Je ne me rappelle par de l'ordre des paramètres dans les fonctions PHP, sont-ils aléatoires ?

PHP rassemble des centaines de bibliothèques externes et ça peut paraître parfois déroutant. Cependant, une règle simple à retenir :

Les paramètres concernant les fonctions sur les tableaux sont dans l'ordre "needle, haystack" tandis que les paramètres sur les fonctions gérants les chaînes sont exactement à l'opposé "haystack, needle".

J'aimerais écrire un script PHP générique qui pourrait traiter les données provenant de tout formulaire. Comment savoir quelles variables de la méthode POST sont disponibles ?

PHP fournit plusieurs variables pré-définies, comme la superglobale $_POST. Vous pouvez boucler sur $_POST puisque c'est un tableau associatif de toutes les valeurs envoyés par la méthode POST. Par exemple, bouclons dessus simplement avec foreach, vérifions les valeurs vides et affichons-les.

<?php
$empty = $post = array();
foreach ($_POST as $nomvar => $valeurvar) {
if (empty($varvalue)) {
$empty[$nomvar] = $valeurvar;
} else {
$post[$nomvar] = $valeurvar;
}
}

echo '<pre>';
if (empty($empty)) {
print "Aucune valeur POSTée n'est vide, postées :\n";
var_dump($post);
} else {
print "Nous avons " . count($empty) . " valeurs vides\n";
print "Postées :\n"; var_dump($post);
print "Vides :\n"; var_dump($empty);
exit;
}
echo '</pre>';
?>

Il faut que je convertisse tous les guillemets simples (') en un antislash suivi d'un guillemet simple (\'). Comment le faire avec une expression régulière ? J'aimerais aussi convertir " en \" et \ en \\.

Si l'on suppose que c'est pour une base de données, utilisez le méchanisme d'échappement fourni avec la base de données. Par exemple, utilisez la fonction mysql_real_escape_string() avec MySQL et pg_escape_string() avec PostgreSQL. Il y a également les fonctions génériques comme addslashes() et stripslashes(), qui sont plus communes avec l'ancien code PHP.

Quand je fais ce qui suit, l'affichage se fait dans le mauvais ordre :
<?php
function mafonction($argument)
{
echo $argument + 10;
}
$variable = 10;
echo "mafonction($variable) = " . mafonction($variable);
?>
que se passe-t-il ?

Pour pouvoir utiliser le résultat de votre fonction dans une expression (comme le concaténer avec une chaîne comme dans cet exemple), vous devez retourner la valeur avec return, et non pas l'afficher avec echo.

Hey, où sont mes nouvelles lignes ?
<pre>
<?php echo "Ceci est ma première ligne."; ?>
<?php echo "Celle-ci devrait s'afficher en dessous de la première."; ?>
</pre>

En PHP, la fin d'un bloc de code est soit "?>" ou "?>\n" (où \n signifie une nouvelle ligne). Donc dans l'exemple plus haut, les phrases affichées le seront sur une seule ligne, car PHP oublie les nouvelles lignes après la fin du bloc. Cela signifie que vous devez insérer une nouvelle ligne de plus après chaque bloc de code PHP pour la lui faire afficher.

Pourquoi PHP fait-il cela ? Car lors du formatage du HTML, cela vous simplifie la vie car vous ne voulez pas de cette nouvelle ligne, mais vous devez créer de très longues lignes ou rendre la source brute de la page illisible pour arriver à cet effet.

J'obtiens le message 'Warning: Cannot send session cookie - headers already sent...' ou 'Cannot add header information - headers already sent...'.

Les fonctions header(), setcookie(), et les fonctions de session doivent ajouter des en-têtes au flux de sortie, mais ceux-ci ne peuvent être envoyés qu'avant le reste du contenu. Il ne doit y avoir aucun affichage avant d'utiliser ces fonctions, comme le HTML par exemple. La fonction headers_sent() vérifiera si votre script a déjà envoyé des en-têtes. Voyez aussi les fonctions de bufferisation de sortie.

J'ai besoin d'accéder à des informations dans l'en-tête de requête directement. Comment puis-je le faire ?

La fonction getallheaders() le fera si vous exécutez PHP en tant que module Apache. Le code suivant vous montrera tous les en-têtes de requête :

<?php
$headers = getallheaders();
foreach ($headers as $nom => $contenu) {
echo "headers[$nom] = $contenu<br />\n";
}
?>

Voir aussi
apache_lookup_uri(),
apache_response_headers() et
fsockopen().

Quand j'essaye d'utiliser l'identification avec IIS j'obtiens 'No Input file specified'.

Le modèle sécuritaire de IIS est en faute. C'est un problème commun à tous les programmes CGI fonctionnant avec IIS. Une alternative est de créer un fichier HTML (non exécuté par PHP) comme page d'entrée dans le dossier où il faut s'identifier. Utilisez alors une balise META pour rediriger vers la page PHP, ou encore proposez un lien vers celle-ci. PHP reconnaîtra alors l'identification correctement. Cela ne devrait pas non plus affecter d'autres serveurs NT. Pour plus d'informations, voyez : » http://support.microsoft.com/kb/q160422/ et la section du manuel concernant l'identification HTTP.

Windows: Je ne peux pas accéder aux fichiers partagés sur un autre ordinateur utilisant IIS

Vous devez modifier le service Go to Internet Information Services. Localisez votre fichier PHP et éditez ces propriétés. Placez-vous sur l'onglet File Security, Edit -< Anonymous access and authentication control.

Vous pouvez résoudre ce souci soit en décochant la case Anonymous Access et en laissant la case Integrated Window Authentication cochée, soit en cochant la case Anonymous Access et en éditant l'utilisateur qui ne doit pas avoir les droits d'accès.

Comment mélanger XML et PHP ? PHP se plaint de mes balises <?xml !

Pour inclure <?xml dans votre code PHP, vous devrez désactiver les short tags en configurant la directive PHP short_open_tags à 0. Vous ne pouvez pas modifier cette directive avec ini_set(). Que short_open_tags soit à on ou off, vous pouvez toujours faire ceci : <?php echo '<?xml'; ?>. La valeur par défaut pour cette directive est On.

Où puis-je trouver une liste complète des variables prédéfinies que je peux utiliser dans mes scripts PHP ?

Lisez la page du manuel qui concerne les variables prédéfinies vu qu'elle présente une liste partielle des variables prédéfinies disponibles dans votre script. Une liste complète des variables disponibles (et beaucoup d'informations) peut être vue en appelant la fonction phpinfo(). Lisez la section du manuel traitant des variables non-issues de PHP, elle décrit des scénarios communs pour les variables externes, comme celles issues d'un formulaire HTML, d'un cookie, et de l'URL.

Comment puis-je générer des fichiers PDF sans utiliser les bibliothèques non libres PDFLib ? J'aimerais une façon gratuite et qui ne requiert pas de bibliothèques PDF externes.

Il y a quelques alternatives écrites en PHP tel que » FPDF et » TCPDF.

Certaines directives PHP peuvent prendre des noms littéraux, et pas seulement des valeurs entier. Quelles sont tous les raccourcis disponibles?

Les options disponibles sont K (pour Kilo octets) et M (pour mégaoctet) et G (pour gigaoctet), ils sont insensibles à la casse. Tout autre syntaxe est supposée représenter des octets. 1M équivaut à un mégaoctet ou 1048576 octets. 1K équivaut à un kilooctet ou 1024 octets. Ces notations abrégées peuvent être utilisées dans le fichier php.ini et dans la fonction ini_set(). Notez que la valeur numérique est transtypé en entier ; par exemple, 0.5M est interprété comme 0.

Note: kilooctet contre kibibyte

La notation PHP décrit un kilooctet comme étant égal à 1024 octets, alors que le standard IEC considère ça comme un kibioctet (kibibyte). En bref: k et K = 1024 octets.

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.


Hachage de mots de passe sûr

Cette section explique les raisons d'utiliser des fonctions de hachage pour les mots de passe, ainsi que la façon de le faire efficacement.

  1. Pourquoi devrais-je hacher les mots de passe envoyés par les utilisateurs de mon application ?
  2. Pourquoi les fonctions traditionnelles de hachage comme md5 et sha1 sont-elles inappropriées aux mots de passe ?
  3. Alors, comment hacher mes mots de passe ?
  4. Qu'est ce que le grain de sel ?
  5. Comment stocker mes salts ?
Pourquoi devrais-je hacher les mots de passe envoyés par les utilisateurs de mon application ?

Le hachage de mot de passe est l'une des pratiques de sécurité les plus basiques qui doit être effectuée. Sans cela, chaque mot de passe stocké peut être volé si le support de stockage (typiquement une base de données) est compromis. Ce mot de passe peut alors être immédiatement utilisé pour accéder frauduleusement non seulement à votre application mais aussi sur d'autres applications si l'utilisateur utilise le même mot de passe ailleurs.

En appliquant un hachage sur le mot de passe avant de le stocker, vous rendez la tâche d'un attaquant très difficile pour connaitre le mot de passe original, et vous avez toujours la possibilité de comparer le mot de passe hashé à une chaîne reçue.

Il est important de noter que le hachage ne fait que protéger les mots de passe dans la base, pas leur éventuelle interception alors qu'ils sont envoyés à l'application par l'utilisateur, via du code malicieux injecté dans l'application, par exemple.

Pourquoi les fonctions traditionnelles de hachage comme md5() et sha1() sont-elles inappropriées aux mots de passe ?

Les algorithmes de hachage comme MD5, SHA1 et SHA256 sont destinés à être rapides et efficaces. Avec les équipements informatiques modernes, il est devenu facile d'attaquer par force brute la sortie de ces algorithmes pour retrouver la chaîne originale.

C'est la raison pour laquelle de nombreux experts en sécurité considèrent ces algorithmes comme faibles et les déconseillent fortement pour hacher un mot de passe utilisateur.

Alors, comment hacher mes mots de passe ?

Lorsqu'on hashe des mots de passe, les deux considérations les plus importantes sont le temps de traitement, et le grain de sel. Plus la puissance de traitement requise est élevée, plus il faudra du temps pour casser le mot de passe en analysant sa sortie.

PHP fournit une API native de hachage de mot de passe qui gère à la fois le hachage et la vérification de mots de passe, le tout, de manière totalement sécurisée.

Une autre option est la fonction crypt(), qui supporte différents algorithmes de hachage. Lors de l'utilisation de cette fonction, vous avez la garantie que l'algorithme sélectionné est disponible, sachant que PHP contient une implémentation native de chaque algorithme supporté, dans le cas où un ou plusieurs algorithmes n'est pas supporté par votre système.

L'algorithme suggéré à utiliser pour le hachage de mots de passe est Blowfish, qui est aussi l'algorithme par défaut de l'API de hachage de mots de passe, sachant qu'il est significativement plus gourmand en calcul que MD5 ou SHA1, mais plus évolutif.

Notez que si vous utilisez la fonction crypt() pour vérifier un mot de passe, vous devez faire attention aux attaques de synchronisation, en utilisant une constante de temps pour la comparaison. Ni les opérateurs == et === ni la fonction strcmp() n'effectuent de comparaisons en utilisant des constantes de temps. Sachant que la fonction password_verify() le fera pour vous, vous êtes vivement encouragé à utiliser l'API native de hachage de mots de passe lorsque vous le pouvez.

Qu'est ce que le grain de sel ?

Un grain de sel, ou "salt", en cryptographie, est appliqué durant le processus de hachage pour éliminer la possibilité d'attaques par dictionnaires (hachages enregistrés dans une grande liste et comparés).

En d'autres termes, un grain de sel est une petite donnée additionnelle qui renforce significativement la puissance du hachage pour le rendre beaucoup plus difficile à cracker. Il existe de nombreux services en ligne qui proposent de volumineux dictionnaires de mots de passe avec leur hash. L'utilisation d'un grain de sel rend ces dictionnaires inutiles.

password_hash() va créer un salt aléatoire si vous n'en fournissez pas, et c'est généralement la façon la plus sécurisée et la plus simple.

Comment stocker mes salts ?

Lors de l'utilisation de la fonction password_hash() ou de la fonction crypt(), la valeur retournée inclue le salt comme parti du hash généré. Cette valeur devrait être stockée telle quelle dans votre base de données, sachant qu'elle inclue les informations sur la fonction de hachage utilisée et peut donc être fournie directement à la fonction password_verify() ou la fonction crypt() lors de la vérification des mots de passe.

Le diagramme suivant montre le format d'une valeur retournée de la fonction crypt() ou password_hash(). Comme vous pouvez le voir, tout est présent, comme toutes les informations sur l'algorithme et le salt nécessaires pour une future vérification de mots de passe.

Les composants de la valeur retournée par la fonction password_hash et crypt : dans l'ordre, l'algorithme choisi, les options de l'algorithme, le salt utilisé, et le mot de passe hashé.

User Contributed Notes

tamas at microwizard dot com 22-Sep-2021 08:23
While I am reading the comments some old math lessons came into my mind and started thinking. Using constants in a mathematical algorythms do not change the complexity of the algorythm itself.

The reason of salting is to avoid using rainbow tables (sorry guys this is the only reason) because it speeds up (shortcuts) the "actual" processing power.
(((Longer stored hashes AND longer password increases complexity of cracking NOT adding salt ALONE.)))

PHP salting functions returns all the needed information for checking passwords, therfore this information should be treated as constant from farther point of view. It is also a target for rainbow tables (sure: for much-much larger ones).

What is the solution?
The solution is to store password hash and salt on different places.
The implementation is yours. Every two different places will be good enough.

Yes, it will make problems for hackers. He/she needs to understand your system. No speed up for password cracking will work for him/her without reimplementing your whole system.

This is my two cent.
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 et HTML

PHP et HTML sont très interactifs : PHP peut générer du HTML et HTML peut passer des informations à PHP. Avant de lire cette faq (foire aux questions), il est important que vous appreniez comment récupérer des variables externes à PHP. La page du manuel correspondante contient beaucoup d'exemples.

  1. Quel encodage/décodage ai-je besoin lors du passage d'une valeur via un formulaire/une URL ?
  2. J'essaye d'utiliser <input type="image"> mais les variables $foo.x et $foo.y ne sont pas disponibles. $_GET['foo.x'] n'existe pas non plus. Où sont-elles ?
  3. Comment créer un tableau dans une balise <form> HTML ?
  4. Comment puis-je récupérer le résultat d'un champ HTML SELECT multiple ?
  5. Comment puis-je passer une variable de Javascript vers PHP ?
Quel encodage/décodage ai-je besoin lors du passage d'une valeur via un formulaire/une URL ?

Il y a plusieurs étapes pour lesquelles le codage est important. En supposant que vous avez une chaîne de caractères $data, qui contient la chaîne que vous voulez passer de manière non-encodée, voici les étapes appropriées :

  • Interprétation HTML. Afin d'indiquer une chaîne aléatoire, vous devez l'inclure entre doubles guillemets et utiliser la fonction htmlspecialchars() pour encoder la chaîne.

  • URL : une URL est constituée de plusieurs parties. Si vous voulez que vos données soient interprétées comme un seul élément, vous devez les encoder avec la fonction urlencode().

Exemple #1 Un élément de formulaire HTML caché

<?php
echo '<input type="hidden" value="' . htmlspecialchars($data) . '" />'."\n";
?>

Note: Il n'est pas correct d'utiliser la fonction urlencode() pour vos données $data, car il en est de la responsabilité du navigateur de les encoder. Tous les navigateurs populaires le font correctement. Notez que cela s'effectue sans considération de la méthode utilisée (c'est-à-dire GET ou POST). Vous devez uniquement noter ce cas pour les requêtes GET, car les requêtes POST sont généralement cachées.

Exemple #2 Données éditables par l'utilisateur

<?php
echo "<textarea name=\"mydata\">\n";
echo htmlspecialchars($data)."\n";
echo '</textarea>';
?>

Note: Les données sont montrées dans le navigateur comme prévues, car celui-ci interprétera les symboles HTML échappés. Au moment de la validation, via la méthode GET ou POST, les données devraient être url-encodées par le navigateur avant le transfert et directement url-décodées par PHP. Donc, finalement, vous n'avez pas à effectuer d'url-encodage/url-decodage vous-même, tout est effectué automatiquement.

Exemple #3 Dans une URL

<?php
echo '<a href="' . htmlspecialchars("/nextpage.php?stage=23&data=" .
urlencode($data)) . '">'."\n";
?>

Note: En fait, vous simulez une requête GET HTML, il est nécessaire d'utiliser manuellement la fonction urlencode() sur vos données.

Note: Vous devez utiliser htmlspecialchars() sur l'URL complète, car l'URL se comporte comme la valeur d'un attribut HTML. Dans ce cas, le navigateur fera un htmlspecialchars() sur la valeur et passera le résultat à l'URL. PHP devrait comprendre l'URL correctement, car vous avez url-encodé les données. Vous devez noter que & dans l'URL est remplacé par &amp;. Bien que la plupart des navigateurs devraient corriger cela si vous l'oubliez, ce n'est pas toujours le cas. Donc, même si votre URL n'est pas dynamique, vous devez utiliser la fonction htmlspecialchars() sur l'URL.

J'essaye d'utiliser <input type="image"> mais les variables $foo.x et $foo.y ne sont pas disponibles. $_GET['foo.x'] n'existe pas non plus. Où sont-elles ?

Lorsque vous validez un formulaire, il est possible d'utiliser une image au lieu du bouton standard de type "submit" avec une balise du type :

<input type="image" src="image.gif" name="foo" />
Lorsque l'utilisateur clique sur l'image, le formulaire est transmis au serveur avec deux variables supplémentaires : foo.x et foo.y qui représentent les coordonnées du point cliqué.

Comme foo.x et foo.y sont des noms de variables invalides en PHP, elles sont automatiquement converties en foo_x et foo_y. Les points sont remplacés par des soulignés. Donc, vous devez accéder à ces variables comme n'importe quelle autre variable tel que décrit dans la section "Variables provenant d'autres sources". Par exemple, en utilisant $_GET['foo_x'].

Note:

Les espaces dans les noms de variables sont également converties en un souligné bas.

Comment créer un tableau dans une balise <form> HTML ?

Pour envoyer le résultat du <form> comme un tableau de variables à votre script PHP, vous devez nommer, via l'attribut name, les balises <input>, <select> ou <textarea> comme cela :

<input name="MonTableau[]" />
<input name="MonTableau[]" />
<input name="MonTableau[]" />
<input name="MonTableau[]" />
Noter les crochets après le nom de la variable, c'est ce qui fait que celle-ci sera un tableau. Vous pouvez grouper les éléments dans différents tableaux de variables en assignant le même nom à différents éléments :
<input name="MonTableau[]" />
<input name="MonTableau[]" />
<input name="MonAutreTableau[]" />
<input name="MonAutreTableau[]" />
Cela produira deux tableaux de variables, MonTableau et MonAutreTableau, qui seront envoyés au script PHP. Il est également possible d'assigner des clés spécifiques à votre tableau :
<input name="UnAutreTableau[]" />
<input name="UnAutreTableau[]" />
<input name="UnAutreTableau[email]" />
<input name="UnAutreTableau[telephone]" />
Le tableau UnAutreTableau contiendra les clés 0, 1, email et telephone.

Note:

Le fait de spécifier une clé à un tableau est optionnel en HTML. Si vous ne le faites pas, les clés du tableau suiveront l'ordre d'apparition des éléments dans le formulaire. Dans notre premier exemple, le tableau contient les clés 0, 1, 2 et 3.

Voir aussi les fonctions sur les tableaux de variables et la section sur les variables provenant d'autres sources.

Comment puis-je récupérer le résultat d'un champ HTML SELECT multiple ?

Le champ SELECT multiple en HTML permet à l'utilisateur de sélectionner plusieurs éléments d'une liste. Ces éléments seront transmis à la page pointée par l'attribut action de la balise form. Le problème est que ces éléments sont tous passés avec le même nom de variable.

<select name="var" multiple="yes">
Chaque option sélectionnée arrivera au mécanisme de traitement sous la forme :
var=option1
var=option2
var=option3
Chaque option effacera donc le contenu de la précédente variable $var. La solution consiste à utiliser un tableau de variables dans cet élément de formulaire HTML, par exemple :
<select name="var[]" multiple="yes">
Cela fera que PHP traitera $var comme un tableau de variables et que chaque assignement de valeur à var[] ajoutera un index au tableau. La première option choisie sera mise dans $var[0], la suivante sera mise dans $var[1], etc. La fonction count() peut être utilisée pour déterminer combien d'options ont été sélectionnées, et la fonction sort() peut être utilisée pour trier le tableau, si nécessaire.

Notez que si vous utilisez Javascript, [] dans le nom de l'élément peut vous poser problème lorsque vous tenterez d'accéder à celui-ci par son nom. Utilisez plutôt l'indice numérique de l'élément dans ce cas, ou bien utilisez les simples guillemets pour entourer cet élément, comme :

variable = document.forms[0].elements['var[]'];

Comment puis-je passer une variable de Javascript vers PHP ?

Javascript est (habituellement) une technologie côté client et PHP est (habituellement) une technologie côté serveur et sachant que HTTP est un protocole statique, les deux langages ne peuvent pas directement partager des variables.

Cependant, il est possible de faire passer des variables entre les deux. Une des solutions pour cela est de générer un code Javascript à l'aide de PHP et de faire rafraîchir le navigateur tout seul, passant ainsi des variables spécifiques au script PHP. L'exemple suivant montre précisément comme réaliser cela -- il permet à PHP de récupérer les dimensions de l'écran du client, ce qui est normalement possible qu'en technologie coté client.

Exemple #4 Génération de Javascript avec PHP

<?php
if (isset($_GET['largeur']) AND isset($_GET['hauteur'])) {
// Affichage des variables
echo 'La largeur de l\'écran est : ' . $_GET['largeur'] ."<br />\n";
echo 'La hauteur de l\'écran est : ' . $_GET['hauteur'] . "<br />\n";
} else {
// passage des variables de dimensions
// (préservation de la requête d'origine
// -- les variables par méthode POST doivent être traitées différemment)

echo "<script type=\"text/javascript\">\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&largeur=\" + screen.width + \"&hauteur=\" + screen.height;\n";
echo "</script>\n";
exit();
}
?>

User Contributed Notes

There are no user contributed notes for this page.


PHP et COM

PHP peut être utilisé pour accéder à des objets COM et DCOM sur les plates-formes Win32.

  1. J'ai compilé une DLL pour calculer quelque chose. Y a-t-il un moyen d'utiliser cette DLL sous PHP ?
  2. Que signifie 'Unsupported variant type: xxxx (0xxxxx)' ?
  3. Est-il possible de manipuler des objets visuels en PHP ?
  4. Puis-je stocker un objet COM dans une session ?
  5. Comment puis-je intercepter des erreurs COM ?
  6. Puis-je générer des fichiers DLL à partir de PHP comme je le fais avec Perl ?
  7. Que signifie 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' ?
  8. Comment puis-je utiliser des objets COM à partir d'un serveur distant ?
  9. J'obtiens 'DCOM is disabled in C:\path...\scriptname.php on line 6', que dois-je faire ?
  10. Est-il possible de charger/manipuler des objets ActiveX dans une page en PHP ?
  11. Est-il possible d'obtenir une instance fonctionnelle d'un composant ?
  12. Y a-t-il moyen de manipuler un événement envoyé par un objet COM ?
  13. J'ai des problèmes quand j'invoque une méthode d'un objet COM qui expose plus d'une interface. Que puis-je faire ?
  14. Bon, PHP fonctionne avec COM, mais qu'en est-il de COM+ ?
  15. Si PHP peut manipuler des objets COM, peut-on imaginer d'utiliser des ressources de composants, en conjonction avec PHP ?
J'ai compilé une DLL pour calculer quelque chose. Y a-t-il un moyen d'utiliser cette DLL sous PHP ?

Si c'est une DLL simple, il n'y a aucun moyen pour le moment de l'utiliser avec PHP. Si la DLL contient un serveur COM, vous pourrez l'utiliser si elle implémente l'interface IDispatch.

Que signifie 'Unsupported variant type: xxxx (0xxxxx)' ?

Il y a des dizaines de types de VARIANT et de combinaisons entre elles. La plupart d'entre elles sont déjà supportées, mais quelques une ne sont toujours pas implémentées. Les tableaux ne sont pas complètement supportés. Seuls le tableaux unidimensionnels indexés peuvent être transmis entre PHP et COM. Si vous trouvez d'autres types qui ne sont pas supportés, reportez-les nous comme un bogue (si ce n'est pas déjà fait) et fournissez le plus d'informations possibles.

Est-il possible de manipuler des objets visuels en PHP ?

Généralement, c'est possible, mais comme PHP est utilisé le plus souvent en tant que langage de script web et dans un environnement de serveur web, les objets visuels n'apparaîtront jamais sur le bureau du serveur. Si vous voulez utiliser PHP pour scripter des applications, par exemple avec PHP-GTK, il n'y a aucune limitation à accéder et manipuler des objets visuels via COM.

Puis-je stocker un objet COM dans une session ?

Non, vous ne pouvez pas. Les instances COM sont traitées comme des ressources, ce qui signifie qu'elles ne sont disponibles que dans un seul contexte de script.

Comment puis-je intercepter des erreurs COM ?

L'extension COM envoie des exceptions com_exception, que vous pouvez intercepter en inspectant le membre code pour déterminer que faire.

Puis-je générer des fichiers DLL à partir de PHP comme je le fais avec Perl ?

Non, il n'y a malheureusement pas d'outil disponible pour le faire en PHP.

Que signifie 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' ?

Cette erreur peut avoir plusieurs causes :

  • le CLSID est incorrect
  • la DLL demandée est introuvable
  • le composant demandé n'implémente pas l'interface IDispatch

Comment puis-je utiliser des objets COM à partir d'un serveur distant ?

Exactement de la même manière qu'avec des objets locaux. Vous devez juste passer l'adresse IP de la machine distante en deuxième paramètre du constructeur COM.

Assurez-vous que vous avez spécifié com.allow_dcom =true dans votre php.ini.

J'obtiens 'DCOM is disabled in C:\path...\scriptname.php on line 6', que dois-je faire ?

Éditez votre php.ini et mettez com.allow_dcom =true.

Est-il possible de charger/manipuler des objets ActiveX dans une page en PHP ?

Cela n'a rien à voir avec PHP. Les objets ActiveX sont chargés côté client s'ils sont demandés par le document HTML. Il n'y a aucune relation avec le script PHP et il n'y a pas d'interaction directe possible avec le serveur.

Est-il possible d'obtenir une instance fonctionnelle d'un composant ?

C'est possible avec l'aide de monikers. Si vous voulez des références multiples au même mot d'instance, vous pouvez créer une instance de la façon suivante :

<?php
$word = new COM("C:\docs\word.doc");
?>

Cela créera une nouvelle instance s'il n'y en a aucune disponible ou retournera un descripteur vers l'instance courante, si elle est disponible.

Y a-t-il moyen de manipuler un événement envoyé par un objet COM ?

Vous pouvez définir un moniteur d'événement (sink) et le lier en utilisant com_event_sink(). Vous pouvez utiliser com_print_typeinfo() pour que PHP génère un squelette pour la classe du moniteur d'événement.

J'ai des problèmes quand j'invoque une méthode d'un objet COM qui expose plus d'une interface. Que puis-je faire ?

La réponse est aussi simple que non satisfaisante. Je ne sais pas exactement, mais je pense que vous ne pouvez rien faire. Si quelqu'un a des informations spécifiques sur ce sujet, faites-le » moi savoir :)

Bon, PHP fonctionne avec COM, mais qu'en est-il de COM+ ?

COM+ étend COM avec un canevas pour gérer des composants via MTS et MSMQ mais il n'y a rien de particulier que PHP doit supporter pour utiliser de tels composants.

Si PHP peut manipuler des objets COM, peut-on imaginer d'utiliser des ressources de composants, en conjonction avec PHP ?

PHP ne supporte pas encore les transactions. Ainsi, si une erreur se produit, aucun rollback n'est initié. Si vous utilisez des composants qui supportent les transactions, vous devrez implémenter le gestionnaire de transactions par vous-même.

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.


Questions diverses

Il y'a quelques questions inclassables. Vous les trouverez ici.

  1. Comment puis-je manipuler le manuel compressé en bzip2 sous Windows ?
Comment puis-je manipuler le manuel compressé en bzip2 sous Windows ?

Si vous n'avez pas d'outil d'archivage prenant en charge les fichiers au format bz2, » téléchargez l'outil en ligne de commande à partir de Redhat (merci de lire les informations plus bas).

Si vous préférez ne pas utiliser d'outil en ligne de commande, vous pouvez essayer des outils gratuits comme » Stuffit Expander, » UltimateZip, » 7-Zip, ou » Quick Zip. Si vous avez des outils comme » WinRAR ou » Power Archiver, vous pouvez facilement décompresser les fichiers bz2 avec. Si vous utilisez Total Commander (autrefois Windows Commander), un plugin bz2 est disponible gratuitement sur le site de » Total Commander.

L'outil en ligne commande bzip2 de Redhat :

Les utilisateurs du service pack 2 de Win2K doivent prendre la version 1.0.2, tous les autres utilisateurs de Windows doivent prendre la version 1.00. Après avoir téléchargé, renommez l'exécutable en bzip2.exe. Pour votre convenance, mettez-le dans un dossier dans votre path, c'est à dire C:\Windows où C représente votre disque où Windows est installé.

Note : Dans ce qui suit, lang représente votre langue et x le format désiré, par exemple : pdf. Pour décompresser php_manual_lang.x.bz2 suivez les instructions suivantes :

  • ouvrez un invite de commande
  • déplacez-vous dans le dossier où se trouvent les fichiers php_manual_lang.x.bz2
  • lancez la commande bzip2 -d php_manual_lang.x.bz2, pour extraire php_manual_lang.x dans ce même dossier

Dans le cas où vous avez téléchargé le fichier php_manual_lang.tar.bz2 avec beaucoup de fichiers HTML à l'intérieur, la procédure est la même. La seule différence est que vous obtiendrez un fichier php_manual_lang.tar. Le format tar est connu pour être pris en compte par la plupart des archiveurs de Windows, comme » WinZip.

User Contributed Notes

There are no user contributed notes for this page.


Annexes

  • Histoire de PHP
    • Histoire de PHP
    • Quelques projets liés à PHP
    • Livres traitant de PHP
    • Publications à propos de PHP
  • Migrating from PHP 8.2.x to PHP 8.3.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
    • Windows Support
  • Migration de PHP 8.1.x vers PHP 8.2.x
    • Nouvelles fonctionnalités
    • Nouvelles fonctions
    • Nouvelles constantes globales
    • Modifications entrainant une incompatibilité ascendante
    • Fonctionnalités obsolètes
    • Autres changements
    • Support Windows
  • Migration de PHP 8.0.x vers PHP 8.1.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
  • Migration de PHP 7.4.x vers PHP 8.0.x
    • New Features
    • Modifications entrainant une incompatibilité ascendante
    • Fonctionnalités obsolètes
    • Other Changes
  • Migration de PHP 7.3.x vers PHP 7.4.x
    • Nouvelles fonctionnalités
    • Nouvelles Classes et Interfaces
    • Nouvelles fonctions
    • Nouvelles constantes globales
    • Modifications entrainant une incompatibilité ascendante
    • Fonctionnalités obsolètes
    • Extensions supprimées
    • Autres changements
    • Gestion de Windows
  • Migration de PHP 7.2.x vers PHP 7.3.x
    • Nouvelles fonctionnalités
    • Nouvelles fonctions
    • Nouvelles constantes globales
    • Modifications entrainant une incompatibilité ascendante
    • Fonctionnalités devenues obsolètes
    • Autres changements
    • Support de Windows
  • Migration de PHP 7.1.x vers PHP 7.2.x
    • Nouvelles fonctionnalités
    • Nouvelles fonctions
    • Nouvelles constantes globales
    • Évolutions incompatibles avec les versions précédentes
    • Fonctionnalités devenues obsolètes en PHP 7.2.x
    • Autres changements
  • Migration de PHP 7.0.x vers PHP 7.1.x
    • Nouvelles fonctionnalités
    • Nouvelles fonctions
    • Nouvelles constantes globales
    • Modifications entrainant une incompatibilité ascendante
    • Les fonctionnalités dépréciées dans PHP 7.1.x
    • Fonctions modifiées
    • Autres changements
    • Support Windows
  • Migration de PHP 5.6.x vers PHP 7.0.x
    • Modifications entrainant une incompatibilité ascendante
    • Nouvelles fonctionnalités
    • Les fonctionnalités dépréciées dans PHP 7.0.x
    • Fonctions modifiées
    • Nouvelles fonctions
    • Nouvelles Classes et Interfaces
    • Nouvelles constantes globales
    • Modifications des modules SAPI
    • Extensions et SAPI supprimées
    • Autres changements
  • Migration de PHP 5.5.x à PHP 5.6.x
    • Modifications entrainant une incompatibilité ascendante
    • Nouvelles fonctionnalités
    • Fonctionnalités devenues obsolètes en PHP 5.6.x
    • Fonctions modifiées
    • Nouvelles fonctions
    • Changement pour OpenSSL dans PHP 5.6.x
    • Autres modifications dans les extensions
    • Nouvelles constantes globales
  • Débogueur PHP
    • À propos du débogueur en PHP
  • Options de configuration
    • Liste des options de configuration internes
  • Directives du php.ini
    • Liste des directives du php.ini
    • Liste des sections du fichier php.ini
    • Description des directives internes du php.ini
  • Catégorie/Liste des extensions
    • Par ordre alphabétique
    • Adhésion
    • État
  • Liste des alias
  • Mots réservés en PHP
    • Liste de mots-clés
    • Classes prédéfinies
    • Constantes pré-définies
    • Autre liste de mots réservés
  • Types des ressources PHP
  • Liste des filtres standards
    • Filtres de chaînes de caractères
    • Filtres de conversion
    • Filtres de compression
    • Filtres de chiffrement
  • Liste des modes de transport de sockets disponibles
    • Domaines Internet : TCP, UDP, SSL et TLS
    • Domaine Unix : UNIX et UDG
  • Comparaison de types en PHP
  • Liste des jetons de l'analyseur
  • Guide de nommage de l'espace utilisateur
    • Espace de noms global
    • Règles
    • Astuces
  • À propos du manuel
    • Formats
    • À propos des notes utilisateurs
    • Comment lire la définition d'une fonction (prototype)
    • Versions de PHP documentées dans ce manuel
    • Où trouver plus d'informations sur PHP ?
    • Comment aider à l'amélioration de la documentation ?
    • Comment sont générées les documentations
    • Traductions
  • Creative Commons Attribution 3.0
  • Liste de l'index
    • Liste des fonctions et des méthodes
    • Liste d'exemples
  • Historique des modifications

User Contributed Notes

There are no user contributed notes for this page.


Histoire de PHP

Sommaire

  • Histoire de PHP
  • Quelques projets liés à PHP
  • Livres traitant de PHP
  • Publications à propos de PHP

PHP a suivi un long chemin depuis sa naissance au milieu de l'année 1990. Depuis ses débuts modestes, jusqu'à devenir l'un des plus éminents langage de programmation pour le web, l'évolution de PHP est un véritable conte de fées technologique. Figurez-vous qu'une telle croissance n'a pas été tâche facile. Ceux d'entre vous qui sont intéressés par un bref récapitulatif de ce qu'a été l'histoire de PHP jusqu'à aujourd'hui, poursuivez la lecture de ce document. Si vous souhaitez récupérer des pièces uniques de l'histoire d'Internet, vous pouvez trouver les anciennes versions de PHP dans notre » musée.

User Contributed Notes

okhalelawrence at gmail dot com 07-Aug-2021 06:12
The Birth of PHP 6;

After Version 5: PHP received mixed reviews due to lacking native Unicode support at the core language level. In 2005, a project headed by Andrei Zmievski was initiated to bring native Unicode support throughout PHP, by embedding the International Components for Unicode (ICU) library, and representing text strings as UTF-16 internally. Since this would cause major changes both to the internals of the language and to user code, it was planned to release this as version 6.0 of the language, along with other major features then in development.

The Birth of PHP 7;

During 2014 and 2015, a new major PHP version was developed, PHP 7. The numbering of this version involved some debate among internal developers.While the PHP 6 Unicode experiment had never been released, several articles and book titles referenced the PHP 6 name, which might have caused confusion if a new release were to reuse the name. After a vote, the name PHP 7 was chosen.

The foundation of PHP 7 is a PHP branch that was originally dubbed PHP next generation (phpng). It was authored by Dmitry Stogov, Xinchen Hui and Nikita Popov, and aimed to optimize PHP performance by refactoring the Zend Engine while retaining near-complete language compatibility. By 14 July 2014, WordPress-based benchmarks, which served as the main benchmark suite for the phpng project, showed an almost 100% increase in performance. Changes from phpng make it easier to improve performance in future versions, as more compact data structures and other changes are seen as better suited for a successful migration to a just-in-time (JIT) compiler. Because of the significant changes, the reworked Zend Engine was called Zend Engine 3, succeeding Zend Engine 2 used in PHP 5.

Because of the major internal changes in phpng, it must receive a new major version number of PHP, rather than a minor PHP 5 release, according to PHP's release process. Major versions of PHP are allowed to break backward-compatibility of code and therefore PHP 7 presented an opportunity for other improvements beyond phpng that require backward-compatibility breaks.

The Birth of PHP 8;

PHP 8 was released on November 26, 2020. PHP 8 is a major version and has breaking changes from previous versions.New features and notable changes include:
Just-in-time compilation
Just-in-time compilation is supported in PHP 8.
PHP 8's JIT compiler can provide substantial performance improvements for some use cases.PHP developer Nikita Popov has stated that the performance improvements for most websites will be less substantial than the upgrade from PHP 5 to PHP 7.Performance improvements due to the addition of the JIT compiler are expected to be more substantial for mathematical-type operations than for common web-development use cases.Additionally, the JIT compiler provides future potential to move some code from C to PHP, due to the performance improvements for some use cases.
Addition of the match expression
Main article: PHP syntax and semantics § Match
PHP 8 introduced the match expression.The match expression is conceptually similar to a switch statement and is more compact for some use cases.Because match is an expression, its result can be caught into a variable or returned from a function.
Type changes and additions
PHP 8 introduced union types, a new static return type, and a new mixed type.
"Attributes", often referred to as "annotations" in other programming languages, were added in PHP 8, which allow metadata to be added to classes.
throw was changed from being a statement to being an expression. This allows exceptions to be thrown in places that were not previously possible. Sorce: wikipedia


Histoire de PHP

PHP Tools, FI, Construction Kit, et PHP/FI

PHP, tel qu'il est connu aujourd'hui, est le successeur d'un produit appelé PHP/FI. Créée en 1994 par Rasmus Lerdorf, la toute première incarnation de PHP était un simple jeu de binaires CGI écrits en langage C. Originairement utilisée pour suivre les visiteurs de son curriculum vitae en ligne, il nomme cette suite de scripts "Personal Home Page Tools" (ndt : Outils pour page personnelle), plus fréquemment appelée "PHP Tools". Au fil du temps, de plus en plus de fonctionnalités sont demandées, et Rasmus ré-écrit les outils PHP, produisant ainsi une implémentation plus large et plus riche. Ce nouveau modèle était capable d’interagir avec une base de données, mais aussi, fournissait un framework permettant aux utilisateurs de développer une application dynamique simple pour le web, comme des livres d'or. En Juin 1995, Rasmus » fournit le code source de PHP Tools au grand public, permettant ainsi aux développeurs de l'utiliser comme bon leur semblait. Ceci a également permis - et encouragé - aux utilisateurs de fournir des patches pour corriger les bogues, mais aussi pour éprouver la stabilité du produit.

En septembre de cette année là, Rasmus continua d'élargir PHP et - pour un temps très court - supprima le nom PHP. Faisant dorénavant référence aux outils sous le nom de FI (abréviation pour "Forms Interpreter" ou interpréteur de formulaire), la nouvelle implémentation incluait plusieurs fonctionnalités de base que nous connaissons encore aujourd'hui. Elle avait ces variables qui ressemblent au Perl, un système d'interprétation automatique des variables de formulaires, et une syntaxe qui s'intègre facilement dans HTML. La syntaxe elle-même était similaire à celle du Perl, bien que beaucoup plus limitée, plus simple, et un peu incohérente. En fait, pour embarquer du code dans un fichier HTML, les développeurs devaient utiliser des commentaires HTML. Malgré le fait que cette méthode ne soit pas accueillie avec un grand enthousiasme, FI continua de rassembler de plus en plus de monde, et fut accepté comme outil CGI --- mais toujours pas comme un langage. Cependant, ceci commença à changer les mois suivants ; en octobre 1995, Rasmus livra une nouvelle version totalement ré-écrite. Reprenant le nom de PHP, elle était maintenant nommée (brièvement) "Personal Home Page Construction Kit", et était la première version à mettre en avant le fait que PHP était considéré comme une interface de scripts avancée. Le langage fut délibérément architecturé pour ressembler à la structure du C, rendant ainsi son adoption facile pour les développeurs familiers avec les langages comme C, Perl et consorts. Dans un premier temps limité aux systèmes Unix et POSIX, son potentiel pour une implémentation sous Windows NT commença à être exploré.

Le code fut de nouveau repris de zéro, et en Avril 1996, combinant les noms des précédentes versions, Rasmus introduisit PHP/FI. Cette implémentation de seconde génération commença à faire réellement évoluer PHP d'une simple suite d'outils vers un vrai langage de programmation. Il incluait un support interne pour les bases de données DBM, mSQL et Postgres95, pour les cookies, un support des fonctions définies par l'utilisateur, et bien plus. Ce mois de Juin, PHP/FI prenait un statut de version 2.0. Un point intéressant, cependant, était qu'il n'existait qu'une seule et unique version de PHP 2.0. Quand elle est finalement sortie du statut bêta en Novembre 1997, le moteur d'analyse interne était déjà en cours de ré-écriture complète.

Bien qu'il fournît un cycle de développement très court, il continua de gagner en popularité dans ce monde où le développement web était encore très récent. En 1997 et 1998, PHP/FI comptait plusieurs milliers d'utilisateurs à travers le monde. Le site de surveillance Netcraft, en Mai 1998, indiquait qu'environ 60.000 domaines exportaient l'en-tête "PHP", indiquant ainsi que le serveur hôte l'avait d'installé. Ce nombre correspondait à environ 1% des domaines d'Internet de l'époque. Malgré ce chiffre impressionnant, la maturation de PHP/FI était condamnée à ses limitations ; bien qu'il y ait plusieurs contributeurs mineurs, il était encore principalement développé par un seul individu.

Exemple #1 Exemple de code PHP/FI

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hé, vous utilisez Netscape !<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Désolé, cette ligne n'existe pas<p>
<!--endif exit-->
  Bienvenue <!--$user--> !<p>
  Vous avez <!--$index:0--> crédits sur votre compte.<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 fut la première version du langage tel que nous le connaissons actuellement. Trouvant que PHP/FI 2.0 était toujours insuffisant et manquait de fonctionnalités nécessaires pour mettre en oeuvre une application d'eCommerce, qu'ils développaient dans le cadre d'un projet universitaire, Andi Gutmans et Zeev Suraski de la ville de Tel Aviv (Israël) commencèrent encore une autre ré-écriture complète de l'analyseur interne en 1997. Se rapprochant de Rasmus via le web, ils discutèrent de divers aspects de l'implémentation courante et de leur re-développement de PHP. Dans une logique d'amélioration du moteur, et pour profiter des utilisateurs existant de PHP/FI, Andi, Rasmus et Zeev décidèrent de collaborer dans le développement d'un nouvel et indépendant langage de programmation. Ce tout nouveau langage a été publié sous un nouveau nom, qui supprima l'idée d'utilisation personnelle limitée inclue dans le nom de PHP/FI 2.0. Il fut ainsi tout simplement renommé 'PHP', dont la signification devint un acronyme récursif - PHP: Hypertext Preprocessor.

Une des améliorations notables de PHP 3.0 fut ses capacités d'extension. En plus de fournir une infrastructure mature pour de multiples bases de données, protocoles, et APIs, la facilité d'extension du langage en lui-même attira des dizaines de développeurs, qui produisirent de nombreux modules. Ce fut sans aucun doute une des clés de l'énorme succès de PHP 3.0. Une autre de ces clés fut l'introduction d'un support de programmation orientée objet, ainsi qu'une syntaxe de langage bien plus puissante et plus consistante.

En Juin 1998, avec plusieurs nouveaux développeurs de par le monde rejoignant le projet, PHP 3.0 fut annoncé par la nouvelle équipe de développement de PHP comme le successeur officiel de PHP/FI 2.0. Le développement actif de PHP/FI 2.0, qui avait en réalité cessé depuis le mois de Novembre de l'année précédente, était maintenant officiellement terminé. Après environ 9 mois de tests publics, lorsque l'annonce de la version officielle de PHP 3.0 fut publiée, il était déjà installé sur plus de 70.000 domaines à travers le monde, et n'était plus limité aux systèmes POSIX. Une petite partie des domaines rapportant une installation de PHP étaient installés sur des serveurs fonctionnant sous Windows 95, 98, NT, et Macintosh. À son apogée, PHP 3.0 était installé sur approximativement 10% des serveurs web d'Internet.

PHP 4

Durant l'hiver 1998, juste après la publication de PHP 3.0, Andi Gutmans et Zeev Suraski commencèrent une réécriture du moteur interne de PHP. Les objectifs étaient d'améliorer les performances de PHP sur les applications complexes, et d'améliorer la modularité du code. Ces applications étaient rendues possibles par les nouvelles fonctionnalités de PHP 3.0 et le support d'un grand nombre de bases de données et d'APIs, mais PHP 3.0 n'était pas conçu pour gérer efficacement des applications si complexes.

Le nouveau moteur, appelé 'Zend Engine' (combinaison des prénoms de Zeev et Andi), atteignit cet objectif avec succès, et la première version fut publiée vers la mi-1999. PHP 4.0, s'appuyant sur ce moteur, et amélioré par un grand nombre de nouvelles fonctionnalités, fut publié officiellement en mai 2000, presque 2 ans après son prédécesseur. En plus de performances nettement plus élevées, PHP 4.0 apportait le support de nombreux serveurs web, des sessions HTTP, la bufferisation de sortie, une sécurité accrue de la gestion des informations visiteurs, et plusieurs nouvelles structures de langage.

PHP 5

PHP 5 est sorti en Juillet 2004, après un long développement et plusieurs pré-versions. Il est régi par son moteur, le Zend Engine 2.0 avec un nouveau modèle objet et des dizaines d'autres nouvelles fonctionnalités.

L'équipe de développement de PHP regroupe des dizaines de développeurs, en plus des dizaines d'autres travaillant sur des projets en rapport avec PHP, comme PEAR, PECL, et la documentation, ainsi qu'un réseau d'infrastructure sous-jacent d'une centaine de serveurs web individuels sur 6 des 7 continents du monde. En s'appuyant sur une estimation basée sur les statistiques de l'année précédente, il est convenable de supposer que PHP est maintenant installé sur des dizaines, voire même des centaines, de millions de domaines autour du monde.

User Contributed Notes

There are no user contributed notes for this page.


Quelques projets liés à PHP

PEAR

» PEAR, qui signifie PHP Extension and Application Repository (initialement, PHP Extension and Add-on Repository), est la première version des classes de base en PHP, et pourrait devenir à terme un moyen privilégié de distribuer des extensions PHP entre développeurs.

PEAR est né durant les débats tenus lors des PHP Developers' Meeting (PDM) (Rencontres de développeurs PHP), qui ont eu lieu en Janvier 2000 à Tel Aviv. Il a été créé à l'initiative de Stig S. Bakken, et est dédié à sa première fille, Malin Bakken.

Depuis l'an 2000, PEAR a grossi jusqu'à devenir un projet significatif avec un groupe de développeurs compétents, qui travaillent à mettre en place une bibliothèque complète, réutilisable et commune, au bénéfice de la communauté PHP entière. Aujourd'hui, PEAR inclut une vaste sélection de classes de base pour accéder à des bases de données, pour stocker du contenu en cache, réaliser des calculs mathématiques, des transactions de commerce électronique, etc.

Plus d'informations sur PEAR sont disponibles dans » le manuel.

Equipe d'assurance Qualité

» L'équipe d'assurance Qualité de PHP a été mise en place durant l'été 2000, en réponse aux critiques reçues par PHP 3.0, qui n'était pas suffisamment testé pour des environnements de production. L'équipe est maintenant composée d'un groupe de développeurs de haut niveau, qui ont une bonne connaissance des sources PHP. Ces développeurs passent une bonne partie de leur temps à localiser et corriger les bogues trouvés dans PHP. De plus, il y a un bon nombre d'autres membres du groupe PHP qui testent et fournissent un compte-rendu fidèle de l'utilisation de PHP sur différentes plateformes.

PHP-GTK

» PHP-GTK est la solution PHP pour écrire des applications avec interface graphique, côté client. Andrei Zmievski se souvient de la création de PHP-GTK :

La programmation d'interface GUI m'a toujours intéressée, et je pensais que Gtk+ était une excellente bibliothèque, hormis le fait que programmer avec en C est plutôt laborieux. Après avoir assisté aux implémentations de PyGtk et GTK-Perl, j'ai décidé de voir si PHP pouvait disposer de sa propre interface avec Gtk+, même minimale. J'ai commencé au mois d'août 2000, alors que j'avais un peu plus de temps libre, et j'ai réalisé les premières expérimentations. Mon guide principal fut l'implémentation de PyGtk, qui était plutôt complète et avait une interface orientée objet. James Henstridge, l'auteur de PyGtk, fut d'une aide précieuse au démarrage de ce projet.

Réécrire toutes les interfaces de Gtk+ à la main était hors de question et j'ai pensé à réaliser un générateur de code, exactement comme PyGtk l'avait fait. Le générateur de code est un programme PHP qui lit un ensemble de fichiers .defs, contenant les classes, constantes et méthodes Gtk+, puis génére le code C qui sert d'interface à PHP. Ce qui ne peut pas être généré automatiquement peut être écrit à la main, dans le fichier .overrides.

Travailler sur le générateur de code et sur l'infrastructure prit un peu de temps, car je n'avais que peu de temps à consacrer à PHP-GTK durant l'automne 2000. Après que j'ai montré PHP-GTK à Frank Kromann, il s'y intéressa et commença à m'aider sur le générateur et l'implémentation Win32. Lorsque nous écrivîmes le premier programme 'Hello World', ce fut extrêmement excitant. Il fallut encore quelques mois pour que le projet soit présentable, et la version initiale fut publiée en mars 2001. La nouvelle fut rapidement relayée sur SlashDot.

Anticipant que PHP-GTK pourrait devenir un projet à part entière, j'ai mis en place des listes de diffusion et un serveur CVS indépendants, de même que le site gtk.php.net avec l'aide de Colin Viebrock. La documentation avait aussi besoin d'être rédigée, et James Moore vint me porter une aide précieuse.

Depuis sa publication PHP-GTK a gagné en popularité. Nous avons notre propre équipe de documentation, le manuel s'améliore de plus en plus, des gens ont commencé à écrire des extensions pour PHP-GTK, ainsi des applications de plus en plus importantes l'utilisant.

User Contributed Notes

There are no user contributed notes for this page.


Livres traitant de PHP

Au fur et à mesure que PHP a évolué, il est petit à petit devenu une plate-forme de développement mondialement populaire. Un des signes qui ne trompent pas est que le nombre de livres dédiés à PHP a augmenté en parallèle, au fil des années.

À notre connaissance, le premier livre dédié à PHP fut 'PHP - tvorba interaktivních internetových aplikací' (PHP - Créer des Applications Interactives pour Internet), un livre tchèque publié en avril 1999, écrit par Jirka Kosek. Le mois suivant parut un livre allemand écrit par Egon Schmid, Christian Cartus et Richard Blume. Le premier livre en anglais sur PHP fut publié juste après : 'Core PHP Programming' par Leon Atkinson. Ces livres se rapportaient à PHP 3.0.

Même si ces livres étaient les premiers de leur genre, ils furent rapidement suivis par un grand nombre d'autres livres, de différents auteurs et éditeurs. On dénombre plus de 400 livres en anglais, plus de 100 en allemand, et plus de 50 en français ou espagnol ! De plus, on peut maintenant trouver des livres à propos de PHP dans de nombreuses autres langues, comme le coréen, le japonais ou l'hébreu.

De toute évidence, ce grand nombre de livres, écrits par différents auteurs et publiés par de nombreux éditeurs, ainsi que leur disponibilité en différentes langues, témoigne clairement du succès planétaire de PHP.

User Contributed Notes

There are no user contributed notes for this page.


Publications à propos de PHP

À notre connaissance, le premier article consacré à PHP dans un magazine papier fut publié dans la version tchèque de Computerworld, au printemps 1998, et se rapportait à PHP 3.0. Comme pour les livres, ce fut le premier d'une longue série d'articles publiés dans un nombre important de magazines.

Des articles sur PHP ont été publiés dans Dr. Dobbs, Linux Enterprise, Linux Magazine et bien d'autres. Il existe même des articles sur la migration d'applications ASP vers PHP sous Windows dans la bibliothèque MSDN de Microsoft.

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 8.2.x to PHP 8.3.x

Sommaire

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

Voir aussi les guides de migration entre les différentes versions de PHP 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x, 8.2.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Readonly Amendments

Anonymous classes may now be marked as readonly.

Readonly properties can now be reinitialized during cloning.

Typed Class Constants

Class, interface, trait, and enum constants now support type declarations.

Closures created from magic methods

Closures created from magic methods can now accept named arguments.

The final modifier with a method from a trait

The final modifier may now be used when using a method from a trait.

Override Attribute

Added the #[\Override] attribute to check that a method exists in a parent class or implemented interface.

Fetch class constant dynamically syntax

Class constants can now be accessed dynamically using the C::{$name} syntax.

Static variable Initializers

Static variable initializers can now contain arbitrary expressions.

Fallback value syntax for ini variables

php.ini now supports fallback/default value syntax.

<?php
/*
On /path/to/user.ini contains the following settings:

listen = localhost:${DRUPAL_FPM_PORT:-9000}
*/

$user_ini = parse_ini_file('/path/to/user.ini');
echo $user_ini['listen']; // localhost:9000

CLI

It is now possible to lint multiple files.

DOM

Added properties DOMElement::$className and DOMElement::$id. These are not binary-safe at the moment because of underlying limitations of libxml2. This means that the property values will be cut off at a NUL byte.

Added properties DOMNode::$isConnected and DOMNameSpaceNode::$isConnected.

Added properties DOMNode::$parentElement and DOMNameSpaceNode::$parentElement.

FFI

It is now possible to assign FFI\CData to other FFI\CData. Meaning CData can now be assigned to structs and fields.

Opcache

opcache_get_status()['scripts'][n]['revalidate'] now contains a Unix timestamp of when the next revalidation of the scripts timestamp is due, dictated by the opcache.revalidate_freq INI directive.

POSIX

posix_getrlimit() now takes an optional $res parameter to allow fetching a single resource limit.

posix_isatty() now raises type warnings for integers following the usual ZPP semantics.

posix_ttyname() now raises type warnings for integers following the usual ZPP semantics and value warnings for invalid file descriptor integers.

Streams

Streams can now emit the STREAM_NOTIFY_COMPLETED notification. This was previously not implemented.

User Contributed Notes

There are no user contributed notes for this page.


New Classes and Interfaces

Date

  • DateError
  • DateObjectError
  • DateRangeError
  • DateException
  • DateInvalidOperationException
  • DateInvalidTimeZoneException
  • DateMalformedIntervalStringException
  • DateMalformedPeriodStringException
  • DateMalformedStringException

Random

  • Random\IntervalBoundary

User Contributed Notes

There are no user contributed notes for this page.


New Functions

Date

  • DatePeriod::createFromISO8601String()

DOM

  • DOMElement::getAttributeNames()
  • DOMElement::insertAdjacentElement()
  • DOMElement::insertAdjacentText()
  • DOMElement::toggleAttribute()
  • DOMNode::contains()
  • DOMNode::getRootNode()
  • DOMNode::isEqualNode()
  • DOMNameSpaceNode::contains()
  • DOMParentNode::replaceChildren()

Intl

  • IntlCalendar::setDate()
  • IntlCalendar::setDateTime()
  • IntlGregorianCalendar::createFromDate()
  • IntlGregorianCalendar::createFromDateTime()

JSON

  • json_validate()

LDAP

  • ldap_connect_wallet()
  • ldap_exop_sync()

MBString

  • mb_str_pad()

Posix

  • posix_sysconf()
  • posix_pathconf()
  • posix_fpathconf()
  • posix_eaccess()

PostgreSQL

  • pg_set_error_context_visibility() (libpq >= 9.6)

Random

  • Random\Randomizer::getBytesFromString()
  • Random\Randomizer::nextFloat()
  • Random\Randomizer::getFloat()

Reflection

  • ReflectionMethod::createFromMethodName()

Sockets

  • socket_atmark()

Standard

  • str_increment()
  • str_decrement()
  • stream_context_set_options()

Zip

  • ZipArchive::getArchiveFlag()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

cURL

  • CURLINFO_CAPATH (libcurl >= 7.84.0)
  • CURLINFO_CAINFO (libcurl >= 7.84.0)
  • CURLOPT_MIME_OPTIONS (libcurl >= 7.81.0)
  • CURLMIMEOPT_FORMESCAPE (libcurl >= 7.81.0)
  • CURLOPT_WS_OPTIONS (libcurl >= 7.86.0)
  • CURLWS_RAW_MODE (libcurl >= 7.86.0)
  • CURLOPT_SSH_HOSTKEYFUNCTION (libcurl >= 7.84.0)
  • CURLOPT_PROTOCOLS_STR (libcurl >= 7.85.0)
  • CURLOPT_REDIR_PROTOCOLS_STR (libcurl >= 7.85.0)
  • CURLOPT_CA_CACHE_TIMEOUT (libcurl >= 7.87.0)
  • CURLOPT_QUICK_EXIT (libcurl >= 7.87.0)
  • CURLKHMATCH_OK (libcurl >= 7.19.6)
  • CURLKHMATCH_MISMATCH (libcurl >= 7.19.6)
  • CURLKHMATCH_MISSING (libcurl >= 7.19.6)
  • CURLKHMATCH_LAST (libcurl >= 7.19.6)

Intl

  • MIXED_NUMBERS (Spoofchecker)
  • HIDDEN_OVERLAY (Spoofchecker)

OpenSSL

  • OPENSSL_CMS_OLDMIMETYPE
  • PKCS7_NOOLDMIMETYPE

PCNTL

  • SIGINFO

PDO_ODBC

  • PDO_ODBC_TYPE

Posix

  • POSIX_SC_ARG_MAX
  • POSIX_SC_PAGESIZE
  • POSIX_SC_NPROCESSORS_CONF
  • POSIX_SC_NPROCESSORS_ONLN
  • POSIX_PC_LINK_MAX
  • POSIX_PC_MAX_CANON
  • POSIX_PC_MAX_INPUT
  • POSIX_PC_NAME_MAX
  • POSIX_PC_PATH_MAX
  • POSIX_PC_PIPE_BUF
  • POSIX_PC_CHOWN_RESTRICTED
  • POSIX_PC_NO_TRUNC
  • POSIX_PC_ALLOC_SIZE_MIN
  • POSIX_PC_SYMLINK_MAX

Sockets

The following socket options are now defined if they are supported:

  • SO_ATTACH_REUSEPORT_CBPF (Linux)
  • SO_DETACH_BPF (Linux)
  • SO_DETACH_FILTER (Linux)
  • TCP_QUICKACK (Linux)
  • IP_DONTFRAG (FreeBSD)
  • IP_MTU_DISCOVER (Linux)
  • IP_PMTUDISC_DO (Linux)
  • IP_PMTUDISC_DONT (Linux)
  • IP_PMTUDISC_WANT (Linux)
  • IP_PMTUDISC_PROBE (Linux)
  • IP_PMTUDISC_INTERFACE (Linux)
  • IP_PMTUDISC_OMIT (Linux)
  • AF_DIVERT (FreeBSD)
  • SOL_UDPLITE
  • UDPLITE_RECV_CSCOV
  • UDPLITE_SEND_CSCOV
  • SO_RERROR (NetBSD)
  • SO_ZEROIZE (OpenBSD)
  • SO_SPLICE (OpenBSD)
  • TCP_REPAIR (Linux)
  • SO_REUSEPORT_LB (FreeBSD)
  • IP_BIND_ADDRESS_NO_PORT (Linux)

Zip

  • ZipArchive::ER_DATA_LENGTH (libzip >= 1.10)
  • ZipArchive::ER_NOT_ALLOWED (libzip >= 1.10)
  • ZipArchive::AFL_RDONLY (libzip >= 1.10)
  • ZipArchive::AFL_IS_TORRENTZIP (libzip >= 1.10)
  • ZipArchive::AFL_WANT_TORRENTZIP (libzip >= 1.10)
  • ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE (libzip >= 1.10)
  • ZipArchive::FL_OPEN_FILE_NOW
  • ZipArchive::LENGTH_TO_END as default value for
ZipArchive::addFile() and
ZipArchive::replaceFile()
  • ZipArchive::LENGTH_UNCHECKED (libzip >= 1.10)

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

Programs that were very close to overflowing the call stack

Programs that were very close to overflowing the call stack may now throw an Error when using more than zend.max_allowed_stack_size-zend.reserved_stack_size bytes of stack (fiber.stack_size-zend.reserved_stack_size for fibers).

Executing proc_get_status() multiple times

Executing proc_get_status() multiple times will now always return the right value on POSIX systems. Previously, only the first call of the function returned the right value. Executing proc_close() after proc_get_status() will now also return the right exit code. Previously this would return -1. Internally, this works by caching the result on POSIX systems. If the previous behaviour is required, it is possible to check the "cached" key in the array returned by proc_get_status() to check whether the result was cached.

Zend Max Execution Timers

Zend Max Execution Timers is now enabled by default for ZTS builds on Linux.

Uses of traits with static properties

Uses of traits with static properties will now redeclare static properties inherited from the parent class. This will create a separate static property storage for the current class. This is analogous to adding the static property to the class directly without traits.

Assigning a negative index to an empty array

Assigning a negative index $n to an empty array will now make sure that the next index is $n+1 instead of 0.

Class constant visibility variance check

Class constant visibility variance is now correctly checked when inherited from interfaces.

WeakMap entries whose key maps to itself

WeakMap entries whose key maps to itself (possibly transitively) may now be removed during cycle collection if the key is not reachable except by iterating over the WeakMap (reachability via iteration is considered weak). Previously, such entries would never be automatically removed.

Date

The DateTime extension has introduced Date extension specific exceptions and errors under the DateError and DateException hierarchies, instead of warnings and generic exceptions. This improves error handling, at the expense of having to check for errors and exceptions.

DOM

Calling DOMChildNode::after(),
DOMChildNode::before(),
DOMChildNode::replaceWith()
on a node that has no parent is now a no-op instead of a hierarchy
exception, which is the behaviour demanded by the DOM specification.

Using the DOMParentNode and DOMChildNode methods without a document now works instead of throwing a DOM_HIERARCHY_REQUEST_ERR DOMException. This is in line with the behaviour demanded by the DOM specification.

Calling DOMDocument::createAttributeNS() without specifying a prefix would incorrectly create a default namespace, placing the element inside the namespace instead of the attribute. This bug is now fixed.

DOMDocument::createAttributeNS() would previously incorrectly throw a DOM_NAMESPACE_ERRNAMESPACE_ERR DOMException when the prefix was already used for a different URI. It now correctly chooses a different prefix when there's a prefix name conflict.

New methods and properties were added to some DOM classes. If a userland class inherits from these classes and declare a method or property with the same name, the declarations must be compatible. Otherwise, a typical compile error about incompatible declarations will be thrown. See the list of new features and new functions for a list of the newly implemented methods and properties.

FFI

C functions that have a return type of void now return null instead of returning the following object object(FFI\CData:void) { }

Opcache

The opcache.consistency_checks INI directive was removed. This feature was broken with the tracing JIT, as well as with inheritance cache, and has been disabled without a way to enable it since PHP 8.1.18 and PHP 8.2.5. Both the tracing JIT and inheritance cache may modify shm after the script has been persisted by invalidating its checksum. The attempted fix skipped over the modifiable pointers but was rejected due to complexity. For this reason, it was decided to remove the feature instead.

Phar

The type of Phar class constants are now declared.

Standard

The range() function has had various changes:

  • A TypeError is now thrown when passing objects, resources, or arrays as the boundary inputs.
  • A more descriptive ValueError is thrown when passing 0 for $step.
  • A ValueError is now thrown when using a negative $step for increasing ranges.
  • If $step is a float that can be interpreted as an int, it is now done so.
  • A ValueError is now thrown if any argument is infinity or NAN.
  • An E_WARNING is now emitted if $start or $end is the empty string. The value continues to be cast to the value 0.
  • An E_WARNING is now emitted if $start or $end has more than one byte, only if it is a non-numeric string.
  • An E_WARNING is now emitted if $start or $end is cast to an integer because the other boundary input is a number. (e.g. range(5, 'z');).
  • An E_WARNING is now emitted if $step is a float when trying to generate a range of characters, except if both boundary inputs are numeric strings (e.g. range('5', '9', 0.5); does not produce a warning).
  • range() now produce a list of characters if one of the boundary inputs is a string digit instead of casting the other input to int (e.g. range('9', 'A');).
<?php
range('9', 'A'); // ["9", ":", ";", "<", "=", ">", "?", "@", "A"], as of PHP 8.3.0
range('9', 'A'); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], prior to PHP 8.3.0
?>

The file() flags error check now catches all invalid flags. Notably FILE_APPEND was previously silently accepted.

SNMP

The type of SNMP class constants are now declared.

User Contributed Notes

There are no user contributed notes for this page.


Deprecated Features

PHP Core

Saner Increment/Decrement operators

Using the increment operator (++) on empty, non-numeric, or non-alphanumeric strings is now deprecated. Moreover, incrementing non-numeric strings is soft deprecated. That means no E_DEPRECATED diagnostic is emitted, but this feature should not be used when producing new code. The new str_increment() function should be used instead.

Using the decrement operator (--) on empty or non-numeric strings is now deprecated.

get_class()/get_parent_class() call without arguments

Calling get_class() and get_parent_class() without arguments is now deprecated.

DBA

Calling dba_fetch() with $dba as the 3rd argument is now deprecated.

FFI

Calling FFI::cast(), FFI::new(), and FFI::type() statically is now deprecated.

Intl

The U_MULTIPLE_DECIMAL_SEP*E*RATORS constant had been deprecated, using the U_MULTIPLE_DECIMAL_SEP*A*RATORS constant instead is recommended.

The NumberFormatter::TYPE_CURRENCY constant has been deprecated.

LDAP

Calling ldap_connect() with separate $hostname and $port is deprecated.

MBString

Passing a negative $width to mb_strimwidth() is now deprecated.

Phar

Calling Phar::setStub() with a resource and a $length is now deprecated. Such calls should be replaced by: $phar->setStub(stream_get_contents($resource));

Random

The MT_RAND_PHP Mt19937 variant is deprecated.

Reflection

Calling ReflectionProperty::setValue() with only one parameter is deprecated. To set static properties, pass null as the first parameter.

Standard

The assert_options() function is now deprecated.

The ASSERT_ACTIVE, ASSERT_BAIL, ASSERT_CALLBACK, ASSERT_EXCEPTION, and ASSERT_WARNING constants have been deprecated.

The assert.* INI settings have been deprecated. See the Changes to INI File Handling page for further details.

SQLite3

Using exceptions is now preferred, warnings will be removed in the future. Calling SQLite3::enableExceptions(false) will trigger a deprecation warning in this version.

Zip

The ZipArchive::FL_RECOMPRESS constant is deprecated and will be removed in a future version of libzip.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Core changes

FFI

FFI::load() is now allowed during preloading when opcache.preload_user is the current system user. Previously, calling FFI::load() was not possible during preloading if the opcache.preload_user directive was set.

FPM

FPM CLI test now fails if the socket path is longer than supported by OS.

Opcache

In the CLI and phpdbg SAPIs, preloading does not require the opcache.preload_user directive to be set anymore when running as root. In other SAPIs, this directive is required when running as root because preloading is done before the SAPI switches to an unprivileged user.

Streams

Blocking fread() on socket connection returns immediately if there are any buffered data instead of waiting for more data.

Memory stream no longer fails if seek offset is past the end. Instead the memory is increase on the next write and date between the old end and offset is filled with zero bytes in the same way how it works for files.

stat() access operations like file_exists() and similar will now use real path instead of the actual stream path. This is consistent with stream opening.

Changes in SAPI Modules

CLI

The STDOUT, STDERR and STDIN streams are no longer closed on resource destruction which is mostly when the CLI finishes. It is however still possible to explicitly close those streams using fclose() and similar.

Changed Functions

Core

gc_status() has added the following 8 fields:

  • "running" => bool
  • "protected" => bool
  • "full" => bool
  • "buffer_size" => int
  • "application_time" => float: Total application time, in seconds (including collector_time)
  • "collector_time" => float: Time spent collecting cycles, in seconds (including destructor_time and free_time)
  • "destructor_time" => float: Time spent executing destructors during cycle collection, in seconds
  • "free_time" => float: Time spent freeing values during cycle collection, in seconds

class_alias() now supports creating an alias of an internal class.

Setting open_basedir at runtime using ini_set('open_basedir', ...); no longer accepts paths containing the parent directory (..). Previously, only paths starting with .. were disallowed. This could easily be circumvented by prepending ./ to the path.

User exception handlers now catch exceptions during shutdown.

The resultant HTML of highlight_string() and highlight_file() has changed. Whitespace between outer HTML tags is removed. Newlines and spaces are no longer converted to HTML entities. The whole HTML is now wrapped in a <pre> tag. The outer <span> tag has been merged with the <code> tag.

Calendar

easter_date() now supports years from 1970 to 2,000,000,000 on 64-bit systems, previously it only supported years in the range from 1970 to 2037.

Curl

curl_getinfo() now supports two new constants: CURLINFO_CAPATH and CURLINFO_CAINFO. If option is null, the following two additional keys are present: "capath" and "cainfo".

DOM

Changed DOMCharacterData::appendData() tentative return type to true.

DOMDocument::loadHTML(), DOMDocument::loadHTMLFile(), and DOMDocument::loadXML() now have a tentative return type of bool. Previously, this was documented as having a return type of DOMDocument|bool, but, as of PHP 8.0.0, DOMDocument cannot be returned as it is no longer statically callable.

Gd

The signature of imagerotate() has changed. The $ignore_transparent parameter has been removed, as it was ignored since PHP 5.5.0.

Intl

datefmt_set_timezone() (and its alias IntlDateformatter::setTimeZone()) now returns true on success, previously null was returned.

IntlBreakiterator::setText() now returns false on failure, previously null was returned. It now returns true on success, previously null was returned.

IntlChar::enumCharNames() is now returning a boolean. Previously it returned null on success and false on failure.

IntlDateFormatter::__construct() throws an U_ILLEGAL_ARGUMENT_ERROR exception when an invalid locale had been set.

MBString

mb_strtolower() and mb_convert_case() implement conditional casing rules for the Greek letter sigma. For mb_convert_case(), conditional casing only applies to MB_CASE_LOWER and MB_CASE_TITLE modes, not to MB_CASE_LOWER_SIMPLE and MB_CASE_TITLE_SIMPLE.

mb_decode_mimeheader() interprets underscores in QPrint-encoded MIME encoded words as required by RFC 2047; they are converted to spaces. Underscores must be encoded as "=5F" in such MIME encoded words.

In rare cases, mb_encode_mimeheader() will transfer-encode its input string where it would pass it through as raw ASCII in PHP 8.2.

mb_encode_mimeheader() no longer drops NUL (zero) bytes when QPrint-encoding the input string. This previously caused strings in certain text encodings, especially UTF-16 and UTF-32, to be corrupted by mb_encode_mimeheader.

mb_detect_encoding()'s "non-strict" mode now behaves as described in the documentation. Previously, it would return false if the same byte (for example, the first byte) of the input string was invalid in all candidate encodings. More generally, it would eliminate candidate encodings from consideration when an invalid byte was seen, and if the same input byte eliminated all remaining encodings still under consideration, it would return false. On the other hand, if all candidate encodings but one were eliminated from consideration, it would return the last remaining one without regard for how many encoding errors might be encountered later in the string. This is different from the behavior described in the documentation, which says: "If strict is set to false, the closest matching encoding will be returned."

mysqli

mysqli_fetch_object() now raises a ValueError instead of an Exception when the $constructor_args argument is non empty with the class not having constructor.

mysqli_poll() now raises a ValueError when neither the $read nor the $error arguments are passed.

mysqli_field_seek() and mysqli_result::field_seek() now specify the return type as true instead of bool.

ODBC

odbc_autocommit() now accepts null for the $enable parameter. Passing null has the same behaviour as passing only 1 parameter, namely indicating if the autocommit feature is enabled or not.

PGSQL

pg_fetch_object() now raises a ValueError instead of an Exception when the $constructor_args argument is non empty with the class not having constructor.

pg_insert() now raises a ValueError instead of a E_WARNING when the table specified is invalid.

pg_insert() and pg_convert() raises a ValueError or a TypeError instead of a E_WARNING when the value/type of a field does not match properly with a PostgreSQL's type.

The $row parameter of
pg_fetch_result(),
pg_field_prtlen(), and
pg_field_is_null() is now nullable.

Random

Changed mt_srand() and srand() to not check the number of arguments to determine whether a random seed should be used. Passing null will generate a random seed, 0 will use zero as the seed. The functions are now consistent with Random\Engine\Mt19937::__construct().

Reflection

Return type of ReflectionClass::getStaticProperties() is no longer nullable.

Standard

E_NOTICEs emitted by unserialize() have been promoted to E_WARNING.

unserialize() now emits a new E_WARNING if the input contains unconsumed bytes.

array_pad() is now only limited by the maximum number of elements an array can have. Before, it was only possible to add at most 1048576 elements at a time.

strtok() raises an E_WARNING in the case token is not provided when starting tokenization.

password_hash() will now chain the underlying Random\RandomException as the ValueError's $previous Exception when salt generation fails.

If using an array as the $command for proc_open(), it must now have at least one non empty element. Otherwise a ValueError is thrown.

proc_open() returns false if $command array is invalid command instead of resource object that produces warning later. This was already the case for Windows but it is now also the case if posix_spawn implementation is in use (most Linux, BSD and MacOS platforms). There are still some old platforms where this behavior is not changed as posix_spawn is not supported there.

array_sum() and array_product() now warn when values in the array cannot be converted to int/float. Previously arrays and objects where ignored whilst every other value was cast to int. Moreover, objects that define a numeric cast (e.g. GMP) are now casted instead of ignored.

The $decimal of number_format() now properly handles negative integers. Rounding with a negative value for $decimal means that $num is rounded to $decimals significant digits before the decimal point. Previously negative $decimals were silently ignored and the number got rounded to zero decimal places.

A new $before_needle argument has been added to strrchr(). It behaves like its counterpart in the strstr() or stristr() functions.

str_getcsv() and fgetcsv() now return an empty string instead of a string with a single null byte for the last field which only contains an unterminated enclosure.

Other Changes to Extensions

Core

Using the increment/decrement operators (++/--) on values of type bool now emit warnings. This is because it currently has no effect, but will behave like $bool += 1 in the future.

Using the decrement operator (--) on values of type null now emit warnings. This is because it currently has no effect, but will behave like $null -= 1 in the future.

Internal objects that implement an _IS_NUMBER cast but not a do_operator handler that overrides addition and subtraction now can be incremented and decrement as if one would do $o += 1 or $o -= 1

DOM

The DOM lifetime mechanism has been reworked such that implicitly removed nodes can still be fetched. Previously this resulted in an exception.

SQLite3

The SQLite3 class now throws SQLite3Exception (extends Exception) instead of Exception.

The SQLite error code is now passed in the exception error code instead of being included in the error message.

Changes to INI File Handling

  • The assert.* INI settings have been deprecated. This comprises the following INI settings:

    • assert.active
    • assert.bail
    • assert.callback
    • assert.exception
    • assert.warning
    If the value of the setting is equal to the default value, no deprecation notice is emitted. The zend.assertions INI setting should be used instead.

  • zend.max_allowed_stack_size is a new INI directive to set the maximum allowed stack size. Possible values are 0 (detect the process or thread maximum stack size), -1 (no limit), or a positive number of bytes. The default is 0. When it is not possible to detect the process or thread maximum stack size, a known system default is used. Setting this value too high has the same effect as disabling the stack size limit. Fibers use fiber.stack_size as maximum allowed stack size. An Error is thrown when the process call stack exceeds zend.max_allowed_stack_size-zend.reserved_stack_size bytes, to prevent stack-overflow-induced segmentation faults, with the goal of making debugging easier. The stack size increases during uncontrolled recursions involving internal functions or the magic methods __toString(), __clone(), __sleep(), __destruct(). This is not related to stack buffer overflows, and is not a security feature.

  • zend.reserved_stack_size is a new INI directive to set the reserved stack size, in bytes. This is subtracted from the max allowed stack size, as a buffer, when checking the stack size.

Performance

DOM

Looping over a DOMNodeList now uses caching. Therefore requesting items no longer takes quadratic time by default.

Getting text content from nodes now avoids an allocation, resulting in a performance gain.

DOMChildNode::remove() now runs in O(1) performance.

Standard

The file() flags error check is now about 7% faster.

SPL

RecursiveDirectoryIterator now performs less I/O when looping over a directory.

User Contributed Notes

There are no user contributed notes for this page.


Windows Support

Core

Minimum supported Windows version has been bumped to Windows 8 or Windows Server 2012.

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 8.1.x vers PHP 8.2.x

Sommaire

  • Nouvelles fonctionnalités
  • Nouvelles fonctions
  • Nouvelles constantes globales
  • Modifications entrainant une incompatibilité ascendante
  • Fonctionnalités obsolètes
  • Autres changements
  • Support Windows

Cette nouvelle version mineure apporte un certain nombre de nouvelles fonctionnalités et quelques incompatibilités qui devraient être testées avant de changer de version de PHP dans des environnements de production.

Voir aussi les guides de migration entre les différentes versions de PHP 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x.

User Contributed Notes

Anonymous 03-Mar-2023 01:02
that’s incredible version of PHP,The performance is really nicer than older version.


Nouvelles fonctionnalités

Cœur de PHP

Attribut SensitiveParameter

Ajout de l'attribut #[\SensitiveParameter] pour expurger les données sensibles dans les backtraces.

Directive INI error_log_mode

La directive INI error_log_mode a été ajoutée pour permettre de définir les permissions du fichier d'enregistrement des erreurs.

Propriétés des énumérations dans les expressions constantes

Il est maintenant possible de récupérer les propriétés des énumérations dans des expressions constantes.

Améliorations du système de types

Il est maintenant possible d'utiliser null et false en tant que types indépendants.

Le type true a été ajouté.

Il est désormais possible de combiner les types intersection et union. Le type doit être écrit en DNF.

Constantes dans les traits

Il est désormais possible de définir des constantes dans les traits.

Classes en lecture seule

La prise en charge de readonly sur les classes a été ajoutée.

cURL

Ajout de l'option CURLINFO_EFFECTIVE_METHOD, qui renvoie la méthode HTTP effective dans la valeur de retour de curl_getinfo().

Exposition de plusieurs nouvelles constantes de libcurl 7.62 à 7.80.

Ajout de la fonction curl_upkeep() pour effectuer les vérifications de maintien de la connexion.

DBA

Le pilote LMDB accepte désormais les drapeaux DBA_LMDB_USE_SUB_DIR ou DBA_LMDB_NO_SUB_DIR pour déterminer s'il doit créer ou non un sous-répertoire lors de la création d'un fichier de base de données.

OCI8

Ajout de la directive INI oci8.prefetch_lob_size et de la fonction oci_set_prefetch_lob() pour améliorer les performances des requêtes LOB en réduisant le nombre d'aller-retour entre PHP et la base de données Oracle lors de la récupération des LOBS. Ceci est utilisable avec les bases de données Oracle 12.2 ou plus récentes.

OpenSSL

Ajout du support AEAD pour l'algorithme chacha20-poly1305.

ODBC

Ajout des fonctions odbc_connection_string_is_quoted(), odbc_connection_string_should_quote(), et odbc_connection_string_quote(). Elles sont principalement utilisées en arrière-plan dans les extensions ODBC et PDO_ODBC, mais sont exposées à l'espace utilisateur pour faciliter les tests unitaires, et pour que les applications et les bibliothèques utilisateur puissent effectuer elles-mêmes le "quoting".

PCRE

Ajout de la prise en charge du modificateur n (NO_AUTO_CAPTURE), qui rend les groupes simples (xyz) non capturables. Seuls les groupes nommés comme (?<name>xyz) sont capturables. Cela n'affecte que les groupes qui sont capturés, il est toujours possible d'utiliser des références de sous-motifs numérotés, et le tableau des correspondances contiendra toujours des résultats numérotés.

Random

Il s'agit d'une nouvelle extension qui organise et consolide les implémentations existantes relatives aux générateurs de nombres aléatoires. De nouveaux et meilleurs RNG sont disponibles et les problèmes de portée sont éliminés.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctions

cURL

  • curl_upkeep()

IMAP

  • imap_is_open() (à partir de PHP 8.2.1)

MySQLi

  • mysqli_execute_query()

ODBC

  • odbc_connection_string_is_quoted()
  • odbc_connection_string_should_quote()
  • odbc_connection_string_quote()

OpenSSL

  • openssl_cipher_key_length()

Reflection

  • ReflectionFunction::isAnonymous()
  • ReflectionMethod::hasPrototype()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20_xor_ic()

Standard

  • memory_reset_peak_usage()
  • ini_parse_quantity()

XML

  • libxml_get_external_entity_loader()

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles constantes globales

COM

  • DISP_E_PARAMNOTFOUND
  • LOCALE_NEUTRAL

cURL

  • CURLALTSVC_H1 (libcurl >= 7.64.1)
  • CURLALTSVC_H2 (libcurl >= 7.64.1)
  • CURLALTSVC_H3 (libcurl >= 7.64.1)
  • CURLALTSVC_READONLYFILE (libcurl >= 7.64.1)
  • CURLAUTH_AWS_SIGV4 (libcurl >= 7.75.0)
  • CURLE_PROXY (libcurl >= 7.73.0)
  • CURLFTPMETHOD_DEFAULT
  • CURLHSTS_ENABLE (libcurl >= 7.74.0)
  • CURLHSTS_READONLYFILE (libcurl >= 7.74.0)
  • CURLINFO_PROXY_ERROR (libcurl >= 7.73.0)
  • CURLINFO_REFERER (libcurl >= 7.76.0)
  • CURLINFO_RETRY_AFTER (libcurl >= 7.66.0)
  • CURLMOPT_MAX_CONCURRENT_STREAMS (libcurl >= 7.67.0)
  • CURLOPT_ALTSVC_CTRL (libcurl >= 7.64.1)
  • CURLOPT_ALTSVC (libcurl >= 7.64.1)
  • CURLOPT_AWS_SIGV4 (libcurl >= 7.75.0)
  • CURLOPT_CAINFO_BLOB (libcurl >= 7.77.0)
  • CURLOPT_DOH_SSL_VERIFYHOST (libcurl >= 7.76.0)
  • CURLOPT_DOH_SSL_VERIFYPEER (libcurl >= 7.76.0)
  • CURLOPT_DOH_SSL_VERIFYSTATUS (libcurl >= 7.76.0)
  • CURLOPT_HSTS_CTRL (libcurl >= 7.74.0)
  • CURLOPT_HSTS (libcurl >= 7.74.0)
  • CURLOPT_MAIL_RCPT_ALLLOWFAILS (libcurl >= 7.69.0)
  • CURLOPT_MAXAGE_CONN (libcurl >= 7.65.0)
  • CURLOPT_MAXFILESIZE_LARGE
  • CURLOPT_MAXLIFETIME_CONN (libcurl >= 7.80.0)
  • CURLOPT_PROXY_CAINFO_BLOB (libcurl >= 7.77.0)
  • CURLOPT_SASL_AUTHZID (libcurl >= 7.66.0)
  • CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 (libcurl >= 7.80.0)
  • CURLOPT_SSL_EC_CURVES (libcurl >= 7.73.0)
  • CURLOPT_UPKEEP_INTERVAL_MS (libcurl >= 7.62.0)
  • CURLOPT_UPLOAD_BUFFERSIZE (libcurl >= 7.62.0)
  • CURLOPT_XFERINFOFUNCTION (libcurl >= 7.32.0)
  • CURLPROTO_MQTT (libcurl >= 7.71.0)
  • CURLPX_BAD_ADDRESS_TYPE (libcurl >= 7.73.0)
  • CURLPX_BAD_VERSION (libcurl >= 7.73.0)
  • CURLPX_CLOSED (libcurl >= 7.73.0)
  • CURLPX_GSSAPI (libcurl >= 7.73.0)
  • CURLPX_GSSAPI_PERMSG (libcurl >= 7.73.0)
  • CURLPX_GSSAPI_PROTECTION (libcurl >= 7.73.0)
  • CURLPX_IDENTD_DIFFER (libcurl >= 7.73.0)
  • CURLPX_IDENTD (libcurl >= 7.73.0)
  • CURLPX_LONG_HOSTNAME (libcurl >= 7.73.0)
  • CURLPX_LONG_PASSWD (libcurl >= 7.73.0)
  • CURLPX_LONG_USER (libcurl >= 7.73.0)
  • CURLPX_NO_AUTH (libcurl >= 7.73.0)
  • CURLPX_OK (libcurl >= 7.73.0)
  • CURLPX_RECV_ADDRESS (libcurl >= 7.73.0)
  • CURLPX_RECV_AUTH (libcurl >= 7.73.0)
  • CURLPX_RECV_CONNECT (libcurl >= 7.73.0)
  • CURLPX_RECV_REQACK (libcurl >= 7.73.0)
  • CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED (libcurl >= 7.73.0)
  • CURLPX_REPLY_COMMAND_NOT_SUPPORTED (libcurl >= 7.73.0)
  • CURLPX_REPLY_CONNECTION_REFUSED (libcurl >= 7.73.0)
  • CURLPX_REPLY_GENERAL_SERVER_FAILURE (libcurl >= 7.73.0)
  • CURLPX_REPLY_HOST_UNREACHABLE (libcurl >= 7.73.0)
  • CURLPX_REPLY_NETWORK_UNREACHABLE (libcurl >= 7.73.0)
  • CURLPX_REPLY_NOT_ALLOWED (libcurl >= 7.73.0)
  • CURLPX_REPLY_TTL_EXPIRED (libcurl >= 7.73.0)
  • CURLPX_REPLY_UNASSIGNED (libcurl >= 7.73.0)
  • CURLPX_REQUEST_FAILED (libcurl >= 7.73.0)
  • CURLPX_RESOLVE_HOST (libcurl >= 7.73.0)
  • CURLPX_SEND_AUTH (libcurl >= 7.73.0)
  • CURLPX_SEND_CONNECT (libcurl >= 7.73.0)
  • CURLPX_SEND_REQUEST (libcurl >= 7.73.0)
  • CURLPX_UNKNOWN_FAIL (libcurl >= 7.73.0)
  • CURLPX_UNKNOWN_MODE (libcurl >= 7.73.0)
  • CURLPX_USER_REJECTED (libcurl >= 7.73.0)
  • CURLSSLOPT_AUTO_CLIENT_CERT (libcurl >= 7.77.0)
  • CURLSSLOPT_NATIVE_CA (libcurl >= 7.71.0)
  • CURLSSLOPT_NO_PARTIALCHAIN (libcurl >= 7.68.0)
  • CURLSSLOPT_REVOKE_BEST_EFFORT (libcurl >= 7.70.0)
  • CURL_VERSION_GSASL (libcurl >= 7.76.0)
  • CURL_VERSION_HSTS (libcurl >= 7.74.0)
  • CURL_VERSION_HTTP3 (libcurl >= 7.66.0)
  • CURL_VERSION_UNICODE (libcurl >= 7.72.0)
  • CURL_VERSION_ZSTD (libcurl >= 7.72.0)

DBA

  • DBA_LMDB_USE_SUB_DIR
  • DBA_LMDB_NO_SUB_DIR

Filtre

  • FILTER_FLAG_GLOBAL_RANGE

Sockets

Les options de socket suivantes sont désormais définies si elles sont prises en charge :

  • SO_INCOMING_CPU
  • SO_MEMINFO
  • SO_RTABLE (OpenBSD)
  • TCP_KEEPALIVE (MacOS)
  • TCP_KEEPCNT (Linux, autres)
  • TCP_KEEPIDLE (Linux, autres)
  • TCP_KEEPINTVL (Linux, autres)
  • TCP_NOTSENT_LOWAT
  • LOCAL_CREDS_PERSISTENT (FreeBSD)
  • SCM_CREDS2 (FreeBSD)
  • LOCAL_CREDS (NetBSD)
  • SO_BPF_EXTENSIONS
  • SO_SETFIB
  • TCP_CONGESTION (Linux, FreeBSD)
  • SO_ZEROCOPY (Linux)
  • MSG_ZEROCOPY (Linux)

User Contributed Notes

There are no user contributed notes for this page.


Modifications entrainant une incompatibilité ascendante

Date

DateTime::createFromImmutable() a désormais un type de retour provisoire static, auparavant c'était DateTime.

DateTimeImmutable::createFromMutable() a désormais un type de retour provisoire static, auparavant c'était DateTimeImmutable.

Les symboles numériques dans les formats relatifs n'acceptent plus les signes multiples, par exemple +-2.

ODBC

L'extension ODBC échappe désormais le nom d'utilisateur et le mot de passe dans le cas où une chaîne de connexion et un nom d'utilisateur/mot de passe sont transmis, et que la chaîne doit être ajoutée. Auparavant, les valeurs utilisateur contenant des valeurs nécessitant un échappement pouvaient créer une chaîne de connexion malformée ou injecter des valeurs à partir de données fournies par l'utilisateur. Les règles d'échappement devraient être identiques au comportement de DbConnectionOptions dans la BCL .NET.

PDO_ODBC

L'extension PDO_ODBC échappe également le nom d'utilisateur et le mot de passe lorsqu'une chaîne de connexion est transmise. Voir la modification de l'extension ODBC pour plus de détails.

Standard

glob() retourne désormais un tableau vide si tous les chemins d'accès sont restreints par open_basedir. Auparavant, elle retournait false. De plus, un avertissement est désormais émis même si seulement quelques chemins sont restreints par open_basedir.

FilesystemIterator::__construct(): antérieur à PHP 8.2.0, le constante FilesystemIterator::SKIP_DOTS était toujours définie et ne pouvait pas être désactivée. Afin de conserver le comportement précédent, la constante doit être explicitement définie lors de l'utilisation du paramètre flags. La valeur par défaut du paramètre flags n'a pas été modifiée.

strtolower(),
strtoupper(),
stristr(),
stripos(),
strripos(),
lcfirst(),
ucfirst(),
ucwords(),
et str_ireplace() ne sont plus sensibles à la locale.
Elles effectuent désormais une conversion ASCII de la casse, comme si la locale était "C".
Des versions localisées de ces fonctions sont disponibles dans l'extension MBString.
De plus, array_change_key_case() et le tri avec
SORT_FLAG_CASE utilisent désormais également la conversion ASCII.

str_split() retourne désormais un tableau vide pour une chaîne de caractères vide. Auparavant, elle retournait un tableau avec une seule chaîne vide comme entrée. mb_str_split() n'est pas affectée par ce changement car elle se comportait déjà de la sorte.

ksort() et krsort() font désormais des comparaisons numériques de chaînes de caractères sous SORT_REGULAR en utilisant les règles standards de PHP 8.

var_export() n'omet plus le backslash de tête pour les classes exportées, c'est-à-dire qu'elles sont désormais pleinement qualifiées.

Bibliothèque standard de PHP (SPL)

Les méthodes suivantes enforcent désormais leur signature :

  • SplFileInfo::_bad_state_ex()
  • SplFileObject::getCsvControl()
  • SplFileObject::fflush()
  • SplFileObject::ftell()
  • SplFileObject::fgetc()
  • SplFileObject::fpassthru()

SplFileObject::hasChildren() a désormais un type de retour provisoire false, auparavant c'était bool.

SplFileObject::getChildren() a désormais un type de retour provisoire null, auparavant c'était ?RecursiveIterator.

GlobIterator retourne désormais un tableau vide si tous les chemins d'accès sont restreints par open_basedir. Auparavant, elle retournait false. De plus, un avertissement est désormais émis même si seulement certains chemins sont restreints par open_basedir.

User Contributed Notes

There are no user contributed notes for this page.


Fonctionnalités obsolètes

PHP Core

Utilisation des propriétés dynamiques

La création de propriétés dynamiques est obsolète, à moins que la classe ne l'autorise en utilisant l'attribut #[\AllowDynamicProperties]. stdClass autorise les propriétés dynamiques. L'utilisation des méthodes magiques __get()/__set() n'est pas affectée par ce changement. L'avertissement d'obsolescence des propriétés dynamiques peut être adressé en :

  • Déclarant la propriété (préférable).
  • Ajoutant l'attribut #[\AllowDynamicProperties] à la classe (qui s'applique également à toutes les classes enfants).
  • Utilisant un WeakMap si des données supplémentaires doivent être associées à un objet dont on n'est pas propriétaire.

Callables relatifs

Les callables qui ne sont pas acceptés par la syntaxe $callable() (mais qui sont acceptés par call_user_func()) sont obsolètes. En particulier :

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
Cela n'affecte pas les callables de méthode normaux tels que "A::method" ou ["A", "method"].

Interpolation de style "${var}" et "${expr}".

Les styles d'interpolation de chaîne "${var}" et "${expr}" sont obsolètes. Utilisez respectivement "$var"/"{$var}" et "{${expr}}".

MBString

L'utilisation des formats QPrint, Base64, Uuencode et HTML-ENTITIES est obsolète pour toutes les fonctions MBString. Contrairement à tous les autres encodages de texte supportés par MBString, ceux-ci n'encodent pas une séquence de points de code Unicode, mais plutôt une séquence d'octets bruts. Les valeurs de retour de la plupart des fonctions MBString ne sont pas claires lorsqu'un de ces non-encodages est spécifié. De plus, PHP a des implémentations distinctes pour chacun d'entre eux ; par exemple, les données UUencoded peuvent être gérées en utilisant convert_uuencode()/convert_uudecode().

SPL

La méthode interne SplFileInfo::_bad_state_ex() a été rendue obsolète.

Standard

utf8_encode() et utf8_decode() ont été rendues obsolètes.

User Contributed Notes

tabflo at gmx dot at 13-Jul-2023 01:43
a have a baseclass for all databasemodels and handle my dynamic property setter and getter this way:

    public array $dynamicProperties = [];

    public function __set(string $name, mixed $value) {
        if(property_exists($this, $name))
            $this->{$name} = $value;
        else
            $this->dynamicProperties[$name] = $value;
    }

    public function __get(string $name) {
        if(property_exists($this, $name))
            return $this->$name;
        else
            return $this->dynamicProperties[$name];
    }

just put the content into a class and extend from it. enjoy :)


Autres changements

Changements du cœur

Le type iterable est maintenant un alias intégré à la compilation pour le type array|Traversable. Les messages d'erreur relatifs à iterable utiliseront donc array|Traversable. La réflexion sur le type est préservée pour les simples iterable (et ?iterable) pour produire une classe ReflectionNamedType avec le nom iterable, cependant, l'utilisation de iterable dans les types union sera converti en array|Traversable.

Le format de date des cookies envoyés est désormais 'D, d M Y H:i:s \G\M\T'; auparavant, il était 'D, d-M-Y H:i:s T'.

Changements dans les modules SAPI

CLI

Les flux STDOUT, STDERR et STDIN ne sont plus fermés lors de la destruction des ressources ce qui est généralement le cas lorsque le CLI se termine. Il est cependant toujours possible de fermer explicitement ces flux en utilisant fclose() et similaires.

Fonctions modifiées

Cœur

Les fonctions strcmp(), strcasecmp(), strncmp(), strncasecmp(), et substr_compare(), qui utilisent une comparaison binaire sûre des chaînes de caractères, retournent désormais -1, 0 et 1.

DBA

dba_open() et dba_popen() ont désormais la signature enforcée suivante :

dba_open(
string $path,
string $mode,
?string $handler = null,
int $permission = 0644,
int $map_size = 0,
?int $flags = null
): resource|false

l'argument optionnel skip de dba_fetch() est maintenant à la fin en accord avec la sémantique de PHP. Sa signature est désormais :

dba_fetch(string|array $key, resource $handle, int $skip): string|false
La signature surchargée :
dba_fetch(string|array $key, int $skip, resource $handle): string|false
est toujours acceptée, mais il est recommandé d'utiliser la nouvelle variante standard.

Random

random_bytes() et random_int() lancent désormais \Random\RandomException en cas d'échec du CSPRNG. Auparavant, une simple \Exception était lancée à la place.

SPL

Le paramètre iterator de iterator_to_array() et iterator_count() est étendu à iterable au lieu de Iterator, ce qui permet de transmettre des tableaux.

Autres modifications apportées aux extensions

Date

Les propriétés de DatePeriod sont désormais correctement déclarées.

Intl

Les instances de IntlBreakIterator, IntlRuleBasedBreakIterator, IntlCodePointBreakIterator, IntlPartsIterator, IntlCalendar, Collator, IntlIterator, UConverter, IntlDateFormatter, IntlDatePatternGenerator, MessageFormatter, ResourceBundle, Spoofchecker, IntlTimeZone, et Transliterator ne sont plus sérialisables. Auparavant, elles pouvaient être sérialisés, mais la désérialisation produisait des objets inutilisables ou échouait.

MySQLi

Le support de libmysql a été supprimé et il n'est plus possible de compiler mysqli avec libmysql. Désormais, l'extension mysqli ne peut être compilée qu'avec mysqlnd. Toutes les fonctionnalités de libmysql non disponibles dans mysqlnd ont été supprimées :

  • La propriété reconnect de mysqli_driver
  • La directive INI mysqli.reconnect
  • La constante MYSQLI_IS_MARIADB est obsolète

OCI8

La version minimale requise de la bibliothèque Oracle Client est désormais 11.2.

PCRE

Les caractères NUL (\0) dans les chaînes de motifs sont maintenant supportés.

Session

Essayer de modifier le session.cookie_samesite alors que la session est active ou que la sortie a déjà été envoyée échouera désormais et émettra un avertissement. Le comportement est ainsi aligné sur tous les autres paramètres INI de session.

SQLite3

sqlite3.defensive est maintenant PHP_INI_USER.

Standard

getimagesize() indique désormais les dimensions réelles de l'image, bits et canaux des images AVIF. Auparavant, les dimensions étaient indiquées sous la forme 0x0, et les bits et les canaux n'étaient pas indiqués du tout.

Tidy

Les propriétés de la classe tidy sont désormais correctement déclarées. Et celles de la classe tidyNode sont maintenant correctement déclarées en lecture seule.

Zip

L'extension Zip a été mise à jour à la version 1.20.0, qui ajoute les méthodes suivantes :

  • ZipArchive::clearError()
  • ZipArchive::getStreamName()
  • ZipArchive::getStreamIndex()

Changements dans la gestion des fichiers INI

La prise en charge des préfixes binaires (0b/0B) et octaux (0o/0O) a été ajoutée aux paramètres INI pour les nombres entiers. Les paramètres INI entiers qui commencent par un zéro (0) continuent d'être interprétés comme des nombres entiers octaux.

L'analyse de certaines valeurs mal formatées déclenche désormais un avertissement alors qu'elle était auparavant ignorée silencieusement. Pour des raisons de compatibilité ascendante, l'interprétation de ces valeurs n'a pas changé. Cela affecte les paramètres suivants :

  • bcmath.scale
  • com.code_page
  • default_socket_timeout
  • fiber.stack_size
  • hard_timeout
  • intl.error_level
  • ldap.max_links
  • max_input_nesting_level
  • max_input_vars
  • mbstring.regex_retry_limit
  • mbstring.regex_stack_limit
  • mysqli.allow_local_infile
  • mysqli.allow_persistent
  • mysqli.default_port
  • mysqli.max_links
  • mysqli.max_persistent
  • mysqli.rollback_on_cached_plink
  • mysqlnd.log_mask
  • mysqlnd.mempool_default_size
  • mysqlnd.net_read_buffer_size
  • mysqlnd.net_read_timeout
  • oci8.default_prefetch
  • oci8.max_persistent
  • oci8.persistent_timeout
  • oci8.ping_interval
  • oci8.prefetch_lob_size
  • oci8.privileged_connect
  • oci8.statement_cache_size
  • odbc.allow_persistent
  • odbc.check_persistent
  • odbc.max_persistent
  • odbc.max_links
  • odbc.defaultbinmode
  • odbc.default_cursortype
  • odbc.defaultlrl
  • opcache.consistency_checks
  • opcache.file_update_protection
  • opcache.force_restart_timeout
  • opcache.interned_strings_buffer
  • opcache.jit_bisect_limit
  • opcache.jit_blacklist_root_trace
  • opcache.jit_blacklist_side_trace
  • opcache.jit_debug
  • opcache.jit_hot_func
  • opcache.jit_hot_loop
  • opcache.jit_hot_return
  • opcache.jit_hot_side_exit
  • opcache.jit_max_exit_counters
  • opcache.jit_max_loop_unrolls
  • opcache.jit_max_polymorphic_calls
  • opcache.jit_max_recursive_calls
  • opcache.jit_max_recursive_returns
  • opcache.jit_max_root_traces
  • opcache.jit_max_side_traces
  • opcache.log_verbosity_level
  • opcache.max_file_size
  • opcache.opt_debug_level
  • opcache.optimization_level
  • opcache.revalidate_freq
  • output_buffering
  • pcre.backtrack_limit
  • pcre.recursion_limit
  • pgsql.max_links
  • pgsql.max_persistent
  • post_max_size
  • realpath_cache_size
  • realpath_cache_ttl
  • session.cache_expire
  • session.cookie_lifetime
  • session.gc_divisor
  • session.gc_maxlifetime
  • session.gc_probability
  • soap.wsdl_cache_limit
  • soap.wsdl_cache_ttl
  • unserialize_max_depth
  • upload_max_filesize
  • user_ini.cache_ttl
  • xmlrpc_error_number
  • zend.assertions
  • zlib.output_compression_level

User Contributed Notes

There are no user contributed notes for this page.


Support Windows

Cœur

Les messages d'erreur spécifiques à Windows ne sont plus localisés, mais toujours affichés en anglais pour mieux correspondre aux messages d'erreur de PHP.

Un support préliminaire et hautement expérimental pour la construction sur ARM64 a été ajouté.

OCI8

Parce que la construction avec Oracle Client 10g n'est plus supportée de toute façon, l'option de configuration --with-oci8 a été abandonnée. Les options de configuration --with-oci8-11g, --with-oci8-12c et --with-oci8-19 sont toujours supportées.

Zip

L'extension Zip a été mise à jour à la version 1.21.0, et est maintenant compilée en tant que bibliothèque partagée (DLL) par défaut.

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 8.0.x vers PHP 8.1.x

Sommaire

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes

Cette nouvelle version mineure apporte un certain nombre de nouvelles fonctionnalités et quelques incompatibilités qui devraient être testées avant de changer de version de PHP dans des environnements de production.

Voir aussi les guides de migration entre les différentes versions de PHP 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Integer Octal Literal Prefix

Octal integers can now use an explicit 0o/0O prefix in integer literals, similarly to binary and hexadecimal integer literals.

<?php
014; // Non-prefix octal literal
0o14; // Prefixed octal literal
?>

Array Unpacking with String Keys

Added support for array unpacking with strings keys.

<?php
$arr1 = [1, 'a' => 'b'];
$arr2 = [...$arr1, 'c' => 'd']; //[1, 'a' => 'b', 'c' => 'd']
?>

Named Argument After Argument Unpacking

It is now possible to specify named arguments after an argument unpack. e.g. foo(...$args, named: $arg).

full-path Key for File Uploads

File uploads now provide an additional full_path key, which contains the full path (rather than just the basename) of the uploaded file. This is intended for use in conjunction with "upload webkitdirectory".

Enumerations

Support for Enumerations has been added.

Fibers

Support for Fibers has been added.

First Class Callable Syntax

Closures for callables can now be created using the syntax myFunc(...), which is identical to Closure::fromCallable('myFunc').

Note: The ... is part of the syntax, and not an omission.

Intersection Types

Support for intersection types has been added.

Attention

Intersection types cannot be used together with union types

Never type

A new return only type never has been added. This indicates that a function either exit(), throws an exception, or doesn't terminate.

new in Initializers

It is now possible to use new ClassName() expressions as the default value of a parameter, static variable, global constant initializers, and as attribute arguments. Objects can also be passed to define() now.

Readonly properties

Support for readonly has been added.

Final class constants

Added support for the final modifier for class constants. Also, interface constants become overridable by default.

CURL

Added the CURLOPT_DOH_URL option.

Added options for blob certificate when libcurl >= 7.71.0:

  • CURLOPT_ISSUERCERT_BLOB
  • CURLOPT_PROXY_ISSUERCERT
  • CURLOPT_PROXY_ISSUERCERT_BLOB
  • CURLOPT_PROXY_SSLCERT_BLOB
  • CURLOPT_PROXY_SSLKEY_BLOB
  • CURLOPT_SSLCERT_BLOB
  • CURLOPT_SSLKEY_BLOB

Added CURLStringFile, which can be used to post a file from a chaîne de caractères rather than a file:

<?php
$file = new CURLStringFile($data, 'filename.txt', 'text/plain');
curl_setopt($curl, CURLOPT_POSTFIELDS, ['file' => $file]);
?>

FPM

Added openmetrics status format. It can be used by Prometheus to fetch FPM metrics.

Added new pool option for the dynamic process manager called pm.max_spawn_rate. It allows to start a number of children at a faster rate when dynamic pm is selected. The default value is 32 which was the previous hard coded value.

GD

Avif support is now available through imagecreatefromavif() and imageavif(), if libgd has been built with Avif support.

Hash

The following functions hash(), hash_file(), and hash_init() now support an additional optional options argument, which can be used to pass algorithm specific data.

MurmurHash3

Added support for MurmurHash3 with streaming support. The following variants are implemented:

  • murmur3a, 32-bit hash
  • murmur3c, 128-bit hash for x86
  • murmur3f, 128-bit hash for x64

The initial hash state can be passed through the seed key in the options array, for example:

<?php
$h = hash("murmur3f", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
A valid seed value is within the range from 0 to the platform defined UINT_MAX, usually 4294967295.

xxHash

Added support for xxHash. The following variants are implemented:

  • xxh32, 32-bit hash
  • xxh64, 64-bit hash
  • xxh3, 64-bit hash
  • xxh128, 128-bit hash

The initial hash state can be passed through the seed key in the options array, for example:

<?php
$h = hash("xxh3", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
Secret usage is supported through passing the secret key in the options array, too:
<?php
$h = hash("xxh3", $data, options: ["secret" => "at least 136 bytes long secret here"]);
echo $h, "\n";
?>
The quality of the custom secret is crucial for the quality of the resulting hash. It is highly recommended for the secret to use the best possible entropy.

MySQLi

New INI directive mysqli.local_infile_directory

The mysqli.local_infile_directory INI directive has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if mysqli.allow_local_infile is not enabled, as all directories are allowed in that case.

Binding parameters in execute

It is now possible to bind parameters by passing them as an array to mysqli_stmt::execute(). All values will be bound as strings. Only list arrays are allowed. This new feature is not available when MySQLi is compiled with libmysqlclient.

<?php
$stmt = $mysqli->prepare('INSERT INTO users(id, name) VALUES(?,?)');
$stmt->execute([1, $username]);
?>

New method mysqli_result::fetch_column()

mysqli_result::fetch_column() has been added to allow fetching a single scalar value from the result set. The new method accepts an optional 0-based column parameter of type entier specifying which column to fetch from.

<?php
$result = $mysqli->query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_column();
?>

PDO

The PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY attribute has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if PDO::MYSQL_ATTR_LOCAL_INFILE is not enabled, as all directories are allowed in that case.

PDO_SQLite

SQLite's "file:" DSN syntax is now supported, which allows specifying additional flags. This feature is not available if open_basedir is set.

<?php
new PDO('sqlite:file:path/to/sqlite.db?mode=ro')
?>

POSIX

Added POSIX_RLIMIT_KQUEUES and POSIX_RLIMIT_NPTS. These rlimits are only available on FreeBSD.

Standard

fputcsv() now accepts a new eol argument which allows to define a custom End of Line sequence, the default remains the same and is "\n".

SPL

SplFileObject::fputcsv() now accepts a new eol argument which allows to define a custom End of Line sequence, the default remains the same and is "\n".

User Contributed Notes

There are no user contributed notes for this page.


New Classes and Interfaces

cURL

  • CURLStringFile

Intl

  • IntlDatePatternGenerator

Reflection

  • ReflectionFiber

User Contributed Notes

There are no user contributed notes for this page.


New Functions

PHP Core

  • array_is_list()

GD

  • imagecreatefromavif()
  • imageavif()

MySQLi

  • mysqli_result::fetch_column()
  • mysqli_fetch_column()

Process Control

  • pcntl_rfork()

Reflection

  • ReflectionFunctionAbstract::getClosureUsedVariables()

Standard

  • fsync()
  • fdatasync()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20()
  • sodium_crypto_stream_xchacha20_keygen()
  • sodium_crypto_stream_xchacha20_xor()

Ristretto255

Ristretto255 functions are available as of libsodium 1.0.18.

  • sodium_crypto_core_ristretto255_add()
  • sodium_crypto_core_ristretto255_from_hash()
  • sodium_crypto_core_ristretto255_is_valid_point()
  • sodium_crypto_core_ristretto255_random()
  • sodium_crypto_core_ristretto255_scalar_add()
  • sodium_crypto_core_ristretto255_scalar_complement()
  • sodium_crypto_core_ristretto255_scalar_invert()
  • sodium_crypto_core_ristretto255_scalar_mul()
  • sodium_crypto_core_ristretto255_scalar_negate()
  • sodium_crypto_core_ristretto255_scalar_random()
  • sodium_crypto_core_ristretto255_scalar_reduce()
  • sodium_crypto_core_ristretto255_scalar_sub()
  • sodium_crypto_core_ristretto255_sub()
  • sodium_crypto_scalarmult_ristretto255()
  • sodium_crypto_scalarmult_ristretto255_base()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

cURL

  • CURLOPT_DOH_URL
  • CURLOPT_ISSUERCERT_BLOB
  • CURLOPT_PROXY_ISSUERCERT
  • CURLOPT_PROXY_ISSUERCERT_BLOB
  • CURLOPT_PROXY_SSLCERT_BLOB
  • CURLOPT_PROXY_SSLKEY_BLOB
  • CURLOPT_SSLCERT_BLOB
  • CURLOPT_SSLKEY_BLOB

GD

  • IMG_AVIF
  • IMG_WEBP_LOSSLESS

MySQLi

  • MYSQLI_REFRESH_REPLICA

    This constant has been added as a replacement for MYSQLI_REFRESH_SLAVE, in line with an upstream change in MySQL. The old constant is still available for backwards-compatibility reasons, but may be deprecated/removed in the future.

PCNTL

  • PRIO_DARWIN_BG
  • PRIO_DARWIN_THREAD

POSIX

  • POSIX_RLIMIT_KQUEUES
  • POSIX_RLIMIT_NPTS

Sockets

The following socket options are now defined if they are supported:

  • SO_ACCEPTFILTER
  • SO_DONTTRUNC
  • SO_WANTMORE
  • SO_MARK
  • TCP_DEFER_ACCEPT

Sodium

  • SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES
  • SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES
  • SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES
  • SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES

Tokenizer

  • T_READONLY

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

$GLOBALS Access Restrictions

Access to the $GLOBALS array is now subject to a number of restrictions. Read and write access to individual array elements like $GLOBALS['var'] continues to work as-is. Read-only access to the entire $GLOBALS array also continues to be supported. However, write access to the entire $GLOBALS array is no longer supported. For example, array_pop($GLOBALS) will result in an error.

Usage of static Variables in Inherited Methods

When a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method.

<?php
class A {
public static function counter() {
static $counter = 0;
$counter++;
return $counter;
}
}
class B extends A {}
var_dump(A::counter()); // int(1)
var_dump(A::counter()); // int(2)
var_dump(B::counter()); // int(3), previously int(1)
var_dump(B::counter()); // int(4), previously int(2)
?>
This means that static variables in methods now behave the same way as static properties.

Optional parameters specified before required parameters

An optional parameter specified before required parameters is now always treated as required, even when called using named arguments. As of PHP 8.0.0, but prior to PHP 8.1.0, the below emits a deprecation notice on the definition, but runs successfully when called. As of PHP 8.1.0, an error of class ArgumentCountError is thrown, as it would be when called with positional arguments.

<?php
function makeyogurt($container = "bowl", $flavour)
{
return "Making a $container of $flavour yogurt.\n";
}
try
{
echo makeyogurt(flavour: "raspberry");
}
catch (Error $e)
{
echo get_class($e), ' - ', $e->getMessage(), "\n";
}
?>

Résultat de l'exemple ci-dessus en PHP 8.0 :

Deprecated: Required parameter $flavour follows optional parameter $container
 in example.php on line 3
Making a bowl of raspberry yogurt.

Résultat de l'exemple ci-dessus en PHP 8.1 :

Deprecated: Optional parameter $container declared before required parameter
 $flavour is implicitly treated as a required parameter in example.php on line 3
ArgumentCountError - makeyogurt(): Argument #1 ($container) not passed

Note that a default value of null can be used before required parameters to specify a nullable type, but the parameter will still be required.

Return Type Compatibility with Internal Classes

Most non-final internal methods now require overriding methods to declare a compatible return type, otherwise a deprecated notice is emitted during inheritance validation. In case the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a ReturnTypeWillChange attribute can be added to silence the deprecation notice.

New Keywords

readonly is a keyword now. However, it still may be used as function name.

never is now a reserved word, so it cannot be used to name a class, interface or trait, and is also prohibited from being used in namespaces.

Resource to Object Migration

Several ressources have been migrated to objets. Return value checks using is_resource() should be replaced with checks for false.

  • The FileInfo functions now accept and return finfo objects instead of fileinfo ressources.

  • The FTP functions now accept and return FTP\Connection objects instead of ftp ressources.

  • The IMAP functions now accept and return IMAP\Connection objects instead of imap ressources.

  • The LDAP functions now accept and return LDAP\Connection objects instead of ldap link ressources.

  • The LDAP functions now accept and return LDAP\Result objects instead of ldap result ressources.

  • The LDAP functions now accept and return LDAP\ResultEntry objects instead of ldap result entry ressources.

  • The PgSQL functions now accept and return PgSql\Connection objects instead of pgsql link ressources.

  • The PgSQL functions now accept and return PgSql\Result objects instead of pgsql result ressources.

  • The PgSQL functions now accept and return PgSql\Lob objects instead of pgsql large object ressources.

  • The PSpell functions now accept and return PSpell\Dictionary objects instead of pspell ressources.

  • The PSpell functions now accept and return PSpell\Config objects instead of pspell config ressources.

MySQLi

mysqli_fetch_fields(), and mysqli_fetch_field_direct() will now always return 0 for the max_length. This information can be computed by iterating over the result set, and taking the maximum length. This is what PHP was doing internally previously.

The MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH option no longer has any effect.

The MYSQLI_STORE_RESULT_COPY_DATA option no longer has any effect. Passing any value to the mode parameter of mysqli::store_result() no longer has any effect.

mysqli::connect() now returns true instead of null on success.

The default error handling mode has been changed from "silent" to "exceptions" See the MySQLi reporting mode page for more details on what this entails, and how to explicitly set this attribute. To restore the previous behaviour use: mysqli_report(MYSQLI_REPORT_OFF);

Classes extending mysqli_stmt::execute() are now required to specify the additional optional parameter.

MySQLnd

The mysqlnd.fetch_data_copy INI directive has been removed. This should not result in user-visible behavior changes.

OpenSSL

EC private keys will now be exported in PKCS#8 format rather than traditional format, just like all other keys.

openssl_pkcs7_encrypt() and openssl_cms_encrypt() will now to default using AES-128-CBC rather than RC2-40. The RC2-40 cipher is considered insecure and not enabled by default by OpenSSL 3.

PHP Data Objects

PDO::ATTR_STRINGIFY_FETCHES now stringifies values of type booléen to "0" or "1". Previously booléens were not stringified.

Calling PDOStatement::bindColumn() with PDO::PARAM_LOB will now constantly bind a stream result when PDO::ATTR_STRINGIFY_FETCHES is not enabled. Previously, the result would either be a stream or a string depending on the used database driver and the time the binding is performed.

MySQL Driver

Integers and floats in result sets will now be returned using native PHP types instead of chaîne de caractèress when using emulated prepared statements. This matches the behavior of native prepared statements. The previous behaviour can be restored by enabling the PDO::ATTR_STRINGIFY_FETCHES option.

SQLite Driver

Integers and floats in results sets will now be returned using native PHP types. The previous behaviour can be restored by enabling the PDO::ATTR_STRINGIFY_FETCHES option.

Phar

To comply with the ArrayAccess interface, Phar::offsetUnset() and PharData::offsetUnset() no longer return a booléen.

Standard

version_compare() no longer accepts undocumented operator abbreviations.

htmlspecialchars(), htmlentities(), htmlspecialchars_decode(), html_entity_decode(), and get_html_translation_table() now use ENT_QUOTES | ENT_SUBSTITUTE rather than ENT_COMPAT by default. This means that ' is escaped to &#039; while previously nothing was done. Additionally, malformed UTF-8 will be replaced by a Unicode substitution character, instead of resulting in an empty string.

debug_zval_dump() now prints the refcount of a reference wrappers with their refcount, instead of only prepending & to the value. This more accurately models reference representation since PHP 7.0.

debug_zval_dump() now prints interned instead of a dummy refcount for interned strings and immutable arrays.

Standard PHP Library (SPL)

SplFixedArray, will now be JSON encoded like an tableau

User Contributed Notes

There are no user contributed notes for this page.


Deprecated Features

PHP Core

Implementing Serializable without __serialize() and __unserialize()

Either only the new methods should be implemented, if no support for PHP prior to version 7.4 is provided, or both should be implemented.

Passing null to non-nullable parameters of built-in functions

Scalar types for built-in functions are nullable by default. This behaviour is deprecated to align with the behaviour of user-defined functions, where scalar types need to be marked as nullable explicitly.

<?php
var_dump(str_contains("foobar", null));
// Deprecated: Passing null to parameter #2 ($needle) of type string
// is deprecated
?>

Implicit incompatible nombre décimal to entier conversions

The implicit conversion of nombre décimal to entier which leads to a loss in precision is now deprecated. This affects tableau keys, entier type declarations in coercive mode, and operators working on entiers.

<?php
$a = [];
$a[15.5]; // deprecated, as key value loses the 0.5 component
$a[15.0]; // ok, as 15.0 == 15
?>

Calling a static element on a trait

Calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.

Returning a non-tableau from __sleep()

Returning a value which is not an tableau from __sleep() now generates a diagnostic.

Returning by reference from a void function

<?php
function &test(): void {}
?>
Such a function is contradictory, and already emits the following E_NOTICE when called: Only variable references should be returned by reference.

Autovivification from false

Autovivification is the process of creating a new tableau when appending to a value. Autovivification is prohibited from scalar values, false however was an exception. This is now deprecated.

<?php
$arr = false;
$arr[] = 2; // deprecated
?>

Note:

Autovivification from null and undefined values is still allowed:

<?php
// From undefined
$arr[] = 'some value';
$arr['doesNotExist'][] = 2;
// From null
$arr = null;
$arr[] = 2;
?>

ctype

Verifying non-string arguments

Passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to chaîne de caractères or an explicit call to chr() should be made. All ctype_*() functions are affected.

Date

date_sunrise() and date_sunset() have been deprecated in favor of date_sun_info().

strptime() has been deprecated.
Use date_parse_from_format() instead (for locale-independent parsing),
or IntlDateFormatter::parse() (for locale-dependent parsing).

strftime() and gmstrftime() have been deprecated.
Use date() instead (for locale-independent formatting),
or IntlDateFormatter::format() (for locale-dependent formatting).

Filter

The FILTER_SANITIZE_STRING and FILTER_SANITIZE_STRIPPED filters are deprecated.

The filter.default INI directive is deprecated.

GD

The num_points of imagepolygon(), imageopenpolygon() and imagefilledpolygon() has been deprecated.

Hash

The mhash(),
mhash_keygen_s2k(),
mhash_count(),
mhash_get_block_size(),
and mhash_get_hash_name() have been deprecated.
Use the hash_*() functions instead.

IMAP

The NIL constant has been deprecated. Use 0 instead.

Intl

Calling IntlCalendar::roll() with a booléen argument is deprecated. Use 1 and -1 instead of true and false respectively.

Multibyte String

Calling mb_check_encoding() without any arguments is deprecated.

MySQLi

The mysqli_driver::$driver_version property has been deprecated. It was meaningless and outdated, use PHP_VERSION_ID instead.

Calling mysqli::get_client_info() or mysqli_get_client_info() with the mysqli argument has been deprecated. Call mysqli_get_client_info() without any arguments to obtain the version information of the client library.

The mysqli::init() method has been deprecated.
Replace calls to parent::init() with
parent::__construct().

OCI8

The oci8.old_oci_close_semantics INI directive is deprecated.

ODBC

odbc_result_all() has been deprecated.

PDO

The PDO::FETCH_SERIALIZE fetch mode has been deprecated.

PgSQL

Not passing the connection argument to all pgsql_*() functions has been deprecated.

SOAP

The ssl_method option of SoapClient::__construct() has been deprecated in favor of SSL stream context options.

Standard

Calling key(), current(), next(), prev(), reset(), or end() on objets is deprecated. Either convert the objet to an tableau using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead.

The auto_detect_line_endings INI directive is deprecated. If necessary, handle "\r" line breaks manually instead.

The FILE_BINARY and FILE_TEXT constants have been deprecated. They never had any effect.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Changes in SAPI Modules

CLI

Using -a without the readline extension will now result in an error. Previously, -a without readline had the same behavior as calling php without any arguments, apart from printing an additional "Interactive mode enabled" message. This mode was not interactive.

PHPDBG

Remote functionality from phpdbg has been removed.

Changed Functions

Core

The order of properties used in foreach, var_dump(), serialize(), object comparison, etc. was changed. Properties are now ordered naturally according to their declaration and inheritance. Properties declared in a base class are going to be before the child properties.

This order is consistent with internal layout of properties in zend_object structure and repeats the order in default_properties_table[] and properties_info_table[]. The old order was not documented and was caused by class inheritance implementation details.

Filter

The FILTER_FLAG_ALLOW_OCTAL flag of the FILTER_VALIDATE_INT filter now accept octal string with the leading octal prefix ("0o"/"0O").

GMP

All GMP functions now accept octal string with the leading octal prefix ("0o"/"0O").

PDO ODBC

PDO::getAttribute() with
PDO::ATTR_SERVER_INFO and
PDO::ATTR_SERVER_VERSION
now return values instead of throwing PDOException.

Reflection

ReflectionProperty::setAccessible() and ReflectionMethod::setAccessible() no longer have an effect. Properties and methods are now always considered accessible via Reflection.

Standard

syslog() is now binary safe.

Other Changes to Extensions

GD

imagewebp() can now do lossless WebP encoding by passing IMG_WEBP_LOSSLESS as the quality.

This constant is only defined, if the used libgd supports lossless WebP encoding.

MySQLi

mysqli_stmt::next_result() and mysqli::fetch_all() are now available when linking against libmysqlclient.

OpenSSL

  • The OpenSSL extension now requires at least OpenSSL version 1.0.2.

  • OpenSSL 3.0 is now supported. Be aware that many ciphers are no longer enabled by default (part of the legacy provider), and that parameter validation (e.g. minimum key sizes) is stricter now.

Phar

  • SHA256 is now used by default for signatures.

  • Added support for OpenSSL_SHA256 and OpenSSL_SHA512 signatures.

SNMP

  • Added support for SHA256 and SHA512 for the security protocol.

Standard

--with-password-argon2 now uses pkg-config to detect libargon2. As such, an alternative libargon2 location should now be specified using PKG_CONFIG_PATH.

Changes to INI File Handling

  • The log_errors_max_len INI directive has been removed. It no longer had an effect since PHP 8.0.0.

  • A leading dollar in a quoted string can now be escaped: "\${" will now be interpreted as a string with contents ${.

  • Backslashes in double quoted strings are now more consistently treated as escape characters. Previously, "foo\\" followed by something other than a newline was not considered as a terminated string. It is now interpreted as a string with contents foo\. However, as an exception, the string "foo\" followed by a newline will continue to be treated as a valid string with contents foo\ rather than an unterminated string. This exception exists to support naive uses of Windows file paths such as "C:\foo\".

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 7.4.x vers PHP 8.0.x

Sommaire

  • New Features
  • Modifications entrainant une incompatibilité ascendante
  • Fonctionnalités obsolètes
  • Other Changes

Cette nouvelle version majeure apporte un certain nombre de nouvelles fonctionnalités et quelques incompatibilités qui devraient être testées avant de changer de version de PHP dans des environnements de production.

Voir aussi les guides de migration entre les différentes versions de 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.


New Features

PHP Core

Named Arguments

Support for Named Arguments has been added.

Attributes

Support for Attributes has been added.

Constructor Property Promotion

Support for constructor property promotion (declaring properties in the constructor signature) has been added.

Union Types

Support for union types has been added.

Match Expression

Support for match expressions has been added.

Nullsafe Operator

Support for the nullsafe operator (?->) has been added.

Other new Features

  • The WeakMap class has been added.

  • The ValueError class has been added.

  • Any number of function parameters may now be replaced by a variadic argument, as long as the types are compatible. For example, the following code is now allowed:

    <?php
    class A {
    public function     method(int $many, string $parameters, $here) {}
    }
    class     B extends A {
    public function     method(...$everything) {}
    }
    ?>

  • static (as in "late static binding") can now be used as a return type:

    <?php
    class Test {
    public function     create(): static {
    return new static();
    }
    }
    ?>

  • It is now possible to fetch the class name of an object using $object::class. The result is the same as get_class($object).

  • new and instanceof can now be used with arbitrary expressions, using new (expression)(...$args) and $obj instanceof (expression).

  • Some consistency fixes to variable syntax have been applied, for example writing Foo::BAR::$baz is now allowed.

  • Added Stringable interface, which is automatically implemented if a class defines a __toString() method.

  • Traits can now define abstract private methods. Such methods must be implemented by the class using the trait.

  • throw can now be used as an expression. That allows usages like:

    <?php
    $fn     = fn() => throw new Exception('Exception in arrow function');
    $user = $session->user ?? throw new Exception('Must have user');

  • An optional trailing comma is now allowed in parameter lists.

    <?php
    function functionWithLongSignature(
    Type1 $parameter1,
    Type2 $parameter2, // <-- This comma is now allowed.
    ) {
    }

  • It is now possible to write catch (Exception) to catch an exception without storing it in a variable.

  • Support for mixed type has been added.

  • 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.

  • The InternalIterator has been added.

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.


Modifications entrainant une incompatibilité ascendante

Cœur de PHP

Comparaison entre une chaîne de caractères et un nombre

Les comparaisons non strictes entre les nombres et les chaînes non numériques fonctionnent désormais en transformant le nombre en chaîne et en comparant les chaînes. Les comparaisons entre les nombres et les chaînes numériques continuent de fonctionner comme auparavant. Cela signifie notamment que 0 == "not-a-number" est désormais considéré comme faux.

Comparaison | Avant | Après
0 == "0" | true | true
0 == "0.0" | true | true
0 == "foo" | true | false
0 == "" | true | false
42 == " 42" | true | true
42 == "42foo" | true | false

Autres changements incompatibles

  • match est désormais un mot-clé réservé.

  • mixed est désormais un mot réservé, il ne peut donc pas être utilisé pour nommer une classe, une interface ou un trait, et il est également interdit de l'utiliser dans les espaces de noms.

  • Les échecs d'assertion sont maintenant lancés par défaut. Si l'ancien comportement est souhaité, assert.exception=0 peut être défini dans les paramètres INI.

  • Les méthodes portant le même nom que la classe ne sont plus interprétées comme des constructeurs. La méthode __construct() doit être utilisée à la place.

  • La possibilité d'appeler des méthodes non statiques de manière statique a été supprimée. Ainsi, is_callable() échouera lors de la vérification d'une méthode non statique avec un nom de classe (il faut vérifier avec une instance d'objet).

  • Les castings (real) et (unset) ont été supprimés.

  • La directive ini track_errors a été supprimée. Cela signifie que php_errormsg n'est plus disponible. La fonction error_get_last() peut être utilisée à la place.

  • La possibilité de définir des constantes insensibles à la casse a été supprimée. Le troisième argument de define() ne peut plus être true.

  • La possibilité de spécifier un autochargeur en utilisant une fonction __autoload() a été supprimée. spl_autoload_register() doit être utilisée à la place.

  • L'argument errcontext ne sera plus passé aux gestionnaires d'erreurs personnalisés paramétrés avec set_error_handler().

  • create_function() a été supprimée. Les fonctions anonymes peuvent être utilisées à la place.

  • each() a été supprimée. foreach ou ArrayIterator doivent être utilisées à la place.

  • La possibilité de délier this des fermetures qui ont été créées à partir d'une méthode, en utilisant Closure::fromCallable() ou ReflectionMethod::getClosure() a été supprimée.

  • La possibilité de délier this des fermetures appropriées qui contiennent des utilisations de this a également été supprimée.

  • La possibilité d'utiliser array_key_exists() avec des objets a été supprimée. isset() ou property_exists() peuvent être utilisées à la place.

  • Le comportement de array_key_exists() concernant le type du paramètre key a été rendu cohérent avec isset() et l'accès normal aux tableaux. Tous les types de clés utilisent maintenant les coercions habituels et les clés de type tableau/objet lancent une TypeError.

  • Tout tableau dont la première clé numérique est un nombre n utilisera n+1 pour sa prochaine clé implicite, même si n est négatif.

  • Le niveau de signalement des erreurs par défaut (error_reporting) est désormais E_ALL. Auparavant, il excluait E_NOTICE et E_DEPRECATED.

  • display_startup_errors est désormais activée par défaut.

  • L'utilisation de parent à l'intérieur d'une classe qui n'a pas de parent entraîne désormais une erreur fatale à la compilation.

  • L'opérateur @ ne silence plus les erreurs fatales (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_PARSE). Les gestionnaires d'erreurs qui s'attendent à ce que error_reporting soit égal à 0 lorsque @ est utilisé, doivent être ajustés pour utiliser une vérification de masque à la place :

    <?php
    // Remplacer
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (    error_reporting() == 0) {
    return     false;
    }
    // ...
    }

    // Par
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (!(    error_reporting() & $err_no)) {
    return     false;
    }
    // ...
    }
    ?>

    En outre, il faut veiller à ce que les messages d'erreur ne soient pas affichés dans les environnements de production, ce qui peut entraîner des fuites d'informations. Veillez à ce que l'option display_errors=Off soit utilisée en conjonction avec la journalisation des erreurs.

  • #[ n'est plus interprété comme le début d'un commentaire, car cette syntaxe est désormais utilisée pour les attributs.

  • Les erreurs d'héritage dues à des signatures de méthodes incompatibles (violations de LSP) génèrent désormais une erreur fatale. Auparavant, un avertissement était généré dans certains cas.

  • La priorité de l'opérateur de concaténation a été modifiée par rapport aux décalages de bits, à l'addition ainsi qu'à la soustraction.

    <?php
    echo "Sum: " . $a + $b;
    // était auparavant interprété comme:
    echo ("Sum: " . $a) + $b;
    // est désormais interprété comme:
    echo "Sum:" . ($a + $b);
    ?>

  • Les arguments avec une valeur par défaut qui se résout en null à l'exécution ne marqueront plus implicitement le type d'argument comme nullable. Il faut utiliser soit un type explicite nullable, soit une valeur par défaut explicite null à la place.

    <?php
    // Remplacer
    function test(int $arg = CONST_RESOLVING_TO_NULL) {}
    // Par
    function test(?int $arg = CONST_RESOLVING_TO_NULL) {}
    // Ou
    function test(int $arg = null) {}
    ?>

  • Un certain nombre d'avertissements ont été convertis en exceptions Error:

    • Tentative d'écriture sur une propriété d'un non-objet. Auparavant, cela créait implicitement un objet stdClass pour null, false et les chaînes vides.
    • Tentative d'ajout d'un élément à un tableau pour lequel la clé PHP_INT_MAX est déjà utilisée.
    • Tentative d'utilisation d'un type invalide (tableau ou objet) comme clé de tableau ou comme index de chaîne de caractères.
    • Tentative d'écriture sur un index de tableau d'une valeur scalaire.
    • Tentative de décompactage d'un non tableau/Traversable.
    • Tentative d'accès à des constantes non qualifiées qui sont indéfinies. Auparavant, les accès à des constantes non qualifiées entraînaient un avertissement et étaient interprétés comme des chaînes de caractères.
    • Passer le nombre incorrect d'arguments à une fonction intégrée non variadique entraînera le déclenchement d'une ArgumentCountError.

    Un certain nombre de notices ont été convertis en avertissements :

    • Tentative de lecture d'une variable non définie.
    • Tentative de lecture d'une propriété non définie.
    • Tentative de lecture d'une clé de tableau non définie.
    • Tentative de lecture d'une propriété d'un non-objet.
    • Tentative d'accès à un index de tableau d'un non-tableau.
    • Tentative de conversion d'un tableau en chaîne de caractères.
    • Tentative d'utilisation d'une ressource comme clé de tableau.
    • Tentative d'utilisation de null, d'un booléen ou d'un nombre flottant comme index de chaîne.
    • Tentative de lecture d'un index de chaîne hors limites.
    • Tentative d'affectation d'une chaîne vide à un index de chaîne.

  • Tenter d'assigner plusieurs octets à un index de chaîne émettra désormais un avertissement.

  • Les caractères inattendus dans les fichiers source (tels que les octets NUL à l'extérieur des chaînes de caractères) entraîneront désormais une exception ParseError au lieu d'un avertissement de compilation.

  • Les exceptions non capturée passent maintenant par un "arrêt propre", ce qui signifie que les destructeurs seront appelés après une exception non capturée.

  • L'erreur fatale à la compilation "Only variables can be passed by reference" a été retardée jusqu'à l'exécution, et convertie en une exception Error "Argument cannot be passed by reference".

  • Certaines notices "Only variables should be passed by reference" ont été convertis en exception "Argument cannot be passed by reference".

  • Le nom généré pour les classes anonymes a changé. Il inclura désormais le nom du premier parent ou interface :

    <?php
    new class extends ParentClass {};
    // -> ParentClass@anonymous
    new class implements FirstInterface, SecondInterface {};
    // -> FirstInterface@anonymous
    new class {};
    // -> class@anonymous
    ?>

    Le nom ci-dessus est toujours suivi d'un octet NUL et d'un suffixe unique.

  • Les références de méthodes de traits non absolues dans les adaptations d'alias de traits doivent désormais être non ambiguës :

    <?php
    class X {
    use     T1, T2 {
    func as otherFunc;
    }
    function     func() {}
    }
    ?>

    Si T1::func() et T2::func() existent tous les deux, ce code était auparavant accepté silencieusement, et func était supposé faire référence à T1::func. Désormais, il génère une erreur fatale, et T1::func ou T2::func doivent être écrit explicitement.

  • La signature des méthodes abstraites définies dans les traits est maintenant vérifiée par rapport à la méthode dans la classe d'implémentation:

    <?php
    trait MyTrait {
    abstract private function     neededByTrait(): string;
    }

    class     MyClass {
    use     MyTrait;

    // Error, because of return type mismatch.
    private function neededByTrait(): int { return 42; }
    }
    ?>

  • Les fonctions désactivées sont désormais traitées exactement comme des fonctions inexistantes. L'appel d'une fonction la signalera comme inconnue, et il est désormais possible de redéfinir une fonction désactivée.

  • Les enveloppes de flux data:// ne sont plus inscriptibles, ce qui correspond au comportement documenté.

  • Les opérateurs arithmétiques et binaires +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++, -- lancent désormais systématiquement une TypeError lorsqu'un des opérandes est un tableau, ressource ou un objet non surchargé. La seule exception à cette règle est l'opération de fusion de tableau +, qui reste supportée.

  • La conversion de nombres flottants en chaînes de caractères se fera désormais indépendamment de la localisation.

    <?php
    setlocale    (LC_ALL, "de_DE");
    $f = 3.14;
    echo     $f, "\n";
    // Previously: 3,14
    // Now: 3.14
    ?>

    Voir printf(), number_format() et NumberFormatter() pour personnaliser le formatage des nombres.

  • La prise en charge des accolades pour l'accès aux index a été supprimée.

    <?php
    // Instead of:
    $array{0};
    $array{"key"};
    // Write:
    $array[0];
    $array["key"];
    ?>

  • L'application du modificateur final sur une méthode privée produira désormais un avertissement à moins que cette méthode ne soit le constructeur.

  • Si un constructeur d'objet appelle exit(), le destructeur d'objet n'est plus appelé. Cela correspond au comportement lorsque le constructeur lance une exception.

  • Les noms d'espace de nommage ne peuvent plus contenir d'espace blanc : Alors que Foo\Bar sera reconnu comme un nom à espace de noms, Foo \ Bar ne le sera pas. Inversement, les mots-clés réservés sont désormais autorisés en tant que segments d'espace de noms, ce qui peut également modifier l'interprétation du code : new\x est maintenant la même chose que constant('new\x'), et pas new \x().

  • Les ternaires imbriqués nécessitent désormais des parenthèses explicites.

  • debug_backtrace() et Exception::getTrace() ne fourniront plus de références aux arguments. Il ne sera plus possible de modifier les arguments d'une fonction par le biais de la trace.

  • La gestion des chaînes numériques a été modifiée pour être plus intuitive et moins sujette aux erreurs. L'espacement de fin est désormais autorisé dans les chaînes numériques pour des raisons de cohérence avec le traitement des espaces de tête. Ceci affecte principalement :

    • La fonction is_numeric()
    • Les comparaisons entre deux chaîne de caractères
    • Les déclarations de type
    • Les opérations d'incrémentation et de décrémentation

    Le concept de "chaînes débutant numériquement" a été pratiquement abandonné ; les cas où il subsiste existent afin de faciliter la migration. Les chaînes de caractères qui émettaient une erreur E_NOTICE "A non wellformed numeric value encountered" émettront désormais une erreur E_WARNING "A nonumeric value encountered" et toutes les chaînes qui émettaient une erreur E_WARNING "A non-numeric value encountered" émettront désormais une erreur de type TypeError. Ceci affecte principalement :

    • les opérations arithmétiques
    • les opérations binaires

    Cette modification de E_WARNING à TypeError affecte également l'erreur E_WARNING "Illegal string offset 'string'" pour les index de chaîne illégaux. Le comportement des transformations explicites en int/float à partir de chaînes de caractères n'a pas été modifié.

  • Les arguments et les types de retour des méthodes magiques seront désormais vérifiés s'ils ont été déclarés. Les signatures doivent correspondre à la liste suivante :

    • __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

  • Les clés des tableaux call_user_func_array() seront désormais interprétées comme des noms de paramètres, au lieu d'être ignorées silencieusement.

  • La déclaration d'une fonction appelée assert() à l'intérieur d'un espace de noms n'est plus autorisée, et émet une E_COMPILE_ERROR. La fonction assert() est soumise à un traitement spécial par le moteur, ce qui peut conduire à un comportement incohérent lors de la définition d'une fonction de l'espace de noms portant le même nom.

Migration des ressources vers les objets

Plusieurs ressources ont été migrées en objets. Les vérifications de la valeur retournée utilisant is_resource() devraient être remplacées par des vérifications pour false.

  • curl_init() retourne désormais un objet CurlHandle plutôt qu'une ressource. La fonction curl_close() n'a plus d'effet, l'instance CurlHandle est automatiquement détruite si elle n'est plus référencée.

  • curl_multi_init() retourne désormais un objet CurlMultiHandle plutôt qu'un ressource. La fonction curl_multi_close() n'a plus d'effet, l'instance CurlMultiHandle est automatiquement détruite si elle n'est plus référencée.

  • curl_share_init() retourne désormais un objet CurlShareHandle plutôt qu'un ressource. La fonction curl_share_close() n'a plus d'effet, l'instance CurlShareHandle est automatiquement détruite si elle n'est plus référencée.

  • enchant_broker_init() retourne désormais un objet EnchantBroker plutôt qu'une ressource.

  • enchant_broker_request_dict() et enchant_broker_request_pwl_dict() retournent désormais un objet EnchantDictionary au lieu d'une ressource.

  • L'extension GD utilise désormais les objets GdImage comme structure de données sous-jacente pour les images, plutôt que des ressources. La fonction imagedestroy() n'a plus d'effet ; à la place, l'instance est automatiquement détruite si elle n'est plus référencée. GdImage est automatiquement détruite si elle n'est plus référencée.

  • openssl_x509_read() et openssl_csr_sign() retournent désormais un objet OpenSSLCertificate plutôt qu'une ressource. La fonction openssl_x509_free() est obsolète et n'a plus d'effet, l'instance OpenSSLCertificate est automatiquement détruite si elle n'est plus référencée.

  • openssl_csr_new() retourne désormais un objet OpenSSLCertificateSigningRequest plutôt qu'une ressource.

  • openssl_pkey_new() retourne désormais un objet OpenSSLAsymmetricKey plutôt qu'une ressource. La fonction openssl_pkey_free() est obsolète et n'a plus d'effet, l'instance OpenSSLAsymmetricKey est automatiquement détruite si elle n'est plus référencée.

  • shmop_open() retourne désormais un objet Shmop plutôt qu'une ressource. La fonction shmop_close() n'a plus d'effet, et est obsolète ; l'instance Shmop est automatiquement détruite si elle n'est plus référencée.

  • socket_create(), socket_create_listen(),
socket_accept(), socket_import_stream(),
socket_addrinfo_connect(), socket_addrinfo_bind(), et
socket_wsaprotocol_info_import() retournent désormais un objet
Socket plutôt qu'une ressource.
socket_addrinfo_lookup() retourne désormais un tableau d'objets
AddressInfo au lieu de ressources.

  • msg_get_queue() retourne désormais un objet SysvMessageQueue plutôt qu'une ressource.

  • sem_get() retourne désormais un objet SysvSemaphore plutôt qu'une ressource.

  • shm_attach() retourne désormais un objet SysvSharedMemory plutôt qu'une ressource.

  • xml_parser_create() et xml_parser_create_ns() retournent désormais un objet XMLParser au lieu d'une ressource. La fonction xml_parser_free() n'a plus d'effet, l'instance de XMLParser est automatiquement détruite si elle n'est plus référencée.

  • Les fonctions XMLWriter acceptent et retournent désormais, respectivement, des objets XMLWriter au lieu de ressources.

  • inflate_init() retourne désormais un objet InflateContext plutôt qu'une ressource.

  • deflate_init() retourne désormais un objet DeflateContext plutôt qu'une ressource.

COM et .Net (Windows)

La possibilité d'importer des constantes insensibles à la casse à partir de bibliothèques de types a été supprimée. Le deuxième argument de com_load_typelib() ne peut plus être false ; com.autoregister_casesensitive ne peut plus être désactivé ; les marqueurs insensibles à la casse dans com.typelib_file sont ignorés.

CURL

CURLOPT_POSTFIELDS n'accepte plus les objets sous forme de tableaux. Pour interpréter un objet comme un tableau, il faut effectuer un cast explicite (array). Cela s'applique également aux autres options acceptant les tableaux.

Date et heure

mktime() et gmmktime() requièrent désormais au moins un argument. time() peut être utilisée pour obtenir l'horodatage actuel.

DOM

Les classes non implémentées de l'extension DOM qui n'avaient pas de comportement et contenaient des données de test ont été supprimées. Ces classes ont également été supprimées dans la dernière version de la norme du standard DOM :

  • DOMNameList
  • DomImplementationList
  • DOMConfiguration
  • DomError
  • DomErrorHandler
  • DOMImplementationSource
  • DOMLocator
  • DOMUserDataHandler
  • DOMTypeInfo
  • DOMStringExtend

Les méthodes non implémentées de l'extension DOM qui n'avaient pas de comportement ont été supprimées :

  • DOMNamedNodeMap::setNamedItem()
  • DOMNamedNodeMap::removeNamedItem()
  • DOMNamedNodeMap::setNamedItemNS()
  • DOMNamedNodeMap::removeNamedItemNS()
  • DOMText::replaceWholeText()
  • DOMNode::compareDocumentPosition()
  • DOMNode::isEqualNode()
  • DOMNode::getFeature()
  • DOMNode::setUserData()
  • DOMNode::getUserData()
  • DOMDocument::renameNode()

Enchant

  • enchant_broker_list_dicts(), enchant_broker_describe() et enchant_dict_suggest() retourneront désormais un tableau vide au lieu de null.

Exif

read_exif_data() a été supprimée ; exif_read_data() doit être utilisée à la place.

Filter

  • Les drapeaux FILTER_FLAG_SCHEME_REQUIRED et FILTER_FLAG_HOST_REQUIRED pour le filtre FILTER_VALIDATE_URL ont été supprimés. Le schéma et l'hôte sont (et ont toujours été) nécessaires.

  • Les sources INPUT_REQUEST et INPUT_SESSION pour filter_input() etc. ont été supprimées. Elles n'ont jamais été mises en œuvre et leur utilisation a toujours généré un avertissement.

GD

  • La fonction obsolète image2wbmp() a été supprimée.

  • Les fonctions obsolètes png2wbmp() et jpeg2wbmp() ont été supprimées.

  • Le paramètre par défaut mode d'imagecropauto() n'accepte plus -1. IMG_CROP_DEFAULT doit être utilisé à la place.

  • Sous Windows, php_gd2.dll a été renommé en php_gd.dll.

GMP

gmp_random() a été supprimée. L'une des fonctions gmp_random_range() ou gmp_random_bits() doit être utilisée à la place.

Iconv

Les implémentations iconv qui ne définissent pas correctement errno en cas d'erreur ne sont plus supportées.

IMAP

  • L'argument inutilisé default_host de imap_headerinfo() a été supprimé.

  • La fonction imap_header() qui est un alias de imap_headerinfo() a été supprimée.

Fonctions d'internationalisation

  • La constante obsolète INTL_IDNA_VARIANT_2003 a été supprimée.

  • La constante obsolète Normalizer::NONE a été supprimée.

LDAP

  • Les fonctions ldap_sort(),
ldap_control_paged_result() et
ldap_control_paged_result_response() ont été supprimées.

  • L'interface de ldap_set_rebind_proc() a changée ; le paramètre callback n'accepte plus les chaînes vides ; null doit être utilisé à la place.

MBString

  • La directive mbstring.func_overload a été supprimée. Les constantes MB_OVERLOAD_MAIL, MB_OVERLOAD_STRING, et MB_OVERLOAD_REGEX ont également été supprimées. Enfin, les entrées "func_overload" et "func_overload_list" dans mb_get_info() ont été supprimées.

  • mb_parse_str() ne peut plus être utilisée sans spécifier un tableau de résultats.

  • Un certain nombre d'alias mbregex obsolètes ont été supprimés. Voir la liste suivante pour savoir quelles fonctions doivent être utilisées à la place :

    • 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()

  • Le modificateur e pour mb_ereg_replace() a été supprimé. mb_ereg_replace_callback() doit être utilisé à la place.

  • Un argument de motif autre qu'une chaîne de caractères à mb_ereg_replace() sera désormais interprété comme une chaîne de caractères au lieu d'un point de code ASCII. Le comportement précédent peut être restauré avec un appel explicite à chr().

  • L'argument needle pour mb_strpos(),
mb_strrpos(), mb_stripos(),
mb_strripos(), mb_strstr(),
mb_stristr(), mb_strrchr() et
mb_strrichr() peut désormais être vide.

  • Le paramètre is_hex, qui n'était pas utilisé en interne, a été supprimé de mb_decode_numericentity().

  • L'ancien comportement consistant à passer l'encodage comme troisième argument au lieu d'un offset pour la fonction mb_strrpos() a été supprimé ; un index explicite de 0 avec l'encodage doit être fourni comme quatrième argument.

  • Les alias de codage de caractères ISO_8859-* ont été remplacés par ISO8859-* pour une meilleure interopérabilité avec l'extension iconv. Les alias mbregex ISO 8859 avec des traits de soulignement(ISO_8859_* et ISO8859_*) ont également été supprimés.

  • mb_ereg() et mb_eregi() retourneront désormais le booléen true en cas de correspondance réussie. Auparavant, elles retournaient l'entier 1 si matches n'était pas passé, ou max(1, strlen($matches[0])) si matches était passé.

OCI8

  • La classe OCI-Lob s'appelle désormais OCILob, et la classe OCI-Collection s'appelle maintenant OCICollection pour la conformité des noms avec l'outil d'annotation de type arginfo de PHP 8.

  • Plusieurs fonctions alias ont été marquées comme obsolètes.

  • oci_internal_debug() et son alias ociinternaldebug() ont été supprimés.

ODBC

  • odbc_connect() ne réutilise plus les connexions.

  • Le paramètre inutilisé flags de odbc_exec() a été supprimé.

OpenSSL

  • openssl_seal() et openssl_open() requièrent désormais le paramètre method car l'ancienne valeur par défaut "RC4" est considéré comme peu sûr.

Expressions régulières (compatibles avec Perl)

Lorsque des séquences d'échappement invalides sont passées, elles ne sont plus interprétées comme des littéraux. Ce comportement nécessitait auparavant le modificateur X qui est maintenant ignoré.

Objets de données PHP (PDO)

  • Le mode de gestion des erreurs par défaut a été changé de "silencieux" à "exceptions". Voir Erreurs et gestion des erreurs pour plus de détails.

  • Les signatures de certaines méthodes PDO ont changé :

    • PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs)
    • PDOStatement::setFetchMode(int $mode, mixed ...$args)

PDO ODBC

La directive php.ini pdo_odbc.db2_instance_name a été supprimée.

PDO MySQL

PDO::inTransaction() indique désormais l'état réel de la transaction de la connexion, plutôt qu'une approximation maintenue par PDO. Si une requête soumise à un "commit implicite" est exécutée, PDO::inTransaction() retournera par la suite false, car la transaction n'est plus active.

PostgreSQL

  • La syntaxe obsolète pg_connect() utilisant plusieurs paramètres au lieu d'une chaîne de connexion n'est plus supportée.

  • La signature pg_lo_import() et pg_lo_export() qui transmet la connexion comme dernier argument n'est plus supportée. La connexion doit être passée comme premier argument à la place.

  • pg_fetch_all() retourne maintenant un tableau vide au lieu de false pour les jeux de résultats avec zéro ligne.

Phar

Les métadonnées associées à un phar ne seront plus automatiquement désérialisées, afin de corriger des vulnérabilités de sécurité potentielles dues à l'instanciation d'objets, à l'autoloading, etc.

Reflection

  • Les signatures de méthodes

    • ReflectionClass::newInstance($args)
    • ReflectionFunction::invoke($args)
    • ReflectionMethod::invoke($object, $args)

    ont été remplacées par :

    • ReflectionClass::newInstance(...$args)
    • ReflectionFunction::invoke(...$args)
    • ReflectionMethod::invoke($object, ...$args)

    Le code qui doit être compatible avec PHP 7 et PHP 8 peut utiliser les signatures suivantes pour être compatible avec les deux versions :

    • ReflectionClass::newInstance($arg = null, ...$args)
    • ReflectionFunction::invoke($arg = null, ...$args)
    • ReflectionMethod::invoke($object, $arg = null, ...$args)

  • La méthode ReflectionType::__toString() retourne maintenant une représentation complète de débogage du type, et n'est plus dépréciée. En particulier, le résultat inclura un indicateur de nullité pour les types nullables. Le format de la valeur retournée n'est pas stable et peut changer changer d'une version de PHP à l'autre.

  • Les méthodes de réflexion export() ont été supprimées. A la place, les objets de réflexion peuvent être transformés en chaînes de caractères.

  • ReflectionMethod::isConstructor() et ReflectionMethod::isDestructor() retournent désormais également true pour les méthodes __construct() et __destruct() des interfaces. Auparavant, ce n'était le cas que pour les méthodes des classes et des traits.

  • La méthode ReflectionType::isBuiltin() a été déplacée vers ReflectionNamedType. ReflectionUnionType n'a pas cette méthode.

Sockets

  • Les drapeaux obsolètes AI_IDN_ALLOW_UNASSIGNED et AI_IDN_USE_STD3_ASCII_RULES flags pour socket_addrinfo_lookup() ont été supprimés.

Bibliothèque standard de PHP (SPL)

  • SplFileObject::fgetss() a été supprimée.

  • SplFileObject::seek() cherche maintenant toujours le début de la ligne. Auparavant, les positions >=1 recherchaient le début de la ligne suivante.

  • SplHeap::compare() spécifie désormais une signature de méthode. Les classes héritées implémentant cette méthode devront désormais utiliser une signature de méthode compatible.

  • SplDoublyLinkedList::push(), SplDoublyLinkedList::unshift() et SplQueue::enqueue() retournent désormais void au lieu de true.

  • spl_autoload_register() lancera désormais toujours une TypeError en cas d'arguments invalides, donc le second argument do_throw est ignoré et une notification sera émise s'il est défini à false.

  • SplFixedArray est maintenant un IteratorAggregate et non plus un Iterator. SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next(), et SplFixedArray::valid() ont été supprimées. A leur place, SplFixedArray::getIterator() a été ajoutée. Tout code qui utilise l'itération explicite sur SplFixedArray doit maintenant obtenir une valeur de Iterator à travers SplFixedArray::getIterator(). Cela signifie que SplFixedArray peut désormais être utilisé en toute sécurité dans les boucles imbriquées.

Bibliothèque standard

  • assert() n'évalue plus les arguments de type chaîne de caractères, ils sont traités comme n'importe quel autre argument. assert($a == $b) doit être utilisé à la place de assert('$a == $b'). La directive ini assert.quiet_eval et la constante ASSERT_QUIET_EVAL ont également été supprimées, car elles n'auraient plus d'effet.

  • parse_str() ne peut plus être utilisé sans spécifier un tableau de résultats.

  • Le filtre string.strip_tags a été supprimé.

  • L'argument needle de strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr(), et stristr() sera désormais toujours interprété comme une chaîne de caractères. Auparavant, les needle étaient interprétés comme des points de code ASCII. Un appel explicite à chr() peut être utilisé pour rétablir le comportement précédent.

  • L'argument needle pour strpos(),
 strrpos(), stripos(), strripos(),
strstr(), stristr() et strrchr() peut
désormais être vide.

  • L'argument length pour substr(), substr_count(), substr_compare() et iconv_substr() peut désormais être null. Les valeurs null se comporteront comme si aucun argument de longueur n'avait été fourni et retourneront donc le reste de la chaîne de caractères au lieu d'une chaîne vide.

  • L'argument length pour array_splice() peut maintenant être null. Les valeurs null se comporteront de la même manière que si l'on omettait l'argument, c'est-à-dire qu'elles supprimeront tout ce qui se trouve de l'offset à la fin du tableau.

  • L'argument args de vsprintf(), vfprintf(), et vprintf() doit maintenant être un tableau. Auparavant n'importe quel type était accepté.

  • L'option 'salt' de password_hash() n'est plus supportée. Si l'option 'salt' est utilisée, un avertissement est généré, le salt fourni est ignoré et un salt généré est utilisé à la place.

  • La fonction quotemeta() retourne désormais une chaîne vide si une chaîne vide a été passée. Auparavant, elle retournait false.

  • Les fonctions suivantes ont été supprimées :

    • hebrevc()
    • convert_cyr_string()
    • money_format()
    • ezmlm_hash()
    • restore_include_path()
    • get_magic_quotes_gpc()
    • get_magic_quotes_runtime()
    • fgetss()

  • FILTER_SANITIZE_MAGIC_QUOTES a été supprimée.

  • L'appel à implode() avec des paramètres dans l'ordre inverse ($pieces, $glue) n'est plus supporté.

  • parse_url() distingue désormais les requêtes et les fragments absents ou vides :

    • 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 = ""
    Auparavant, dans tous les cas, la requête et le fragment étaient des null.

  • var_dump() et debug_zval_dump() imprimeront maintenant les nombres à virgule flottante en utilisant serialize_precision plutôt que la précision. Dans une configuration par défaut, cela signifie que les nombres à virgule flottante sont désormais imprimés avec une précision totale par ces fonctions de débogage.

  • Si le tableau retourné par __sleep() contient des propriétés inexistantes, celles-ci sont désormais ignorées de manière silencieuse. Auparavant, de telles propriétés auraient été sérialisées comme si elles avaient la valeur null.

  • La locale par défaut au démarrage est désormais toujours "C". Aucune locale n'est héritée de l'environnement par défaut. Auparavant, LC_ALL était réglé sur "C", tandis que LC_CTYPE était hérité de l'environnement. Cependant, certaines fonctions ne respectaient pas les paramètres linguistiques hérités sans un appel explicite à setlocale(). Un appel explicite à setlocale() est désormais toujours nécessaire si un composant de locale doit être modifié par rapport à la valeur par défaut.

  • La solution de repli DES dans crypt() a été supprimée. Si un format de salt inconnu est passé à crypt(), la fonction échouera avec *0 au lieu de se rabattre sur un hachage DES faible.

  • Spécifier des rounds hors plage pour SHA256/SHA512 crypt() échouera maintenant avec *0 au lieu de se caler sur la limite la plus proche. Cela correspond au comportement de la glibc.

  • Le résultat des fonctions de tri peut avoir changé, si le tableau contient des éléments qui se comparent comme étant égaux.

  • Toutes les fonctions acceptant des fonctions de rappels qui ne sont pas explicitement spécifiées pour accepter des paramètres par référence seront désormais averties si une fonction de rappel avec des paramètres par référence est utilisée. Les exemples incluent array_filter() et array_reduce(). C'était déjà le cas pour la plupart des fonctions, mais pas toutes.

  • L'enveloppe de flux HTTP utilisée par des fonctions telles que file_get_contents() annonce désormais HTTP/1.1 au lieu de HTTP/1.0 par défaut. Cela ne modifie pas le comportement du client mais les serveurs peuvent réagir différemment. Pour conserver l'ancien comportement, définissez l'option de contexte de flux 'protocol_version', par exemple

    <?php
    $ctx     = stream_context_create(['http' => ['protocol_version' => '1.0']]);
    echo     file_get_contents('http://example.org', false, $ctx);
    ?>

  • L'appel à crypt() sans salt explicite n'est plus supporté. Si vous souhaitez produire un hachage fort avec un salt auto-généré, utilisez plutôt password_hash() à la place.

  • substr(), mb_substr(), iconv_substr() et grapheme_substr() fixent désormais de manière cohérente les index hors limites à la limite de la chaîne de caractères. Auparavant, false était retourné au lieu de la chaîne vide dans certains cas.

  • Sous Windows, les fonctions d'exécution de programmes(proc_open(), exec(), popen() etc.) utilisant l'interpréteur de commandes, exécutent désormais systématiquement %comspec% /s /c "$commandline", ce qui a le même effet que l'exécution de $commandline (sans les guillemets supplémentaires).

Sysvsem

  • Le paramètre auto_release de sem_get() a été modifié pour accepter les valeurs booléen au lieu de entier.

Tidy

  • Le paramètre use_include_path, qui n'était pas utilisé en interne, a été supprimé de tidy_repair_string().

  • tidy::repairString() et tidy::repairFile() sont devenues des méthodes statiques.

Tokenizer

  • Les tokens T_COMMENT n'incluront plus de nouvelle ligne à la fin. La nouvelle ligne fera partie d'un jeton T_WHITESPACE suivant. Il convient de noter que T_COMMENT n'est pas toujours suivi d'un espace blanc, il peut également être suivi de T_CLOSE_TAG ou d'une fin de fichier.

  • Les noms à espace de nommage sont désormais représentés à l'aide des attributs T_NAME_QUALIFIED (Foo\Bar), T_NAME_FULLY_QUALIFIED(\Foo\Bar) et T_NAME_RELATIVE(namespace\Foo\Bar). T_NS_SEPARATOR n'est utilisé que pour les séparateurs d'espace de noms autonomes, et n'est syntaxiquement valide qu'en conjonction avec les déclarations d'utilisation de groupe.

XMLReader

XMLReader::open() et XMLReader::xml() sont désormais des méthodes statiques. Elles peuvent toujours être appelées en tant que méthodes d'instance, mais les classes qui en héritent doivent les déclarer comme statiques si elles surchargent ces méthodes.

XML-RPC

L'extension XML-RPC a été déplacée vers PECL et ne fait plus partie de la distribution de PHP. et ne fait plus partie de la distribution de PHP.

Zip

ZipArchive::OPSYS_Z_CPM a été supprimée (ce nom était une erreur de frappe). Utilisez plutôt ZipArchive::OPSYS_CPM à la place.

Zlib

  • gzgetss() a été supprimée.

  • zlib.output_compression n'est plus automatiquement désactivée pour Content-Type: image/*.

Packs de test PHP pour Windows

Le programme de test a été renommé de run-test.php à run-tests.php, pour correspondre à son nom dans php-src.

User Contributed Notes

aphpguy at galaxy dot za dot net 06-Jul-2023 12:33
If you have older projects that break with PHP7 to 8 migration due to the loose comparison issue:

i.e. if ($a == 0) different behaviour between PHP 7 and PHP 8
(for case like $a = "" or $a = "123foo" and other cases listed at top)

replace in old code:

if ($a == 0) { .. }

with

if (cmp_eq($a, $b)) { .. }

Tested with a wide range of scenarios, even against arrays, booleans, file handles, pipe handles, objects, scalars and numbers.

So old code still behave like before.
Then both PHP8.x and older PHP up to ver 7.x will give the exact same boolean true or false output for loose comparisons.

function cmp_eq($a, $b) {
// If both $a and $b are of type strings, compare them as strings
if (is_string($a) && is_string($b)) { return $a == $b; } // may not be === because php says '42' equals '042' true yet '42' === '042' is false.

// If both $a and $b are numeric strings, compare them as numbers
if (is_numeric($a) && is_numeric($b)) { return $a == $b; }

// If $a is an empty string and $b is 0, or vice versa, return true
if (($a === '' && $b === 0) || ($a === 0 && $b === '')) { return true; }

// If $a is a non-numeric string and $b is 0, or vice versa, return true
if ((is_string($a) && ($a !== '') && ($b === 0)) || (($a === 0) && is_string($b) && ($b !== ''))) {
return true;
}
// special case '123abc' == 123 .. php 7 casts 123abc to 123, then 123 == 123 results in true. lets mimic that.
if ((is_string($a) && ($a !== '') && (is_numeric($b)) && ((bool)$b))) {
$number = filter_var($a, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); //"-234.56xyz"
return $number == $b;
}
if (is_numeric($a) && ((bool)$a) && is_string($b) && ($b !== '')) {
$number = filter_var($b, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); //"-234.56xyz"
return $a == $number;
}

// If $a is a number and $b is a non-numeric string, cast $a to string and compare
if (is_numeric($a) && is_string($b)) { return strval($a) == $b; }

// If $b is a number and $a is a non-numeric string, cast $b to string and compare
if (is_string($a) && is_numeric($b)) { return $a == strval($b); }

// If $a and $b are both non-numeric strings, compare them directly, we should return true if they are the same
return $a == $b;
} // end func cmp_eq

Note: the better way would be to port code to PHP 8, use strict variable typing and rather make use of the === and !== operators.

But in some cases having lots of old code to quickly patch, this might help.
1035041238 at qq dot com 15-Nov-2022 02:41
In PHP 8, an empty string is less than any number, an English letter is always bigger than any number.

More interesting are the punctuation marks and non-word characters, some bigger than numbers, some smaller than numbers

$string = '`~!@#$%^&*()-_=+[]{};:\'"\\|,.<>/?';

$number = 999999999999;

$str_len = strlen($string);

$bigger = $smaller = $equal = [];
for ( $i = 0; $i < $str_len; ++$i ) {
    if ( $string[$i] > $number ) {
        $bigger[] = $string[$i];
    } elseif ( $string[$i] < $number ) {
        $smaller[] = $string[$i];
    } else {
        $equal[] = $string[$i];
    }
}

var_dump( $bigger ); //['`', '~', '@', '^', '_', '=', '[', ']', '{', '}', ';', ':', '\', '|', '<', '>', '?']
var_dump( $smaller); //['!', '#', '$', '%', '&', '*', '(', ')', '-', '+', ''', '"', ',', '.', '/']
var_dump( $equal); //[]
retry, abort, fail 25-Feb-2022 11:57
The change in string to int comparison mentioned above (e.g. '' == 0 now equates to false) has some other nasty consequences:

$a = '';

// php 8

if ( $a < 0 ) echo 'true'; // echos true
if ( $a < -1) echo 'true'; // echos true
if ( $a < -100 ) echo 'true'; // echos true

// php 7

if ( $a < 0 ) echo 'true'; // no output
if ( $a < -1) echo 'true'; // no output
if ( $a < -100 ) echo 'true'; // no output

So in a situation where you may have a web form input and expected an empty value to equate to 0, watch out not only for == 0, != 0, and <= 0 comparisons, but ALL < or <= comparisons to negative integers.


Fonctionnalités obsolètes

PHP Core

  • Si un paramètre avec une valeur par défaut est suivi d'un paramètre obligatoire, la valeur par défaut n'a pas d'effet. Ceci est obsolète à partir de PHP 8.0.0 et peut généralement être résolu en supprimant la valeur par défaut du paramètre, sans changer la fonctionnalité.

    <?php
    function test($a = [], $b) {} // Avant
    function test($a, $b) {} // Après
    ?>

    Une exception à cette règle sont les paramètres de la forme Type $param = null, où la valeur par défaut null rend le type implicitement nullable. Cette utilisation reste autorisée, mais il est recommandé d'utiliser un type explicitement nullable :

    <?php
    function test(A $a = null, $b) {} // Toujours autorisé
    function test(?A $a, $b) {} // Recommandé
    ?>

  • Appeler get_defined_functions() avec exclude_disabled explicitement à false est obsolète et n'a plus d'effet. get_defined_functions() n'inclura jamais les fonctions désactivées.

Enchant

  • enchant_broker_set_dict_path() et enchant_broker_get_dict_path() sont obsolètes, car cette fonctionnalité n'est pas disponible dans libenchant < 1.5 ni dans libenchant-2.

  • enchant_dict_add_to_personal() est obsolète ; utilisez plutôt enchant_dict_add() à la place.

  • enchant_dict_is_in_session() est obsolète ; utilisez plutôt enchant_dict_is_added() à la place.

  • enchant_broker_free() et enchant_broker_free_dict() sont obsolètes ; détruissez l'objet à la place.

  • Les constantes ENCHANT_MYSPELL et ENCHANT_ISPELL sont obsolètes.

LibXML

libxml_disable_entity_loader() est maintenant obsolète. Comme libxml 2.9.0 est désormais requis, le chargement d'entités externes est garanti d'être désactivé par défaut, et cette fonction n'est plus nécessaire pour se protéger contre les attaques XXE, à moins d'utiliser la constante (toujours vulnérable) LIBXML_NOENT. Dans ce cas, il est recommandé de refactoriser le code en utilisant libxml_set_external_entity_loader() pour supprimer le chargement des entités externes.

PGSQL / PDO PGSQL

  • La constante PGSQL_LIBPQ_VERSION_STR a maintenant la même valeur que PGSQL_LIBPQ_VERSION et est donc obsolète.

  • Les alias de fonctions de l'extension pgsql sont obsolètes. Voir la liste suivante pour savoir quelles fonctions doivent être utilisées à la place :

    • 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()

Bibliothèque standard

  • Les fonctions de comparaison de tri qui retournent true ou false lèveront désormais un avertissement d'obsolescence, et doivent être remplacées par une implémentation qui retourne un entier inférieur, égal ou supérieur à zéro.

    <?php
    // Remplacer
    usort($array, fn($a, $b) => $a > $b);
    // Par
    usort($array, fn($a, $b) => $a <=> $b);
    ?>

Zip

  • L'utilisation d'un fichier vide en tant que ZipArchive est obsolète. Libzip 1.6.0 n'accepte plus les fichiers vides comme des archives zip valides. La solution de contournement existante sera supprimée dans la prochaine version.

  • L'API procédurale de Zip est obsolète. Utilisez plutôt ZipArchive. L'itération sur toutes les entrées peut être réalisée en utilisant ZipArchive::statIndex() et une boucle for:

    <?php
    // itère à l'aide de l'API procédurale
    assert(is_resource($zip));
    while (    $entry = zip_read($zip)) {
    echo     zip_entry_name($entry);
    }

    // itère à l'aide de l'API orientée objet
    assert($zip instanceof ZipArchive);
    for (    $i = 0; $entry = $zip->statIndex($i); $i++) {
    echo     $entry['name'];
    }
    ?>

Reflection

  • ReflectionFunction::isDisabled() est obsolète, car il n'est plus possible de créer un ReflectionFunction pour une fonction désactivée. Cette méthode retourne maintenant toujours false.

  • ReflectionParameter::getClass(),
ReflectionParameter::isArray(), et
ReflectionParameter::isCallable() sont obsolètes.
Les APIs ReflectionParameter::getType() et
ReflectionType doivent être utilisées à la place.

User Contributed Notes

dominique dot vienne at ik dot me 21-Jun-2021 01:23
If you try to get all methods / functions assigning an optional argument before a mandatory one, try this regex (single line)

<?php
function\s+[a-z][a-zA-Z0-9_]*\((?:\$[a-z][a-zA-Z0-9]*\s*,\s*)*
(?:\$[a-z][A-Za-z0-9_]*\s*=[^\$\)]+)+\$[a-z][a-zA-Z0-9_]*\)
?>

for
<?php
public function test($a, $b) {
$a = [];
$b = [$abc => $ss[],
];
}

private function too($c, $a = true, $b) {
}

protected function bar($a = []) {
}

public function foo($a, $b = true) {
}

public function fooBar32($a=true, $b = [], $c) {
}

private function oo_bAr($a = []) {
}
?>
it will match too() and fooBar32()

Have a nice migration! ;)


Other Changes

Changes in SAPI Modules

Apache2Handler

The PHP module has been renamed from php7_module to php_module.

Changed Functions

Reflection

ReflectionClass::getConstants() and ReflectionClass::getReflectionConstants() results can be now filtered via a new parameter filter. Three new constants were added to be used with it:

  • ReflectionClassConstant::IS_PUBLIC
  • ReflectionClassConstant::IS_PROTECTED
  • ReflectionClassConstant::IS_PRIVATE

Standard

The math functions abs(), ceil(), floor() and round() now properly heed the strict_types directive. Previously, they coerced the first argument even in strict type mode.

Zip

  • The ZipArchive::addGlob() and ZipArchive::addPattern() methods accept more values in the options array argument:

    • flags
    • comp_method
    • comp_flags
    • env_method
    • enc_password

  • ZipArchive::addEmptyDir(), ZipArchive::addFile() and ZipArchive::addFromString() methods have a new flags argument. This allows managing name encoding (ZipArchive::FL_ENC_*) and entry replacement (ZipArchive::FL_OVERWRITE).

  • ZipArchive::extractTo() now restores the file modification time.

Other Changes to Extensions

CURL

  • The CURL extension now requires at least libcurl 7.29.0.

  • The deprecated parameter version of curl_version() has been removed.

Date and Time

DatePeriod now implements IteratorAggregate (instead of Traversable).

DOM

DOMNamedNodeMap and DOMNodeList now implement IteratorAggregate (instead of Traversable).

Intl

IntlBreakIterator and ResourceBundle now implement IteratorAggregate (instead of Traversable).

Enchant

The enchant extension now uses libenchant-2 by default when available. libenchant version 1 is still supported but is deprecated and could be removed in the future.

GD

  • The num_points parameter of imagepolygon(), imageopenpolygon() and imagefilledpolygon() is now optional, i.e. these functions may be called with either 3 or 4 arguments. If the argument is omitted, it is calculated as count($points)/2.

  • The function imagegetinterpolation() to get the current interpolation method has been added.

JSON

The JSON extension cannot be disabled anymore and is always an integral part of any PHP build, similar to the date extension.

MBString

The Unicode data tables have been updated to version 13.0.0.

PDO

PDOStatement now implements IteratorAggregate (instead of Traversable).

LibXML

The minimum required libxml version is now 2.9.0. This means that external entity loading is now guaranteed to be disabled by default, and no extra steps need to be taken to protect against XXE attacks.

MySQLi / PDO MySQL

  • When mysqlnd is not used (which is the default and recommended option), the minimum supported libmysqlclient version is now 5.5.

  • mysqli_result now implements IteratorAggregate (instead of Traversable).

PGSQL / PDO PGSQL

The PGSQL and PDO PGSQL extensions now require at least libpq 9.1.

Readline

Calling readline_completion_function() before the interactive prompt starts (e.g. in auto_prepend_file) will now override the default interactive prompt completion function. Previously, readline_completion_function() only worked when called after starting the interactive prompt.

SimpleXML

SimpleXMLElement now implements RecursiveIterator and absorbed the functionality of SimpleXMLIterator. SimpleXMLIterator is an empty extension of SimpleXMLElement.

Changes to INI File Handling

  • com.dotnet_version is a new INI directive to choose the version of the .NET framework to use for dotnet objects.

  • zend.exception_string_param_max_len is a new INI directive to set the maximum string length in an argument of a stringified stack strace.

EBCDIC

EBCDIC targets are no longer supported, though it's unlikely that they were still working in the first place.

Performance

  • A Just-In-Time (JIT) compiler has been added to the opcache extension.

  • array_slice() on an array without gaps will no longer scan the whole array to find the start offset. This may significantly reduce the runtime of the function with large offsets and small lengths.

  • strtolower() now uses a SIMD implementation when using the "C" LC_CTYPE locale (which is the default).

User Contributed Notes

barry dot nelson at amobiledevice dot com 16-Jan-2023 12:18
If loading the PHP8 apache module on SuSe Linux, the configuration scripts incorrectly try to load it with automatically generated load statement of:
LoadModule php8_module                     /usr/lib64/apache2/mod_php8.so
This does not work, the patch below fixes the conf file generator...

--- /usr/share/apache2/get_module_list    2023-01-14 22:41:49.586825349 -0500
+++ /usr/share/apache2/get_module_list    2023-01-14 22:42:02.171600410 -0500
@@ -91,4 +91,8 @@
     esac

+    if [ "$module_id" = "php8_module" ]; then
+        module_id="php_module"
+    fi
+
     if [[ -f $module_path ]]; then
         printf "LoadModule %-30s %s\n" $module_id $module_path >&3


Migration de PHP 7.3.x vers PHP 7.4.x

Sommaire

  • Nouvelles fonctionnalités
  • Nouvelles Classes et Interfaces
  • Nouvelles fonctions
  • Nouvelles constantes globales
  • Modifications entrainant une incompatibilité ascendante
  • Fonctionnalités obsolètes
  • Extensions supprimées
  • Autres changements
  • Gestion de Windows

Cette nouvelle version mineure apporte un certain nombre de nouvelles fonctionnalités et quelques incompatibilités qui devraient être testées avant de changer les versions PHP dans les environnements de production.

Voir aussi les guides de migration entre les différentes versions de PHP 7.0.x, 7.1.x, 7.2.x et 7.3.x.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctionnalités

Cœur de PHP

Propriétés typées

Les propriétés des classes supportent désormais la déclaration du type.

<?php
class User {
public int $id;
public string $name;
}
?>
L'exemple ci-dessus s'assurera que $user->id ne peut se voir attribuer que des valeurs d'entier et $user->name ne peut se voir attribuer que des valeurs chaîne de caractères.

Fonctions flèches

Les fonctions flèches fournissent une syntaxe courte pour définir des fonctions qui lient la portée par valeur implicitement.

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

Type de retour covariant et type d'argument contravariant limité

Le code suivant va désormais fonctionner :

<?php
class A {}
class B extends A {}

class Producer {
public function method(): A {}
}
class ChildProducer extends Producer {
public function method(): B {}
}
?>
Le support de variance totale est seulement disponible quand l'autoloading est utilisé. Dans un fichier unique seules des références de types non cycliques sont possibles, car toutes les classes doivent être disponibles avant qu'elles soient référencées.

Opérateur d'assignement de fusion Null

<?php
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
$array['key'] = computeDefault();
}
?>

Déballage dans les tableaux

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

Séparateur numérique litéral

Les nombres littéraux peuvent contenir un caractère de soulignement entre les chiffres.

<?php
6.674_083e-11; // float
299_792_458; // decimal
0xCAFE_F00D; // hexadecimal
0b0101_1111; // binary
?>

Références faibles

Les références faibles permettent au développeur de retenir une référence à un objet qui n'empêche pas l'objet d'être détruit.

Autoriser des Exceptions depuis __toString()

Lancer des exceptions depuis __toString() est désormais permis. Précédemment, ceci résultait en une erreur fatale. Les erreurs fatales récupérables dans les conversions de chaîne de caractères ont été converties en exceptions Error.

CURL

CURLFile supporte désormais les enveloppes de flux en plus des noms de fichiers bruts, si l'extension a été compilée avec libcurl >= 7.56.0.

Filtre

Le filtre FILTER_VALIDATE_FLOAT supporte désormais les options min_range et max_range, avec la même sémantique que FILTER_VALIDATE_INT.

FFI

FFI est une nouvelle extension, qui fournit une manière simple d'appeler les fonctions natives, un accès natif aux variables, et la création/l'accès à des structures de données définies dans des bibliothèques C.

GD

Ajout du filtre d'image IMG_FILTER_SCATTER pour appliquer un filtre à dispersions aux images.

Hash

Ajout du hash crc32c utilisant le polynôme de Castagnoli. Cette variante de CRC32 est utilisée par les systèmes de stockage, tels que iSCSI, SCTP, Btrfs et ext4.

Chaînes multioctets

Ajout de la fonction mb_str_split(), qui fournit la même fonctionnalité que str_split(), mais opère sur des points de code au lieu d'octets.

OPcache

Le support pour le préchargement de code a été ajouté.

Expressions Régulières (Compatible Perl)

Les fonctions preg_replace_callback() et preg_replace_callback_array() acceptent désormais un argument flags additionnel, avec le support des drapeaux PREG_OFFSET_CAPTURE et PREG_UNMATCHED_AS_NULL. Ceci influence le format du tableau de matchs passé à la fonction de rappel.

PDO

Le nom d'utilisateur et le mot de passe peuvent désormais être spécifiés en tant que partie du DSN PDO pour les pilotes mysql, mssql, sybase, dblib, firebird et oci. Précédemment, ceci était seulement supporté pour le pilote pgsql. Si un nom d'utilisateur/mot de passe est défini à la fois dans le constructeur et le DSN, le constructeur prend précédence.

Il est désormais possible d'échapper les points d'interrogations dans les requêtes SQL pour éviter qu'ils ne soient interprétés comme paramètre fictif. Écrire ?? permet d'envoyer un seul point d'interrogation à la base de données et, par exemple, utiliser l'opérateur PostgreSQL JSON pour savoir si une clef existe (?).

PDO_OCI

PDOStatement::getColumnMeta() est désormais disponible.

PDO_SQLite

PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) permet de vérifier si la déclaration est en lecture seule, c.à.d. si elle ne modifie pas la base de données.

PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) active l'utilisation des codes de résultats étendus dans PDO::errorInfo() et PDOStatement::errorInfo().

SQLite3

Ajout de SQLite3::lastExtendedErrorCode() pour récupérer le dernier code étendu du résultat.

Ajout de SQLite3::enableExtendedResultCodes($enable = true), qui fera retourner des codes de résultats étendus par SQLite3::lastErrorCode().

Standard

strip_tags() avec un tableau de noms de tag

strip_tags() accepte désormais un tableau de tags autorisés : au lieu de strip_tags($str, '<a><p>') il est désormais possible d'écrire strip_tags($str, ['a', 'p']).

Sérialisation personnalisée d'objets

Un nouveau mécanisme de sérialisation personnalisée d'objets a été ajouté, qui utilise deux nouvelles méthodes magiques : __serialize et __unserialize.

<?php
// Retourne un tableau contenant tout l'état nécessaire de l'objet.
public function __serialize(): array;

// Restaure l'état d'un objet depuis le tableau de données fourni.
public function __unserialize(array $data): void;
?>
Le nouveau mécanisme de sérialisation succèdera à l'interface Serializable, qui sera rendu obsolète dans le futur.

Les fonctions array merge sans arguments

array_merge() et array_merge_recursive() peuvent désormais être appelées sans arguments, dans ce cas-là elles retourneront un tableau vide. Ceci est utile en conjonction avec l'opérateur de décomposition, par exemple array_merge(...$arrays).

La fonction proc_open()

proc_open() accepte désormais un tableau au lieu d'une chaîne de caractères pour la commande. Dans ce cas-là, le processus est ouvert directement (sans passer à travers un shell) et PHP s'occupera d'échapper les arguments lorsque nécessaire.

<?php
proc_open(['php', '-r', 'echo "Hello World\n";'], $descriptors, $pipes);
?>

proc_open() supporte désormais les descripteurs redirect et null.

<?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) sans libargon

password_hash() a désormais les implémentations de argon2i et argon2id de l'extension sodium quand PHP est compilé sans 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.


  • « Nouvelles fonctionnalités
  • Nouvelles fonctions »
  • PHP Manual
  • Migration de PHP 7.3.x vers PHP 7.4.x
  • Nouvelles Classes et Interfaces

Nouvelles Classes et Interfaces

Reflection

  • ReflectionReference

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctions

PHP Core

  • get_mangled_object_vars()
  • password_algos()
  • sapi_windows_set_ctrl_handler()

GD

  • imagecreatefromtga()

Chaînes Multi-octets

  • mb_str_split()

OpenSSL

  • openssl_x509_verify()

Process Control

  • pcntl_unshare()

SQLite3

  • SQLite3::backup()
  • SQLite3Stmt::getSQL()

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles constantes globales

PHP Core

  • PHP_WINDOWS_EVENT_CTRL_C
  • PHP_WINDOWS_EVENT_CTRL_BREAK

Chaîne multioctets

  • MB_ONIGURUMA_VERSION

Sockets

Added the following FreeBSD-specific socket options:

  • 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.


Modifications entrainant une incompatibilité ascendante

PHP Core

Accès de type tableau des non-tableaux

Essayer d'utiliser des valeurs de type null, bool, int, float ou ressource comme un tableau (comme $null["clé"]) va maintenant générer un avis.

Fonction get_declared_classes()

La fonction get_declared_classes() ne renvoie plus les classes anonymes qui n'ont pas encore été instanciées.

mot-clé fn

fn est maintenant un mot-clé réservé. En particulier, il ne peut plus être utilisé comme une fonction ou un nom de classe. Il peut encore être utilisé comme une méthode ou un nom de constante de classe.

<?php tag à la fin du fichier

<?php à la fin du fichier (sans nouvelle ligne) sera désormais interprété comme une balise PHP d'ouverture. Auparavant, il était interprété soit comme une balise courte d'ouverture suivie d'une php littérale et aboutissait à une erreur de syntaxe (avec short_open_tag=1) ou était interprété comme une chaîne <?php (avec short_open_tag=0).

Filtres de flux

Lors de l'utilisation de include/require sur un flux, streamWrapper::stream_set_option() sera invoqué avec l'option STREAM_OPTION_READ_BUFFER. Les implémentations de filtre de flux personnalisés peuvent avoir besoin d'implémenter la méthode streamWrapper::stream_set_option() pour éviter un avertissement (toujours retouner false est une implémentation suffisante).

Sérialisation

Le format o de sérialisation a été supprimé. Comme il n'est jamais produit par PHP, cela peut seulement briser la désérialisation des chaînes construites manuellement.

Constantes d'algorithme de mot de passe

Les identificateurs d'algorithme de hachage de mot de passe sont maintenant des chaînes nullables plutôt que des entiers.

  • PASSWORD_DEFAULT était l'entier 1 ; maintenant c'est la chaîne '2y' (en PHP 7.4.0, 7.4.1, et 7.4.2 c'était null)
  • PASSWORD_BCRYPT était l'entier 1; maintenant est '2y'
  • PASSWORD_ARGON2I était l'entier 2; maintenant est 'argon2i'
  • PASSWORD_ARGON2ID était l'entier 3; maintenant est 'argon2id'

Les applications utilisant correctement les constantes PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I, et PASSWORD_ARGON2ID continueront à fonctionner correctement.

Fonction htmlentities()

htmlentities() va maintenant lever un avis (au lieu d'un avertissement de normes strictes) s'il est utilisé avec un codage pour lequel seule la substitution d'entité de base est supportée, auquel cas il est équivalent à htmlspecialchars().

Les fonctions fread() et fwrite()

fread() et fwrite() vont maintenant retourner false si l'opération échoue. Auparavant, une chaîne vide ou 0 était retourné(e). EAGAIN/EWOULDBLOCK ne sont pas considérés comme des échecs.

Ces fonctions soulèvent également un avis sur l'échec, par exemple lorsque vous essayez d'écrire à une ressource de fichier en lecture uniquement.

BCMath Arbitrary Precision Mathematics

Les fonctions BCMath avertiront désormais si un nombre non bien formé est adopté, tel que "32foo". L'argument sera interprété comme zéro, comme avant.

CURL

Tenter de sérialiser une classe CURLFile va maintenant générer une exception. Auparavant, l'exception n'était lancée que sur la désérialisation.

L'utilisation de CURLPIPE-HTTP1 est dépréciée et n'est plus prise en charge à partir de cURL 7.62.0.

Le paramètre $version de curl_version () est déprécié. Si une valeur n'est pas égale à la valeur par défaut CURLVERSION_NOW est passé, un avertissement est levé et le paramètre est ignoré.

Date et heure

Appeler var_dump() ou similaire sur une instance DateTime ou DateTimeImmutable ne laissera plus de propriétés accessibles sur l'objet.

La comparaison des objets DateInterval (à l'aide de ==, <, etc.) va maintenant générer un avertissement et toujours retourner false. Auparavant, tous les objets DateInterval étaient considérés comme égaux, à moins qu'ils n'aient des propriétés.

Intl

La valeur par défaut du paramètre de idn_to_ascii() et idn_to_utf8() est maintenant INTL_IDNA_VARIANT_UTS46 au lieu de la valeur déconseillée INTL_IDNA_VARIANT_2003.

MySQLi

La fonctionnalité du serveur intégré a été supprimée. Elle a été cassée depuis au moins PHP 7.0.

La propriété non documentée mysqli::$stat a été supprimée au profit de mysqli::stat().

OpenSSL

La fonction openssl_random_pseudo_bytes() lance une exception dans les situations d'erreur, semblable à random_bytes(). En particulier, un Error est lancé si le nombre d'octets demandés est inférieur ou égal à zéro, et une Exception est lancée si un caractère aléatoire suffisant ne peut pas être recueilli. L'argument de sortie $crypto_strong output est garanti d'être toujours true si la fonction ne lance pas d'exception, afin de vérifier explicitement qu'il n'est pas nécessaire.

Expressions régulières (compatible Perl)

Lorsque le mode PREG_UNMATCHED_AS_NULL est utilisé, les groupes de capture non trouvés seront désormais également réglés à null (ou [null, -1] si la capture offset est activée). Cela signifie que la taille de $matches sera toujours la même.

PHP Data Objects

Une tentative de sérialisation d'une instance de PDO ou PDOStatement va désormais générer une Exception plutôt qu'une PDOException, compatible avec d'autres classes internes qui ne prennent pas en charge la sérialisation.

Reflection

Les objets Reflection génèrent désormais une exception si une tentative est faite pour les sérialiser. La sérialisation des objets Reflection n'a jamais été prise en charge et a donné lieu à des objets Reflection corrompus. Il a été explicitement interdit maintenant.

La valeur des constantes de classe de ReflectionClassConstant, ReflectionMethod et ReflectionProperty ont été changé.

Bibliothèque PHP standard (SPL)

L'appel get_object_vars() sur une instance ArrayObject retournera toujours les propriétés de l'ArrayObject lui-même (ou d'une sous-classe). Auparavant, il retournait les valeurs du tableau/objet à moins que le drapeau ArrayObject::STD_PROP_LIST n'ait été spécifié.

Les autres opérations touchées sont les suivantes :

  • ReflectionObject::getProperties()
  • reset(), current(), etc. Utiliser plutôt les méthodes d'Iterator.
  • Potentiellement d'autres fonctions travaillant sur les propriétés de l'objet comme une liste, e.g. array_walk().

Les modifications de type (array) ne sont pas affectées. Elles continueront à retourner soit le tableau enveloppé, soit les propriétés ArrayObject, selon que le drapeau ArrayObject::STD_PROP_LIST est utilisé.

SplPriorityQueue::setExtractFlags() lancera une exception si zéro est passé. Auparavant, cela générerait une erreur fatale récupérable lors de la prochaine opération d'extraction.

ArrayObject, ArrayIterator, SplDoublyLinkedList et SplObjectStorage gèrent maintenant __serialize() et __unserialize() en plus de l'interface Serializable. Cela signifie que les charges utiles de sérialisation créées sur les anciennes versions PHP peuvent toujours être désérialisées, mais les nouvelles charges utiles créées par PHP 7.4 ne seront pas compatibles par les anciennes versions.

Tokenizer

token_get_all() émettra maintenant un jeton T-BAD-CHARACTER pour les caractères inattendus au lieu de laisser derrière eux des trous dans le flux de jetons.

Cookies entrants

Depuis PHP 7.4.11, les noms des cookies entrants ne sont plus url-décodés pour des raisons de sécurité.

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


Fonctionnalités obsolètes

Cœur de PHP

Opérateurs ternaires imbriqués sans parenthèses explicites

Les opérateurs ternaires imbriqués doivent explicitement utiliser des parenthèses pour dicter l'ordre des opérations. Précédemment, quand utilisée sans parenthèses, l'associativité-gauche ne résulterait pas dans le comportement attendu pour la plupart des cas.

<?php
1 ? 2 : 3 ? 4 : 5; // obsolète
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

Les parenthèses ne sont pas requises lors de l'imbrication dans l'opérant du milieu car ceci est toujours sans ambiguïté et n'est pas affecté par l'associativité :

1 ? 2 ? 3 : 4 : 5 // ok

Accès de position de tableau et de chaînes en utilisant les accolades

La syntaxe pour accéder à la position des tableaux et chaîne de caractères avec les accolades est obsolète. Utiliser $var[$idx] au lieu de $var{$idx}.

Le transtypage (real) et la fonction is_real()

Le transtypage (real) est obsolète, utiliser (float) à la place.

La fonction is_real() est aussi obsolète, utiliser is_float() à la place.

Délier $this quand $this est utilisé

Délier $this d'une fermeture non statique qui utilise $this est obsolète.

Mot-clé parent sans classe parente

L'utilisation de parent à l'intérieur d'une classe sans parent est obsolète, et émettra une erreur lors de la compilation dans le futur. Actuellement seule une erreur sera générée si/quand un parent est accédé lors de l'exécution.

Option INI allow_url_include

La directive INI allow_url_include est obsolète. L'activer génèrera un avis d'obsolescence lors du démarrage.

Caractères invalides dans les fonctions de conversion de base

Passer des caractères invalides à base_convert(), bindec(), octdec() et hexdec() génèrera désormais un avis d'obsolescence. Le résultat sera toujours calculé comme si les caractères invalides n'existaient pas. Les caractères d'espacement blanc, aussi bien que les préfixes de type 0x (en fonction de la base) continuent d'être acceptés.

L'utilisation de array_key_exists() sur des objets

L'utilisation de array_key_exists() sur des objets est obsolète. À la place isset() ou property_exists() devraient être utilisés.

Fonctions des guillemets magiques

Les fonctions get_magic_quotes_gpc() et get_magic_quotes_runtime() sont obsolètes. Elles retournent toujours false.

Fonction hebrevc()

La fonction hebrevc() est obsolète. Elle peut être remplacée par nl2br(hebrev($str)) ou, de préférence, en utilisant le support Unicode RTL (Droite à Gauche).

Fonction convert_cyr_string()

La fonction convert_cyr_string() est obsolète. Elle peut être remplacée par l'une de mb_convert_string(), iconv() ou UConverter.

Fonction money_format()

La fonction money_format() est obsolète. Elle peut être remplacée par la fonctionnalité intl NumberFormatter.

Fonction ezmlm_hash()

La fonction ezmlm_hash() est obsolète.

Fonction restore_include_path()

La fonction restore_include_path() est obsolète. Elle peut être remplacée par ini_restore('include_path').

Implode avec l'ordre de paramètre historique

Passer les paramètres à implode() dans l'ordre inverse est obsolète, utiliser implode($glue, $parts) au lieu de implode($parts, $glue).

COM

L'importation de bibliothèques de type avec l'enregistrement de constantes non sensibles à la casse a été rendue obsolète.

Filtre

FILTER_SANITIZE_MAGIC_QUOTES est obsolète, utiliser FILTER_SANITIZE_ADD_SLASHES à la place.

Chaînes Multi-octets

Passer un pattern qui n'est pas une chaîne de caractères à mb_ereg_replace() est obsolète. Actuellement, les patterns qui ne sont pas des chaîne de caractères sont interprétés en tant que point de code ASCII. En PHP 8, le pattern sera interprété comme une chaîne de caractères à la place.

Passer l'encodage en tant que troisième paramètre à mb_strrpos() est obsolète. À la place passer une position de 0, et l'encodage en tant que quatrième paramètre.

Lightweight Directory Access Protocol (LDAP)

ldap_control_paged_result_response() et ldap_control_paged_result() sont obsolètes. Les contrôles de paginations peuvent être envoyés avec ldap_search() à la place.

Reflection

L'appel à ReflectionType::__toString() génère maintenant un avis d'obsolescence. Cette méthode a été dépréciée en faveur de ReflectionNamedType::getName() dans la documentation à partir de PHP 7.1, mais ne lançait pas un avis d'obsolescence pour des raisons techniques.

Les méthodes export() dans toutes les classes Reflection sont obsolètes. Créer un objet Reflection et le convertir en chaîne de caractères à la place :

<?php
// ReflectionClass::export(Foo::class, false) est :
echo new ReflectionClass(Foo::class), "\n";

// $str = ReflectionClass::export(Foo::class, true) est :
$str = (string) new ReflectionClass(Foo::class);
?>

Socket

Les drapeaux AI_IDN_ALLOW_UNASSIGNED et AI_IDN_USE_STD3_ASCII_RULES pour socket_addrinfo_lookup() sont obsolètes, en raison d'une dépréciation en amont dans 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


Extensions supprimées

Ces extensions ont été transférées à PECL et ne font plus partie de la distribution PHP. Les versions paquet PECL de ces extensions seront créées en fonction de la demande des utilisateurs.

  • Firebird/Interbase - l'accès à une base de données InterBase et/ou Firebird est toujours disponible avec le pilote Firebird du PDO.
  • Recode
  • WDDX

User Contributed Notes

There are no user contributed notes for this page.


Autres changements

Amélioration des Performances

Cœur de PHP

Un opcode de VM spécialisé pour la fonction array_key_exists() a été ajouté, ceci améliore les performances de cette fonction si elle peut être résolue statiquement. Dans du code sous un espace de nom, ceci peut nécessiter d'écrire \array_key_exists() ou importer explicitement la fonction.

Expressions Régulières (Compatible Perl)

Quand preg_match() en mode UTF-8 (modificateur "u") est appelée à plusieurs reprises sur la même chaîne de caractères (mais possiblement à différentes positions), elle ne sera vérifiée qu'une seule fois pour la validité UTF-8.

Modifications Apportées à la Gestion de Fichiers INI

zend.exception_ignore_args est une nouvelle directive INI pour inclure ou exclure les arguments des traces de pile générées par les exceptions.

opcache.preload_user est une nouvelle directive INI permettant de spécifier le compte utilisateur ayant pour rôle d'exécuter le code pré-chargé (l'utilisateur root n'est pas autorisé pour des raisons de sécurité).

Migration vers pkg-config

Un nombre d'extensions a été migré pour utiliser exclusivement pkg-config pour la détection des dépendances de bibliothèques. Généralement, ceci signifie qu'au lieu d'utiliser --with-foo-dir=DIR ou similaire seul --with-foo est utilisé. Les chemins de bibliothèques personnalisées peuvent être spécifiés soit en ajoutant des dossiers supplémentaires à PKG_CONFIG_PATH soit en spécifiant les options de compilations explicitement à travers FOO_CFLAGS et FOO_LIBS.

Les extensions et SAPIs suivantes sont affectées :

  • CURL :
    • --with-curl n'accepte plus un dossier.
  • Enchant :
    • --with-enchant n'accepte plus un dossier.
  • FPM :
    • --with-fpm-systemd utilise désormais uniquement pkg-config pour les vérifications libsystem. La version minimale libsystemd requise est 209.
  • GD :
    • --with-gd devient --enable-gd (pour activer l'extension) et --with-external-gd (pour opter pour l'utilisation d'un libgd externe, plutôt que celui fourni).
    • --with-png-dir a été supprimé. libpng est requis.
    • --with-zlib-dir a été supprimé. zlib est requis.
    • --with-freetype-dir devient --with-freetype
    • --with-jpeg-dir devient --with-jpeg
    • --with-webp-dir devient --with-webp
    • --with-xpm-dir devient --with-xpm
  • IMAP :
    • --with-kerberos-systemd n'accepte plus un dossier.
  • Intl :
    • --with-icu-dir a été supprimé. Si --enable-intl est passé, alors libicu est toujours requis.
  • LDAP :
    • --with-ldap-sasl n'accepte plus un dossier.
  • Libxml :
    • --with-libxml-dir a été supprimé.
    • --enable-libxml devient --with-libxml.
    • --with-libexpat-dir a été renommé en --with-expat et n'accepte plus un dossier.
  • Litespeed :
    • --with-litespeed devient --enable-litespeed.
  • Mbstring :
    • --with-onig a été supprimé. Sauf si --disable-mbregex a été passé, libonig est requis.
  • ODBC :
    • --with-iodbc n'accepte plus un dossier.
    • --with-unixODBC sans un dossier utilise désormais phg-config (préférable). Le dossier est toujours accepté pour les anciennes versions sans libodbc.pc.
  • OpenSSL :
    • --with-openssl n'accepte plus un dossier.
  • PCRE :
    • --with-pcre-regex a été supprimé. À la place --with-external-pcre est offert pour opter pour l'utilisation d'une bibliothèque PCRE externe, plutôt que celle fournie.
  • PDO_SQLite :
    • --with-pdo-sqlite n'accepte plus un dossier.
  • Readline :
    • --with-libedit n'accepte plus un dossier.
  • Sodium :
    • --with-sodium n'accepte plus un dossier.
  • SQLite3 :
    • --with-sqlite3 n'accepte plus un dossier.
  • XSL :
    • --with-xsl n'accepte plus un dossier.
  • Zip :
    • --with-libzip a été supprimé.
    • --enable-zip devient --with-zip.

Échappement CSV

fputcsv(),
fgetcsv(),
SplFileObject::fputcsv(),
SplFileObject::fgetcsv(), et
SplFileObject::setCsvControl()
acceptent désormais une chaîne de caractères vide en tant qu'argument
$escape, qui désactive le mécanisme d'échappement
propriétaire de PHP.

Le comportement de str_getcsv() a été ajusté en conséquence (auparavant, une chaîne de caractères vide était identique à utiliser les valeurs par défaut).

SplFileObject::getCsvControl() peut, par conséquent désormais aussi retourner une chaîne de caractères vide pour le troisième élément du tableau.

Filtrage de Données

L'extension filter n'expose plus --with-pcre-dir pour les builds Unix et peut désormais être compilée de manière fiable en tant que partagé lors de l'utilisation de ./configure

GD

Le comportement de imagecropauto() dans la bibliothèque libgd fourni a été synchronisé avec celui de libgd système :

  • IMG_CROP_DEFAULT ne se replie plus sur IMG_CROP_SIDES
  • Le seuil de recadrage (Threshold-cropping) utilise désormais l'algorithme de libgd système.

La paramètre par défaut $mode de imagecropauto() a été modifié en IMG_CROP_DEFAULT ; fournir -1 est désormais obsolète.

imagescale() supporte désormais la préservation du rapport hauteur / largeur lors de la mise à l'échelle à une hauteur fixe en passant -1 à $new_width.

HASH Message Digest Framework

L'extension hash ne peut plus être désactivée et fait toujours partie intégrante de n'importe quel build PHP, similaire à l'extension date.

Intl

L'extension intl requiert désormais au moins ICU 50.1.

ResourceBundle implémente désormais Countable.

Lightweight Directory Access Protocol (LDAP)

Le support pour nsldap et umich_ldap a été supprimé.

Libxml

Toutes les extensions basées sur libxml nécessitent libxml 2.7.6 ou ultérieur.

Chaînes multioctets

La bibliothèque oniguruma n'est plus fournie avec PHP, à la place libonig doit être disponible sur le système. Alternativement --disable-mbregex peut être utilisé pour désactiver le composant mbregex.

OPcache

Les options de configurations --disable-opcache-file et --enable-opcache-file ont été supprimées en faveur de la directive INI opcache.file_cache.

Hachage de Mot de Passe

Les fonctions password_hash() et password_needs_rehash() acceptent désormais des chaîne de caractères et entier nullable pour l'argument $algo.

PEAR

L'installation de PEAR (inclus PECL) n'est plus activée par défaut. Ceci peut être explicitement activé en utilisant --with-pear. Cette option est obsolète et pourra être supprimée dans le futur.

Reflection

Les valeurs numériques des constantes de modificateur (IS_ABSTRACT, IS_DEPRECATED, IS_EXPLICIT_ABSTRACT, IS_FINAL, IS_IMPLICIT_ABSTRACT, IS_PRIVATE, IS_PROTECTED, IS_PUBLIC, et IS_STATIC) sur les classes ReflectionClass, ReflectionFunction, ReflectionMethod, ReflectionObject, et ReflectionProperty ont été modifiées.

SimpleXML

SimpleXMLElement implémente désormais Countable.

SQLite3

La bibliothèque libsqlite intégrée a été supprimée. Pour compiler l'extension SQLite3 une libsqlite3 = 3.7.4 du système est désormais requise. Pour compiler l'extension PDO_SQLite une libsqlite3 = 3.5.0 du système est désormais requise.

La sérialisation et désérialisation de SQLite3, SQLite3Stmt et SQLite3Result est désormais explicitement interdite. Auparavant, la sérialisation d'instances de ces classes était possible, mais la désérialisation générait des objets inutilisables.

La notation @param peut désormais être utilisée pour dénoter les paramètres de requête SQL.

Zip

La bibliothèque libzip intégrée a été supprimée. Une libzip >= 0.11 du système est désormais requise pour compiler l'extension zip.

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.


Gestion de Windows

Drapeaux configure

configure supporte les variables d'environnement CFLAGS et LDFLAGS.

Traitement CTRL

CTRL+C et CTRL+BREAK sur la console peuvent être prises en définissant un gestionnaire avec la fonction sapi_windows_set_ctrl_handler().

L'option "create_process_group" peut être passée à proc_open() sur Windows. Elle est nécessaire si le processus enfant est censé gérer les événements CTRL.

OPcache

OPcache prend désormais en charge un nombre arbitraire de caches séparés par utilisateur via la directive INI opcache.cache-id. Tous les processus avec le même identifiant de cache et le même utilisateur partagent une instance OPcache.

stat

L'implémentation de la stat a été refactorisée.

  • Un numéro d'inode est livré et est basé sur l'index de fichier NTFS.
  • Le numéro de l'appareil est maintenant basé sur le numéro de série du volume.

Notez que les deux valeurs sont dérivées du système et fournies tel qu'il est sur les systèmes 64 bits. Sur les systèmes 32 bits, ces valeurs peuvent dépasser l'entier 32 bits dans PHP, donc ils sont faux.

libsqlite3

libsqlite3 n'est plus compilé statiquement en php_sqlite3.dll et php_pdo_sqlite.dll, mais est plutôt disponible en tant que libsqlite3.dll. Se référer aux instructions d'installation de SQLite3 et PDO_SQLITE, respectivement.

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 7.2.x vers PHP 7.3.x

Sommaire

  • Nouvelles fonctionnalités
  • Nouvelles fonctions
  • Nouvelles constantes globales
  • Modifications entrainant une incompatibilité ascendante
  • Fonctionnalités devenues obsolètes
  • Autres changements
  • Support de Windows

Cette nouvelle version mineure apporte un certain nombre de nouvelles fonctionnalités et quelques incompatibilités qui devraient être testées avant de changer les versions PHP dans les environnements de production.

Voir aussi les guides de migration entre les différentes versions de PHP 7.0.x, 7.1.x et 7.2.x.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctionnalités

Cœur de PHP

Syntaxe Plus Flexible pour Heredoc et Nowdoc

Le marqueur fermant pour les chaînes doc n'est plus requis d'être suivi par un point virgule ou un retour à la ligne. Additionellement le marqueur fermant peut être indenté, dans ce cas l'indentation sera retirée de toutes les lignes dans la chaîne doc.

La Déstructuration de Tableaux prend en charge les Assignations de Référence

La déstructuration de tableaux supporte désormais les assignements de référence en utilisant la syntaxe [&$a, [$b, &$c]] = $d. Ceci est aussi supporté pour list().

L'Opérateur Instanceof accepte les Littéraux

instanceof accepte désormais les littéraux comme premier opérant, dans ce cas le résultat est toujours false.

Exception CompileError au lieu de quelques Erreurs de Compilation

Une nouvelle exception CompileError a été ajoutée, duquel ParseError inhérite. Un petit nombre d'erreurs de compilation lanceront désormais CompileError au lieu de générer une erreur fatale. Actuellement ceci affecte uniquement les erreurs de compilation qui peuvent être lancées par token_get_all() dans le mode TOKEN_PARSE, mais plus d'erreurs pourront être converties dans le futur.

Les Virgules de Fin sont Autorisées dans les Appels

Les virgules de fin dans les appels de fonctions et méthodes sont désormais autorisées.

Support pour Argon2id

L'argument de configuration --with-password-argon2[=dir] fournit désormais le support pour les hash Argon2i et Argon2id dans les fonctions password_hash(), password_verify(), password_get_info(), et password_needs_rehash(). Les mots de passe peuvent être hachés et vérifiés en utilisant la constante PASSWORD_ARGON2ID. Le support pour Argon2i et Argon2id dans les fonctions password_*() nécessite désormais que PHP soit lié à la bibliothèque de référence libargon2 = 20161029.

Gestionnaire de Processus FastCGI

De nouvelles options ont été ajoutées pour personnaliser les journaux d'événements FPM :

log_limit
Cette option globale peut être utilisée pour définir la limite de journal pour la ligne journalisée, ce qui permet de consigner des messages de plus de 1024 caractères sans retour à la ligne. Il corrige également divers problèmes d'emballage (retour à la ligne).
log_buffering
Cette option globale permet une journalisation expérimentale sans mise en mémoire tampon supplémentaire.
decorate_workers_output
Cette option de pool permet de désactiver la décoration de sortie pour les sorties des workers quand catch_workers_output est activé.

Fonctions BC Math

bcscale() peut désormais être utilisé en tant que récupérateur pour récupérer la précision actuellement en utilisation.

Lightweight Directory Access Protocol

Le support total pour les Contrôles LDAP a été ajouté aux fonctions de requête LDAP et ldap_parse_result() :

  • Un paramètre $serverctrls pour envoyer les contrôles
au serveur dans ldap_add(),
ldap_mod_replace(), ldap_mod_add(),
ldap_mod_del(), ldap_rename(),
ldap_compare(), ldap_delete(),
ldap_modify_batch(),
ldap_search(), ldap_list() et
ldap_read() a été ajouté.
  • Le paramètre de sortie $serverctrls pour récupérer les contrôles depuis le serveur dans ldap_parse_result() a été ajouté.
  • Support pour LDAP_OPT_SERVER_CONTROLS et LDAP_OPT_CLIENT_CONTROLS dans ldap_get_option() et ldap_set_option() a été corrigé.

Fonctions pour les Chaînes Multi-Octets

Support pour le Mappage Pleine Casse et Pliage de Casse

Le support pour le mappage pleine casse et pliage de casse a été ajouté. Contrairement au mappage basique de casse, le mapping pleine casse peut modifier la longueur de la chaîne. Par exemple :

<?php
mb_strtoupper("Straße");
// Produit STRAßE en PHP 7.2
// Produit STRASSE en PHP 7.3
?>
Les différents modes de mappage et de pliage de casse sont disponibles à travers mb_convert_case() :
  • MB_CASE_LOWER (utilisé par mb_strtolower())
  • MB_CASE_UPPER (utilisé par mb_strtoupper())
  • MB_CASE_TITLE
  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE (utilisé par les opérations insensibles à la casse)
Seul un mappage complet des cas, inconditionnel et indépendant de la langue, est effectué.

Les Opérations de Chaînes Insensibles à la Casse utilisent le Pliage de Casse

Les opérations de chaînes insensibles à la casse utilisent désormais le pliage de casse au lieu du mappage de casse lors des comparaisons. Ceci signifie que plus de caractères seront considérés (insensible à la casse) égaux désormais.

MB_CASE_TITLE exécute une Conversion de casse de titre

mb_convert_case() avec MB_CASE_TITLE exécute désormais une conversion de casse de titre basée sur les propriétés dérivées Unicode Cased et CaseIgnorable. En particulier ceci améliore aussi la gestion des guillemets et apostrophes.

Support pour Unicode 11

Les tables de données pour les Chaînes Multi-octets ont été mis à jour pour Unicode 11.

Support pour les Chaînes Longues

Les Fonctions de Chaînes Multi-Octets supportent désormais correctement les chaînes plus grandes que 2Go.

Amélioration des Performances

Les performances de l'extension des Chaînes Multi-Octets ont été améliorées de façon significative à tous les niveaux. Les plus grandes améliorations sont dans les fonctions de conversion de casse.

Support pour les Captures Nommées

Les fonctions mb_ereg_* supportent désormais les captures nommées. Les fonctions de correspondances comme mb_ereg() retourneront désormais les captures nommées en utilisant à la fois leurs numéros de groupe et leurs noms, similaires à PCRE :

<?php
mb_ereg('(?<word>\w+)', '?', $matches);
// => [0 => "?", 1 => "?", "word" => "?"];
?>
De plus, mb_ereg_replace() supporte désormais les notations \k<> et \k'' pour faire référence aux captures nommées dans la chaîne de remplacement :
<?php
mb_ereg_replace('\s*(?<word>\w+)\s*', "_\k<word>_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\k<> et \k'' peuvent aussi être utilisés pour les références numériques, qui fonctionnent aussi avec des nombres de groupe supérieur à 9.

Readline

Le support pour les options completion_append_character et completion_suppress_append a été ajouté à readline_info(). Ces options sont seulement disponibles si PHP est lié à libreadline (plutôt que 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

?>


Nouvelles fonctions

Cœur de PHP

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()
  • net_get_interfaces()

FastCGI Process Manager

  • fpm_get_status()

Date et Temps

  • DateTime::createFromImmutable()

GNU Multiple Precision

  • gmp_binomial()
  • gmp_kronecker()
  • gmp_lcm()
  • gmp_perfect_power()

Fonctions d'Internationalisation

  • Normalizer::getRawDecomposition()
  • normalizer_get_raw_decomposition()
  • Spoofchecker::setRestrictionLevel()

Lightweight Directory Access Protocol (LDAP)

  • 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.


Nouvelles constantes globales

Cœur de PHP

  • PASSWORD_ARGON2ID

Librairie Client URL

  • 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 (à partir de PHP 7.3.6)
  • CURL_VERSION_ASYNCHDNS
  • CURL_VERSION_BROTLI
  • CURL_VERSION_CONV
  • CURL_VERSION_CURLDEBUG (à partir de 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 (à partir de PHP 7.3.6)
  • CURL_VERSION_SPNEGO
  • CURL_VERSION_SSPI
  • CURL_VERSION_TLSAUTH_SRP

Filtrage des données

  • 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

Chaîne de caractères multioctets

  • 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.


Modifications entrainant une incompatibilité ascendante

Cœur de PHP

Interprétation des Labels de Terminaison Heredoc/Nowdoc

Avec l'introduction de la syntaxe flexible heredoc / nowdoc, les chaîne de caractères doc qui contiennent le label de terminaison dans leur corps peuvent causer des erreurs de syntaxe ou changer en interprétation. Par exemple dans :

<?php
$str = <<<FOO
abcdefg
 FOO
FOO;
?>
l'occurrence indentée de FOO n'avait pas de signification particulière précédemment. Désormais elle sera interprétée comme la fin de la chaîne de caractères heredoc et le FOO; suivant causera une erreur de syntaxe. Ce problème peut toujours être résolu en choisissant un label de terminaison qui n'apparait pas dans le contenu de la chaîne de caractères.

Continue visant Switch génèrent des Avertissements

Les déclarations continue visant les structures de flux de contrôle switch généreront désormais un avertissement. En PHP ces déclarations continue sont équivalentes à break, alors qu'elles se comportent comme continue 2 dans d'autres langages.

<?php
while ($foo) {
switch ($bar) {
case "baz":
continue;
// Warning: "continue" targeting switch is equivalent to
// "break". Did you mean to use "continue 2"?
}
}
?>

Interprétation Stricte des Clés de Chaînes de Caractères Entiers sur ArrayAccess

Les accès de tableau du type $obj["123"], où $obj implémente ArrayAccess et "123" est une chaîne de caractères d'entier litérale ne résulteront plus en une conversion implicite en entier, c.à.d., $obj->offsetGet("123") sera appellé au lieu de $obj->offsetGet(123). Ceci correspond au comportement pour les non litérales. Le comportement des tableau n'est pas affecté d'une quelconque manière, ils continuent de convertir implicitement des clés de chaîne de caractères en entier.

Les Propriétés Statiques ne sont plus séparées par l'Affectation de Référence

En PHP, les propriétés statiques sont partagées entre les classes héritantes, sauf si la propriété statique est explicitement remplacée dans une classe enfant. Cependant à cause d'un artefact d'implémentation il était possible de séparer les propriétés statiques en affectant une référence. Cette lacune a été corrigée.

<?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)
?>

Les références retournées par les tableaux et les accès aux propriétés sont immédiatement décompressées

Les références retournées par les tableaux et les accès aux propriétés sont désormais décompressées dans le cadre de l'accès. Ceci signifie qu'il n'est plus possible de modifier la référence entre l'accès et l'utilisation de la valeur accédée :

<?php
$arr = [1];
$ref =& $arr[0];
var_dump($arr[0] + ($arr[0] = 2));
// Previously: int(4), Now: int(3)
?>
Ceci rend le comportement des références et non références cohérent. Il est à noter que lire et écrire une valeur à l'intérieur d'une unique expression continue d'être un comportement non défini et peut changer de nouveau dans le futur.

La décompression d'arguments de Traversables avec des clés non-entières n'est plus prise en charge

La décompression d'arguments a cessé de fonctionner avec Traversables avec des clés non-entières Le code suivant fonctionnait en PHP 5.6-7.2 par accident.

<?php
function foo(...$args) {
var_dump($args);
}
function gen() {
yield 1.23 => 123;
}
foo(...gen());
?>

Divers

L'utilitaire ext_skel a été entièrement repensé avec de nouvelles options et certaines anciennes options supprimées. Ceci est maintenant écrit en PHP et n'a aucune dépendance externe.

Le support pour BeOS a été abandonné.

Les exceptions lancées à cause d'une conversion automatique d'avertissements en exceptions avec le mode EH_THROW (par exemple certaines exceptions de DateTime) ne remplissent plus l'état de error_get_last(). En tant que telles, elles fonctionnent désormais de la même manière que les exceptions levées manuellement.

TypeError rapporte désormais les mauvais types en tant que int et bool au lieu de integer et boolean, respectivement.

Les variables indéfinies passées à compact() seront désormais rapportées avec une notice.

getimagesize() et les fonctions connexes rapportent désormais le type MIME des images BMP en tant que image/bmp au lieu de image/x-ms-bmp, car le premier a été inscrit avec l'IANA (voir » RFC 7903).

stream_socket_get_name() retourne désormais les adresses IPv6 avec des crochets. Par exemple "[::1]:1337" sera retourné au lieu de "::1:1337".

BCMath Arbitrary Precision Mathematics

Tous les avertissements lancés par les fonctions BCMath utilisent désormais le gestionnaire d'erreur de PHP. Auparavant certains avertissements étaient écrits directement à stderr.

bcmul() et bcpow() retourne désormais les nombres avec la précision demandée. Auparavant, certains nombres pouvaient omettre les zéros de fin décimaux.

IMAP, POP3 et NNTP

Les authentifications rsh/ssh sont désactivées par défaut. Utilisez imap.enable_insecure_rsh si vous voulez les activer. Il est à noter que la bibliothèque IMAP ne filtre pas les noms des boîtes aux lettres avant de les passer aux commandes rsh/ssh, ainsi passer des données non fiables à cette fonction avec rsh/ssh activé est dangereux.

Chaînes de caractères multioctets

En raison de la prise en charge des captures nommées, les masques mb_ereg_*() utilisant les captures nommées se comporteront différemment. En particulier les captures nommées feront partie des correspondances et mb_ereg_replace() interprétera la syntaxe additionnelle. Voir Captures Nommées pour plus d'information.

Extension MySQL Améliorée (MySQLi)

Les déclarations préparées rapportent désormais les fractions de secondes pour les colonnes DATETIME, TIME et TIMESTAMP avec spécificateur décimal (par exemple TIMESTAMP(6) lors de l'utilisation de microsecondes). Auparavant les fractions de secondes étaient tout simplement omises des valeurs de retours.

Fonctions MySQL (PDO_MYSQL)

Les déclarations préparées rapportent désormais les fractions de secondes pour les colonnes DATETIME, TIME et TIMESTAMP avec spécificateur décimal (par exemple TIMESTAMP(6) lors de l'utilisation de microsecondes). Auparavant les fractions de secondes étaient tout simplement omises des valeurs de retours. Veuillez noter que ceci affecte uniquement l'utilisation de PDO_MYSQL avec les déclarations préparées émulées désactivées (par exemple en utilisant la fonctionnalité native de préparation). Les déclarations utilisant des connexions qui ont PDO::ATTR_EMULATE_PREPARES=true (ce qui est par défaut) ne sont pas affectées par la correction de bogue et récupéraient déjà les valeurs des fractions de secondes depuis le moteur.

Reflection

Les exportations de Reflection en chaîne de caractères utilisent désormais int et bool au lieu de integer et boolean, respectivement.

Bibliothéque Standard de PHP (SPL)

Si un autochargeur SPL lance une exception, les autochargeurs suivants ne seront pas exécutés. Précédemment tous les autochargeurs étaient exécutés et les exceptions étaient chainées.

SimpleXML

Les opérations mathématiques impliquant les objets SimpleXML traiteront désormais le texte comme un entier ou un nombre décimal, selon ce qui est plus approprié. Auparavant les valeurs étaient traitées comme un entier sans condition.

Cookies entrants

Depuis PHP 7.3.23, les noms des cookies entrants ne sont plus url-décodés pour des raisons de sécurité.

User Contributed Notes

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.


Fonctionnalités devenues obsolètes

Cœur de PHP

Constantes non sensibles à la casse

La déclaration des constantes non sensibles à la casse a été déconseillée. Le passage de true comme troisième argument à define() générera désormais un avertissement d'obsolescence. L'utilisation de constantes non sensibles à la casse avec une casse qui diffère de la déclaration est également obsolète.

assert() dans un espace de nom

La déclaration d'une fonction appelée assert() dans un espace de noms est déconseillée. La fonction assert() est sujette à une manipulation spéciale par le moteur, ce qui peut conduire à un comportement incohérent lors de la définition d'une fonction dans un espace de nom avec le même nom.

Recherche de chaînes avec Needle non-chaîne

Passer une valeur recherchée qui n'est pas du texte dans les fonctions de recherche est déconseillé. Dans le futur la valeur recherchée sera interprétée comme une chaîne en ASCII. Selon le comportement prévu, vous devez soit explicitement caster la recherche en chaîne soit effectuer un appel explicite à chr(). Les fonctions suivantes sont affectées :

  • strpos()
  • strrpos()
  • stripos()
  • strripos()
  • strstr()
  • strchr()
  • strrchr()
  • stristr()

Strip-Tags Streaming

La fonction fgetss() et le filtre de flux string.strip_tags sont maintenant déconseillés. Cela affecte également la méthode SplFileObject::fgetss() et la fonction gzgetss().

Filtrage des données

L'utilisation explicite des constantes FILTER_FLAG_SCHEME_REQUIRED et FILTER_FLAG_HOST_REQUIRED est maintenant déconseillée; les deux sont implicites pour FILTER_VALIDATE_URL de toute façon.

Traitement d'image et GD

La fonction image2wbmp() est déconseillée.

Fonctions d'internationalisation

L'utilisation de la forme Normalizer::NONE lève un avertissement d'obsolescence, si PHP est lié à l'ICU = 56.

Chaîne multioctets

Les alias mbereg_*() non documentés suivants sont déconseillés. Utilisez plutôt les variantes mb_ereg_*() correspondantes.

  • 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()

Fonction ODBC et DB2 (PDO_ODBC)

Le paramètre ini pdo_odbc.db2_instance_name a été formellement déconseillé. Il est déconseillé dans la documentation à partir de PHP 5.1.1.

User Contributed Notes

There are no user contributed notes for this page.


Autres changements

PHP Core

Set(raw)cookie accepte l'argument $option

setcookie() et setrawcookie() prennent également la signature suivante :

setcookie(string $name, string $value = "", array $options = []): bool
où $options est un tableau associatif qui peut avoir l'une des clés suivantes "expires", "path", "domain", "secure", "httponly" et "samesite".

Nouvelles directives INI Syslog

Les directives INI suivantes ont été ajoutées pour personnaliser l'enregistrement, si error_log est défini sur syslog:

syslog.facility
Spécifie quel type de programme enregistre le message.
syslog.filter
Spécifie le type de filtre pour filtrer les messages enregistrés, avec les types de filtres pris en charge - all, no-ctrl et ascii. À partir de PHP 7.3.8, raw est aussi disponible, restaurant le comportement de syslog correspondant au versions antérieures de PHP. Ce filtre affectera aussi les appels à syslog().
syslog.ident
Spécifie la chaîne ident qui préfixera chaque message.

Collecteur de mémoire

Le GC cyclique a été amélioré, ce qui améliore grandement les performances.

Divers

var_export() exporte maintenant les objets stdClass comme un tableau modifié en objet ((object) array( ... )), plutôt que d'utiliser la méthode inexistante stdClass::__setState().

debug_zval_dump() a été modifié pour afficher les tableaux et les objets récursifs de la même manière que var_dump(). Maintenant, il ne les affiche pas deux fois.

array_push() et array_unshift() peuvent maintenant être appelés avec un seul argument, ce qui est particulièrement pratique avec l'opétateur de décomposition.

Débogueur PHP interactif

Les constantes inutilisées PHPDBG_FILE, PHPDBG_METHOD, PHPDBG_LINENO et PHPDBG_FUNC ont été supprimées.

Gestionnaire de processus FastCGI

La fonction getallheaders() est maintenant également disponible.

Bibliothèque URL client

libcurl = 7.15.5 est maintenant nécessaire.

Filtrage des données

FILTER_VALIDATE_FLOAT gère maintenant l'option thousand, qui définit l'ensemble de caractères de séparation pour les milliers. La valeur par défaut est ("',.") entièrement rétrocompatible avec les anciennes versions PHP.

FILTER_SANITIZE_ADD_SLASHES a été ajouté comme un alias du filtre magic_quotes (FILTER_SANITIZE_MAGIC_QUOTES). Le filtre magic_quotes est susceptible d'être supprimé dans les futures versions de PHP.

FTP

Le mode de transfert par défaut a été modifié pour binary.

Fonctions d'internationalisation

Normalizer::NONE est déprécié, lorsque PHP est lié à ICU = 56.

Introduction de Normalizer::FORM_KC_CF en tant qu'argument de Normalizer::normalize() pour la normalisation NFKC_Casefold; disponible lorsque PHP est lié à ICU = 56.

Notation d'objets JavaScript

Un nouveau drapeau été ajouté, JSON_THROW_ON_ERROR, qui peut être utilisé avec json_decode() ou json_encode() et provoque la levée de la nouvelle exception JsonException lors d'une erreur, au lieu de définir l'état d'erreur global qui est récupéré avec json_last_error() et json_last_error_msg(). JSON_PARTIAL_OUTPUT_ON_ERROR prend le pas sur JSON_THROW_ON_ERROR.

Chaîne multioctet

L'option de configuration --with-libmbfl n'est plus disponible.

ODBC (Unifié)

La gestion de ODBCRouter et Birdstep incluant la directive ini birdstep.max_links ont été supprimés.

OPcache

La directive ini opcache.inherited_hack a été supprimée. La valeur était ignorée depuis PHP 5.3.0.

OpenSSL

Les options de flux ssl min_proto_version et max_proto_version ainsi que des constantes liées pour d'éventuelles valeurs de protocole TLS ont été ajoutées.

Expressions régulières (Perl-Compatible)

L'extension PCRE a été mise à niveau vers PCRE2, ce qui peut provoquer des changements mineurs de comportement (par exemple, les plages de caractères dans les classes sont maintenant plus strictement interprétées), et augmente la syntaxe d'expression rationnelle existante.

preg_quote() échappe désormais le caractère '#'.

Fonctions Microsoft SQL Server et Sybase (PDO_DBLIB)

L'attribut PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS a été ajouté pour permettre le saut automatique des ensembles de lignes vides.

L'attribut PDO::DBLIB_ATTR_TDS_VERSION a été ajouté pour exposer la version de TDS.

Les colonnes DATETIME2 sont désormais traitées comme des colonnes DATETIME.

Fonctions SQLite (PDO_SQLITE)

Les bases de données SQLite3 peuvent désormais être ouvertes en lecture seule en définissant le nouvel attribut PDO::SQLITE_ATTR_OPEN_FLAGS à PDO::SQLITE_OPEN_READONLY.

Manipulation de session

session_set_cookie_params() gère désormais en charge la signature suivante :

session_set_cookie_params(array $options): bool
où $options est un tableau associatif qui peut contenir chacune de ces clés "lifetime", "path", "domain", "secure", "httponly" et "samesite". Par conséquent, la valeur de retour de session_get_cookie_params() a maintenant également un élément avec la clé "samesite". En outre, la nouvelle directive ini session.cookie_samesite a été ajoutée pour définir la valeur par défaut de SameSite pour les cookies. Par défaut à "" (chaîne vide), de sorte qu'aucune directive SameSite n'est définie. La valeur peut être "Lax" ou "Strict", qui définit la valeur de SameSite.

Tidy

Construire avec » tidyp est maintenant géré de façon transparente. Etant donné que tidyp n'offre pas d'API pour obtenir la date de sortie, tidy_get_release() et tidy::getRelease() retourne 'unknown' dans ce cas.

Parseur XML

La valeur de retour de la procédure de rappel de xml_set_external_entity_ref_handler() n'est plus ignorée si l'extension a été construite avec libxml. Auparavant, la valeur de retour était ignorée, et l'analyse ne cessait jamais.

Zip

Construire statiquement libzip est déconseillé, mais toujours possible en ajoutant l'option de configuration --without-libzip.

Zlib Compression

L'option de contexte zlib/level pour compress.zlib wrapper pour faciliter la définition du niveau de compression souhaité a été ajoutée.

User Contributed Notes

There are no user contributed notes for this page.


Support de Windows

Cœur de PHP

Suppression de fichier plus conforme à POSIX

Les descripteurs de fichiers sont ouverts en mode partagé lecture/écriture/suppression par défaut. Cela mappe efficacement la sémantique POSIX et permet de supprimer des fichiers avec des pointeurs en cours d'utilisation. Il n'est pas 100% identique, certaines différences de plate-forme persistent encore. Après la suppression, l'entrée de nom de fichier est bloquée, jusqu'à ce que tous les pointeurs ouverts soit fermés.

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 7.1.x vers PHP 7.2.x

Sommaire

  • Nouvelles fonctionnalités
  • Nouvelles fonctions
  • Nouvelles constantes globales
  • Évolutions incompatibles avec les versions précédentes
  • Fonctionnalités devenues obsolètes en PHP 7.2.x
  • Autres changements

Cette nouvelle version mineure apporte un certain nombre de nouvelles fonctionnalités et quelques incompatibilités qui devraient être testées avant de changer les versions PHP dans les environnements de production.

Voir aussi les guides de migration entre les différentes versions de PHP 7.0.x et 7.1.x.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctionnalités

Nouveau type object

Un nouveau type, object, a été introduit. Il peut être utilisé pour typer un paramètre (contravariant) ou pour typer le retour (covariant).

<?php

function test(object $obj) : object
{
return new SplQueue();
}

test(new stdClass());

Chargement des extensions par leur nom

Les extensions partagées ne demanderont plus de saisir leur nom complet (.so pour Unix ou .dll pour Windows). C'est actif pour le fichier php.ini et pour la fonction dl().

Substitution de méthode abstraite

Les méthodes abstraites peuvent maintenant être surchargées quand une classe abstraite étend une autre classe abstraite.

<?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;
}

Sodium est maintenant une extension du noyau

La bibliothèque moderne de cryptographie sodium est maintenant devenue une extension de base dans PHP.

Pour une référence de fonction complète, consultez le chapitre Sodium.

Hachage de mot de passe avec Argon2

Argon2 a été ajouté à l'API pour le hachage de mot de passe, et les constantes suivantes ont été exposées :

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

Extension des types de chaîne PDO

Le type de chaîne de PDO a été étendu pour prendre en charge le type de caractère national lors de l’utilisation des requêtes préparées. Cela a été fait avec l’une des constantes suivantes :

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

Ces constantes sont utilisées avec l’opérateur de bits OR et PDO::PARAM_STR :

<?php

$db->quote('über', PDO::PARAM_STR | PDO::PARAM_STR_NATL);

Ajout d'information de débogage pour l'émulation des requêtes préparées pour PDO

La méthode PDOStatement::debugDumpParams() a été mise à jour pour inclure le SQL envoyé à la DB, où la requête complète, requête brute (y compris les espaces réservés remplacés par leurs valeurs liées) sera montrée. Ceci a été ajouté afin de faciliter le débogage de l'émulation des requêtes préparées (et donc il sera disponible lorsque l'émulation des requêtes préparées est activée).

Prise en charge des opérations étendues de LDAP

La prise en charge des EXOP a été ajoutée dans l'extension LDAP. Cela a été fait en exposant les constantes et les fonctions suivantes :

  • 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

Informations additionnelles des adresses dans l'extension Sockets

L'extension sockets a maintenant la capacité de rechercher les informations sur l'adresse, mais aussi de s'y connecter, de se lier dessus et de l'expliquer. Les quatre fonctions suivantes ont été ajoutées pour cela :

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Elargissement du type des arguments

Les types de paramètres des méthodes substituées et des implémentations de l’interface peuvent maintenant être omises. C’est toujours dans le respect de LSP, puisque les types de paramètres sont contravariants.

<?php

interface A
{
public function Test(array $input);
}

class B implements A
{
public function Test($input){} // type omis pour $input
}

Permettre une virgule de fin pour les espaces de noms groupés

Une virgule de fin peut maintenant être ajoutée à la syntaxe d’utilisation groupée introduite en PHP 7.0.

<?php

use Foo\Bar\{
Foo,
Bar,
Baz,
};

Prise en charge sur Windows de proc_nice()

La fonction proc_nice() est maintenant prise en charge sur Windows.

Prise en charge de endian pour pack() et unpack()

Les fonctions pack() et unpack() prennent en charge les nombres décimaux et doubles dans les deux Little et Big endian.

Améliorations de l'extension EXIF

L'extension EXIF a été mise à jour pour prendre en charge une gamme beaucoup plus large de formats. Cela signifie que ces balises spécifiques au format sont maintenant correctement traduites lors de l'analyse des images avec la fonction exif_read_data(). Les nouveaux formats suivants sont désormais pris en charge :

  • Samsung
  • DJI
  • Panasonic
  • Sony
  • Pentax
  • Minolta
  • Sigma/Foveon
  • AGFA
  • Kyocera
  • Ricoh
  • Epson

Les fonctions EXIF exif_read_data() et exif_thumbnail() prennent désormais en charge des flux en tant que premier argument.

Nouvelles fonctionnalités dans PCRE

  • Le modificateur J pour définir PCRE_DUPNAMES a été ajouté.

SQLite3 permet l'écriture de BLOBs

SQLite3::openBlob() permet maintenant d'ouvrir des champs BLOB en mode écriture; auparavant, seul le mode lecture était pris en charge.

Oracle OCI8 prise en charge du Transparent Application Failover

La prise en charge de la fonction de rappel de Transparent Application Failover (TAF) a été ajouté. TAF permet aux applications PHP oci8 de se reconnecter automatiquement à une base de données préconfigurée lorsqu'une connexion est rompue. Le nouveau support de rappel TAF permet aux applications PHP de surveiller et de contrôler la reconnexion pendant le basculement.

Améliorations de l'extension ZIP

La prise en charge de la lecture et de l'écriture d'archives chiffrées a été ajoutée (nécessite libzip 1.2.0).

La classe ZipArchive implémente maintenant l'interface Countable.

Le flux zip:// accepte maintenant l'option de contexte 'password'.

User Contributed Notes

antonfedonyuk at gmail dot com 21-Apr-2021 12:27
Note: "omitted" = "removed":
<?php
declare(strict_types=1);

interface ITest
{
    public function run(array $input);
}

class Test implements ITest
{
    public function run($input) {
       return $input;
   }
}

echo (new Test())->run('foo'); // display foo, no error
?>
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).


Nouvelles fonctions

Cœur de 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()

Chaînes multioctets

  • 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.


Nouvelles constantes globales

Constantes prédéfinies

  • PHP_FLOAT_DIG
  • PHP_FLOAT_EPSILON
  • PHP_FLOAT_MIN
  • PHP_FLOAT_MAX
  • PHP_OS_FAMILY

Informations sur les fichiers

  • 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

Table de hachage de mot de passe

  • 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.


Évolutions incompatibles avec les versions précédentes

Empêcher number_format() de retourner zéro négatif

Auparavant, il était possible pour la fonction number_format() retourne -0. Bien que cela soit parfaitement valide conformément à la norme "IEEE 754 floating point spécification", cette bizarrerie n'était pas souhaitable pour l’affichage des nombres mis en forme sous une forme lisible par l'homme.

<?php

var_dump(number_format(-0.01)); // maintenant affiche string(1) "0" à la place de string(2) "-0"

Conversion des clés numériques dans les objets et tableaux lors de cast

Les clé numériques sont maintenant mieux appréhendées lors de cast d'un tableau en objet et d'un objet en tableau (cast explicite ou par la fonction settype()).

Cela signifie que les clés représentées par un entier (ou un entier sous forme de texte) d'un tableau casté en objet sont désormais accessibles :

<?php

// tableau vers un objet
$arr = [0 => 1];
$obj = (object)$arr;
var_dump(
$obj,
$obj->{'0'}, // désormais accessible
$obj->{0} // désormais accessible
);

L'exemple ci-dessus va afficher :

object(stdClass)#1 (1) {
  ["0"]=>    // désormais clé texte plutôt qu'une clé entière
  int(1)
}
int(1)
int(1)

Et les clés au format entier (ou entier sous forme de texte) des objets convertis en tableaux sont désormais accessibles :

<?php

// objet vers tableau
$obj = new class {
public function __construct()
{
$this->{0} = 1;
}
};
$arr = (array)$obj;
var_dump(
$arr,
$arr[0], // désormais accessible
$arr['0'] // désormais accessible
);

L'exemple ci-dessus va afficher :

array(1) {
  [0]=>    // désormais clé entière plutôt qu'une clé texte
  int(1)
}
int(1)
int(1)

Interdire de passer null à get_class()

Auparavant, passer null à la fonction get_class() retournait le nom de la classe en cours. Ce comportement a été supprimé, une erreur E_WARNING est affichée à la place. Pour retrouver le même comportement qu'avant, l’argument devrait simplement être supprimé.

Avertir lors du comptage de types non dénombrables

Un E_WARNING sera émis lors de la tentative d'utilisation de la fonction count() sur un type non dénombrable (cela inclut la fonction alias sizeof()).

<?php

var_dump(
count(null), // NULL is not countable
count(1), // un entier n'est pas dénombrable
count('abc'), // une chaîne n'est pas dénombrable
count(new stdClass), // un objet qui n'implémente pas l'interface Countable n'est pas dénombrable
count([1,2]) // un tableau est dénombrable
);

L'exemple ci-dessus va afficher :

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)

Remplacement ext/hash de ressources en objets

Dans le cadre de la migration à long terme des ressources, l’extension Hash a été mise à jour pour utiliser les objets au lieu de ressources. Le changement devrait être transparent pour les développeurs PHP, à l’exception où des vérifications avec is_resource() ont été faites (il sera nécessaire de remplacer par is_object()).

Améliorer les valeurs par défaut SSL/TLS

Les modifications suivantes concernant les valeurs par défaut ont été apportées :

  • tls:// maintenant par défaut TLSv1.0 ou TLSv1.1 ou TLSv1.2
  • ssl:// est un alias de tls://
  • STREAM_CRYPTO_METHOD_TLS_* constantes par défaut de TLSv1.0 ou TLSv1.1 + TLSv1.2, à la place de TLSv1.0 uniquement.

gettype() valeur de retour sur les ressources fermées

Auparavant, l'utilisation de gettype() sur une ressource fermée retournait une chaîne "unknown type". Maintenant, la chaîne "resource (closed)" sera retournée.

is_object() et __PHP_Incomplete_Class

Auparavant, l'utilisation de is_object() sur la classe __PHP_Incomplete_Class retournait false. Maintenant, true sera retourné.

Augmentation du niveau d'erreur des constantes non définies

Les références non qualifiées aux constantes non définies généreront désormais une E_WARNING (à la place d'une E_NOTICE). Dans la prochaine version majeure de PHP, elles généreront une exception Error.

Prise en charge de Windows

Les versions minimales officiellement supportées pour Windows sont Windows 7/ Server 2008 R2.

Vérification des valeurs par défaut des propriétés des traits

Les contrôles de compatibilité sur les valeurs par défaut des propriétés de trait n'effectueront plus la conversion.

object pour les noms de classes

Le nom object était précédement soft-réservé en PHP 7.0. Il est maintenant réservé, interdisant son utilisation comme nom de classe, de trait ou d'interface.

Prise en charge de NetWare

La prise en charge de NetWare a maintenant été supprimée.

array_unique() avec SORT_STRING

Alors que array_unique() avec SORT_STRING copiait anciennement le tableau et supprimait des éléments non uniques (sans emballer le tableau par la suite), maintenant un nouveau tableau est construit en ajoutant les éléments uniques. Cela peut entraîner des index numériques différents.

bcmod() change pour des nombres décimaux

La fonction bcmod() ne tronque plus les nombres fractionnaires en entiers. En tant que tel, son comportement suit maintenant fmod(), plutôt que l'opérateur %. Par exemple bcmod('4', '3.5') retourne maintenant 0.5 à la place de 1.

Fonctions de hachage et hachages non cryptographiques

Les fonctions hash_hmac(), hash_hmac_file(), hash_pbkdf2(), et hash_init() (avec HASH_HMAC) n'acceptent plus les hachages non cryptographiques.

Options de la fonction json_decode()

L'option JSON_OBJECT_AS_ARRAY de la fonction json_decode() est maintenant utilisée si le second paramètre (assoc) est null. Précédemment JSON_OBJECT_AS_ARRAY a toujours été ignoré.

Sortie de rand() et mt_rand()

Les séquences générées par rand() et mt_rand() pour des cas spécifiques peuvent différer de PHP 7.1 sur les machines 64 bits (en raison de la correction d'un bug dans l'implémentation de la polarisation du modulo).

Suppression du paramètre INI sql.safe_mode

Le paramètre INI sql.safe_mode a maintenant été supprimé.

Changement dans date_parse() et date_parse_from_format()

L'élément de zone du tableau retourné par date_parse() et date_parse_from_format() représente des secondes au lieu des minutes, et son signe est inversé. Par exemple -120 est maintenant 7200.

Incoming Cookies

Depuis PHP 7.2.34, les noms des cookies entrants ne sont plus url-décodés pour des raisons de sécurité.

User Contributed Notes

There are no user contributed notes for this page.


Fonctionnalités devenues obsolètes en PHP 7.2.x

Des chaînes non délimitées

Des chaînes qui sont des constantes globales inexistantes sont considérées comme des chaînes d’elles-mêmes. Ce comportement émettait une E_NOTICE, mais maintenant émet une E_WARNING. Dans la prochaine version majeure de PHP, une exception sera levée à la place.

<?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() et jpeg2wbmp()

Les fonctions png2wbmp() et jpeg2wbmp() de l'extension GD ont maintenant été désapprouvées et seront supprimées dans la prochaine version majeure de PHP.

Variante INTL_IDNA_VARIANT_2003

L'extension Intl a désapprouvé la variante INTL_IDNA_VARIANT_2003, qui est actuellement utilisée par idn_to_ascii() et idn_to_utf8(). La valeur par défaut sera changée dans PHP 7.4 par INTL_IDNA_VARIANT_UTS46, et la valeur INTL_IDNA_VARIANT_2003 sera supprimée dans la prochaine version majeure de PHP.

Méthode __autoload()

La méthode __autoload() a été déconseillée car inférieure à spl_autoload_register() (car elle n'est pas capable d'accepter plusieurs chargeurs automatiques), et les deux styles de chargement automatique ne sont pas interopérables.

Directive de configuration track_errors et la variable $php_errormsg

Lorsque la directive de configuration track_errors est activée, une variable $php_errormsg est créée dans la portée locale lorsqu'une erreur non fatale se produit. Étant donné que le meilleur moyen de récupérer ces informations d’erreur est d'utiliser error_get_last(), cette fonctionnalité a été désapprouvée.

Fonction create_function()

Étant donnés les problèmes de sécurité de cette fonction (qui est un wrapper mince autour de eval()) cette ancienne fonction est maintenant obsolète. Le meilleur moyen de créer des fermetures est en définissant des fonctions anonymes.

Directive de configuration mbstring.func_overload

Étant donnés les problèmes d’interopérabilité des fonctions basées sur une chaîne utilisées dans les environnements lorsque ce paramètre est activé, il est maintenant obsolète.

(unset) cast

Casting de n’importe quelle expression à ce type entraînera toujours un résultat null, et ce type de cast superflu est maintenant obsolète.

parse_str() sans second argument

Sans second argument à la fonction parse_str(), les paramètres de la requête sont alloués dans des variables locales. Étant données les implications de ce fonctionnement sur la sécurité, l'utilisation de parse_str() sans un second argument est maintenant obsolète. La fonction doit toujours être utilisée avec deux arguments, car le deuxième argument entraîne l'analyse de la chaîne de requête dans un tableau.

Fonction gmp_random()

Cette fonction génère un nombre aléatoire basé sur une plage qui est calculée par une taille non exposée, spécifique à la plateforme membre. Pour cette raison, la fonction est maintenant obsolète. Le meilleur moyen de générer un nombre aléatoire est l'utilisation de l’extension GMP avec les fonctions gmp_random_bits() et gmp_random_range().

Fonction each()

Cette fonction est beaucoup plus lente à l’itération qu’un classique foreach et entraîne des problèmes de mise en œuvre de certains changements de langue. Elle a donc été désapprouvée.

assert() avec un argument texte

Lors de l'utilisation d'assert() avec un argument texte, il est nécessaire que le texte soit évalué par la fonction eval(). Compte tenu du potentiel pour l’exécution de code à distance, avec un argument de chaîne à l’aide de assert() a maintenant été désapprouvée en faveur de l’utilisation des expressions booléennes.

$errcontext argument de gestionnaires d’erreurs

L’argument $errcontext contient toutes les variables locales de l’emplacement de l’erreur. Compte tenu de son utilisation rare et les problèmes qu'elle provoque avec des optimisations internes, il est maintenant devenu obsolète. Au lieu de cela, un débogueur doit être utilisé pour récupérer des informations sur les variables locales à l’emplacement de l’erreur.

Fonction read_exif_data()

L'alias read_exif_data() a été déconseillé. La fonction exif_read_data() peut être utilisée à la place.

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.


Autres changements

Déplacement de utf8_encode() et utf8_decode()

Les fonctions utf8_encode() et utf8_decode() ont maintenant été déplacées vers l'extension standard en tant que fonctions de chaîne, alors qu'avant l'extension XML était requise pour qu'elles soient disponibles.

Changement pour mail() et mb_send_mail()

Le paramètre $additional_headers de mail() et mb_send_mail() accepte maintenant un array à la place d'un string

Prise en charge de LMDB

L'extension DBA prend maintenant en charge LMDB.

Modifications apportées au système build de PHP

  • Unix: Autoconf 2.64 ou plus est maintenant nécessaire pour construire PHP.
  • Unix: L'argument de configuration --with-pdo-oci n'a plus besoin de la version de Oracle Instant Client.
  • Unix: L'argument de configuration --enable-gd-native-ttf a été supprimé. Il n'a pas été utilisé depuis PHP 5.5.0.
  • Windows: L'argument de configuration --with-config-profile a été ajouté. Cela peut être utilisé pour enregistrer des configurations spécifiques, un peu comme le fichier magique config.nice.bat.

Changement dans GD

  • imageantialias() est également disponible si construit avec libgd du système.
  • imagegd() stocke des images TrueColor comme de vraies images TrueColor. Auparavant, elles étaient converties en palette.

Déplacement de MCrypt vers PECL

L'extension MCrypt a maintenant été déplacée du noyau vers PECL. Étant donné que la bibliothèque mcrypt n'a pas vu de mises à jour depuis 2007, son utilisation est fortement découragée. Au lieu de cela, soit OpenSSL soit l'extension Sodium doivent être utilisées.

session_module_name()

Le passage de "user" à session_module_name() déclenche maintenant une erreur de niveau E_RECOVERABLE_ERROR. Auparavant, cela a été ignoré silencieusement.

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 7.0.x vers PHP 7.1.x

Sommaire

  • Nouvelles fonctionnalités
  • Nouvelles fonctions
  • Nouvelles constantes globales
  • Modifications entrainant une incompatibilité ascendante
  • Les fonctionnalités dépréciées dans PHP 7.1.x
  • Fonctions modifiées
  • Autres changements
  • Support Windows

Cette nouvelle version mineure apporte un certain nombre de nouvelles fonctionnalités et quelques incompatibilités qui devraient être testées avant de changer les versions PHP dans les environnements de production.

Voir aussi les guides de migration entre les différentes versions de PHP 7.0.x.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctionnalités

Type nullable

La déclaration des types de paramètre et de valeur de retour peut désormais être marquée en tant que nullable en préfixant le nom du type avec un point d'interrogation. Ceci signifie que le type spécifié aussi bien que null peuvent être passés comme argument, ou retournés en tant que valeur, respectivement.

<?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();

L'exemple ci-dessus va afficher :

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Fonctions Void

Le type de retour void a été introduit. Les fonctions déclarées avec un type de retour void doivent soit omettre la déclaration de retour entièrement, soit utiliser une déclaration de retour vide. null n'est pas un type de retour valide pour une fonction void.

<?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);

L'exemple ci-dessus va afficher :

null
int(2)
int(1)

Essayer d'utiliser la valeur de retour d'une fonction void évalue simplement à null, sans avertissement émit. La raison pour ceci est qu'un avertissement impliquerait l'usage de fonction générique d'ordre supérieur.

Déconstruction symétrique de tableau

L'abréviation de la syntaxe array [] peut désormais être utilisée pour déconstruire des tableaux pour des affectations (y compris au sein de foreach), à la place de la syntaxe existante list(), qui est toujours supportée.

<?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
}

Visibilité des constantes de classes

Le support pour spécifier la visibilité des constantes de classes a été ajouté.

<?php
class ConstDemo
{
const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}

Le pseudo-type iterable

Un nouveau pseudo-type (similaire à callable) appellé iterable a été introduit. Il peut être utilisé avec les paramètres et retours typés, où il accepte soit des tableau soit des objets qui implémentent l'interface Traversable. En ce qui concerne le sous-typage, les types de paramètres des classes enfant peuvent élargir une déclaration d'un parent de array ou Traversable en iterable. Avec les types de retour, les classes enfant peuvent restreindre le type de retour iterable du parent en array ou un objet qui implémente Traversable.

<?php
function iterator(iterable $iter)
{
foreach ($iter as $val) {
//
}
}

Gestion du catch de plusieurs exceptions

Plusieurs exceptions par bloc catch peuvent désormais être spécifiées en utilisant le caractère barre verticale (|). Ceci est utile quand différentes exceptions sont gérées de façon identique.

<?php
try {
// du code
} catch (FirstException | SecondException $e) {
// gère les exceptions first et second
}

Support des clés dans list()

Il est désormais possible de spécifier des clés dans list(), ou sa nouvelle syntaxe abrégée []. Ceci permet la déconstruction des tableaux qui ont des clés non entières ou non séquentielles.

<?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)) {
// logique ici avec $id et $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
// logique ici avec $id et $name
}

Support pour les positions négatives des chaîne de caractères

Le support des positions négatives des chaîne de caractères a été ajouté aux fonctions de manipulation de chaîne de caractères qui acceptent une position, ainsi qu'à l'indexation de chaîne de caractères avec [] ou {}. Dans de tels cas, une position négative est interprétée comme une position en partant de la fin de la chaîne de caractères.

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

L'exemple ci-dessus va afficher :

string (1) "e"
int(3)

Les positions négatives des chaîne de caractères et tableaux sont aussi supportées avec la syntaxe simple d'analyse dans les chaîne de caractères.

<?php
$string = 'bar';
echo "Le dernier caractère de '$string' est '$string[-1]'.\n";
?>

L'exemple ci-dessus va afficher :

Le dernier caractère de 'bar' est 'r'.

Support pour AEAD dans ext/openssl

Support pour AEAD (modes GCM et CCM) a été ajouté en étendant les fonctions openssl_encrypt() et openssl_decrypt() avec des paramètres additionnels.

Convertir des callables en Closures avec Closure::fromCallable()

Une nouvelle méthode statique a été introduite dans la classe Closure pour permettre des callables d'être facilement convertit en objets 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');

L'exemple ci-dessus va afficher :

string(10) "some value"

Gestion des signaux asynchrones

Une nouvelle fonction appellée pcntl_async_signals() a été introduite pour permettre la gestion des signaux asynchrones sans utiliser les ticks (ce qui introduisait beaucoup de surcoût).

<?php
pcntl_async_signals(true); // activer les signaux asynchrones

pcntl_signal(SIGHUP, function($sig) {
echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

L'exemple ci-dessus va afficher :

SIGHUP

Support des push serveur HTTP/2 dans ext/curl

Le support pour les push serveur a été ajouté à l'extension CURL (nécessite la version 7.46 ou ultérieure). Ceci peut être exploité à travers la fonction curl_multi_setopt() avec la nouvelle constante CURLMOPT_PUSHFUNCTION. Les constantes CURL_PUSH_OK et CURL_PUSH_DENY ont aussi été ajoutées pour que l'exécution de la fonction de rappel du push serveur puisse être approuvée ou refusée.

Options du contexte de flux (Stream Context Options)

L'option du contexte de flux tcp_nodelay a été ajoutée.

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


Nouvelles fonctions

Cœur de PHP

  • 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.


Nouvelles constantes globales

Core Predefined Constants

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Data Filtering

  • FILTER_FLAG_EMAIL_UNICODE

Image Processing et 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.


Modifications entrainant une incompatibilité ascendante

Exception en passant trop peu d'arguments de fonction

Auparavant, un avertissement était émis pour invoquer des fonctions définies par l'utilisateur avec trop peu d'arguments. Maintenant, cet avertissement a été promu en une exception d'erreur. Cette modification s'applique uniquement aux fonctions définies par l'utilisateur, et non aux fonctions internes. Par exemple:

<?php
function test($param){}
test();

Résultat de l'exemple ci-dessus est similaire à :

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

Interdire les appels dynamiques aux fonctions d'introspection de portée

Les appels dynamiques pour certaines fonctions ont été interdits (sous la forme de $func() ou array_map('extract', ...), etc.). Ces fonctions inspectent ou modifient une autre étendue, et présentent avec eux un comportement ambigu et non fiable. Les fonctions sont les suivantes:

  • assert() - avec une chaîne comme premier argument
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - avec un argument
  • parse_str() - avec un argument
<?php
(function () {
$func = 'func_num_args';
$func();
})();

L'exemple ci-dessus va afficher :

Warning: Cannot call func_num_args() dynamically in %s on line %d

Nom de classe, interface, et trait invalide

Les noms suivants ne peuvent pas être utilisés pour nommer des classes, des interfaces ou des traits:

  • void
  • iterable

Les conversions de chaînes numériques respectent désormais la notation scientifique

Les opérations entières et les conversions sur les chaînes numériques respectent désormais la notation scientifique. Cela inclut également l'opération de cast (int) et les fonctions suivantes: intval() (où la base est 10), settype(), decbin(), decoct() et dechex().

Correctifs à l'algorithme mt_rand()

mt_rand() utilise désormais par défaut la version fixe de l'algorithme Mersenne Twister. Si la sortie déterministe de mt_srand() a été invoquée, alors MT_RAND_PHP peut être utilisé comme second paramètre optionnel de mt_srand() pour préserver l'ancienne (et incorrecte) implémentation.

rand() alias de mt_rand() et srand() alias de mt_srand()

rand() et srand() sont désormais des alias de mt_rand() et mt_srand(), respectivement. Cela signifie que la sortie pour les fonctions suivantes a été modifiée : rand(), shuffle(), str_shuffle() et array_rand().

Interdire le caractère de contrôle de suppression ASCII dans les identificateurs

Le caractère de contrôle de suppression ASCII (0X7f) ne peut plus être utilisé dans les identificateurs qui ne sont pas entre guillemets.

error_log change pour la valeur syslog

Si le paramètre INI error_log est défini sur syslog, les niveaux d'erreur PHP sont mappés aux niveaux d'erreur syslog. Cela apporte une différenciation plus fine dans les journaux d'erreurs contrairement à l'approche précédente où toutes les erreurs sont enregistrées avec le niveau d'avis uniquement.

N'appelez pas les destructeurs sur des objets incomplets

Les destructeurs ne sont désormais jamais appelés pour les objets qui lèvent une exception pendant l'exécution de leur constructeur. Dans les versions précédentes, ce comportement dépendait de la question de savoir si l'objet était référencé en dehors du constructeur (par exemple par une exception backtrace).

call_user_func() gestion des arguments de référence

call_user_func() va maintenant toujours générer un avertissement sur les appels aux fonctions qui attendent des références comme arguments. Auparavant, cela dépendait de la question de savoir si l'appel était entièrement qualifié.

En outre, call_user_func() et call_user_func_array() n'abandonneront plus l'appel de fonction dans ce cas. L'avertissement "référence attendue" sera émis, mais l'appel va continuer comme d'habitude.

L'opérateur d'index vide n'est plus pris en charge pour les chaînes

L'application de l'opérateur d'index vide à une chaîne (par exemple $str[] = $x) lève une erreur fatale au lieu de la convertir silencieusement en tableau.

Affectation via l'accès d'index de chaîne sur une chaîne vide

La modification de chaîne par caractère sur une chaîne vide fonctionne désormais comme pour les chaînes non vides, c'est-à-dire l'écriture dans un décalage hors plage de la chaîne avec des espaces, où les types non entiers sont convertis en entiers, et seul le premier caractère de la chaîne assignée est utilisé. Autrefois, les chaînes vides étaient silencieusement traitées comme un tableau vide.

<?php
$a = '';
$a[10] = 'foo';
var_dump($a);
?>

Résultat de l'exemple ci-dessus en PHP 7.0 :

array(1) {
  [10]=>
  string(3) "foo"
}

Résultat de l'exemple ci-dessus en PHP 7.1 :

string(11) "          f"

Directives ini supprimées

Les directives ini suivantes ont été supprimées :

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

L'ordonnancement des éléments d'un tableau a changé lorsque qu'ils sont créés automatiquement pendant les affectations par référence

L'ordre des éléments dans un tableau a changé lorsque ces éléments ont été créés automatiquement en les référençant dans une assignation par référence. Par exemple:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Résultat de l'exemple ci-dessus en PHP 7.0 :

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Résultat de l'exemple ci-dessus en PHP 7.1 :

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Ordre de tri des éléments égaux

L'algorithme de tri interne a été amélioré, ce qui peut entraîner un ordre de tri différent des éléments, qui se comparaient comme égaux auparavant.

Note:

Ne comptez pas sur l'ordre des éléments qui se comparent comme égaux; il pourrait changer à tout moment.

Message d'erreur pour les erreurs E_RECOVERABLE

Le message d'erreur pour les erreurs E_RECOVERABLE a été modifié de "Catchable fatal error" à "Recoverable fatal error".

Paramètre $options de unserialize()

L'élément allowed_classes du paramètre $options de unserialize() est maintenant strictement typé, c'est-à-dire que si une valeur autre qu'un tableau ou un booléen est donnée, unserialize() retourne false et émet un E_WARNING.

Le constructeur de DateTime incorpore microsecondes

DateTime et DateTimeImmutable intègrent désormais correctement les microsecondes lorsqu'elles sont construites à partir de l'heure actuelle, soit explicitement, soit avec une chaîne relative (par exemple "first day of next month"). Cela signifie que les comparaisons naïves de deux instances nouvellement créées seront désormais plus susceptibles de retourner false au lieu de true:

<?php
new DateTime() == new DateTime();
?>

Conversions des erreurs fatales en exceptions Error

Dans l'extension date, les données de sérialisation invalides pour les classes DateTime ou DatePeriod , ou l'échec de l'initialisation du fuseau horaire à partir de données sérialisées, lèveront désormais une exception Error à partir de la méthode __wakeup() ou __set_state(), au lieu de se traduire par une erreur fatale.

Dans l'extension DBA, les fonctions de modification des données (telles que dba_insert()) lèveront désormais une exception Error au lieu de déclencher une erreur fatale capturable si la clé ne contient pas exactement deux éléments.

Dans l'extension DOM, les contextes de validation de schéma ou de RelaxNG non valides lèveront désormais une exception Error au lieu de résulter en une erreur fatale. De même, la tentative d'inscription d'une classe de nœud qui n'étend pas la classe de base appropriée, ou tente de lire une propriété non valide ou d'écrire dans une propriété en lecture seule, lèvera également une exception Error .

Dans l'extension IMAP, les adresses de messagerie plus longues que 16385 octets lèveront une exception Error au lieu de se traduire par une erreur fatale.

Dans l'extension Intl, le fait de ne pas appeler le constructeur parent dans une classe qui étend Collator avant d'appeler les méthodes parentes lèvera maintenant une Error au lieu d'avoir pour résultat une erreur fatale récupérable. En outre, le clonage d'un objet Transliterator lève désormais une exception Error en cas d'échec du clonage du Transliterator interne au lieu d'une erreur fatale.

Dans l'extension LDAP, la fourniture d'un type de modification inconnu à ldap_batch_modify() lèvera désormais une exception Error au lieu d'une erreur fatale.

Dans l'extension mbstring, les fonctions mb_ereg() et mb_eregi() lèveront désormais une exception ParseError si une expression PHP non valide est fournie et que l'option 'e' est utilisée.

Dans l'extension mcrypt, mcrypt_encrypt() et mcrypt_decrypt() lèveront maintenant une exception Error au lieu d'une erreur fatale si mcrypt ne peut pas être initialisée.

Dans l'extension mysqli, la tentative de lecture d'une propriété non valide ou d'écriture dans une propriété en lecture seule lève maintenant une exception Error au lieu de se traduire par une erreur fatale.

Dans l'extension Reflection, le fait de ne pas récupérer un objet de réflexion ou de récupérer une propriété d'objet lève maintenant une exception Error au lieu de se traduire par une erreur fatale.

Dans l'extension de session, les gestionnaires de session personnalisés qui ne retournent pas de chaînes pour les ID de session lèveront désormais une exception Error au lieu de provoquer une erreur fatale lorsqu'une fonction est appelée pour générer un ID de session.

Dans l'extension SimpleXML, la création d'un attribut sans nom ou dupliqué va maintenant lever une exception Error au lieu de générer une erreur fatale.

Dans l'extension SPL, une tentative de clonage d'un objet SplDirectory va maintenant lever une exception Error au lieu de générer une erreur fatale. De même, appeler ArrayIterator::append() lors de l'itération sur un objet lèvera également une exception Error.

Dans l'extension standard, la fonction assert(), lorsqu'elle est fournie avec un argument de chaîne comme premier paramètre, lèvera maintenant une exception ParseError au lieu d'une erreur fatale capturable si le code PHP n'est pas valide. De même, l'appel à forward_static_call() en dehors d'une étendue de classe lève maintenant une exception Error .

Dans l'extension Tidy, la création manuelle d'un tidyNode lèvera une exception Error au lieu d'une erreur fatale.

Dans l'extension WDDX, une référence circulaire lors de la sérialisation va maintenant lever une exception Error au lieu d'une erreur fatale.

Dans l'extension XML-RPC, une référence circulaire lors de la sérialisation lève maintenant une instance d'exception Error au lieu de se traduire par une erreur fatale.

Dans l'extension Zip, la méthode ZipArchive::addGlob() lève maintenant une exception Error au lieu de se traduire par une erreur fatale si la prise en charge de glob n'est pas disponible.

Les variables liées lexiquement ne peuvent pas réutiliser les noms

Les variables liées à une fonction anonyme via la construction use ne peuvent pas utiliser le même nom que n'importe quelle superglobals, $this ou n'importe quel paramètre. Par exemple, toutes ces définitions de fonction entraîneront une erreur fatale :

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

long2ip() changement de type de paramètre

long2ip() attend maintenant un int à la place de string.

Encodage et décodage JSON

Le paramètre INI serialize_precision contrôle maintenant la précision de sérialisation lors de l'encodage des floats.

Le décodage d'une clé vide entraîne désormais un nom de propriété vide, plutôt que _empty_ comme nom de propriété.

<?php
var_dump(json_decode(json_encode(['' => 1])));

Résultat de l'exemple ci-dessus est similaire à :

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

Lorsque vous fournissez l'indicateur JSON_UNESCAPED_UNICODE à json_encode(), les séquences U+2028 et U+2029 sont maintenant échappées.

Modifications de la sémantique des paramètres de mb_ereg() et mb_eregi()

Le troisième paramètre des fonctions mb_ereg() et mb_eregi() (regs) est désormais défini sur un tableau vide si rien n'a été mis en correspondance. Auparavant, le paramètre n'aurait pas été modifié.

Abandon des flux sslv2

Le flux SSLv2 a maintenant été abandonné dans OpenSSL.

Interdit "return;" pour les retours typés lors de la compilation

Une déclaration de retour sans arguments dans les fonctions qui déclarent un type de retour émet désormais E_COMPILE_ERROR (sauf si le type de retour est déclaré comme void), même si la déclaration de retour ne serait jamais atteinte.

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);


Les fonctionnalités dépréciées dans PHP 7.1.x

ext/mcrypt

L'extension mcrypt a été abandonnée pendant près d'une décennie maintenant, et était également assez complexe à utiliser. Elle a donc été dépréciée en faveur de OpenSSL, et elle sera retirée du noyau et dans PECL en PHP 7.2.

L'options Eval pour mb_ereg_replace() et mb_eregi_replace()

Le modificateur de motif e a été déprécié pour les fonctions mb_ereg_replace() et mb_eregi_replace().

User Contributed Notes

There are no user contributed notes for this page.


Fonctions modifiées

Cœur de PHP

  • getopt() a un troisième paramètre optionnel qui expose l'index de l'élément suivant dans la liste des vecteurs d'arguments à traiter. Ceci est fait via un paramètre by-ref.
  • getenv() ne nécessite plus son paramètre. Si le paramètre est omis, les variables d'environnement actuelles seront renvoyées en tant que tableau associatif.
  • get_headers() a maintenant un paramètre supplémentaire pour permettre le passage de contextes de flux personnalisés.
  • output_reset_rewrite_vars() ne réinitialise plus la réécriture des URL des variables de session.
  • parse_url() est maintenant plus restrictif et supporte RFC3986.
  • unpack() accepte maintenant un troisième paramètre optionnel pour spécifier l'offset du début du dépaquetage.

Système de fichier

  • file_get_contents() accepte maintenant un offset de recherche négatif si le flux est cherchable.
  • tempnam() émet maintenant un notice quand on revient dans le répertoire système temporaire.

JSON

  • json_encode() accepte maintenant une nouvelle option, JSON_UNESCAPED_LINE_TERMINATORS, pour désactiver l'échappement des caractères U+2028 et U+2029 quand JSON_UNESCAPED_UNICODE est fournit.

Chaîne multioctet

  • mb_ereg() rejette maintenant les séquences d'octets illégales.
  • mb_ereg_replace() rejette maintenant les séquences d'octets illégales.

PDO

  • PDO::lastInsertId() pour PostgreSQL va maintenant déclencher une erreur quand nextval n'a pas été appelé pour la session courante. (la connexion postgres).

PostgreSQL

  • pg_last_notice() accepte maintenant un paramètre optionnel pour spécifier une opération. Ceci peut être fait avec une des nouvelles constantes suivantes : PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL, or PGSQL_NOTICE_CLEAR.
  • pg_fetch_all() accepte maintenant un second paramètre optionnel pour spécifier le type de résultat (similaire au troisième paramètre de pg_fetch_array()).
  • pg_select() accepte maintenant un quatrième paramètre pour spécifier le type de résultat (similaire au troisième paramètre de pg_fetch_array()).

Session

  • session_start() maintenant retourne false et n'initialise plus $_SESSION quand le démarrage de la session échoue.

User Contributed Notes

There are no user contributed notes for this page.


Autres changements

Notices et avertisements sur opérations arithmétiques avec chaînes invalides

Des nouvelles erreurs E_WARNING et E_NOTICE ont été introduites quand des chaîne de caractères invalides sont contraintes en utilisant des opérateurs s'attendant à des nombres (+ - * / ** % << >> | & ^) ou leurs assignements équivalents. Une E_NOTICE est émise quand la chaîne de caractères commence avec une valeur numérique mais contient des caractères non numériques de fin, et une E_WARNING est émise quand la chaîne de caractères ne contient pas une valeur numérique.

<?php
'1b' + 'something';

L'exemple ci-dessus va afficher :

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

Avertissement en cas de débordement de la séquence d'échappement octale

Auparavant, les séquences d'échappement de chaîne octale de 3 octets débordaient silencieusement. Désormais, elles déborderont toujours, mais une E_WARNING sera émise.

<?php
var_dump("\500");

L'exemple ci-dessus va afficher :

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

Correction des incohérences de $this

Bien que $this soit considérée comme une variable spéciale en PHP, il lui manquait des contrôles appropriés pour s'assurer qu'elle n'était pas utilisée comme nom de variable ou réassignée. Ceci a été désormais rectifié pour s'assurer que $this ne peut pas être une variable définie par l'utilisateur, réassignée à une différente valeur ou globalisée.

Génération d'ID de session sans hachage

Les IDs de session ne seront plus hachés dès la génération. Avec ce changement ceci amène à la suppression des quatres paramètres ini suivants :

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Et l'addition des deux paramètres ini suivants :

  • session.sid_length - définit la longueur de l'ID de session, par défaut 32 caractères pour la rétrocompatibilité.
  • session.sid_bits_per_character - définit le nombre de bits à enregistrer par caractère (c.à.d augmente l'intervale de caractères qui peuvent être utilisés dans l'ID de session), par défaut 4 pour la rétrocompatibilité.

Modifications apportées à la gestion des fichiers INI

precision

Si la valeur est définit à -1, alors le mode dtoa 0 est utilisé. La valeur par défaut est toujours 14.

serialize_precision

Si la valeur est définie à -1, alors le mode dtoa 0 est utilisé. La valeur -1 est désormais utilisée par défaut.

gd.jpeg_ignore_warning

La valeur par défaut de ce paramètre php.ini a été modifiée à 1, donc par défaut les avertissements libjpeg sont ignorés.

opcache.enable_cli

La valeur par défaut de ce paramètre php.ini a été modifiée à 1 (activé) en PHP 7.1.2, et retour à 0 (désactivé) en PHP 7.1.7.

Génération des IDs de sessions seulement avec un CSPRNG

Les IDs de sessions seront désormais seulement générés avec un CSPRNG (Crypto Secure Pseudo Random Number Generator)

Des messages TypeError plus informatifs quand null est permis

Les exceptions TypeError pour les vérifications de type arg_info fourniront désormais des messages d'erreurs plus informatifs. Si le type du paramètre ou le type de retour accepte null (soit en ayant une valeur par défaut de null soit en étant un type nullable), alors le message d'erreur mentionnera désormais ceci avec un message "must be ... or null" ou "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
?>


Support Windows

Support pour les chemins longs et UTF-8

Si une application web est conforme à l'UTF-8, aucune action supplémentaire n'est requise. Pour des applications qui dépendent de chemins dans un encodage différent que UTF-8 pour l'I/O, une directive INI doit être explicitement définie. La vérification des paramètres d'encodage INI se fie à l'ordre dans le cœur (core) :

  • internal_encoding
  • default_charset
  • zend.multibyte

Plusieurs fonctions pour la gestion des codepage ont été introduites :

  • 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

Ces fonctions sont thread safe.

La sortie de la console codepage est ajustée en fonction de l'encodage utilisé en PHP. En fonction du codepage OEM du système concret, la sortie visible pourrait ou pourrait ne pas être correcte. Par exemple, avec le cmd.exe par défaut et sur un système avec le codepage OEM 437, les sorties en codepage 1251, 1252, 1253 et d'autres peuvent être affichées correctement en utilisant UTF-8. Sur les mêmes systèmes, les caractères dans codepage tel que 20932 ne seront probablement pas affichées correctement. Ceci fait référence aux règles système particulières pour codepage, la compabilité de la police et le choix du programme de console utilisé. PHP définit automatiquement la codepage console en accord avec les règles d'encodages depuis php.ini. Utiliser des consoles alternatives à la place de cmd.exe directement pourrait apporter une meilleure expérience dans certains cas.

Toutefois soyez conscient, changer de codepage après que la requête a commencé peut causer des effets secondaires inattendus en CLI. La façon préférable est php.ini. Quand PHP CLI est utilisée dans un émulateur de console, qui ne supporte pas Unicode, il est possiblement nécessaire, d'éviter de changer la codepage de la console. La meilleure façon pour achever ceci est de définir l'encodage interne ou par défaut pour correspondre à la codepage ANSI. Une autre méthode est de définir la directive INI output_encoding et input_encoding à la codepage requise, cependant dans ce cas la différence entre les codepages internes et I/O risque de causer du mojibake. Dans de rares cas, si PHP arrive à planter gracieusement, la codepage originale de la console peut ne pas être restaurée. Dans ce cas, la commande chcp peut être utilisée, pour la restaurer manuellement.

Attention particulière pour les systèmes DBCS - le changement de codepage lors de l'exécution en utilisant ini_set() risque de causer des problèmes d'affichage. À la différence des systèmes non DBCS, c'est que les caractères étendus nécessitent deux consoles pour être affichés. Dans certains cas, seule la mise en correspondance des caractères dans le jeu de glyphes de la police pourrait se produire, aucun changement de police ne se produit. Ceci est la nature des systèmes DBCS, la manière la plus simple de prévenir des problèmes d'affichages est d'éviter l'usage de ini_set() pour le changement de codepage.

En conséquence du support d'UTF-8 dans les flux, les scripts PHP ne sont plus limités à des noms de fichiers ASCII ou ANSI. Ceci est prêt à l'emploi en CLI. Pour d'autres SAPI, la documentation pour le serveur correspondant est utile.

Le support des chemins longs est transparent. Les chemins plus longs que 260 octets sont automatiquement préfixés par \\?\. La longueur maximale du chemin est limitée à 2018 octets. Soyez conscient, que la limite des segments de chemin (longueur du basename) persiste.

Pour une meilleure portabilité, il est fortement recommandé de gérer les noms de fichiers, I/O et autres sujets connexes UTF-8. En outre, pour les applications console, l'usage d'une police TrueType est préférable et l'usage de ini_set() pour le le changement de codepage est déconseillé.

readline

L'extension readline est supportée à travers la » bibliothèque WinEditLine. Ainsi l'interface système interactive CLI est aussi supportée (php.exe -a).

PHP_FCGI_CHILDREN

PHP_FCGI_CHILDREN est désormais respecté. Si cette variable d'environnement est définie, le premier processus php-cgi.exe exécutera le nombre spécifié d'enfants. Ceux-ci partageront le même socket TCP.

ftok()

Ajout du support pour ftok()

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 5.6.x vers PHP 7.0.x

Sommaire

  • Modifications entrainant une incompatibilité ascendante
  • Nouvelles fonctionnalités
  • Les fonctionnalités dépréciées dans PHP 7.0.x
  • Fonctions modifiées
  • Nouvelles fonctions
  • Nouvelles Classes et Interfaces
  • Nouvelles constantes globales
  • Modifications des modules SAPI
  • Extensions et SAPI supprimées
  • Autres changements

Bien que PHP 7.0 soit une nouvelle version majeure, des efforts ont été faits pour rendre la migration aussi facile que possible. Cette version vise principalement à retirer les fonctionnalités qui ne sont plus supportées et à améliorer la cohérence du langage.

Il y a quelques incompatibilités et nouvelles fonctionnalités qui devraient être considérées, et le code devrait être testé avant de changer la version de PHP dans un environnement de production.

User Contributed Notes

There are no user contributed notes for this page.


Modifications entrainant une incompatibilité ascendante

Modifications apportées à la gestion des erreurs et des exceptions

De nombreuses erreurs fatales et récupérables ont été converties en exceptions dans PHP 7. Ces exceptions d'erreur héritent de la classe Error, qui implémente elle-même l'interface Throwable (la nouvelle interface de base dont toutes les exceptions héritent).

Cela signifie que les gestionnaires d'erreurs personnalisés peuvent ne plus être déclenchés car des exceptions peuvent être levées à la place (provoquant de nouvelles erreurs irrécupérables pour les exceptions Error non interceptées).

Une description plus complète de la façon dont les erreurs fonctionnent en PHP 7 se trouve sur la page des erreurs PHP 7. Ce guide de migration énumérera simplement les modifications qui affectent la rétrocompatibilité.

set_exception_handler() n'est plus garanti de recevoir des objets Exception

Le code qui implémente un gestionnaire d'exceptions inscrit avec set_exception_handler() à l'aide d'une déclaration de type Exception provoquera une erreur fatale lorsqu'un objet Error est levé.

Si le gestionnaire doit fonctionner à la fois avec PHP 5 et 7, vous devriez supprimer la déclaration de type du gestionnaire, tandis que le code qui est migré pour travailler sur PHP 7 exclusivement peut simplement remplacer la déclaration de type Exception par Throwable.

<?php
// Code pour PHP 5 qui va se briser.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// Compatible PHP 5 et 7.
function handler($e) { ... }

// PHP 7 seulement.
function handler(Throwable $e) { ... }
?>

Les constructeurs internes lèvent toujours des exceptions en cas d'échec

Auparavant, certaines classes internes retournaient null ou un objet inutilisable lorsque le constructeur échouait. Toutes les classes internes lèveront maintenant une Exception dans ce cas de la même manière que les classes d'utilisateurs.

Les erreurs d'analyse lèvent une ParseError

Les erreurs d'analyseur lèvent maintenant un objet ParseError. La gestion des erreurs pour eval() doit maintenant inclure un bloc catch qui peut gérer cette erreur.

Changements de gravité des avis E_STRICT

Tous les avis E_STRICT ont été reclassés à d'autres niveaux. La constante E_STRICT est conservée, donc les appels comme error_reporting(E_ALL|E_STRICT) ne provoqueront pas d'erreur.

Changements de gravité des avis E_STRICT
Situation | Nouveau niveau/comportement
Indexation par une ressource | E_NOTICE
Méthodes statiques abstraites | Avis supprimé, ne déclenche aucune erreur
"Redéfinir" un constructeur | Avis supprimé, ne déclenche aucune erreur
Incompatibilité de signature pendant l'héritage | E_WARNING
Même propriété (compatible) dans deux traits utilisés | Avis supprimé, ne déclenche aucune erreur
Accès à une propriété statique non statiquement | E_NOTICE
Seules les variables doivent être attribuées par référence | E_NOTICE
Seules les variables doivent être transmises par référence | E_NOTICE
Appel de méthodes non statiques statiquement | E_DEPRECATED

Modifications apportées à la gestion des variables

PHP 7 utilise maintenant une arborescence de syntaxe abstraite lors de l'analyse des fichiers sources. Cela a permis de nombreuses améliorations à la langue qui étaient auparavant impossibles en raison des limitations dans l'analyseur utilisé dans les versions antérieures de PHP, mais a abouti à la suppression de quelques cas spéciaux pour des raisons de cohérence, qui a abouti à casser la rétro-compatibilité. Ces cas sont détaillés dans cette section.

Modifications apportées à la gestion des variables, propriétés et méthodes indirectes

L'accès indirect aux variables, propriétés et méthodes sera maintenant évalué strictement dans l'ordre de gauche à droite, par opposition à la combinaison précédente de cas spéciaux. Le tableau ci-dessous montre comment l'ordre d'évaluation a changé.

Ancienne et nouvelle évaluation des expressions indirectes
Expression | Interprétation PHP 5 | Interprétation 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']()

Le code qui utilisait l'ancien ordre d'évaluation de droite à gauche doit être réécrit pour utiliser explicitement cet ordre d'évaluation avec des accolades (voir la colonne du milieu ci-dessus). Cela rendra le code compatible avec PHP 7.x et rétrocompatible avec PHP 5.x.

Cela affecte également le mot clé global. La syntaxe des accolades peut être utilisée pour émuler le comportement précédent si nécessaire :

<?php
function f() {
// Valide en PHP 5 uniquement.
global $$foo->bar;

// Valide en PHP 5 et 7.
global ${$foo->bar};
}
?>

Modifications apportées à la gestion des list()

la fonction list() n'assigne plus de variable dans l'ordre inverse

list() assignera désormais des valeurs aux variables dans l'ordre dans lequel elles sont définies, plutôt que dans l'ordre inverse. En général, cela affecte uniquement le cas où list() est utilisée en conjonction avec l'opérateur de tableau [], comme illustré ci-dessous :

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

Résultat de l'exemple ci-dessus en PHP 5 :

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

Résultat de l'exemple ci-dessus en PHP 7 :

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

En général, il est recommandé de ne pas compter sur l'ordre dans lequel les affectations de la fonction list() se produisent, car il s'agit d'un détail d'implémentation qui peut changer à nouveau à l'avenir.

Les affectations de list() vides ont été supprimées

Les constructions de list() ne peuvent plus être vides. Les éléments suivants ne sont plus autorisés :

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
list() ne peut pas défaire chaîne de caractères

list() ne peut plus défaire les variables de chaîne de caractères. str_split() devrait être utilisé à la place.

L'ordre des éléments des tableaux a changé lorsque les éléments sont créés automatiquement pendant les affectations de référence

L'ordre des éléments dans un tableau a changé lorsque ces éléments ont été créés automatiquement en les référençant dans une assignation par référence. Par exemple :

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Résultat de l'exemple ci-dessus en PHP 5 :

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Résultat de l'exemple ci-dessus en PHP 7 :

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Les parenthèses autour des arguments de fonction n'affectent plus le comportement

En PHP 5, l'utilisation de parenthèses redondantes autour d'un argument de fonction peut calmer les avertissements de normes strictes lorsque l'argument de fonction a été passé par référence. L'avertissement est maintenant toujours émis.

<?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()));
?>

L'exemple ci-dessus va afficher :

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

Changements concernant foreach

Des changements mineurs ont été faits sur le comportement de la structure de contrôle foreach, principalement sur la gestion du pointeur interne de tableau et la modification du tableau étant parcouru.

foreach ne modifie plus le pointeur interne de tableau

Antérieur à PHP 7, le pointeur interne de tableau était modifié pendant qu'un tableau était parcouru avec foreach. Cela n'est plus le cas, comme le montre l'exemple suivant :

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
var_dump(current($array));
}
?>

Résultat de l'exemple ci-dessus en PHP 5 :

int(1)
int(2)
bool(false)

Résultat de l'exemple ci-dessus en PHP 7 :

int(0)
int(0)
int(0)

foreach par valeur travaille sur une copie du tableau

Lors de l'utilisation du mode par défaut (par valeur), foreach travaille maintenant sur une copie du tableau en cours parcouru plutôt que sur le tableau lui-même. Cela signifie que les changements réalisés sur le tableau pendant son parcours n'affecteront pas les valeurs qui sont parcourues.

Le comportement du parcours de foreach par référence a été amélioré

Lors du parcours d'un tableau par référence, foreach identifie mieux les changements faits au tableau pendant son parcours. Par exemple, si des valeurs sont ajoutées à un tableau pendant son parcours, alors ces nouvelles valeurs seront également parcourues :

<?php
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}
?>

Résultat de l'exemple ci-dessus en PHP 5 :

int(0)

Résultat de l'exemple ci-dessus en PHP 7 :

int(0)
int(1)

Parcours d'objets non-Traversable

Le parcours d'un objet non-Traversable est maintenant identique au parcours d'un tableau par référence. En conséquence l'amélioration du comportement lors de la modification d'un tableau pendant son parcours est également appliquée lorsque des propriétés sont ajoutées ou supprimées d'un objet.

Modifications apportées à la gestion d'entier

Littéraux octaux non valides

Auparavant, les littéraux octaux qui contenaient des nombres non valides étaient tronqués silencieusement (0128 a été pris comme 012). Désormais, un littéral octal non valide provoquera une erreur d'analyse.

Décalage de bits négatif

Les décalages de bits par nombres négatifs vont maintenant lancer une ArithmeticError:

<?php
var_dump(1 >> -1);
?>

Résultat de l'exemple ci-dessus en PHP 5 :

int(0)

Résultat de l'exemple ci-dessus en 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

Décalage de bits hors plage

Les décalages de bits (dans les deux sens) au-delà de la largeur de bit d'un entier retourneront toujours 0. Auparavant, le comportement de ces décalages était dépendant de l'architecture.

Changements apportés à la division par zéro

Auparavant, lorsque 0 a été utilisé comme diviseur pour les opérateurs de division (/) ou de modulo (%), un E_WARNING était émis et false était retourné. Désormais, l'opérateur de division retourne un float en tant que +INF,-INF ou NAN, comme spécifié par IEEE 754. Le E_WARNING de l'opérateur de modulo a été supprimé et lèvera une exception DivisionByZeroError.

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

Résultat de l'exemple ci-dessus en 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)

Résultat de l'exemple ci-dessus en 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

Modifications apportées à la gestion des chaîne de caractères

Les chaînes hexadécimales ne sont plus considérées comme numériques

Les chaîne de caractères contenant des nombres hexadécimaux ne sont plus considérées comme numériques. Par exemple :

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

Résultat de l'exemple ci-dessus en PHP 5 :

bool(true)
bool(true)
int(15)
string(2) "oo"

Résultat de l'exemple ci-dessus en 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() peut être utilisé pour vérifier si une chaîne de caractères contient un nombre hexadécimal, et aussi pour convertir une chaîne de caractères de ce type en un entier :

<?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{ peut provoquer des erreurs

En raison de l'ajout de la nouvelle syntaxe d'échappement du point de code Unicode, les chaîne de caractères contenant un littéral \u{ suivi d'une séquence non valide provoquera une erreur fatale. Pour éviter cela, la barre oblique inverse principale doit être échappée.

Fonctions supprimées

call_user_method() et call_user_method_array()

Ces fonctions ont été dépréciées en PHP 4.1.0 en faveur de call_user_func() et call_user_func_array(). Vous pourriez également utiliser les fonctions variables et/ou l'opérateur ....

Toutes les fonctions ereg*

Toutes les fonctions ereg ont été supprimées. PCRE est une alternative recommandée.

Aliasmcrypt

La fonction obsolète mcrypt_generic_end() a été remplacée par mcrypt_generic_deinit().

De plus, les fonctions obsolètes mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() et mcrypt_ofb() ont été remplacées par l'utilisation de mcrypt_decrypt() avec la constante appropriée MCRYPT_MODE_*.

Toutes les fonctions ext/mysql

Toutes les fonctions ext/mysql ont été supprimées. Pour plus d'informations sur le choix d'une autre API MySQL, consultez choisir une API MySQL.

Toutes les fonctions ext/mssql

Toutes les fonctions ext/mssql ont été supprimées.

  • PDO_SQLSRV
  • PDO_ODBC
  • SQLSRV
  • Unified ODBC API

intl aliases

Les alias obsolètes datefmt_set_timezone_id() et
IntlDateFormatter::setTimeZoneID() ont été supprimés
et remplacés respectivement par datefmt_set_timezone() et
IntlDateFormatter::setTimeZone().

set_magic_quotes_runtime()

set_magic_quotes_runtime(), ainsi que son alias magic_quotes_runtime(), ont été supprimées. Elles étaient obsolètes à partir PHP 5.3.0, et sans effet depuis la suppression des guillemets magiques en PHP 5.4.0.

set_socket_blocking()

L'alias obsolète set_socket_blocking() a été supprimé et remplacé par stream_set_blocking().

dl() avec PHP-FPM

dl() ne peut plus être utilisé avec PHP-FPM. Il continue à fonctionner dans les SAPIs CLI et Embed.

Fonctions GD Type1

Le support des polices PostScript Type1 a été supprimé de l'extension GD, entraînant la suppression des fonctions suivantes :

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

À la place, il est recommandé d'utiliser les polices TrueType et leurs fonctions associées.

Directives INI supprimées

Fonctionnalités supprimées

Les directives INI suivantes ont été supprimées car leurs fonctionnalités associées ont également été supprimées:

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

La directive xsl.security_prefs a été supprimée. Au lieu de cela, la méthode XsltProcessor::setSecurityPrefs() doit être appelée pour contrôler les préférences de sécurité sur une base du processeur.

Autres modifications rétro-incompatibles

Les nouveaux objets ne peuvent pas être attribués par référence

Le résultat de l'instruction new ne peut plus être assigné à une variable par référence :

<?php
class C {}
$c =& new C;
?>

Résultat de l'exemple ci-dessus en PHP 5 :

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Résultat de l'exemple ci-dessus en PHP 7 :

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

Noms de classe, d'interface et de traits invalides

Les noms suivants ne peuvent pas être utilisés pour nommer des classes, des interfaces ou des traits :

  • bool
  • int
  • float
  • string
  • null
  • true
  • false

En outre, les noms suivants ne doivent pas être utilisés. Bien qu'ils ne génèrent pas une erreur dans PHP 7.0, ils sont réservés pour une utilisation future et doivent être considérés comme obsolètes.

  • resource
  • object
  • mixed
  • numeric

ASP et script PHP Tags supprimés

La prise en charge de l'utilisation des balises ASP et script pour délimiter le code PHP a été supprimée. Les balises affectées sont :

Suppression des balises ASP et script
Balise d'ouverture | Balise de fermeture
<% | %>
<%= | %>
<script language="php"> | </script>

Appels d'un contexte incompatible supprimés

Précédemment déconseillé dans PHP 5.6, les appels statiques effectués à une méthode non statique avec un contexte incompatible se traduiront désormais par la méthode appelée ayant une variable $this non définie et un avertissement d'obsolescence est émis.

<?php
class A {
public function test() { var_dump($this); }
}

// Note: Does NOT extend A
class B {
public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>

Résultat de l'exemple ci-dessus en 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) {
}

Résultat de l'exemple ci-dessus en 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 est maintenant un opérateur associatif à droite

La construction yield ne nécessite plus de parenthèses et a été remplacée par un opérateur associatif droit avec la priorité entre print et =>. Cela peut entraîner un changement de comportement :

<?php
echo yield -1;
// A été précédemment interprété comme
echo (yield) - 1;
// Et est maitenant interprété comme
echo yield (-1);

yield $foo or die;
// A été précédemment interprété comme
yield ($foo or die);
// Et est maitenant interprété comme
(yield $foo) or die;
?>

Les parenthèses peuvent être utilisées pour lever l'ambiguïté sur ces cas.

Les fonctions ne peuvent pas avoir plusieurs paramètres avec le même nom

Il n'est plus possible de définir deux ou plusieurs paramètres de fonction avec le même nom. Par exemple, la fonction suivante déclenchera un E_COMPILE_ERROR:

<?php
function foo($a, $b, $unused, $unused) {
//
}
?>

Fonctions d'inspection des arguments signalent la valeur actuelle du paramètre

func_get_arg(), func_get_args(), debug_backtrace() et les traces d'exception ne signalent plus la valeur d'origine qui a été passée à un paramètre, mais fourniront plutôt la valeur actuelle (qui aurait pu être modifiée).

<?php
function foo($x) {
$x++;
var_dump(func_get_arg(0));
}
foo(1);?>

Résultat de l'exemple ci-dessus en PHP 5 :

1

Résultat de l'exemple ci-dessus en PHP 7 :

2

Les instructions Switch ne peuvent pas avoir plusieurs blocs par défaut

Il n'est plus possible de définir deux ou plusieurs blocs par défaut dans une instruction switch. Par exemple, l'instruction switch suivante déclenchera un E_COMPILE_ERROR :

<?php
switch (1) {
default:
break;
default:
break;
}
?>

$HTTP_RAW_POST_DATA a été supprimée

$HTTP_RAW_POST_DATA n'est plus disponible. Le flux php://input doit être utilisé à la place.

Les commentaires # dans le fichier INI ont été supprimés

La prise en charge des commentaires avec le préfix # dans les fichiers INI a été supprimée. ; (point-virgule) doit être utilisé à la place. Cette modification s'applique aux php.ini, ainsi qu'aux fichiers gérés par parse_ini_file() et parse_ini_string().

Extension JSON remplacée par JSOND

L'extension JSON a été remplacée par JSOND, provoquant trois incompatibilités BC mineures. Premièrement, un nombre ne doit pas se terminer par une virgule décimale (c.-à-d. 34. doit être modifié en 34.0 ou en 34). Deuxièmement, lors de l'utilisation de la notation scientifique, l'exposant e ne doit pas suivre immédiatement un point décimal (c.-à-d. 3.e3 doit être modifié soit en 3.0e3 ou en 3e3). Enfin, une chaîne vide n'est plus considérée comme du JSON valide.

Défaillance de la fonction interne sur le débordement

Auparavant, les fonctions internes devaient tronquer silencieusement les nombres produits à partir de contraintes de type float à entier lorsque le nombre était trop volumineux pour représenter un entier. Désormais, un E_WARNING sera émis et null sera renvoyé.

Correctifs aux valeurs de retour de gestionnaire de session personnalisé

Toutes les fonctions de prédicat implémentées par des gestionnaires de session personnalisés qui retournent false ou -1 seront des erreurs fatales. Si une valeur de ces fonctions autre qu'un booléen, -1 ou 0 est retournée, elle échouera et un E_WARNING sera émis.

Ordre de tri des éléments égaux

L'algorithme de tri interne a été amélioré, ce qui peut entraîner un ordre de tri différent des éléments, qui se comparent comme égaux auparavant.

Note:

Ne comptez pas sur l'ordre des éléments qui se comparent comme égaux; il pourrait changer à tout moment.

Instructions de coupure et de continuation mal placées

Les instructions break et continue en dehors d'une boucle ou d'une structure de contrôle switch sont maintenant détectées au moment de la compilation au lieu de l'exécution comme avant, et déclenchent un E_COMPILE_ERROR.

Mhash n'est plus une extension

L'extension mhash a été entièrement intégrée dans l'extension Hash. Par conséquent, il n'est plus possible de détecter le support mhash avec extension_loaded(); utiliser function_exists() à la place. En outre, mhash n'est plus rapporté par get_loaded_extensions() et les fonctionnalités connexes.

declare(ticks)

La directive declare(ticks) ne fuit plus dans des unités de compilation différentes.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctionnalités

Déclarations du type scalaire

Les déclarations de type scalaire viennent en deux modes : coercitive (par défaut) ou stricte. Les types de paramètres suivants peuvent être renforcés (soit coercitif soit strict) : les chaînes de caractères (string), les entiers (int), les décimaux (float) et les valeurs booléennes (bool). Ils complémentent les autres types introduits dans PHP 5 : les noms des classes, les interfaces, les tableaux (array) et les fonctions appelables (callable).

<?php
// Mode coercitive
function sommeEntiers(int ...$entiers)
{
return array_sum($entiers);
}

var_dump(sommeEntiers(2, '3', 4.1));

L'exemple ci-dessus va afficher :

int(9)

Pour activer le mode strict, une seule directive declare doit être placée en haut du fichier. Ceci signifie que le mode strict de déclaration du type scalaire est configurée par fichier. La directive n'affecte pas seulement la déclaration des paramètres mais aussi le type de retour de la fonction (voir les déclarations du type de retour dans les fonctions PHP et celles issues des extensions).

Une documentation complète et des exemples de déclarations du type scalaire peuvent être trouvés dans la référence : Déclarations de type.

Déclarations du type de retour

PHP 7 ajoute un support pour les déclarations du type de retour. Similaires aux déclarations du type d'argument, les déclarations du type de retour spécifient le type de la valeur qui sera retournée par la fonction. Les mêmes types qui sont disponibles pour les déclarations du type de retour sont disponibles pour les déclarations du type d'argument.

<?php

function sommeTableaux(array ...$tableaux): array
{
return array_map(function(array $tableaux): int {
return array_sum($tableaux);
}, $tableaux);
}

print_r(sommeTableaux([1,2,3], [4,5,6], [7,8,9]));

L'exemple ci-dessus va afficher :

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

Une documentation complète et des exemples de déclarations du type de retour peuvent être trouvés dans la référence : Déclarations du type de retour.

L'opérateur Null coalescent

L'opérateur Null coalescent (??) a été ajouté comme un sucre syntaxique pour les cas de besoin les plus communs d'utiliser une troisième conjonction avec la fonction isset(). Il retourne le premier opérande s'il existe et n'a pas une valeur null; et retourne le second opérande sinon.

<?php
// Récupére la valeur de $_GET['utilisateur'] retourne 'aucun'
// s'il n'existe pas.
$identifiant = $_GET['utilisateur'] ?? 'aucun';
// Ceci est équivalent à :
$identifiant = isset($_GET['utilisateur']) ? $_GET['utilisateur'] : 'aucun';

// L'opérateur permet de faire du chaînage : Ceci va retourner la première
// valeur définie respectivement dans $_GET['utilisateur'], $_POST['utilisateur']
// et 'aucun'.
$identifiant = $_GET['utilisateur'] ?? $_POST['utilisateur'] ?? 'aucun';
?>

L'opérateur Spaceship

L'opérateur Spaceship est utilisé pour comparer deux expressions. Il retourne -1, 0 ou 1 quand $a est respectivement inférieur, égal ou supérieur à $b. Les comparaisons sont effectuées selon les règles de comparaison de types habituelles de PHP.

<?php
// Entiers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Nombres à virgule flottante
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Chaînes de caractères
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

Les tableaux constants à l'aide de define()

Les tableaux (Array) constants peuvent maintenant être définis avec la fonction define(). Dans PHP 5.6, ils pouvaient être définis seulement avec const.

<?php
define('ANIMAUX', [
'chien',
'chat',
'oiseau'
]);

echo ANIMAUX[1]; // affiche "chat"
?>

Les classes anonymes

La prise en charge des classes anonymes a été ajoutée à travers l'instanciation new class. Celle-ci peut être utilisée au lieu de définir toute une classe pour des objets jetables :

<?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());
?>

L'exemple ci-dessus va afficher :

object(class@anonymous)#2 (0) {
}

La documentation complète peut être trouvée dans la référence des classes anonymes.

Syntaxe d’échappement du point de code Unicode

Cela prend un point de code Unicode sous forme hexadécimale, dans une chaîne entre doubles guillemets ou une syntaxe heredoc, pour le convertir en UTF-8. N’importe quel point de code valide est accepté, les zéros en début de chaîne étant facultatifs.

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

L'exemple ci-dessus va afficher :

ª
ª (même affichage que la ligne précédente mais avec des zéros en début de chaîne)
?

Closure::call()

La méthode Closure::call() est devenue plus performante. Une façon plus courte de lier temporairement une fermeture à la portée d'un objet et l'invoquer.

<?php
class A {private $x = 1;}

// Code avant PHP 7
$getX = function() {return $this->x;};
$getXCB = $getX->bindTo(new A, 'A'); // fermeture intermédiaire
echo $getXCB();

// Code PHP 7+
$getX = function() {return $this->x;};
echo $getX->call(new A);

L'exemple ci-dessus va afficher :

1
1

unserialize() est filtrée

Cette fonctionnalité vise à garantir une meilleure sécurité lorsque la désérialisation d’objets est effectuée avec des données non fiables. Elle empêche les injections de code possible en permettant au développeur de whitelister les classes qui peuvent être désérialisées.

<?php

// Convertit tous les objets vers un objet __PHP_Incomplete_Class
$data = unserialize($foo, ["allowed_classes" => false]);

// Convertit tous les objets vers un objet __PHP_Incomplete_Class
// exceptés ceux de MyClass et MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// Comportement par défaut (le même que lorsqu'on omet le deuxième argument)
// qui accepte toutes les classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

La nouvelle classe IntlChar cherche à exposer la fonctionnalité ICU en plus. La classe elle-même définit un nombre de méthodes statiques et de constantes qui peuvent être utilisées pour manipuler les caractères unicode.

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

L'exemple ci-dessus va afficher :

10ffff
COMMERCIAL AT
bool(true)

Pour utiliser cette classe, vous devez installer l'extension Intl.

Les attentes

Les attentes sont une amélioration rétro-compatible apportée à l'ancienne fonction assert(). Ils offrent des assertions à très faible coût dans le code de production et permettent de lever des exceptions personnalisées lorsque l’assertion échoue.

Alors que l'ancienne API continue à être maintenue pour des raisons de compatibilité, la fonction assert() est maintenant une construction de language, permettant au premier paramètre d'être une expression plutôt qu'un string à évaluer ou un bool à tester.

<?php
ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Un message d\'erreur'));
?>

L'exemple ci-dessus va afficher :

Fatal error: Uncaught CustomError: Un message d\'erreur

On trouvera plus de détails sur cette fonctionnalité, y compris la façon de la configurer dans les environnements de développement et de production, dans la section attentes dans la référence de la fonction assert().

Grouper les déclarations use

Les classes, les fonctions et les constantes importées à partir du même namespace peuvent être groupées maintenant dans une seule instruction use.

<?php
// Code avant 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;

// Code 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};
?>

Expressions de retour générateur

Cette fonction se base sur la fonctionnalité de générateur introduite dans PHP 5.5. Elle permet d'utiliser une instruction return dans un générateur pour retourner une expression finale (le retour par référence n'est pas autorisé). Cette valeur peut être extraite en utilisant la nouvelle méthode Generator::getReturn(), qui ne peut être utilisée que lorsque le générateur a fini de rendre les valeurs.

<?php

$gen = (function() {
yield 1;
yield 2;

return 3;
})();

foreach ($gen as $val) {
echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

L'exemple ci-dessus va afficher :

1
2
3

C'est très pratique d'être capable de renvoyer explicitement une valeur finale d'un générateur. Car cela permet à une valeur finale, susceptible d'être gérée spécialement par le code client exécutant le générateur, d'être retournée par le générateur (peut-être à partir d'une forme de calcul coroutine). C'est de loin plus simple que de forcer le code client à vérifier d'abord si la valeur finale a été rendue, puis de gérer spécifiquement la valeur quand c'est le cas.

Délégation de générateur

Les générateurs peuvent maintenant être délégués automatiquement à un autre générateur, un objet Traversable ou un array, en utilisant yield from, sans avoir recours à un boilerplate.

<?php
function gen()
{
yield 1;
yield 2;
yield from gen2();
}

function gen2()
{
yield 3;
yield 4;
}

foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
?>

L'exemple ci-dessus va afficher :

1
2
3
4

La division d’entiers avec intdiv()

La nouvelle fonction intdiv() retourne le résultat de la division d'entiers effectuée sur ses opérandes.

<?php
var_dump(intdiv(10, 3));
?>

L'exemple ci-dessus va afficher :

int(3)

Les options de session

La fonction session_start() accepte maintenant un array d'options qui surcharge les directives de configuration de session manuellement configurées dans le fichier php.ini.

Ces options ont aussi étendu le support pour l'option session.lazy_write, qui est activée par défaut et pousse PHP à surcharger les fichiers de session seulement si les données de session ont été mises à jour, et l'option read_and_close, ne pouvant être passée à la fonction session_start() que pour indiquer si les données de session doivent être lues avant que la session soit terminée sans changements.

Par exemple, pour mettre session.cache_limiter à private et fermer immédiatement la session après l'avoir lue :

<?php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);
?>

preg_replace_callback_array()

La nouvelle fonction preg_replace_callback_array() permet au code d'être écrit de façon plus propre en utilisant la fonction preg_replace_callback(). Avant PHP 7, les fonctions de rappel (callback) devaient être exécutées par expression régulière ce qui demande à la fonction de rappel d'être salie avec beaucoup de ramifications.

Maintenant, les fonctions de rappel peuvent être enregistrées pour chaque expression régulière en utilisant un tableau associatif, là où la clé est une expression régulière ayant la fonction de rappel comme valeur.

Les fonctions CSPRNG

Deux nouvelles fonctions ont été ajoutées pour générer cryptographiquement des entiers et des chaînes de caractères sécurisées de façon multi-plateforme : random_bytes() et random_int().

La fonction list() peut toujours déballer les objets qui implémentent ArrayAccess

Auparavant, la fonction list() ne pouvait pas opérer à 100% sur des objets qui implémentent ArrayAccess. Maintenant, ça a été corrigé.

Autres fonctionnalités

  • L'accès aux membres de la classe (attributs et méthodes) lors du clonage a été ajouté. Exemple, (clone $foo)->bar().

User Contributed Notes

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.
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


Les fonctionnalités dépréciées dans PHP 7.0.x

Constructeurs de PHP 4

Les constructeurs de style PHP 4 (méthodes ayant le même nom que la classe dans laquelle elles sont définies) sont obsolètes et seront supprimés à l’avenir. PHP 7 émet E_DEPRECATED si le constructeur de PHP 4 est le seul constructeur défini dans la classe. Les classes qui implémentent une méthode __construct() ne sont pas affectées par ce changement.

<?php
class foo {
function foo() {
echo 'Je suis le constructeur';
}
}
?>

L'exemple ci-dessus va afficher :

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

Les appels statiques à des méthodes non statiques

Les appels statiques aux méthodes qui ne sont pas déclarées avec le mot-clé static sont dépréciés et peuvent être supprimés dans le futur.

<?php
class foo {
function bar() {
echo 'Je ne suis pas statique !';
}
}

foo::bar();
?>

L'exemple ci-dessus va afficher :

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
Je ne suis pas statique !

L'option salt de la fonction password_hash()

L'option salt de la fonction password_hash() est dépréciée pour épargner aux développeurs de générer leurs propres salts (habituellement non sécurisés). La fonction elle-même génère cryptographiquement un salt sécurisé en l’absence d'un salt fourni par le développeur. Donc, la génération d'un salt sur mesure ne sera plus nécessaire.

L'option capture_session_meta du contexte SSL

L'option capture_session_meta du contexte SSL est dépréciée. Les métadonnées SSL sont maintenant disponibles à travers la fonction stream_get_meta_data().

Dépréciation dans LDAP

Les fonctions suivantes sont dépréciées :

  • ldap_sort()

User Contributed Notes

There are no user contributed notes for this page.


Fonctions modifiées

Cœur de PHP

  • debug_zval_dump() affiche désormais "int" au lieu de "long" et "float" au lieu de "double"
  • La fonction dirname() prend désormais un deuxième paramètre optionnel, depth, pour indiquer le nombre de niveaux plus haut (par rapport au dossier courant) pour atteindre le nom du dossier dans l'arborescence.
  • getrusage() est désormais supporté sur Windows.
  • Les fonctions mktime() et gmmktime() n'acceptent plus le paramètre is_dst.
  • la fonction preg_replace() ne supporte plus "\e" (PREG_REPLACE_EVAL). preg_replace_callback() devrait être utilisé à la place.
  • La fonction setlocale() n'accepte plus que le paramètre category soit passé comme chaîne de caractères. Les constantes LC_* doivent être utilisées à la place.
  • Les fonctions exec(), system() et passthru() ont désormais l'octet NULL de protection.
  • shmop_open() retourne désormais une ressource à la place d'un entier qui doit être passé aux fonctions shmop_size(), shmop_write(), shmop_read(), shmop_close() et shmop_delete().
  • substr() et iconv_substr() retourne désormais une chaîne de caractères vide, si la longueur de la chaîne est égale à $start.
  • xml_parser_free() n'est plus suffisant pour libérer la ressource de l'analyseur, s'il fait référence à un objet et que cet objet fait référence à cette ressource d'analyseur. Dans ce cas, il est nécessaire de libérer également le $parser.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctions

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

Gestion des erreurs et des journaux

  • error_clear_last()

Générateur

  • Generator::getReturn()

GNU Multiple Precision

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

Options/Info PHP

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Compression Zlib

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles Classes et Interfaces

Intl

  • IntlChar

Reflection

  • ReflectionGenerator
  • ReflectionType

Gestion des sessions

  • SessionUpdateTimestampHandlerInterface

Hiérarchie des exceptions

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles constantes globales

Constantes prédéfinies

  • PHP_INT_MIN

GD

  • IMG_WEBP (à partir de 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.


Modifications des modules SAPI

FPM

Les ports d'écoute non qualifiés écoutent maintenant sur IPv4 et IPv6

En PHP 5, une directive d'écoute avec seulement un numéro de port écouterait toutes les interfaces, mais seulement sur IPv4. PHP 7 accepte désormais les demandes faites via IPv4 et IPv6.

Cela n'affecte pas les directives qui incluent des adresses IP spécifiques; celles-ci continueront à écouter seulement sur cette adresse et protocole.

User Contributed Notes

There are no user contributed notes for this page.


Extensions et SAPI supprimées

Extensions supprimées

  • ereg
  • mssql
  • mysql
  • sybase_ct

SAPI supprimées

  • 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.


Autres changements

Assouplissement des restrictions des mots réservés

Globalement, l'utilisation des mots réservés en tant que nom de propriété, constante ou méthode dans des classes, des interfaces ou des traits sont désormais autorisés. Ceci réduit la surface des casses de rétrocompatibilité quand des nouveaux mots-clés sont introduits et évite les restrictions de nommage sur les APIs.

Ceci est particulièrement utile lorsque vous créez des DSLs internes avec des interfaces "fluent" :

<?php
// 'new', 'private' et 'for' étaient inutilisables auparavant
Project::new('Project Name')->private()->for('purpose here')->with('username here');
?>

La seule limitation est que le mot-clé class ne peut toujours pas être utilisé comme nom de constante, sinon il serait en conflit avec la syntaxe de résolution du nom de la classe (ClassName::class).

Enlèvement de l'avertissement date.timezone

Auparavant, un avertissement était émit si le paramètre INI date.timezone n'avait pas été défini avant d'utiliser les fonctions de date/temps. Maintenant, cet avertissement a été supprimé (avec date.timezone qui continue d'être UTC par défaut).

User Contributed Notes

There are no user contributed notes for this page.


Migration de PHP 5.5.x à PHP 5.6.x

Sommaire

  • Modifications entrainant une incompatibilité ascendante
  • Nouvelles fonctionnalités
  • Fonctionnalités devenues obsolètes en PHP 5.6.x
  • Fonctions modifiées
  • Nouvelles fonctions
  • Changement pour OpenSSL dans PHP 5.6.x
  • Autres modifications dans les extensions
  • Nouvelles constantes globales

La majorité des améliorations de PHP 5.6.x n'ont pas d'impact sur le code existant. Il y a néanmoins quelques incompatibilités et nouvelles fonctionnalités qui doivent être prises en considération, et le code doit être testé avant de changer de version sur les environnements de production.

User Contributed Notes

There are no user contributed notes for this page.


Modifications entrainant une incompatibilité ascendante

Bien que la plupart du code PHP 5 existant devrait fonctionner sans aucune modification, vous devez prendre en considération quelques incompatibilités ascendantes :

Les clés des tableaux ne sont pas écrasées lors de la définition d'un tableau comme une propriété d'une classe via un tableau littéral

Précédemment, les tableaux déclarés comme des propriétés de classe qui mixaient des clés explicites et implicites pouvaient voir leurs éléments écrasés sans avertissement si une clé explicite était identique à une clé séquentielle implicite. Par exemple :

<?php
class C {
const ONE = 1;
public $array = [
self::ONE => 'foo',
'bar',
'quux',
];
}

var_dump((new C)->array);
?>

Résultat de l'exemple ci-dessus en PHP 5.5 :

array(2) {
  [0]=>
  string(3) "bar"
  [1]=>
  string(4) "quux"
}

Résultat de l'exemple ci-dessus en PHP 5.6 :

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

Rigueur de json_decode()

json_decode() rejette maintenant les variantes non écrites en minuscule des littéraux JSON true, false et null, en accord avec la spécification JSON, et json_last_error() est renseignée en conséquence. Précédemment, les valeurs passées à json_decode() contenant l'une de ces valeurs en majuscules ou dans une casse mixte étaient acceptées.

Ce changement va affecter uniquement les cas ou du JSON invalide serait passé à json_decode() : du JSON valide ne sera pas affecté et sera analysé normalement.

Les gestionnaires de flux vérifient maintenant par défaut les certificats de pair et les noms d'hôtes lors de l'utilisation de SSL/TLS

Tous les flux clients cryptés activent désormais la vérification par paire par défaut. Par défaut, ceci va utiliser le CA OpenSSL par défaut pour vérifier la paire de certificat. Dans la plupart des cas, aucune modification n'a besoin d'être faite pour communiquer avec des serveurs et des certificats SSL valides, sachant que les distributeurs configurent généralement OpenSSL pour utiliser les CA connus.

Le CA par défaut peut être écrasé sur une base globale en utilisant les options de configuration openssl.cafile ou openssl.capath, ou via une requête basique en utilisant les options de contexte cafile ou capath.

Bien que ce ne soit pas conseillé en général, il est possible de désactiver la vérification de certificats par paire pour une requête en définissant l'option de contexte verify_peer à false, et pour désactiver la validation du nom des paires, en configurant l'option de contexte verify_peer_name à false.

Les ressources GMP sont maintenant des objets

Les ressources GMP sont maintenant des objets. L'API de l'extension GMP n'a pas changé et le code existant devrait continuer à fonctionner sans modification à moins qu'une vérification explicite ne soit faite en utilisant is_resource() ou équivalent.

Les fonctions Mcrypt requièrent maintenant des clés ou IV valides

mcrypt_encrypt(), mcrypt_decrypt(), mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb(), mcrypt_generic() et mcrypt_ofb() n'acceptent plus de clés ou de vecteurs d'initialisation (IVs) de tailles incorrectes, et les modes de ciphers par blocs qui requièrent des IVs échoueront désormais si un IV n'est pas fourni.

Téléchargement de fichiers avec cURL

Le téléchargement de fichier en utilisant la syntaxe @file nécessite maintenant que la directive CURLOPT_SAFE_UPLOAD soit définie à false. CURLFile doit plutôt être utilisé à la place.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctionnalités

Expressions de constante

Il est désormais possible de fournir une expression scalaire impliquant des numériques et des chaîne de caractères littérales et/ou des constantes dans les contextes où PHP attendait précédemment une valeur statique, comme une constante ou une déclaration de propriétés et les arguments par défaut de fonction.

<?php
const UN = 1;
const DEUX = UN * 2;

class C {
const TROIS = DEUX + 1;
const UN_TIERS = UN / self::TROIS;
const RESULTAT = 'La valeur de TROIS est '.self::TROIS;

public function f($a = UN + self::TROIS) {
return $a;
}
}

echo (new C)->f()."\n";
echo C::RESULTAT;
?>

L'exemple ci-dessus va afficher :

4
La valeur de TROIS est 3

Il est aussi possible de définir une constante tableau en utilisant le mot clé const :

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

L'exemple ci-dessus va afficher :

a

Fonctions variables via l'opérateur de décomposition ...

Les fonctions variables peuvent maintenant être implémentées en utilisant l'opérateur de décomposition ..., au lieu d'utiliser la fonction func_get_args().

<?php
function f($req, $opt = null, ...$params) {
// $params est un tableau contenant les arguments restants.
printf('$req: %d; $opt: %d; Nombre d\'arguments : %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);
?>

L'exemple ci-dessus va afficher :

$req: 1; $opt: 0; Nombre d'arguments : 0
$req: 1; $opt: 2; Nombre d'arguments : 0
$req: 1; $opt: 2; Nombre d'arguments : 1
$req: 1; $opt: 2; Nombre d'arguments : 2
$req: 1; $opt: 2; Nombre d'arguments : 3

Décompression des arguments via l'opérateur de décomposition ...

Les Tableaux et les objets Traversable peuvent être décompressés dans la liste d'arguments lors d'appel à une fonction en utilisant l'opérateur de décomposition .... Cette méthode est connue sous le nom d'opérateur astérisque dans d'autres langages comme Ruby par exemple.

<?php
function add($a, $b, $c) {
return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>

L'exemple ci-dessus va afficher :

6

L'exponentiation via l'opérateur **

Un opérateur ** associatif à droite a été ajouté pour supporter l'exponentiation, en conjonction de l'opérateur d'assignement **=.

<?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);
?>

L'exemple ci-dessus va afficher :

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function et use const

L'opérateur use a été étendu pour supporter l'importation de fonctions et de constantes en plus des classes. Ceci est réalisé en utilisant les constructions use function et use const, respectivement.

<?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();
}
?>

L'exemple ci-dessus va afficher :

42
Name\Space\f

phpdbg

PHP inclut désormais un débogueur interactif appelé phpdbg, implémenté comme module SAPI. Pour plus d'informations, visitez la documentation phpdbg.

Encodage de caractères par défaut

default_charset est désormais utilisé comme jeu de caractères par défaut pour les fonctions htmlentities(), html_entity_decode() et htmlspecialchars(). Notez que si les configurations d'encodage (maintenant obsolète) d'iconv et mbstring sont définies, elles prendront le dessus par rapport à la configuration de default_charset pour les fonctions iconv et mbstring, respectivement.

La valeur par défaut pour cette configuration est UTF-8.

php://input est ré-utilisable

php://input peut maintenant être ré-ouvert et lu autant de fois que nécessaire. Ce nouveau mécanisme a permis également de réduire significativement la quantité de mémoire requise lors des opérations POST.

Téléchargement de gros fichiers

Les fichiers de plus de 2 GigaOctets sont maintenant acceptés.

GMP supporte la surcharge d'opérateur

Les objets GMP supportent maintenant la surcharge des opérateurs et le transtypage en types scalaires. Ceci permet un code plus expressif en utilisant 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;
}
?>

L'exemple ci-dessus va afficher :

59
59
59

hash_equals() pour la comparaison des chaîne de caractères permettant d'éviter les attaques de type timing

La fonction hash_equals() a été ajoutée pour comparer deux chaîne de caractères en temps constant. Ceci devrait être utilisé pour éviter les attaques de type timing, par exemple, lors d'un test du hash d'un mot de passe créé via la fonction crypt() (en supposant que vous ne pouvez pas utiliser les fonctions password_hash() et password_verify(), qui ne sont pas sensibles aux attaques de type timing).

<?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));
?>

L'exemple ci-dessus va afficher :

bool(true)
bool(false)

__debugInfo()

La méthode magique __debugInfo() a été ajoutée pour permettre aux objets de changer les propriétés et les valeurs qui sont affichées lorsque l'objet est affiché en utilisant la fonction 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));
?>

L'exemple ci-dessus va afficher :

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

Algorithme de hachage gost-crypto

L'algorithme de hachage gost-crypto a été ajouté. Il implémente la fonction de hachage GOST, en utilisant les tables CryptoPro S-box tel que spécifié par la » RFC 4357, section 11.2.

Améliorations SSL/TLS

Un large éventail d'améliorations ont été réalisé sur le support SSL/TLS en PHP 5.6. Ceci inclut l'activation de la vérification par paire par défaut, supportant la correspondance des certificats d'empreintes, permettant de limiter les attaques à la renégociation TLS, ainsi que plusieurs nouvelles options de contexte SSL permettant un contrôle plus fin du protocole et des vérifications des configurations lors de l'utilisation des flux chiffrés.

Ces modifications sont décrites en détail dans la section sur les changements OpenSSL en PHP 5.6.x du guide de migration.

Support async pgsql

L'extension pgsql supporte désormais les connexions et requêtes asynchrones, en activant un comportement non-bloquant lors de l'interaction avec une base de données PostgreSQL. Les connexions asynchrones peuvent être établies via la constante PGSQL_CONNECT_ASYNC, et les nouvelles fonctions pg_connect_poll(), pg_socket(), pg_consume_input() et pg_flush() peuvent être utilisées pour gérer les connexions et les requêtes asynchrones.

User Contributed Notes

There are no user contributed notes for this page.


Fonctionnalités devenues obsolètes en PHP 5.6.x

Appel depuis un contexte incompatible

L'appel des méthodes depuis un contexte incompatible est désormais obsolète et va générer une erreur E_DEPRECATED au lieu d'une E_STRICT. Le support de ces appels sera retiré dans une version future de PHP.

Un exemple d'un tel appel est :

<?php
class A {
function f() { echo get_class($this); }
}

class B {
function f() { A::f(); }
}

(new B)->f();
?>

L'exemple ci-dessus va afficher :

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 et always_populate_raw_post_data

always_populate_raw_post_data génère désormais une erreur E_DEPRECATED quand la variable $HTTP_RAW_POST_DATA est remplie. Le nouveau code devrait utiliser php://input à la place de $HTTP_RAW_POST_DATA, qui sera supprimé dans une version future de PHP. Vous pouvez basculer vers le nouveau comportement (dans lequel $HTTP_RAW_POST_DATA n'est jamais défini, et donc aucune alerte de niveau E_DEPRECATED ne sera générée) en définissant always_populate_raw_post_data à -1.

Configuration d'encodage iconv et mbstring

Les options de configuration iconv et mbstring relatives à l'encodage sont devenues obsolètes en faveur de l'option default_charset. Les options obsolètes sont :

  • 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.


Fonctions modifiées

Cœur de PHP

  • crypt() lève maintenant une erreur E_NOTICE si le paramètre salt est omit.
  • substr_compare() accepte désormais 0 pour son paramètre length.
  • unserialize() va désormais échouer si les données sérialisées passées ont été manipulées pour instancier un objet sans appeler son constructeur.

cURL

  • L'envoi de fichier en utilisant la syntaxe @file est maintenant uniquement supporté si l'option CURLOPT_SAFE_UPLOAD est définie à false. CURLFile devrait être utilisé à la place.

Mcrypt

  • Le paramètre source de mcrypt_create_iv() a maintenant pour valeur de défaut MCRYPT_DEV_URANDOM à la place de MCRYPT_DEV_RANDOM.

OpenSSL

  • stream_socket_enable_crypto() permet désormais au paramètre crypto_type d'être optionnel si le contexte SSL de flux inclut la nouvelle option crypto_type.

PostgreSQL

  • pg_insert(), pg_select(), pg_update() et pg_delete() ne sont plus à l'état expérimental.
  • pg_send_execute(),
pg_send_prepare(), pg_send_query()
et pg_send_query_params()  ne bloqueront plus jusqu'à
la fin de l'écriture de la requête si la connexion vers la base est
établie en mode non bloquant.

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() autorise désormais les classes internes non-finales à être instanciées.

XMLReader

  • XMLReader::getAttributeNs() et XMLReader::getAttributeNo() retournent maintenant null si l'attribut ne peut être trouvé, comme XMLReader::getAttribute().

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles fonctions

Date et Temps

  • 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.


Changement pour OpenSSL dans PHP 5.6.x

Les wrappers de flux vérifient désormais les certificats d'homologue et les noms d'hôte par défaut lors de l'utilisation de SSL/TLS

Tous les flux clients cryptés activent désormais la vérification par paire par défaut. Par défaut, ceci va utiliser le CA OpenSSL par défaut pour vérifier la paire de certificat. Dans la plupart des cas, aucune modification n'a besoin d'être faite pour communiquer avec des serveurs et des certificats SSL valides, sachant que les distributeurs configurent généralement OpenSSL pour utiliser les CA connus.

Le CA par défaut peut être écrasé sur une base globale en utilisant les options de configuration openssl.cafile ou openssl.capath, ou via une requête basique en utilisant les options de contexte cafile ou capath.

Bien que ce ne soit pas conseillé en général, il est possible de désactiver la vérification de certificats par paire pour une requête en définissant l'option de contexte verify_peer à false, et pour désactiver la validation du nom des paires, en configurant l'option de contexte verify_peer_name à false.

Empreintes digitales de certificat

Le support a été ajouté pour extraire et vérifier les empreintes digitales des certificats. openssl_x509_fingerprint() a été ajouté pour extraire une empreinte digitale d'un certificat X.509 et deux options de contexte de flux SSL ont été ajoutées: capture_peer_cert pour capturer le certificat X.509 de l'homologue et peer_fingerprint pour certifier que le certificat de l'homologue doit correspondre à l'empreinte digitale donnée.

Chiffrements par défaut mis à jour

Les chiffrements par défaut utilisés par PHP ont été mis à jour vers une liste plus sécurisée basée sur les » recommandations de chiffrement de Mozilla, avec deux exclusions supplémentaires: chiffrements Diffie-Hellman anonymes et RC4.

Cette liste est accessible via la nouvelle constante OPENSSL_DEFAULT_STREAM_CIPHERS et peut être remplacée (comme dans les versions précédentes de PHP) en définissant l'option de contexte chiffrements.

Compression désactivée par défaut

La compression SSL/TLS a été désactivée par défaut pour atténuer l'attaque CRIME. PHP 5.4.13 a ajouté une option de contexte disable_compression pour permettre à la compression d'être désactivée: elle est maintenant définie à true (c'est-à-dire que la compression est désactivée) par défaut.

Autoriser les serveurs à préférer leur ordre de chiffrement

L'option de contexte SSL honor_cipher_order a été ajoutée pour permettre aux serveurs de flux chiffrés d'atténuer les vulnérabilités de BEAST en préférant les chiffrements du serveur au client.

Accéder au protocole négocié et au chiffrement

Le protocole et le chiffrement qui ont été négociés pour un flux chiffré peuvent désormais être accédé via stream_get_meta_data() ou stream_context_get_options() lorsque l'option de contexte SSL capture_session_meta est définie à 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);
?>

L'exemple ci-dessus va afficher :

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

De nouvelles options pour la confidentialité persistante sur les serveurs de flux chiffrés

Les flux de clients chiffrés prennent déjà en charge la confidentialité persistante, car il est généralement contrôlé par le serveur. Les flux de serveurs chiffrés en PHP à l'aide de certificats capables d'une confidentialité persistante n'ont pas besoin de prendre d'autres mesures pour activer PFS; Toutefois, un certain nombre de nouvelles options de contexte SSL ont été ajoutées pour permettre un plus grand contrôle sur PFS et traiter les problèmes de compatibilité qui peuvent survenir.

ecdh_curve

Cette option permet de sélectionner une courbe spécifique à utiliser avec les chiffrements ECDH. S'il n'est pas spécifié, prime256v1 sera utilisé.

dh_param

Chemin d'accès à un fichier contenant des paramètres pour l'échange de clés Diffie-Hellman, tel que celui créé par la commande suivante :

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

Si définie à true, une nouvelle paire de clés sera créée lors de l'utilisation des paramètres Diffie-Hellman, améliorant ainsi la confidentialité persistante.

single_ecdh_use

Si définie à true, une nouvelle paire de clés sera toujours générée lors de la négociation des suites de chiffrement ECDH. Cela améliore la confidentialité persistante.

Sélection de la version SSL/TLS

Il est désormais possible de sélectionner des versions spécifiques de SSL et TLS via l'option de contexte SSL crypto_method ou en spécifiant un transport spécifique lors de la création d'un wrapper de flux (par exemple, en appelant stream_socket_client() ou stream_socket_ serveur()).

L'option de contexte SSL crypto_method accepte un masque de bits énumérant les protocoles qui sont autorisés, comme le fait le crypto_type de stream_socket_enable_crypto().

Versions de protocole sélectionnées et options correspondantes
Pprotocole(s) | Drapeau client | Drapeau serveur | Transport
Toute version TLS ou SSL | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Toute version TLS | 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

// Nécessitant TLS 1.0 ou mieux lors de l'utilisation de file_get_contents():
$ctx = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Nécessitant TLS 1.1 ou 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);

// Connexion à l'aide du transport de socket tlsv1.2://.
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

Ajout de openssl_get_cert_locations()

La fonction openssl_get_cert_locations() a été ajoutée : elle renvoie les emplacements par défaut que PHP recherchera lors de la recherche de paquets CA.

<?php
var_dump(openssl_get_cert_locations());
?>

L'exemple ci-dessus va afficher :

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) ""
}

Support de SPKI

Le support a été ajouté pour générer, extraire et vérifier les clés et les défis publics signés (SPKAC). openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge() et openssl_spki_export() ont été ajoutées pour créer, vérifier la clé publique PEM d'exportation et le défi associé de SPKAC générés à partir d'un élément HTML5 KeyGen.

openssl_spki_new

Génère un nouveau SPKAC en utilisant la clé privée, chaîne de caractères de défi et l'algorithme de hachage.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

L'exemple ci-dessus va afficher :

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Vérifie le SPKAC fourni.

<?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

Exportations du défi associé au SPKAC fourni.

<?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;
?>

L'exemple ci-dessus va afficher :

challenge string
openssl_spki_export

Exporte la clé publique RSA au format PEM du SPAKC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

L'exemple ci-dessus va afficher :

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcvQh9SKOPv4DwI8LwSaFx02h7
l9QCiDs6sF2GfsSTEUG61SnjQ/v4uJiLKBgbVOagj9rkSCwtTez23ATPeGaBj2Zg
ipv+tv5IXyqUP8ropXJQ5ELtbXPUN/gvw7cO5EbPHr/7eMhbpw8Gl+AfWxW5hLW8
MGw/+AwwjHBOwong/QIDAQAB
-----END PUBLIC KEY-----

User Contributed Notes

There are no user contributed notes for this page.


Autres modifications dans les extensions

cURL

Un certain nombre de constantes de la bibliothèque cURL, précédemment marqué comme obsolète, ont été supprimés :

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • Le support des jeux de résultats implicites pour Oracle Database 12c a été ajouté via la nouvelle fonction oci_get_implicit_resultset().
  • Utiliser oci_execute($s, OCI_NO_AUTO_COMMIT) pour un SELECT ne lance plus nécessairement un ROLLBACK interne lors la fermeture de la connexion.
  • Ajout de sondes DTrace contrôlées par l'option de configuration --enable-dtrace.
  • oci_internal_debug() n'a plus d'effet.
  • Le format de sortie de phpinfo() pour OCI8 a changé.

Zip

Une option de configuration --with-libzip est ajoutée pour utiliser une installation système de libzip. La version 0.11 de libzip est requise, mais il est recommandé d'utiliser une version 0.11.2 ou plus récente.

MySQLi

Une nouvelle option mysqli.rollback_on_cached_plink a été ajoutée, elle contrôle le comportement de restauration des connexions persistantes.

User Contributed Notes

There are no user contributed notes for this page.


Nouvelles constantes globales

GD

  • IMG_WEBP (depuis 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.


Débogueur PHP

Sommaire

  • À propos du débogueur en PHP

User Contributed Notes

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!


À propos du débogueur en PHP

PHP embarque un débogueur interactif en ligne de commande de base phpdbg.

La plupart des IDE ont une prise en charge de » Xdebug, un outil de débogage gratuit, qui permet de déboguer pas à pas votre code PHP.

User Contributed Notes

There are no user contributed notes for this page.


Options de configuration

Sommaire

  • Liste des options de configuration internes

User Contributed Notes

There are no user contributed notes for this page.


Liste des options de configuration internes

Ci-dessous une liste partielle des options de configuration utilisées par le script PHP configure lors de la compilation sur les systèmes Unix et assimilés. La plupart des options de configuration sont listées dans leur emplacement approprié sur les pages de référence de l'extension et non pas ici. Pour une liste complète des options de configuration, exécutez la commande ./configure --help dans le répertoire contenant les sources de PHP après avoir exécuté la commande autoconf (voir aussi le chapitre sur l'installation de PHP). Vous pouvez également être intéressé par la lecture de la documentation sur la » configuration GNU pour plus d'informations sur les options de la commande configure comme --prefix=PREFIX.

Note:

Elles sont également utilisées lors de la compilation. Si vous voulez modifier la configuration de l'exécution de PHP, lisez le chapitre sur la configuration de l'exécution.

  • Divers
  • Comportement de PHP
  • Serveur

Options de configuration

Options diverses

--enable-debug

Compile en activant les symboles de débogage

--with-layout=TYPE

Spécifie la façon dont les fichiers installés seront présentés. TYPE peut valoir PHP (valeur par défaut) ou GNU. Notez que si vous installez les pages de manuel sous PREFIX (par défaut), choisissez le style GNU afin qu'elles puissent être trouvées dans le chemin de recherche de l'utilitaire manpath.

--with-pear=DIR

Installe PEAR dans le dossier DIR (par défaut, PREFIX/lib/php).

--without-pear

Ne pas installer PEAR.

--enable-sigchild

Active le propre traitement du SIGCHLD de PHP.

--disable-rpath

Désactive le passage de chemins additionnels de recherche de bibliothèques d'exécution.

--enable-libgcc

Active explicitement le lien avec la bibliothèque libgcc.

--enable-php-streams

Inclut le support expérimental des flux PHP. Utilisez-le seulement si vous testez le code !

--with-zlib-dir[=DIR]

Définit le chemin du répertoire d'installation de la bibliothèque zlib.

--with-tsrm-pthreads

Utilise les threads POSIX (par défaut).

--enable-shared[=PKGS]

Compile les bibliothèques de partage [defaut=oui].

--enable-static[=PKGS]

Compile les bibliothèques statiques [default=oui].

--enable-fast-install[=PKGS]

Optimise pour une installation rapide [default=oui].

--with-gnu-ld

Le compilateur C utilise GNU ld [default=non].

--disable-libtool-lock

Évite de verrouiller (cela pourrait casser des constructions parallèles).

--with-pic

Tente d'utiliser uniquement les objets PIC/non-PIC [default=utilisation des deux].

--enable-versioning

Exporte uniquement les symboles requis. Voir le fichier INSTALL pour plus d'informations.

Options PHP

--enable-maintainer-mode

Active des règles de compilation (make) et des dépendances pas toujours utiles aux utilisateurs occasionnels.

--with-config-file-path=PATH

Indique le chemin dans lequel réside le fichier php.ini. Par défaut, c'est PREFIX/lib.

--disable-short-tags

Désactive les balises courtes <?.

--with-libdir

Précise le chemin vers les bibliothèques de construction Unix pour construire PHP. Pour les systèmes 64bits, vous devez renseigner le dossier lib64 comme cela: --with-libdir=lib64.

--enable-zts

Active la sécurité des threads. Antérieur à PHP 8.0.0 sur les systèmes non-Windows, l'option était appelée --enable-maintainer-zts.

Options SAPI

La liste suivante contient les options valides SAPI&s (Server Application Programming Interface) pour PHP.

--with-apxs[=FILE]

Compile un module Apache partagé. FILE est un chemin d'accès optionnel vers les outils apxs d'Apache. Par défaut, c'est apxs. Assurez-vous de spécifier la version d'apxs qui est réellement installée sur votre système, et NON pas celle qui est fournie avec Apache.

--with-apache[=DIR]

Compile le module Apache. DIR est le chemin du dossier d'installation d'Apache. Par défaut, DIR vaut /usr/local/apache.

--with-mod_charset

Active les tables de transfert pour mod_charset (version russe de Apache).

--with-apxs2[=FILE]

Compile le module partagé Apache 2.0. FILE est un chemin d'accès optionnel vers les outils apxs d'Apache. Par défaut, c'est apxs.

--disable-cli

Empêche la compilation de la version CLI de PHP (cela force aussi l'option --without-pear). Plus d'informations dans la section sur l'utilisation de PHP en ligne de commande.

--enable-phpdbg

Active le support du module SAPI de débogage interactif phpdbg.

--enable-embed[=TYPE]

Active la compilation de la bibliothèque intégrée SAPI. TYPE vaut soit shared, soit static. Par défaut, c'est shared.

--with-servlet[=DIR]

Inclut le support des servlets. DIR est le chemin d'installation du JSDK. Cette SAPI impose que l'extension java soit compilée comme une bibliothèque partagée.

--disable-cgi

Empêche la compilation de la version CGI de PHP.

Cet argument active aussi FastCGI.

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


Directives du php.ini

Sommaire

  • Liste des directives du php.ini
  • Liste des sections du fichier php.ini
  • Description des directives internes du php.ini

User Contributed Notes

There are no user contributed notes for this page.


Liste des directives du php.ini

Cette liste inclut les directives du php.ini que vous pouvez définir pour configurer votre installation de PHP.

La colonne "Modifiable" montre les modes déterminant quand et où une directive peut être définie. Voir la section sur les valeurs du mode modifiable pour leurs définitions.

Options de configuration
Nom | Défaut | Modifiable | Historique
allow_url_fopen | "1" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | Obsolète à partir de 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 | Supprimé à partir de PHP 8.0.0.
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 |
cli.prompt | "\\b \\> " | PHP_INI_ALL |
cli_server.color | "0" | PHP_INI_ALL |
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 | À partir de PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
curl.cainfo | NULL | PHP_INI_SYSTEM |
date.default_latitude | "31.7667" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.833333" | PHP_INI_ALL | Avant PHP 8.0.0, la valeur par défaut était "90.583333"
date.sunset_zenith | "90.833333" | PHP_INI_ALL | Avant PHP 8.0.0, la valeur par défaut était "90.583333"
date.timezone | "UTC" | PHP_INI_ALL | À partir de PHP 8.2, un avertissement est émis si l'option est définie avec une valeur invalide ou une chaîne vide.
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | Par défaut "UTF-8".
input_encoding | "" | PHP_INI_ALL |
output_encoding | "" | PHP_INI_ALL |
internal_encoding | "" | PHP_INI_ALL |
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
disable_classes | "" | php.ini uniquement |
disable_functions | "" | php.ini uniquement |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "1" | PHP_INI_ALL | Antérieur à PHP 8.0.0, la valeur par défaut était "0".
docref_ext | "" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | Cette fonctionnalité obsolète sera certainement supprimée dans le futur.
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_log_mode | 0o644 | PHP_INI_ALL | Disponible à partir de PHP 8.2.0
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 uniquement |
extension | NULL | php.ini uniquement |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |
file_uploads | "1" | PHP_INI_SYSTEM |
filter.default | "unsafe_raw" | PHP_INI_PERDIR | Obsolète à partir de PHP 8.1.0.
filter.default_flags | NULL | PHP_INI_PERDIR |
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL |
geoip.custom_directory | "" | PHP_INI_ALL |
hard_timeout | "2" | PHP_INI_SYSTEM | Disponible à partir de 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 | Disponible depuis ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Disponible depuis ibm_db2 1.5.0.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Disponible depuis ibm_db2 1.0.2.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM |
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Disponible depuis ibm_db2 1.8.0.
iconv.input_encoding | "" | PHP_INI_ALL | Obsolète en PHP 5.6.0.
iconv.output_encoding | "" | PHP_INI_ALL | Obsolète en PHP 5.6.0.
iconv.internal_encoding | "" | PHP_INI_ALL | Obsolète en 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 | Disponible à partir de PECL 3.0.0a1
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 uniquement |
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 |
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.http_input | "pass" | PHP_INI_ALL | Obsolète
mbstring.http_output | "pass" | PHP_INI_ALL | Obsolète
mbstring.internal_encoding | NULL | PHP_INI_ALL | Obsolète
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | Obsolète à partir de PHP 7.2.0; supprimée à partir de PHP 8.0.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL |
mbstring.strict_detection | "0" | PHP_INI_ALL |
mbstring.regex_retry_limit | "1000000" | PHP_INI_ALL | Disponible à partir de PHP 7.4.0.
mbstring.regex_stack_limit | "100000" | PHP_INI_ALL | Disponible à partir de PHP 7.3.5.
mcrypt.algorithms_dir | null | PHP_INI_ALL |
mcrypt.modes_dir | null | PHP_INI_ALL |
memcache.allow_failover | "1" | PHP_INI_ALL | Disponible à partir de memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Disponible à partir de memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Disponible à partir de memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Disponible à partir de memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Disponible à partir de memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Disponible à partir de memcache 2.2.0.
memcache.protocol | ascii | PHP_INI_ALL | Supporté à partir de memcache 3.0.0
memcache.redundancy | 1 | PHP_INI_ALL | Supporté à partir de memcache 3.0.0
memcache.session_redundancy | 2 | PHP_INI_ALL | Supporté à partir de memcache 3.0.0
memcache.compress_threshold | 20000 | PHP_INI_ALL | Supporté à partir de memcache 3.0.3
memcache.lock_timeout | 15 | PHP_INI_ALL | Supporté à partir de memcache 3.0.4
memory_limit | "128M" | 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 | "Off" | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
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 |
mysqli.allow_local_infile | "0" | PHP_INI_SYSTEM | Antérieur à PHP 7.2.16 et 7.3.3 la valeur par défaut était "1".
mysqli.local_infile_directory |  | PHP_INI_SYSTEM | Disponible à partir de PHP 8.1.0.
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM |
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM |
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 |
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Supprimée à partir de PHP 8.2.0
mysqli.rollback_on_cached_plink | "0" | PHP_INI_SYSTEM |
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 | Avant PHP 7.2.0 la valeur par défaut était "31536000" et la variabilité était 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 | Supprimé à partir de PHP 8.1.0
oci8.connection_class | "" | PHP_INI_ALL |
oci8.default_prefetch | "100" | PHP_INI_SYSTEM |
oci8.events | Off | PHP_INI_SYSTEM |
oci8.max_persistent | "-1" | PHP_INI_SYSTEM |
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Obsolète à partir de PHP 8.1.0.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM |
oci8.ping_interval | "60" | PHP_INI_SYSTEM |
oci8.prefetch_lob_size | "0" | PHP_INI_SYSTEM | Disponible à partir de PECL OCI8 3.2.
oci8.privileged_connect | Off | PHP_INI_SYSTEM |
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM |
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 |
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | Entre PHP 7.1.2 et 7.1.6 inclusivement, la valeur par défaut était de "1"
opcache.memory_consumption | "128" | PHP_INI_SYSTEM |
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM |
opcache.max_accelerated_files | "10000" | PHP_INI_SYSTEM |
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.fast_shutdown | "0" | PHP_INI_SYSTEM | Supprimé en PHP 7.2.0.
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFEBFFF" | PHP_INI_SYSTEM | Modifié depuis 0x7FFFBFFF en PHP 7.3.0
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | Supprimé en 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 | >Désactivé à partir de PHP 8.1.18 et 8.2.5. Supprimé à partir de PHP 8.3.0.
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.record_warnings | "0" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0.
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 | Disponible à partir de PHP 7.1.0
opcache.file_cache | NULL | PHP_INI_SYSTEM |
opcache.file_cache_only | "0" | PHP_INI_SYSTEM |
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM |
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | Windows uniquement.
opcache.validate_permission | "0" | PHP_INI_SYSTEM | Disponible à partir de PHP 7.0.14
opcache.validate_root | "0" | PHP_INI_SYSTEM | Disponible à partir de PHP 7.0.14
opcache.preload | "" | PHP_INI_SYSTEM | Disponible à partir de PHP 7.4.0
opcache.preload_user | "" | PHP_INI_SYSTEM | Disponible à partir de PHP 7.4.0
opcache.cache_id | "" | PHP_INI_SYSTEM | Windows uniquement. Disponible à partir de PHP 7.4.0
opcache.jit | "tracing" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_buffer_size | "0" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_debug | "0" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_bisect_limit | "0" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_prof_threshold | "0.005" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_max_root_traces | "1024" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_max_side_traces | "128" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_max_exit_counters | "8192" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_hot_loop | "64" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_hot_func | "127" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_hot_return | "8" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_hot_side_exit | "8" | PHP_INI_SYSTEM | Disponible à partir de PHP 8.0.0
opcache.jit_blacklist_root_trace | "16" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_blacklist_side_trace | "8" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_max_loop_unrolls | "8" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_max_recursive_calls | "2" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_max_recursive_returns | "2" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
opcache.jit_max_polymorphic_calls | "2" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0
open_basedir | NULL | PHP_INI_ALL |
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
pcre.backtrack_limit | "1000000" | PHP_INI_ALL |
pcre.recursion_limit | "100000" | PHP_INI_ALL |
pcre.jit | "1" | PHP_INI_ALL |
pdo.dsn.* |  | php.ini seulement |
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL |
pdo_odbc.db2_instance_name | null | PHP_INI_SYSTEM | Cette fonctionnalité obsolète sera certainement supprimée dans le futur.
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 |
pgsql.ignore_notice | "0" | PHP_INI_ALL |
pgsql.log_notice | "0" | PHP_INI_ALL |
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 | Antérieur à PHP 7.1.0, la valeur par défaut était 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 | "0" | PHP_INI_ALL | Antérieur à PHP 7.2.0, la valeur par défaut était "".
session.cookie_httponly | "0" | PHP_INI_ALL | Antérieur à PHP 7.2.0, la valeur par défaut était "".
session.cookie_samesite | "" | PHP_INI_ALL | Disponible à partir de PHP 7.3.0.
session.use_strict_mode | "0" | PHP_INI_ALL |
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 | Disponible à partir de PHP 7.1.0.
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | Disponible à partir de PHP 7.1.0.
session.sid_length | "32" | PHP_INI_ALL | Disponible à partir de PHP 7.1.0.
session.sid_bits_per_character | "4" | PHP_INI_ALL | Disponible à partir de 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 | Supprimé à partir de PHP 7.1.0
session.hash_bits_per_character | "4" | PHP_INI_ALL | Supprimé à partir de PHP 7.1.0
session.entropy_file | "" | PHP_INI_ALL | Supprimé à partir de PHP 7.1.0.
session.entropy_length | "0" | PHP_INI_ALL | Supprimé à partir de 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 |
sqlite3.defensive | 1 | PHP_INI_USER | Disponible à partir de PHP 7.2.17 et 7.3.4 pour libsqlite = 3.26.0. Antérieur à PHP 8.2.0 ce paramètre pouvait seulement être modifié en tant que PHP_INI_SYSTEM.
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | Disponible à partir de PHP 7.3.0.
syslog.filter | "no-ctrl" | PHP_INI_ALL | Disponible à partir de PHP 7.3.0.
syslog.ident | "php" | PHP_INI_SYSTEM | Disponible à partir de 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 |
track_errors | "0" | PHP_INI_ALL | Obsolète à partir de PHP 7.2.0, supprimée à partir de PHP 8.0.0.
unserialize_callback_func | null | PHP_INI_ALL |
unserialize_max_depth | "4096" | PHP_INI_ALL | Disponible à partir de PHP 7.4.0.
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 | Disponible à partir de uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Disponible à partir de uopz 6.0.1
uopz.overloads | "1" | PHP_INI_SYSTEM | Disponible à partir de uopz 2.0.2. Supprimé à partir de uopz 5.0.0.
variables_order | "EGPCS" | PHP_INI_PERDIR |
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 | Disponible à partir de 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.


Liste des sections du fichier php.ini

Cette liste inclut les sections du php.ini que vous pouvez ajuster pour configurer votre PHP selon l'hôte virtuel ou le chemin. Ces sections sont optionnelles.

Ces sections n'affectent pas directement PHP. Elles sont utilisées pour grouper les autres directives de configuration du php.ini et pour les appliquer à un hôte ou à un chemin particulier.

Ces sections ne sont utilisées qu'en mode CGI/FastCGI et elles ne peuvent définir des extensions et des directives zend_extension.

Sections
Nom | Modifiable | Historique
[HOST=] | PHP_INI_SYSTEM |
[PATH=] | PHP_INI_SYSTEM |

Voici un éclaircissement sur l'utilisation des directives de configuration.

[HOST=<host>]

Cette section vous permet de définir un jeu de directives du php.ini qui prendront effet sur l'hôte spécifié.

Exemple #1 Active la sortie d'erreur à l'écran pour dev.site.com

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

Cette section vous permet de définir un jeu de directives du php.ini qui prendront effet quand un script sera lancé depuis le chemin spécifié.

Exemple #2 Ajoute un script de sécurité pour les zones protégées

[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).


Description des directives internes du php.ini

Cette liste inclut les directives internes du php.ini que vous pouvez définir pour personnaliser votre configuration de PHP. Les directives gérées par les extensions sont listées et détaillées dans les pages de documentation respectives des extensions ; les informations concernant les directives sur les sessions, par exemple, peuvent être trouvées sur la page de documentation des sessions.

Note:

Les valeurs par défaut listées ici seront utilisées lorsque php.ini n'est pas chargé ; les valeurs des fichiers php.ini en environnement de production et en environnement de développement peuvent varier.

Options du langage

Options de configuration
Nom | Défaut | Modifiable | Historique
short_open_tag | "1" | PHP_INI_ALL |
precision | "14" | PHP_INI_ALL |
serialize_precision | "-1" | PHP_INI_ALL | Antérieur à PHP 7.1.0, la valeur par défaut était 17.
disable_functions | "" | PHP_INI_SYSTEM uniquement |
disable_classes | "" | php.ini only |
exit_on_timeout | "" | PHP_INI_ALL |
expose_php | "1" | php.ini uniquement |
hard_timeout | "2" | PHP_INI_SYSTEM | Disponible à partir de PHP 7.1.0.
zend.exception_ignore_args | "0" | PHP_INI_ALL | Disponible à partir de PHP 7.4.0
zend.multibyte | "0" | PHP_INI_ALL |
zend.script_encoding | NULL | PHP_INI_ALL |
zend.detect-unicode | NULL | PHP_INI_ALL |
zend.signal_check | "0" | PHP_INI_SYSTEM |
zend.assertions | "1" | PHP_INI_ALL avec des restrictions |
zend.exception_string_param_max_len | "15" | PHP_INI_ALL | Disponible à partir de PHP 8.0.0.

Voici un éclaircissement sur l'utilisation des directives de configuration.

short_open_tag bool

Définit si les balises courtes d'ouverture de PHP (<? ?>) sont autorisées ou non. Si vous voulez utiliser PHP avec XML, vous devez désactiver cette option de configuration pour pouvoir utiliser <?xml ?>. Sinon, vous pouvez l'écrire à l'aide de PHP, par exemple : <?php echo '<?xml version="1.0">'; ?>. Si cette option est désactivée, vous devez utiliser la version longue d'ouverture de balises PHP (<?php ?>).

Note:

Cette directive n'affecte pas l'utilisation de <?=, qui est toujours disponible.

precision int
Le nombre de décimales significatives à afficher dans les nombres à virgule flottante. -1 signifie que le meilleur algorithme pour arrondir ce nombre sera utilisé.
serialize_precision int
Le nombre de chiffres significatifs conservés lors de la sérialisation des nombres à virgule flottante. -1 signifie que le meilleur algorithme pour arrondir ce nombre sera utilisé.
expose_php bool

Expose à tous les clients le fait que PHP est installé sur le serveur. Ceci inclut la version de PHP dans les en-têtes HTTP de la réponse (X-Powered-By : PHP/5.3.7).

disable_functions string

Cette directive vous permet de désactiver certaines fonctions. Elle prend une liste de noms de fonction délimités par une virgule.

Seules les fonctions internes peuvent être désactivées en utilisant cette directive. Les fonctions définies par l'utilisateur ne sont pas affectées.

Cette directive doit être définie dans le php.ini. Par exemple, vous ne pouvez pas la définir dans le fichier httpd.conf.

disable_classes string
Cette directive vous permet de désactiver certaines classes. Elle prend une liste de noms de classes délimités par une virgule. Cette directive doit être définie dans le php.ini. Par exemple, vous ne pouvez pas la définir dans le fichier httpd.conf.
zend.assertions int
Lorsque défini à 1, le code d'assertion sera généré (en mode développement). Lorsque défini à 0, le code d'assertion sera généré, mais sera ignoré (il ne sera pas exécuté) pendant l'exécution. Lorsque défini à -1, le code d'assertion ne sera pas généré, rendant ainsi les assertions totalement neutres (en mode production).

Note:

Si un processus est démarré en mode production, zend.assertions ne peut être changé en cours d'exécution, sachant que le code pour les assertions n'a pas été généré.

Si un processus est démarré en mode développement, zend.assertions ne peut être défini à -1 en cours d'exécution.

zend.exception_string_param_max_len int
La longueur maximale des arguments fonction de chaînes dans les traces de piles convertit sous forme de chaîne. Doit être dans l'intervalle entre "0" et "1000000".
hard_timeout int

Quand le timeout défini dans max_execution_time est atteint, le runtime PHP détruira les ressources gracieusement. Si quelque chose se coince quand ceci se produit, le hard timeout se déclenchera pour le nombre de secondes défini. Quand le hard timeout est atteint, PHP quittera de manière non gracieuse. Quand défini à 0, le hard timeout ne s'activera jamais.

Quand PHP termine d'un hard timeout, ça ressemblera à quelque chose du genre :

Fatal error: Maximum execution time of 30+2 seconds exceeded (terminated) in Unknown on line 0

zend.exception_ignore_args bool

Exclut les arguments dans les stack traces générées depuis les exceptions.

zend.multibyte bool

Active l'analyse lexicale des fichiers PHP dans des encodages multioctets. L'activation de zend.multibyte est nécessaire pour utiliser certains encodages de caractères comme SJIS, BIG5, etc. qui contiennent des caractères spéciaux en encodage multioctets. Les encodages compatibles avec ISO-8859-1 comme UTF-8, EUC, etc. ne nécessitent pas cette option.

Activer zend.multibyte requiert l'extension mbstring.

zend.script_encoding string

Cette valeur sera utilisée à moins qu'une directive declare(encoding=...) n'apparaisse en haut du script. Lorsqu'un encodage incompatible ISO-8859-1 est utilisé, les options zend.multibyte et zend.script_encoding doivent être utilisées.

Les chaines de caractères seront converties depuis zend.script_encoding vers mbstring.internal_encoding, comme si mb_convert_encoding() avait été appelé.

zend.detect_unicode bool

Vérifie le BOM (Byte Order Mark) et regarde si le fichier contient des caractères multioctets valides. Cette détection est effectuée avant le lancement de la fonction __halt_compiler(). Disponible uniquement en mode Zend multioctets.

zend.signal_check bool

Vérifie si un gestionnaire de signaux de remplacement est utilisé lors de l'arrêt.

exit_on_timeout bool

Ceci est une directive Apache1 mod_php uniquement, qui force les fils Apache à sortir si une expiration de délai d'exécution PHP survient. Une telle expiration de délai produit en interne un appel à longjmp() en Apache1 qui peut quitter certaines extensions dans un statut non consistant. En terminant le processus, tous les verrous et la mémoire seront nettoyés.

Limite des ressources

Options de configuration
Nom | Défaut | Modifiable | Historique
memory_limit | "128M" | PHP_INI_ALL |

Voici un éclaircissement sur l'utilisation des directives de configuration.

memory_limit int

Cette option détermine la mémoire limite, en octets, qu'un script est autorisé à allouer. Cela permet de prévenir l'utilisation de toute la mémoire par un script mal codé. Notez que pour n'avoir aucune limite, vous devez définir cette directive à -1.

Lorsqu'un entier est utilisé, sa valeur est mesurée en octets. Vous pouvez également utiliser la notation sténographique comme décrit dans cette entrée de la FAQ..

Voir aussi : max_execution_time.

Réglage de Performance

Réglage de Performance
Nom | Défaut | Modifiable | Historique
realpath_cache_size | "4M" | PHP_INI_SYSTEM | Antérieur à PHP 7.0.16 et 7.1.2, la valeur par défaut était "16K"
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |

Note:

Utiliser open_basedir désactivera le cache realpath.

Voici un éclaircissement sur l'utilisation des directives de configuration.

realpath_cache_size int

Détermine la taille du cache de realpath qui sera utilisée par PHP. Cette valeur devrait être augmentée sur les systèmes où PHP ouvre plusieurs fichiers, pour refléter la quantité d'opérations exécutées sur les fichiers.

La taille représente le nombre total d'octets dans la chaîne stockée du chemin, plus la taille des données associées avec l'entrée du cache. Cela signifie que pour stocker de grands chemins dans le cache, la taille du cache doit être suffisamment grande. Cette valeur ne contrôle pas directement le nombre de chemins distincts qui peuvent être mis en cache.

La taille nécessaire pour les données de l'entrée du cache est dépendante du système.

realpath_cache_ttl int

Temps (en seconde) pour lequel persiste l'information du cache de realpath pour un fichier ou un répertoire donné. Pour des systèmes avec des fichiers qui changent peu souvent, pensez à augmenter cette valeur.

Gestion des données

Options de configuration
Nom | Défaut | Modifiable | Historique
arg_separator.output | "&" | PHP_INI_ALL |
arg_separator.input | "&" | PHP_INI_PERDIR |
variables_order | "EGPCS" | PHP_INI_PERDIR |
request_order | "" | PHP_INI_SYSTEM|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 |
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 |

Voici un éclaircissement sur l'utilisation des directives de configuration.

arg_separator.output string

Le séparateur utilisé lorsque PHP génère les URL pour séparer les arguments.

arg_separator.input string

Liste des séparateur(s) utilisé(s) par PHP pour analyser les URL entrantes et en déduire les valeurs.

Note:

Chaque caractère de cette directive est considéré comme étant un séparateur !

variables_order string

Définit l'ordre d'analyse des variables EGPCS (Environment, Get, Post, Cookie, et Server). Par exemple, si variables_order est défini à "SP" alors PHP créera superglobals $_SERVER et $_POST, mais ne créera pas $_ENV, $_GET, et $_COOKIE. Le fait de définir cet ordre à "" signifie qu'aucune superglobals ne sera définie.

Avertissement

En SAPIs CGI et FastCGI, $_SERVER est également peuplé de valeurs de l'environnement ; S est toujours équivalent à ES au regard de la position de E autre part dans cette directive.

Note:

Le contenu et l'ordre de $_REQUEST sont également affectés par cette directive.

request_order string

Cette directive décrit l'ordre dans lequel PHP place les variables GET, POST et Cookie dans le tableau _REQUEST. Le placement s'effectue de la gauche vers la droite, les valeurs les plus récentes écrasant les valeurs plus anciennes.

Si cette directive n'est pas définie, variables_order est utilisé pour le contenu de $_REQUEST.

Notez que les fichiers php.ini de la distribution par défaut ne contiennent pas 'C' pour les cookies, ceci pour des raisons de sécurité.

auto_globals_jit bool

Quand cette directive est activée, les variables SERVER , REQUEST et ENV sont créées lorsqu'elles sont utilisées : seulement si nécessaire. Si ces variables ne sont pas utilisées dans un script, le script verra un gain de performances.

Avertissement

L'utilisation des variables SERVER, REQUEST et ENV est vérifiée lors de la compilation. Ainsi, les utiliser avec, par exemple, des variables dynamiques ne provoquera pas leur initialisation.

register_argc_argv bool
Dit à PHP s'il doit déclarer ou non les variables argv et argc (qui contiendront les informations GET). Voir aussi les lignes de commande.
enable_post_data_reading bool
Le fait de désactiver cette option fera que les variables $_POST et $_FILES ne seront pas peuplées. La seule façon de lire les données transmises sera alors d'utiliser le gestionnaire de flux php://input. Ceci peut être intéressant pour les requêtes via un proxy ou pour analyser les données transmises directement en mémoire.
post_max_size int
Définit la taille maximale des données reçues par la méthode POST. Cette option affecte également les fichiers chargés. Pour charger de gros fichiers, cette valeur doit être plus grande que la valeur de upload_max_filesize. De façon générale, memory_limit doit être plus grand que post_max_size. Lorsqu'un entier est utilisé, sa valeur est mesurée en octets. Vous pouvez également utiliser la notation sténographique comme décrit dans cette entrée de la FAQ.. Dans le cas où la taille des données reçues par la méthode POST est plus grande que post_max_size, les superglobales $_POST et $_FILES seront vides. Ceci peut être surveillé de différentes façons, e.g. en passant une variable $_GET au script qui traite les données, i.e. <form action="edit.php?processed=1">, et ainsi vérifier si $_GET['processed'] est défini.

Note:

PHP autorise des mots-clés pour les octets, incluant K (kilo), M (méga) et G (giga). PHP effectue la conversion automatiquement si vous les utilisez. Soyez attentif de ne pas dépasser la limite d'un entier signé sur 32 bits (si vous utilisez les versions 32 bits), auquel cas votre script échouera.

Historique pour post_max_size
Version | Description
5.3.4 | post_max_size = 0 ne va pas désactiver la limite lorsque le type de contenu est application/x-www-form-urlencoded ou s'il n'est pas enregistré avec PHP.
5.3.2 , 5.2.12 | Permet une taille d'envoi illimitée en définissant post_max_size à 0.

auto_prepend_file string

Spécifie le nom d'un fichier qui sera automatiquement parcouru avant le fichier principal. Ce fichier est inclus comme s'il l'avait été avec la fonction require, donc include_path est utilisé.

La valeur spéciale none désactive l'ajout automatique.

auto_append_file string

Spécifie le nom du fichier qui sera automatiquement parcouru après le fichier principal. Ce fichier est inclus comme s'il l'avait été avec la fonction require, donc include_path est utilisé.

La valeur spéciale none désactive l'ajout automatique.

Note: Si le script se termine par la fonction exit(), l'ajout automatique ne se fera pas.

default_mimetype string

Par défaut, PHP va envoyer le type de média en utilisant l'entête Content-Type. Pour désactiver ceci, laissez vide cette valeur.

Le type de média défini par défaut dans PHP est text/html.

default_charset string

"UTF-8" est la valeur par défaut et celle-ci est utilisée comme jeu de caractères par défaut pour les fonctions et modules. PHP enverra toujours un jeu de caractères par défaut pour htmlentities(), html_entity_decode() et htmlspecialchars() si le paramètre encoding est omis. La valeur de default_charset sera également utilisée pour définir le jeu de caractères par défaut pour les fonctions iconv si les options de configuration iconv.input_encoding, iconv.output_encoding et iconv.internal_encoding ne sont pas définies, et pour les fonctions mbstring si les options de configuration mbstring.http_input, mbstring.http_output et mbstring.internal_encoding ne sont pas définies.

Toutes les versions de PHP vont utiliser cette valeur comme jeu de caractères par défaut dans l'en-tête par défaut Content-Type envoyé par PHP si l'en-tête n'est pas écrasé via un appel à la fonction header().

Définir un default_charset à une valeur vide n'est pas recommandé.

input_encoding string

Ce paramètre est utilisé pour les modules multibytes tels que mbstring et iconv. Vide par défaut.

output_encoding string

Ce paramètre est utilisé pour les modules multibytes tels que mbstring et iconv. Vide par défaut.

internal_encoding string

Ce paramètre est utilisé pour les modules multibytes tels que mbstring et iconv. Vide par défaut. Si vide alors, default_charset est utilisé.

Chemins et répertoires

Options de configuration
Nom | Défaut | Modifiable | Historique
include_path | ".;/chemin/vers/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 | "/chemin/vers/php" | PHP_INI_SYSTEM |
extension | NULL | php.ini uniquement |
zend_extension | NULL | php.ini uniquement |
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 |

Voici un éclaircissement sur l'utilisation des directives de configuration.

include_path string

Spécifie une liste de répertoires où les fonctions require, include, fopen(), file(), readfile() et file_get_contents() chercheront les fichiers. Le format est identique à la variable d'environnement système PATH : une liste de répertoires séparés par deux points (:) sous Unix ou par un point-virgule (;) sous Windows.

PHP considère chaque entrée du chemin d'inclusion séparément lors de la recherche des fichiers à inclure. Il va vérifier le premier chemin, et s'il ne trouve pas le fichier, il va vérifier le chemin suivant, jusqu'à ce qu'il trouve le fichier à inclure ou bien retourner une alerte de type E_WARNING ou de type E_ERROR. utilisant la fonction set_include_path().

Exemple #1 include_path sous Unix

include_path=".:/php/includes"

Exemple #2 include_path sous Windows

include_path=".;c:\php\includes"

L'utilisation d'un point (.) dans le chemin d'inclusion vous permet de faire des inclusions relatives au répertoire courant. Cependant, il est plus efficace d'inclure explicitement un fichier avec include './file', que de demander à PHP de vérifier le dossier courant à chaque inclusion.

Note:

Les variables ENV sont aussi disponibles dans les fichiers .ini. Aussi, il est possible de faire référence au dossier home en utilisant la syntaxe ${LOGIN} et ${USER}.

Les variables d'environnement peuvent varier suivant les APIs Serveur, tout comme elles peuvent varier suivant les environnements.

Exemple #3 include_path sous Unix en utilisant la variable d'environnement ${USER}

include_path = ".:${USER}/pear/php"

open_basedir string

Limite les fichiers pouvant être accédés par PHP à une architecture de dossiers spécifique, incluant le fichier lui-même.

Lorsqu'un script tente d'accéder à un fichier avec, par exemple, la fonction include ou la fonction fopen(), le chemin vers le fichier est analysé. Lorsque le fichier se trouve à l'extérieur de l'architecture de dossiers spécifié, PHP refusera d'y accéder. Tous les liens symboliques sont résolus, aussi, il n'est pas possible d'outre-passer cette restriction avec un lien symbolique. Si le fichier n'existe pas, alors le lien symbolique ne pourra être résolu et le nom du fichier est comparé avec l'open_basedir.

L'option open_basedir peut affecter plus que les fonctions du système de fichiers ; par exemple, si MySQL est configuré pour utiliser le driver mysqlnd, LOAD DATA INFILE sera affecté par l'option open_basedir. Le plupart des extensions de PHP utilise l'option open_basedir de cette façon.

La valeur spéciale . indique que le dossier courant du script sera utilisé comme dossier de base.Ceci est cependant légèrement dangereux dans le sens où le dossier courant peut être facilement changé grâce à la fonction chdir().

Dans le fichier httpd.conf, open_basedir peut être désactivée (i.e. pour certains hôtes virtuels) de la même façon que n'importe quelle directive de configuration avec "php_admin_value open_basedir none".

Sous Windows, séparez les dossiers avec un point-virgule. Sous tous les autres systèmes, séparez les dossiers avec des deux-points. Lors de l'utilisation d'Apache en module, les chemins de l'open_basedir depuis les dossiers parents sont maintenant automatiquement hérités.

La restriction spécifiée avec l'open_basedir est un nom de dossier, et non pas un préfixe.

Par défaut, tous les fichiers peuvent être ouverts.

Note:

open_basedir peut être affinée au moment de l'exécution. Ceci signifie que si open_basedir est définie à /www/ dans le fichier php.ini, un script peut affiner la configuration en /www/tmp/ au moment de l'exécution en utilisant la fonction ini_set(). Lors d'un parcours de plusieurs dossiers, vous pouvez utiliser la constante PATH_SEPARATOR suivant le système d'exploitation.

Note:

Utiliser open_basedir définira realpath_cache_size à 0 et ainsi désactive le cache realpath.

Attention

open_basedir est juste mesure de protection supplémentaire, et n'est en aucun cas exhaustive, et ne peut donc pas être dépendu quand la sécurité est nécessaire.

doc_root string

Le dossier racine de PHP sur le serveur. Uniquement utilisé si non vide. Si PHP n'a pas été compilé avec FORCE_REDIRECT, vous devez définir le doc_root si vous utilisez PHP en tant que CGI sous n'importe quel serveur web (autre que IIS). Alternativement, vous pouvez utiliser la configuration cgi.force_redirect.

user_ini.cache_ttl int

user_ini.filename string

user_dir string

Le nom de base du répertoire utilisé dans un répertoire utilisateur pour les fichiers PHP, par exemple, public_html.

extension_dir string

Spécifie le répertoire dans lequel PHP doit chercher des extensions externes à charger. Il est recommandé de spécifier un chemin absolut. Voir aussi enable_dl et dl().

extension string

Quelles extensions doivent être chargées dynamiquement lors du démarrage de PHP.

zend_extension string

Nom de l'extension Zend chargeable dynamiquement (par exemple XDebug) à charger lors du démarrage de PHP.

cgi.check_shebang_line bool

Contrôle si PHP CGI vérifie la ligne commençant par #! (shebang) en haut du script exécuté. Cette ligne est nécessaire si le script est destiné à être exécuté en mode autonome et via un PHP CGI. PHP en mode CGI ne lit pas cette ligne et ignore son contenu si cette directive est active.

cgi.discard_path bool

Si activé, le binaire PHP CGI peut être placé en dehors de l'arbre web en toute sécurité et les personnes ne seront pas capables de contourner la sécurité .htaccess.

cgi.fix_pathinfo bool

Fournit un réel PATH_INFO/ PATH_TRANSLATED pour CGI. Le comportement précédent de PHP était de définir PATH_TRANSLATED en SCRIPT_FILENAME et de ne pas remplir PATH_INFO. Pour plus d'informations sur PATH_INFO, lisez les spécificités CGI. Si définie à 1, PHP CGI fixera ce chemin suivant les spécifications. Si définie à 0, PHP appliquera l'ancien comportement. Par défaut, cette directive est activée. Vous devriez modifier vos scripts pour utiliser SCRIPT_FILENAME à la place de PATH_TRANSLATED.

cgi.force_redirect bool

cgi.force_redirect est nécessaire pour des raisons de sécurité lors de l'utilisation de PHP en mode CGI sous la plupart des serveurs web. Si vous ne la définissez pas, PHP l'activera automatiquement par défaut. Vous pouvez la désactiver à vos risques et périls.

Note:

Utilisateurs de Windows : Lors de l'utilisation de IIS, cette option doit est désactivée ; pareil pour OmniHTTPD et Xitami.

cgi.nph bool

Si cgi.nph est activé, il forcera CGI à toujours envoyer le Status: 200 avec chaque requête.

cgi.redirect_status_env string

Si cgi.force_redirect est activé et que vous ne tournez pas sous un serveur web Apache ou Netscape (iPlanet), vous devriez avoir besoin de définir un nom de variable d'environnement que PHP utilisera pour voir si tout est correct pour continuer l'exécution.

Note:

La définition de cette variable peut avoir des conséquences sur la sécurité. Sachez ce que vous faites avant de faire cela.

cgi.rfc2616_headers int

Dit à PHP quel type d'en-tête doit être utilisé lors de l'envoi du code réponse HTTP. Si définie à 0, PHP enverra un en-tête "Status:" (» RFC 3875) qui est supporté par Apache et les autres serveurs web. Lorsque définie à -1, PHP enverra un en-tête répondant à la spécification de la » RFC 2616.

Si cette option est activée, et que vous exécutez PHP en environnement CGI (e.g. PHP-FPM), vous ne devriez pas utiliser les en-têtes de réponse HTTP "status" RFC 2616, mais plutôt utiliser l'équivalent RFC 3875, i.e. au lieu de l'en-tête ("HTTP/1.0 404 Not found"), utilisez ("Status: 404 Not Found").

Laissez ce paramètre à 0 à moins que vous sachiez parfaitement ce que vous faîtes.

fastcgi.impersonate string

FastCGI sous IIS (sur les systèmes d'exploitation basés sur WINNT) supporte la possibilité de déterminer la marque de sécurité du client appelant. Cela permet à IIS de définir le contexte de sécurité sur lequel la requête est exécutée. mod_fastcgi sous Apache ne supporte actuellement pas cette fonctionnalité (03/17/2002). Définie à 1 si vous utilisez IIS. Par défaut, vaut 0.

fastcgi.logging bool

Active la journalisation SAPI avec FastCGI. Activé par défaut.

Chargement de fichiers

Options de configuration
Nom | Défaut | Modifiable | Historique
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_PERDIR |

Voici un éclaircissement sur l'utilisation des directives de configuration.

file_uploads bool

Autorise ou non le chargement de fichiers par HTTP. Voir aussi les directives upload_max_filesize, upload_tmp_dir et post_max_size.

upload_tmp_dir string

Le répertoire temporaire utilisé pour stocker les fichiers lors du chargement. L'utilisateur sous lequel fonctionne PHP doit avoir les droits en écriture sur ce répertoire. Si non spécifié, PHP utilisera celui par défaut du système.

Si le dossier renseigné ici n'est pas accessible en écriture, PHP se rabat alors sur le dossier temporaire par défaut du système. Si open_basedir est activé, alors le dossier temporaire par défaut du système doit être autorisé pour que le chargement des fichiers puisse fonctionner.

upload_max_filesize int

La taille maximale en octets d'un fichier téléversé.

post_max_size doit être plus large que cette valeur.

Lorsqu'un entier est utilisé, sa valeur est mesurée en octets. Vous pouvez également utiliser la notation sténographique comme décrit dans cette entrée de la FAQ..
max_file_uploads int

Le nombre maximum de fichiers pouvant être envoyés simultanément. Les champs de téléchargement laissés vides lors de la soumission ne comptent plus dans le calcul de cette limite.

SQL général

Options de configuration
Nom | Défaut | Modifiable | Historique
sql.safe_mode | "0" | PHP_INI_SYSTEM | Supprimé à partir de PHP 7.2.0

Voici un éclaircissement sur l'utilisation des directives de configuration.

sql.safe_mode bool

Si activé, les fonctions de connexion à la base de données qui spécifient des valeurs par défaut utiliseront ces valeurs au lieu des arguments fournis. Pour les valeurs par défaut, reportez-vous à la documentation des fonctions de connexion pour la base de données concernée.

Avertissement

Cette fonctionnalité a été SUPPRIMÉE à partir de PHP 7.2.0.

Spécifique à Windows

Options de configuration spécifiques à Windows
Nom | Défaut | Modifiable | Historique
windows.show_crt_warning | "0" | PHP_INI_ALL |

Voici un éclaircissement sur l'utilisation des directives de configuration.

windows.show_crt_warning bool

This directive shows the Windows CRT warnings when enabled.

User Contributed Notes

andre dot wetter at myelco dot ch 23-Mar-2021 09:55
If you use Microsoft IIS Windows and want to use open_basedir restrictions with multiple dirs you have to set them into single quotes in the main config xml file of IIS (C:\Windows\System32\inetsrv\config\applicationHost.config). Works fine in IIS 10.

Multiple files with single quotes and ; for windows:
"C:\php\php-cgi.exe|-d open_basedir='C:\Windows\Temp\;D:\mywebsite1\'"

Only one dir works fine without single quotes:
"C:\php\php-cgi.exe|-d open_basedir=D:\mywebsite1\"

In my main config xml file of IIS there are 2 nodes to set per website and the definitions have to be equal:
configuration\Location\system.webServer\handlers\add
configuration\system.webServer\fastCgi
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"
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=Windows-1252"

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.
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


Catégorie/Liste des extensions

Sommaire

  • Par ordre alphabétique
  • Adhésion
  • État

Cette annexe classe par catégorie plus de 150 extensions documentées dans le manuel PHP suivant différents critères.

User Contributed Notes

There are no user contributed notes for this page.


Par ordre alphabétique

  • Apache
  • APCu
  • Les tableaux
  • BC Math
  • Bzip2
  • Calendar
  • Classes/Objets
  • CommonMark
  • COM
  • Componere
  • ctype
  • CUBRID
  • cURL
  • Date/Heure
  • DBA
  • dBase
  • Direct IO
  • Les dossiers
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Gestion des erreurs
  • Ev
  • Event
  • Exécution de programme
  • Exif
  • Expect
  • FANN
  • FDF
  • FFI
  • Fileinfo
  • Système de fichiers
  • Filter
  • Gestionnaire de processus FastCGI
  • FTP
  • Gestion des fonctions
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Hash
  • HRTime
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • Igbinary
  • GD
  • ImageMagick
  • IMAP
  • Options PHP et informations PHP
  • Inotify
  • intl
  • JSON
  • LDAP
  • libxml
  • Lua
  • LuaSandbox
  • LZF
  • Mail
  • Mailparse
  • Math
  • Chaînes de caractères multioctets
  • Mcrypt
  • Memcache
  • Memcached
  • Mhash
  • Misc.
  • mqseries
  • MySQL (Original)
  • Mysql_xdevapi
  • MySQLi
  • Mysqlnd
  • Réseau
  • OAuth
  • OCI8
  • OPcache
  • OpenAL
  • OpenSSL
  • Contrôle de l'affichage
  • parallel
  • Parle
  • Table de hachage de mot de passe
  • PCNTL
  • PCRE
  • PDO
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC et DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • phpdbg
  • POSIX
  • PS
  • Pspell
  • pthreads
  • Quickhash
  • Radius
  • Random
  • Rar
  • Readline
  • Recode
  • Réflexion
  • Rnp
  • RpmInfo
  • RRD
  • runkit7
  • ScoutAPM
  • Seaslog
  • Semaphore
  • Sessions
  • Mémoire partagée
  • Simdjson
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Sodium
  • Solr
  • SPL
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Flux
  • Chaîne de caractères
  • SVM
  • SVN
  • Swoole
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Gestion des variables
  • var_representation
  • Varnish
  • WDDX
  • win32service
  • WinCache
  • wkhtmltox
  • xattr
  • xdiff
  • Xhprof
  • XLSWriter
  • Analyseur syntaxique XML
  • XMLDiff
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yac
  • Yaconf
  • Yaf
  • Yaml
  • Yar
  • YAZ
  • Zip
  • Zlib
  • 0MQ messaging
  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


Adhésion

Extensions internes

Elles ne sont actuellement pas des extensions. Elles font partie intégrante de PHP et ne peuvent pas être enlevées des binaires PHP avec des options de compilation.

  • Les tableaux

  • Classes/Objets

  • Date/Heure

  • Les dossiers

  • Gestion des erreurs

  • Exécution de programme

  • Système de fichiers

  • Gestionnaire de processus FastCGI

  • Gestion des fonctions

  • Hash

  • Options PHP et informations PHP

  • JSON

  • Mail

  • Math

  • Misc.

  • Réseau

  • OPcache

  • Contrôle de l'affichage

  • Table de hachage de mot de passe

  • PCRE

  • Random

  • Réflexion

  • SPL

  • Flux

  • Chaîne de caractères

  • URLs

  • Gestion des variables

Extensions embarquées

Ces extensions sont embarquées avec PHP.

  • Apache

  • BC Math

  • Calendar

  • COM

  • ctype

  • DBA

  • Exif

  • FFI

  • Fileinfo

  • Filter

  • FTP

  • HRTime

  • iconv

  • GD

  • intl

  • Chaînes de caractères multioctets

  • Mhash

  • PCNTL

  • PDO

  • Phar

  • phpdbg

  • POSIX

  • Semaphore

  • Sessions

  • Mémoire partagée

  • Sockets

  • SQLite3

  • Tokenizer

  • Zlib

Extensions externes

Ces extensions sont fournies avec PHP mais pour pouvoir les compiler, des bibliothèques externes peuvent être nécessaires.

  • Bzip2

  • cURL

  • DOM

  • Enchant

  • Gettext

  • GMP

  • IMAP

  • LDAP

  • libxml

  • MySQLi

  • Mysqlnd

  • OCI8

  • OpenSSL

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC et DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • PostgreSQL

  • Pspell

  • Readline

  • SimpleXML

  • SNMP

  • SOAP

  • Sodium

  • Tidy

  • ODBC

  • Analyseur syntaxique XML

  • XMLReader

  • XMLWriter

  • XSL

  • Zip

Extensions PECL

Ces extensions sont disponibles depuis » PECL. Elles peuvent nécessiter des bibliothèques externes. Plus d'extensions PECL existent mais elles ne sont pas encore documentées dans le manuel de PHP.

  • APCu

  • CommonMark

  • Componere

  • CUBRID

  • dBase

  • Direct IO

  • Data Structures

  • Eio

  • Ev

  • Event

  • Expect

  • FANN

  • FDF

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • Firebird/InterBase

  • IBM DB2

  • Igbinary

  • ImageMagick

  • Inotify

  • Lua

  • LuaSandbox

  • LZF

  • Mailparse

  • Mcrypt

  • Memcache

  • Memcached

  • mqseries

  • MySQL (Original)

  • Mysql_xdevapi

  • OAuth

  • OpenAL

  • parallel

  • Parle

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • Recode

  • Rnp

  • RpmInfo

  • RRD

  • runkit7

  • ScoutAPM

  • Seaslog

  • Simdjson

  • Solr

  • SQLSRV

  • ssdeep

  • SSH2

  • Statistics

  • Stomp

  • SVM

  • SVN

  • Swoole

  • Sync

  • Taint

  • TCP

  • Trader

  • UI

  • uopz

  • V8js

  • var_representation

  • Varnish

  • WDDX

  • win32service

  • WinCache

  • wkhtmltox

  • xattr

  • xdiff

  • Xhprof

  • XLSWriter

  • XMLDiff

  • XML-RPC

  • Yac

  • Yaconf

  • Yaf

  • Yaml

  • Yar

  • YAZ

  • 0MQ messaging

  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


État

Cette partie liste les extensions non prévues pour un environnement de production - elles sont soit trop "vieilles" (obsolètes), soit trop "nouvelles" (expérimentales).

Extensions obsolètes

Ces extensions ont été dépréciées habituellement en faveur d'autres extensions.

Extensions expérimentales

Le comportement de ces extensions - incluant le nom de ses fonctions et tout ce qui est documenté à propos de ces extensions - peut être modifié sans aucun avertissement dans les prochaines versions de PHP. Utilisez ces extensions à vos risques et périls.

  • ImageMagick

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • Oracle (PDO)

  • PS

  • Rnp

  • XML-RPC

User Contributed Notes

There are no user contributed notes for this page.


Liste des alias

Il y a beaucoup de fonctions en PHP qui peuvent être appelées sous différents noms. Dans la plupart des cas, il n'y a pas de nom préféré par rapport à un autre, is_int() et is_integer() sont exactement identiques, par exemple. Ces modifications de noms ont été réalisées en général à cause d'un changement dans l'API d'origine ou pour d'autres raisons et les anciens noms sont conservés uniquement pour des raisons de compatiblité ascendante. C'est une très mauvaise habitude d'utiliser ces alias, car ils risquent à tout moment de disparaître, rendus obsolète sans préavis, ou bien par un simple changement de nom, ce qui rend votre script inutilisable avec des versions plus récentes de PHP. Préférez toujours les versions officielles. En fait, cette liste est surtout destinée à ceux qui doivent mettre à jour leurs scripts avec les syntaxes plus récentes.

Aliases
Alias | Fonction principale | Extension mère
_ | gettext() | Gettext
chop | rtrim() | Base syntax
close | closedir() | Base syntax
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | Miscellaneous functions
diskfreespace | disk_free_space() | Filesystem
doubleval | floatval() | Base syntax
fputs | fwrite() | Base syntax
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | Multi-bytes Strings
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings
i18n_http_input | mb_http_input() | Multi-bytes Strings
i18n_http_output | mb_http_output() | Multi-bytes Strings
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings
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() | Base syntax
is_double | is_float() | Base syntax
is_integer | is_int() | Base syntax
is_long | is_int() | Base syntax
is_real | is_float() | Base syntax
is_writeable | is_writable() | Base syntax
join | implode() | Base syntax
key_exists | array_key_exists() | Base syntax
ldap_close | ldap_unbind() | LDAP
mbstrcut | mb_strcut() | Multi-bytes Strings
mbstrlen | mb_strlen() | Multi-bytes Strings
mbstrpos | mb_strpos() | Multi-bytes Strings
mbstrrpos | mb_strrpos() | Multi-bytes Strings
mbsubstr | mb_substr() | Multi-bytes Strings
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 | OCICollection::assignElem | OCI8
ocibindbyname | oci_bind_by_name() | OCI8
ocicancel | oci_cancel() | OCI8
ocicloselob | OCILob::close | OCI8
ocicollappend | OCICollection::append | OCI8
ocicollassign | OCICollection::assign | OCI8
ocicollmax | OCICollection::max | OCI8
ocicollsize | OCICollection::size | OCI8
ocicolltrim | OCICollection::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 | OCICollection::free | OCI8
ocifreecursor | oci_free_statement() | OCI8
ocifreedesc | oci_free_descriptor() | OCI8
ocifreestatement | oci_free_statement() | OCI8
ocigetelem | OCICollection::getElem | OCI8
ociinternaldebug | oci_internal_debug() | OCI8
ociloadlob | OCILob::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 | OCILob::save | OCI8
ocisavelobfile | OCILob::import | OCI8
ociserverversion | oci_server_version() | OCI8
ocisetprefetch | oci_set_prefetch() | OCI8
ocistatementtype | oci_statement_type() | OCI8
ociwritelobtofile | OCILob::export | OCI8
ociwritetemporarylob | OCILob::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() | Base syntax
recode | recode_string() | Recode
show_source | highlight_file() | Base syntax
sizeof | count() | Base syntax
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Base syntax
xptr_new_context | xpath_new_context() |

User Contributed Notes

There are no user contributed notes for this page.


Mots réservés en PHP

Sommaire

  • Liste de mots-clés
  • Classes prédéfinies
  • Constantes pré-définies
  • Autre liste de mots réservés

Cette annexe est une liste d'identifiants prédéfinis en PHP. Aucun des identifiants utilisés ici ne doit être repris comme nom de variable ou de fonction dans vos scripts, sauf s'il est noté explicitement le contraire. Ces identifiants incluent des mots-clés, des constantes, des classes et des variables prédéfinies. Ces listes ne sont pas complètes ni exhaustives.

User Contributed Notes

There are no user contributed notes for this page.


Liste de mots-clés

Ces mots ont un sens spécial pour PHP. Certains représentent des objets ressemblant à des fonctions, d'autres à des constantes, et ainsi de suite, mais ils n'en sont pas vraiment : ce sont des structures de langage. Les mots clés suivant ne peuvent pas être utilisés comme nom de constante, de classe ou de fonction. Ils sont cependant autorisés comme nom de propriété, constante et de méthode dans les classes, interfaces, traits sauf le mot clé class qui ne doit pas être utilisé comme nom de constante.

Mots réservés en PHP
__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 | finally | fn (à partir de PHP 7.4) | for | foreach
function | global | goto | if | implements
include
include_once | instanceof | insteadof | interface
isset() | list() | match (à partir de PHP 8.0) | namespace | new
or | print | private | protected | public
require | readonly (à partir de PHP 8.1.0) * | require_once | return | static
switch | throw | trait | try | unset()
use | var | while | xor | yield
yield from |  |  |  |

* readonly peut être utilisé comme nom de fonction.

Constantes utilisées lors de la compilation
__CLASS__ | __DIR__ | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ | __TRAIT__ |  |  |  |

User Contributed Notes

Johnny D. 22-May-2020 06:37
const FORBIDDEN_TYPES = [
    'null',

    'bool',
    'false',
    'true',

    'int',
    'float',

    'string',
];
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.


Classes prédéfinies

Cette section liste les classes standards prédéfinies. Les autres extensions qui définissent d'autres classes sont décrites dans leur référence.

Classes standards

Ces classes sont définies dans le jeu de classes standards de PHP, inclus dans toutes les versions de PHP.

Directory
Créé par la fonction dir().
stdClass
Une classe vide générique crée par la conversion en objet ou le résultat de diverses fonctions standard.
__PHP_Incomplete_Class
Peut être créé par la fonction unserialize().
Exception
ErrorException
php_user_filter
Closure
La classe prédéfinie finale Closure est utilisée pour représenter les fonctions anonymes.
Generator
La classe finale prédéfinie Generator est utilisée pour représenter les générateurs.
ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

Classes spéciales

Les identifiants suivants ne devraient pas être utilisés en tant que nom de classe à cause de leur rôle particulier.

self
Classe courante.
static
Classe courante au moment de l'exécution.
parent
Classe parent.

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 ());


Constantes pré-définies

Constantes prédéfinies

Ces constantes sont définies par le cœur de PHP. Cela inclut notamment PHP, le moteur Zend et les modules SAPI.

PHP_VERSION (string)
La version courante de PHP sous la forme d'une chaîne de caractères dans la notation "major.minor.release[extra]".
PHP_MAJOR_VERSION (int)
La version majeure courante de PHP sous la forme d'une chaîne de caractères (e.g., int(5) depuis la version "5.2.7-extra").
PHP_MINOR_VERSION (int)
La version mineure courante de PHP sous la forme d'une chaîne de caractères (e.g., int(2) depuis la version "5.2.7-extra").
PHP_RELEASE_VERSION (int)
La version stable courante de PHP sous la forme d'une chaîne de caractères (e.g., int(7) depuis la version "5.2.7-extra").
PHP_VERSION_ID (int)
La version courante de PHP sous la forme d'un entier, utile pour la comparaison de versions (e.g., int(50207) depuis la version "5.2.7-extra").
PHP_EXTRA_VERSION (string)
La version "extra" courante de PHP sous la forme d'une chaîne de caractères(i.e., '-extra' depuis la version "5.2.7-extra"). Habituellement utilisée par les packagers des distributions pour indiquer une version de paquet.
PHP_ZTS (int)
PHP_DEBUG (int)
PHP_MAXPATHLEN (int)
La longueur maximale des noms de fichiers (y compris le chemin) supportée par ce binaire PHP.
PHP_OS (string)
The operating system PHP was built for.
PHP_OS_FAMILY (string)
Le système d'exploitation pour lequel PHP a été compilé. Un de 'Windows', 'BSD', 'Darwin', 'Solaris', 'Linux' ou 'Unknown'. Disponible à partir de PHP 7.2.0.
PHP_SAPI (string)
L'API du serveur pour ce binaire PHP. Voir aussi php_sapi_name().
PHP_EOL (string)
Le symbole correct pour la fin de ligne pour cette plateforme.
PHP_INT_MAX (int)
Le plus grand entier supporté par ce binaire de PHP. Habituellement, int(2147483647) sur les systèmes 32 bit et int(9223372036854775807) sur les systèmes 64 bit.
PHP_INT_MIN (int)
Le plus petit entier supporté dans cette version de PHP. Habituellement, int(-2147483648) sur les systèmes 32 bit et int(-9223372036854775808) sur les systèmes 64 bit. Habituellement, PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (int)
La taille d'un entier, en octets, dans cette version de PHP.
PHP_FLOAT_DIG (int)
Nombre de décimales pouvant être arrondies dans un nombre à virgule flottante et retournées sans perte de précision. Disponible à partir de PHP 7.2.0.
PHP_FLOAT_EPSILON (float)
Le plus petit nombre à virgule flottante positif supporté, de sorte que x + 1.0 != 1.0. Disponible à partir de PHP 7.2.0.
PHP_FLOAT_MIN (float)
Le plus petit nombre à virgule flottante positif supporté. Si vous avez besoin de la plus petite représentation négative de nombre flottant, utiliser - PHP_FLOAT_MAX. Disponible à partir de PHP 7.2.0.
PHP_FLOAT_MAX (float)
Le plus grand nombre à virgule flottante supporté. Disponible à partir de PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
Le répertoire par défaut où chercher pour des extensions chargeable dynamiquement (sauf outrepassé par extension_dir). Par défaut PHP_PREFIX (ou PHP_PREFIX . "\\ext" sur Windows).
PHP_PREFIX (string)
La valeur de --prefix qui a été définie lors de la configuration. Sur Windows, c'est la valeur de --with-prefix qui a été définie lors de la configuration.
PHP_BINDIR (string)
La valeur de --bindir qui a été définie lors de la configuration. Sur Windows, c'est la valeur de --with-prefix qui a été définie lors de la configuration.
PHP_BINARY (string)
Spécifie le chemin vers le binaire PHP lors de l'exécution du script.
PHP_MANDIR (string)
Spécifie le chemin d'installation des pages man.
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)
Le suffixe de la plate-forme de compilation pour les bibliothèques partagées, comme "so" (sous la plupart des Unix) ou "dll" (Windows).
PHP_FD_SETSIZE (int)
Nombre maximal de descripteurs de fichiers pour les appels système sélectionnés. Disponible à partir de PHP 7.1.0.
E_ERROR (int)
Constante de rapport d'erreur
E_WARNING (int)
Constante de rapport d'erreur
E_PARSE (int)
Constante de rapport d'erreur
E_NOTICE (int)
Constante de rapport d'erreur
E_CORE_ERROR (int)
Constante de rapport d'erreur
E_CORE_WARNING (int)
Constante de rapport d'erreur
E_COMPILE_ERROR (int)
Constante de rapport d'erreur
E_COMPILE_WARNING (int)
Constante de rapport d'erreur
E_USER_ERROR (int)
Constante de rapport d'erreur
E_USER_WARNING (int)
Constante de rapport d'erreur
E_USER_NOTICE (int)
Constante de rapport d'erreur
E_RECOVERABLE_ERROR (int)
Constante de rapport d'erreur.
E_DEPRECATED (int)
Constante de rapport d'erreur.
E_USER_DEPRECATED (int)
Constante de rapport d'erreur.
E_ALL (int)
Constante de rapport d'erreur
E_STRICT (int)
Constante de rapport d'erreur.
__COMPILER_HALT_OFFSET__ (int)
true (bool)
Voir Booléens.
false (bool)
Voir Booléens.
null (null)
Voir Null.
PHP_WINDOWS_EVENT_CTRL_C (int)
Évènement Windows CTRL+C. Disponible à partir de PHP 7.4.0 (Windows uniquement).
PHP_WINDOWS_EVENT_CTRL_BREAK (int)
Évènement Windows CTRL+BREAK. Disponible à partir de PHP 7.4.0 (Windows uniquement).

Voir aussi les constantes magiques.

Constantes standards prédéfinies

Toutes les constantes des extensions cœur sont définies en PHP par défaut.

User Contributed Notes

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;
        }
    }

}
?>


Autre liste de mots réservés

Les mots suivants ne peuvent pas être utilisés comme nom de classe, d'interface ou de trait. Antérieur à PHP 8.0, il était également interdit de les utiliser dans les espaces de noms.

Mots réservés
int | float | bool | string
true | false | null | void (à partir de PHP 7.1)
iterable (à partir de PHP 7.1) | object (à partir de PHP 7.2) | mixed (à partir de PHP 8.0) | never (à partir de PHP 8.1)

La liste des mots suivants présente une particularité. Bien qu'ils puissent être utilisés dans les noms de classe, d'interface, et de trait, il convient d'éviter de les utiliser sachant qu'ils peuvent être utilisés dans les futures versions de PHP.

Soft reserved words
enum resource numeric

User Contributed Notes

There are no user contributed notes for this page.


Types des ressources PHP

Voici la liste des fonctions qui créent, utilisent ou détruisent les ressources PHP. Vous pouvez déterminer si une variable contient une ressource avec la fonction is_resource(), et le type d'une ressource que vous utilisez avec la fonction get_resource_type().

Types de ressource
Ressource | Construite par | Utilisée par | Détruite par | Définition
AddressInfo | socket_addrinfo_lookup() | socket_addrinfo_bind(), socket_addrinfo_connect(), socket_addrinfo_explain(), | None | AddressInfo (sockets extension)
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Fichier bzip2
Connexion cubrid | cubrid_connect() cubrid_connect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() | cubrid_close() cubrid_disconnect() | Connexion à une base de données CUBRID
Connexion cubrid persistante | cubrid_pconnect() cubrid_pconnect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() cubrid_lob2_new() | Connexion persistante à une base de données CUBRID
Requête cubrid | cubrid_prepare() cubrid_execute() cubrid_query() cubrid_unbuffered_query() | cubrid_bind() cubrid_column_names() cubrid_column_types() cubrid_current_oid() cubrid_execute() cubrid_free_result() cubrid_get_query_timeout() cubrid_move_cursor() cubrid_next_result() cubrid_num_cols() cubrid_num_rows() cubrid_set_query_timeout() cubrid_data_seek() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_field() cubrid_fetch_lengths() cubrid_fetch_object() cubrid_fetch_row() cubrid_field_flags() cubrid_field_len() cubrid_field_name() cubrid_field_seek() cubrid_field_table() cubrid_field_type() cubrid_num_fields() cubrid_result() cubrid_lob2_bind() | cubrid_close_prepare() cubrid_close_request() | Requête CUBRID
cubrid lob | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close() | Aucun
cubrid lob2 | cubrid_lob2_new() cubrid_fetch() cubrid_fetch_row() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_object() | cubrid_lob2_export() cubrid_lob2_import() cubrid_lob2_read() cubrid_lob2_write() cubrid_lob2_tell() cubrid_lob2_tell64() cubrid_lob2_seek() cubrid_lob2_seek64() cubrid_lob2_size() cubrid_lob2_size64() | cubrid_lob2_close() | Aucun
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | cURL handle
curl_multi | curl_multi_init() | curl_multi_errno(), curl_multi_exec(), curl_multi_info_read(), curl_multi_remove_handle(), curl_multi_select(), curl_multi_setopt() | curl_multi_close() | cURL multi handle
curl_share | curl_share_init() | curl_share_errno(), curl_share_setopt() | curl_share_close() | cURL share handle
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Lien vers une base de données DBA
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | Aucun | Lien persistant vers une base de données DBA
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() | Lien vers une base de données dbase
enchant_broker | enchant_broker_init() | enchant_broker_describe(), enchant_broker_dict_exists(), enchant_broker_get_dict_path(), enchant_broker_get_error(), enchant_broker_list_dicts(), enchant_broker_set_dict_path(), enchant_broker_set_ordering() | enchant_broker_free() | Enchant broker (antérieur à PHP 8.0.0)
enchant_dict | enchant_broker_request_dict() enchant_broker_request_pwl_dict() | enchant_dict_add_to_personal(), enchant_dict_add_to_session(), enchant_dict_check(), enchant_dict_describe(), enchant_dict_get_error(), enchant_dict_is_in_session(), enchant_dict_store_replacement(), enchant_dict_suggest() | enchant_broker_free_dict() | Enchant dictionary (antérieur à PHP 8.0.0)
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() | Fichier FDF
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() | Connexion FTP (antérieur à PHP 8.1.0)
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(), 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() | Image GD (antérieur à PHP 8.0.0)
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | Aucun | Police pour GD (antérieur à PHP 8.1.0)
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() | Lien vers un serveur IMAP ou POP3 (antérieur à PHP 8.1.0)
interbase blob | ibase_blob_create(), ibase_blob_import(), ibase_blob_open() | ibase_blob_add(), ibase_blob_cancel(), ibase_blob_echo(), ibase_blob_get(), ibase_blob_info() | ibase_blob_close()
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Lien vers une base de données Interbase
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | Aucun | Lien persistant vers une base de données Interbase
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Requête Interbase
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Résultat Interbase
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Transaction Interbase
ldap link (antérieur à PHP 8.1.0) | 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() | Lien vers un serveur LDAP
ldap result (antérieur à PHP 8.1.0) | 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() | Résultat de recherche LDAP
ldap result entry (antérieur à PHP 8.1.0)
mailparse_mail_structure | mailparse_msg_create() mailparse_msg_parse_file() | mailparse_msg_extract_part_file() mailparse_msg_extract_part() mailparse_msg_extract_whole_part_file() mailparse_msg_get_part_data() mailparse_msg_get_part() mailparse_msg_get_structure() mailparse_msg_parse() | mailparse_msg_free()
mysql link | mysql_connect() | mysql_affected_rows(), 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() | Lien vers une base de données MySQL
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), 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() | Aucun | Lien persistant vers une base de données MySQL
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() | Résultat MySQL
Collection oci8 | oci_new_collection() | OCICollection::append(), OCICollection::assign(), OCICollection::assignElem(), OCICollection::getElem(), OCICollection::max(), OCICollection::size(), OCICollection::trim() | OCICollection::free() | Oracle Collection
Connexion oci8 | oci_connect(), oci_pconnect(), oci_new_connect() | oci_commit(), oci_error(), oci_new_cursor(), oci_parse(), oci_password_change(), oci_rollback(), oci_server_version(), oci_set_action(), oci_set_client_identifier(), oci_set_client_info(), oci_set_module_name() | oci_close() | Connexion sur une base de données Oracle
oci8 lob | oci_new_descriptor() | OCILob::append(), OCILob::close(), OCILob::eof(), OCILob::erase(), OCILob::export(), OCILob::flush(), OCILob::getBuffering(), OCILob::import(), OCILob::load(), OCILob::read(), OCILob::rewind(), OCILob::save(), OCILob::saveFile(), OCILob::seek(), OCILob::setBuffering(), OCILob::size(), OCILob::tell(), OCILob::truncate(), OCILob::write(), OCILob::writeTemporary(), OCILob::writeToFile(), oci_lob_copy(), oci_lob_is_equal() | OCILob::free() | Objets larges Oracle
Requête oci8 | oci_parse(), oci_new_cursor() | oci_bind_array_by_name(), oci_bind_by_name(), oci_cancel(), oci_define_by_name(), oci_error() oci_execute(), oci_fetch_all(), oci_fetch_array(), oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row(), oci_fetch(), oci_field_is_null(), oci_field_name(), oci_field_precision(), oci_field_scale(), oci_field_size(), oci_field_type_raw(), oci_field_type(), oci_num_fields(), oci_num_rows(), oci_result(), oci_set_prefetch(), oci_statement_type() | oci_free_statement() | Curseur Oracle
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() | Lien vers une base de données ODBC
Lien persistant odbc | 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() | Aucun | Lien persistant vers une base de données ODBC
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() | Résultat ODBC
birdstep link | Link to Birdstep database (antérieur à PHP 7.3.0)
birdstep result | Link to Birdstep database (antérieur à PHP 7.3.0)
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | Clé OpenSSL
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Clé publique
Objet de grande taille pgsql (antérieur à PHP 8.1.0) | 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() | Objet de grande taille PostGreSQL
pgsql link (antérieur à PHP 8.1.0) | 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_meta_data(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Lien vers une base de données PostGreSQL
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_meta_data(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | Aucun | Lien persistant vers une base de données PostGreSQL
pgsql result (antérieur à PHP 8.1.0) | 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() | Résultat PostGreSQL
pgsql string
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() | Aucun | Dictionnaire Pspell (antérieur à PHP 8.1.0)
pspell config | pspell_config_create() | pspell_new_config() | Aucun | Configuration Pspell (antérieur à PHP 8.1.0)
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | Handle d'un bloc de mémoire partagée (antérieur à PHP 8.0.0)
Socket | socket_accept(), socket_addrinfo_bind(), socket_addrinfo_connect(), socket_create(), socket_create_listen(), socket_import_stream(), socket_wsaprotocol_info_import() | socket_accept(), socket_bind(), socket_clear_error(), socket_connect(), socket_get_option(), socket_getpeername(), socket_getsockname(), socket_last_error(), socket_listen(), socket_read(), socket_recv(), socket_recvfrom(), socket_recvmsg(), socket_select(), socket_send(), socket_sendmsg(), socket_sendto(), socket_set_block(), socket_set_nonblock(), socket_set_option(), socket_shutdown(), socket_write(), socket_wsaprotocol_info_export(), socket_wsaprotocol_info_release() | socket_close() | Socket (sockets extension)
Flux | opendir() | readdir(), rewinddir() | closedir() | Dossier
Flux | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | Fichier
Flux | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Processus
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket Handle
SSH2 Session | ssh2_connect() | ssh2_disconnect()
SSH2 Listener | ssh2_forward_listen()
SSH2 SFTP | ssh2_sftp()
SSH2 Publickey Subsystem | ssh2_publickey_init()
sysvmsg queue | msg_get_queue() | msg_queue_exists(), msg_receive(), msg_send(), msg_set_queue(), msg_stat_queue() | msg_remove_queue() | System V Message Queue (antérieur à PHP 8.0.0)
sysvsem | sem_get() | sem_acquire() | sem_release() | Sémaphore Système V (antérieur à PHP 8.0.0)
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | Mémoire partagée Système V (antérieur à PHP 8.0.0)
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | Paquet wddx
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() | Analyseur syntaxique XML (antérieur à PHP 8.0.0)
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | Fichier compressé Gzip
zlib.deflate | deflate_init() | deflate_add() | None | Contexte de décompression incrémentale (antérieur à PHP 8.0.0)
zlib.inflate | inflate_init() | inflate_add(), inflate_get_read_len(), inflate_get_status() | None | Contexte de compression incrémentale (antérieur à PHP 8.0.0)

User Contributed Notes

Anonymous 28-Jul-2023 12:19
Resource of type "process" is returned by proc_open() and used by proc_close()


Liste des filtres standards

Sommaire

  • Filtres de chaînes de caractères
  • Filtres de conversion
  • Filtres de compression
  • Filtres de chiffrement

Cette section contient la liste des filtres de flux, à utiliser avec stream_filter_append(). Votre version de PHP peut avoir des filtres supplémentaires, ou manquants par rapport à cette liste.

Il est bon de noter une légère différence entre stream_filter_append() et stream_filter_prepend(). Tous les flux PHP disposent d'un petit buffer de lecture, où ils stockent des blocs de données lues dans le système de fichiers, ou dans d'autres sources, afin de les traiter plus efficacement. Aussitôt que les données sont lues depuis la ressource dans le buffer interne, les données sont immédiatement passées au filtre, même si l'application PHP n'est pas prête pour lire ces données. Si des données sont déjà en attente dans le buffer lorsqu'un filtre est ajouté au flux (appended), ces données seront immédiatement passées au filtre, pour que la modification soit transparente. Mais si vous ajoutez un filtre avec prepended, les données NE seront PAS filtrées. Elles attendront que le prochain bloc arrive de la ressource.

Pour avoir la liste complète des filtres de votre version de PHP, utilisez la fonction stream_get_filters().

User Contributed Notes

There are no user contributed notes for this page.


Filtres de chaînes de caractères

Chaque filtre fait ce que son nom implique, et se réfère au comportement de la fonction PHP correspondante. Pour plus de détails sur un filtre, reportez-vous au manuel de la fonction de référence.

string.rot13

L'utilisation de ce filtre est équivalente à traiter toutes les données du flux à travers la fonction str_rot13().

Exemple #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "Ceci est un test.\n");
/* affiche : Prpv rfg ha grfg. */
?>

string.toupper

L'utilisation de ce filtre est équivalente à traiter toutes les données du flux à travers la fonction strtoupper().

Exemple #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "Ceci est un test.\n");
/* affiche : CECI EST UN TEST. */
?>

string.tolower

L'utilisation de ce filtre est équivalente à traiter toutes les données du flux à travers la fonction strtolower().

Exemple #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "Ceci est un test.\n");
/* affiche : ceci est un test. */
?>

string.strip_tags

L'utilisation de ce filtre est équivalente à traiter toutes les données du flux à travers la fonction strip_tags(). Le filtre accepte des paramètres sous deux formats : Soit comme une chaîne de caractères contenant une liste de balises, similaire au second paramètre de la fonction strip_tags(), soit en tant qu'un tableau de noms de balises.

Avertissement

Cette fonctionnalité est OBSOLÈTE à partir de PHP 7.3.0. Dépendre de cette fonctionnalité est fortement déconseillé.

Exemple #4 string.strip_tags

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<strong><em><span>");
fwrite($fp, "<strong>Ce texte en gras</strong> finit par être agrandi <h1>en un titre 1</h1>\n");
fclose($fp);
/* affiche : Ce texte en gras finit par être agrandi en un titre 1 */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('strong','em','span'));
fwrite($fp, "<strong>Ce texte en gras</strong> finit par être agrandi <h1>en un titre 1</h1>\n");
fclose($fp);
/* affiche : Ce texte en gras finit par être agrandi en un titre 1 */
?>

User Contributed Notes

There are no user contributed notes for this page.


Filtres de conversion

Comme pour les filtres de chaîne de caractères, les filtres de conversion font ce que leur nom indique. Pour plus d'informations sur un filtre donné, se référer à la page du manuel de la fonction correspondante.

convert.base64-encode et convert.base64-decode

L'utilisation de ce filtre est équivalente à traiter toutes les données du flux à travers les fonctions base64_encode() et base64_decode() respectivement. convert.base64-encode supporte les paramètres sous forme de tableau associatif. Si line-length est fourni, la sortie base64 sera séparée en lignes de line-length caractères. Si line-break-chars est fourni, chaque bloc de caractères sera délimité par le caractère fourni. Ces paramètres donnent le même effet que la fonction base64_encode() utilisée conjointement avec chunk_split().

Exemple #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);
/* affiche : 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);
/* affiche : VGhpcyBp
: cyBhIHRl
: c3QuCg== */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* affiche : This is a test. */
?>

convert.quoted-printable-encode et convert.quoted-printable-decode

L'utilisation de la version decode ce filtre est équivalente à traiter toutes les données du flux à travers la fonction quoted_printable_decode(). Il n'y a pas d'équivalent fonctionnel à convert.quoted-printable-encode. convert.quoted-printable-encode supporte les paramètres sous forme de tableau associatif. En plus des paramètres supportés par convert.base64-encode, convert.quoted-printable-encode accepte aussi les arguments booléen binary et force-encode-first. convert.base64-decode supporte uniquement le paramètre line-break-chars en tant qu'indicateur de type pour l'extraction de la charge codée.

Exemple #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");
/* affiche : =This is a test.=0A */
?>

convert.iconv.*

Les filtres convert.iconv.* sont disponibles, si le support de iconv est activé, et leurs usages sont équivalents à traiter toutes les données du flux avec iconv(). Ces filtres ne supportent pas de paramètres, mais s'attendent à la place à ce que le nom du filtre contienne l'encodage des données en saisie et de sortie, c.à.d. convert.iconv.<input-encoding>.<output-encoding> ou convert.iconv.<input-encoding>/<output-encoding> (les deux notations sont sémantiquement équivalentes).

Exemple #3 convert.iconv.*

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.iconv.utf-16le.utf-8');
fwrite($fp, "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\n\0");
fclose($fp);
/* Outputs: This is a test. */
?>

User Contributed Notes

marcus at synchromedia dot co dot uk 10-May-2022 09:50
It's not quite obvious what all the available parameters are for convert.quoted-printable-encode. If you want the stream filter to act the same way as the quoted_printable_encode function, you need these extra params, for example:

stream_filter_append(
    STDOUT,
    'convert.quoted-printable-encode',
    STREAM_FILTER_WRITE,
    [
        'line-break-chars' => PHP_EOL,
        'line-length' => 75,
    ]
);
echo stream_copy_to_stream(STDIN, STDOUT);

Without these extra params set, you may get no wrapping at all, or wrapping using the wrong line break sequence.


Filtres de compression

Alors que les enveloppes de compression fournissent un moyen pour générer des fichiers aux formats gzip et bz2, ils ne permettent pas de gérer les protocoles réseaux compressés, ni de commencer avec un flux non compressé pour le transformer en flux compressé. Pour cela, un filtre de compression peut être appliqué à tout moment sur n'importe quelle ressource de flux.

Note: Les filtres de compression ne génèrent pas les en-têtes et fins de fichiers, comme le fait l'utilitaire gzip. Ils ne font que compresser et décompresser des portions de flux de données.

zlib.deflate and zlib.inflate

zlib.deflate (compression) et zlib.inflate (décompression) sont les implémentations des méthodes de compression présentées dans la » RFC 1951. Le filtre deflate prend jusqu'à trois paramètres, passés sous la forme de tableau associatif. level spécifie le niveau de compression souhaité, de 1 à 9. Plus le niveau est haut, meilleure est la compression, et plus cher est le coût de compression. Deux niveaux de compression spéciaux existent : 0, qui représente l'absence de compression, et -1, qui représente le niveau par défaut de zlib : actuellement, 6. window est la taille du tampon mémoire, en base 2. Les valeurs supérieures, jusqu'à 15, soit 32768 octets, donnent de meilleures compressions, et les valeurs inférieures, jusqu'à 9, soit 512 octets, occupent le moins d'espace en mémoire. Par défaut, window vaut actuellement 15. memory est une indication du niveau de mémoire nécessaire. Les valeurs valides vont de 1, pour l'allocation minimale, à 9, pour une allocation maximale. L'allocation de mémoire affecte la vitesse d'exécution, et non pas le coût global.

Note: Comme le niveau de compression est le paramètre le plus courant, il peut aussi être fourni en tant que valeur entier, au lieu d'un tableau.

Les filtres de compression zlib.* sont disponibles si le support de zlib est activé.

Exemple #1 zlib.deflate and 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 "Le texte original est long de " . strlen($original_text) . " octets.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "Le fichier compressé fait " . filesize('test.deflated') . " octets de long.\n";
echo "Le texte original était :\n";
/* Utilise readfile et zlib.inflate pour décompresser à la volée */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Affiche :

Le texte original est long de 70 octets
Le fichier compressé fait 56 octets de long.
Le texte original était :
This is a test.
This is only a test.
This is not an important string.

*/
?>

Exemple #2 zlib.deflate simple

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "Le texte original est long de " . strlen($original_text) . " octets.\n";

$fp = fopen('test.deflated', 'w');
/* Ici, "6" indique le niveau de compression de 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "Le fichier compressé fait " . filesize('test.deflated') . " octets de long.\n";

/* Affiche :

Le texte original est long de 70 octets
Le fichier compressé fait 56 octets de long.

*/
?>

bzip2.compress and bzip2.decompress

bzip2.compress et bzip2.decompress fonctionnent de la même manière que les filtres zlib décrits ci-dessus. Le filtre bzip2.compress accepte jusqu'à 2 paramètres, sous la forme d'un tableau associatif : blocks est une valeur entier, de 1 à 9, spécifiant le nombre de blocs de 100 kb de mémoire à allouer à l'espace de travail. work est aussi un entier dont la valeur va de 0 à 250, et qui indique le niveau d'effort fourni avec une méthode de compression avant de passer à une autre méthode, plus lente. Modifier ce paramètre n'a qu'un effet sur la vitesse de compression. Le gain d'espace ou la mémoire utilisée restent les mêmes. Un niveau de 0 indique que la bibliothèque doit utiliser sa configuration par défaut. Le filtre bzip2.decompress accepte uniquement un paramètre, qui peut être passé sous la forme d'un booléen, ou en tant que l'élément small d'un tableau associatif. small, lorsque défini à true, indique à la bibliothèque bzip qu'elle doit faire une décompression en utilisant le moins de mémoire possible, aux dépends de la vitesse.

Les filtres bzip2.* sont disponibles si le support de bz2 est activé.

Exemple #3 bzip2.compress et bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "Le fichier original fait " . strlen(LICENSE) . " octets de 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 "Le fichier compressé fait " . filesize('LICENSE.compressed') . " octets de long.\n";

/* Affiche :

Le fichier original fait 3288 octets de long.
Le fichier compressé fait 1488 octets de long.

*/
?>

User Contributed Notes

TingSong 20-Feb-2023 03:43
To decompress a gzipped stream:

<?php
$stream = fopen('https://example.com/some/file.txt.gz', 'rb');
stream_filter_append($stream, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15+16]);

// read the decompressed line directly
$line = fgets($stream);

// process the lines
?>

As the doc of zlib https://www.zlib.net/manual.html#Advanced

The 'window' parameter between 8 and 15 specified the window size from 28 to 2¹5 bytes. It can be added by 16 for wrapping with gzip header and trailer instead of zlib wrapper.

And, window could be -8..-15 for unwrapping RAW deflate data.
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);


Filtres de chiffrement

Les filtres de chiffrement sont particulièrement utiles pour le chiffrement des fichiers/flux.

mcrypt.* and mdecrypt.*

Avertissement

Cette fonctionnalité est OBSOLÈTE à partir de PHP 7.1.0. Dépendre de cette fonctionnalité est fortement déconseillé.

mcrypt.* et mdecrypt.* fournissent un système de chiffrement symétrique utilisant libmcrypt. Les deux jeux de filtres supportent les mêmes algorithmes disponibles à l'extension mcrypt sous la forme mcrypt.ciphername où ciphername est le nom du chiffrement qui sera transmis à mcrypt_module_open(). Les cinq paramètres suivants sont aussi disponibles :

Paramètres des filtres mcrypt
Paramètre | Obligatoire ? | Par défaut | Valeurs possibles
mode | Optionnel | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Optionnel | ini_get('mcrypt.algorithms_dir') | Chemin vers les algorithmes de modules
modes_dir | Optionnel | ini_get('mcrypt.modes_dir') | Chemin vers les modes de modules
iv | Obligatoire | N/A | Généralement 8, 16 ou 32 octets de données binaires. Dépend du chiffrement
key | Obligatoire | N/A | Généralement 8, 16 ou 32 octets de données binaires. Dépend du chiffrement

Exemple #1 Chiffrement / Déchiffrement avec Blowfish

<?php
//$key supposé être précédemment généré
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$fp = fopen('encrypted-file.enc', 'wb');
fwrite($fp, $iv);
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key);
stream_filter_append($fp, 'mcrypt.blowfish', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'message to encrypt');
fclose($fp);

//déchiffrement...
$fp = fopen('encrypted-file.enc', 'rb');
$iv = fread($fp, $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC));
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key)
stream_filter_append($fp, 'mdecrypt.blowfish', STREAM_FILTER_READ, $opts);
$data = rtrim(stream_get_contents($fp));//trims off null padding
fclose($fp);
echo $data;
?>

Exemple #2 Chiffrer un fichier en utilisant AES-128 CBC avec SHA256 HMAC

<?php
AES_CBC::encryptFile($password, "plaintext.txt", "encrypted.enc");
AES_CBC::decryptFile($password, "encrypted.enc", "decrypted.txt");

class AES_CBC
{
protected static $KEY_SIZES = array('AES-128'=>16,'AES-192'=>24,'AES-256'=>32);
protected static function key_size() { return self::$KEY_SIZES['AES-128']; } //default AES-128
public static function encryptFile($password, $input_stream, $aes_filename){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$fin = fopen($input_stream, "rb");
$fc = fopen($aes_filename, "wb+");
if (!empty($fin) && !empty($fc)) {
fwrite($fc, str_repeat("_", 32) );//placeholder, SHA256 HMAC will go here later
fwrite($fc, $hmac_salt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $esalt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
$opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
stream_filter_append($fc, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $opts);
$infilesize = 0;
while (!feof($fin)) {
$block = fread($fin, 8192);
$infilesize+=strlen($block);
fwrite($fc, $block);
}
$block_size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $block_size - ($infilesize % $block_size);//$padding is a number from 1-16
fwrite($fc, str_repeat(chr($padding), $padding) );//perform PKCS7 padding
fclose($fin);
fclose($fc);
$hmac_raw = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb+");
fwrite($fc, $hmac_raw);//overwrite placeholder
fclose($fc);
}
}
public static function decryptFile($password, $aes_filename, $out_stream) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$hmac_raw = file_get_contents($aes_filename, false, NULL, 0, 32);
$hmac_salt = file_get_contents($aes_filename, false, NULL, 32, $iv_size);
$hmac_calc = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb");
$fout = fopen($out_stream, 'wb');
if (!empty($fout) && !empty($fc) && self::hash_equals($hmac_raw,$hmac_calc)) {
fread($fc, 32+$iv_size);//skip sha256 hmac and salt
$esalt = fread($fc, $iv_size);
$iv = fread($fc, $iv_size);
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
$opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
stream_filter_append($fc, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
while (!feof($fc)) {
$block = fread($fc, 8192);
if (feof($fc)) {
$padding = ord($block[strlen($block) - 1]);//assume PKCS7 padding
$block = substr($block, 0, 0-$padding);
}
fwrite($fout, $block);
}
fclose($fout);
fclose($fc);
}
}
private static function hash_equals($str1, $str2) {
if(strlen($str1) == strlen($str2)) {
$res = $str1 ^ $str2;
for($ret=0,$i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
return !$ret;
}
return false;
}
private static function calculate_hmac_after_32bytes($password, $hsalt, $filename) {
static $init=0;
$init or $init = stream_filter_register("user-filter.skipfirst32bytes", "FileSkip32Bytes");
$stream = 'php://filter/read=user-filter.skipfirst32bytes/resource=' . $filename;
$hkey = hash_pbkdf2("sha256", $password, $hsalt, $iterations=1000, 24, $raw=true);
return hash_hmac_file('sha256', $stream, $hkey, $raw=true);
}
}
class FileSkip32Bytes extends php_user_filter
{
private $skipped=0;
function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$outlen = $bucket->datalen;
if ($this->skipped<32){
$outlen = min($bucket->datalen,32-$this->skipped);
$bucket->data = substr($bucket->data, $outlen);
$bucket->datalen = $bucket->datalen-$outlen;
$this->skipped+=$outlen;
}
$consumed += $outlen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
class AES_128_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-128']; }
}
class AES_192_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-192']; }
}
class AES_256_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-256']; }
}

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.


Liste des modes de transport de sockets disponibles

Sommaire

  • Domaines Internet : TCP, UDP, SSL et TLS
  • Domaine Unix : UNIX et UDG

Voici la liste des différents modes de transport, format URL, dont PHP dispose en interne pour les flux qui exploitent les sockets, tels que fsockopen() et stream_socket_client(). Ces modes de transport ne s'appliquent pas à l'extension sockets.

Pour connaître la liste des modes de transport installés sur votre version de PHP, utilisez stream_get_transports().

User Contributed Notes

alefinvest at outlook dot com 06-Aug-2021 06:47
That was hard to fetch this page mentioned in note by other user long time ago.
I intended to read Appendix P to find some code examples.
Wondering how to implement custom transport extension for php on our server tto be used with some nowadays technologies research.
https://www.php.net/manual/ru/function.stream-context-create.php#75211


Domaines Internet : TCP, UDP, SSL et TLS

ssl://, tls://, sslv2:// & sslv3://.

Note: Si aucun transport n'est spécifié, tcp:// est utilisé.

  • 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

Les sockets du domaine Internet utilisent un numéro de port en plus de l'adresse de l'hôte. Dans le cas de fsockopen(), il est spécifié en deuxième paramètre et, donc, n'a pas d'impact sur le format du mode de transport. Avec stream_socket_client() et les autres fonctions de la même famille, le numéro de port est spécifié comme un suffixe dans l'URL de transport, identifié par le signe deux-points.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Note: Adresse IPv6 et numéro de port
Dans le deuxième exemple ci-dessus, les exemples en IPv4 et les noms d'hôtes sont identiques, mais les IPv6 sont placées entre crochets, en plus d'avoir les deux-points et le numéro de port : [fe80::1]. Cela permet de distinguer les deux-points utilisés en IPv6 et le deux-points utilisés pour délimiter le numéro de port.

Les modes ssl:// et tls:// (disponibles uniquement lorsque le support OpenSSl est compilé avec PHP) sont des extensions de tcp:// qui incluent le chiffrement SSL.

ssl:// va tenter de négocier une connexion SSL V2 ou SSL V3, suivant les capacités et les références de l'hôte distant. sslv2:// et sslv3:// sélectionnent explicitement le protocole.

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.


Domaine Unix : UNIX et UDG

unix:// et udg://.

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// fournit l'accès à un flux de type socket, sur un domaine Unix. udg:// fournit un mode de transport alternatif, avec un protocole de datagrammes utilisateurs.

Les sockets du domaine Unix, contrairement à celles du domaine Internet, n'utilisent pas de numéro de port. Dans ce cas, le paramètre portno de fsockopen() doit valoir 0.

Note: Les sockets du domaine Unix ne sont pas supportés sur Windows.

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.


Comparaison de types en PHP

La table suivante résume les différents comportements de PHP avec les types et opérateurs de comparaison, stricte ou large. Cette table est aussi reliée au transtypage. Elle a été inspirée par différents commentaires d'utilisateurs, et par le travail fait chez » BlueShoes.

Avant d'utiliser ces tables, il est important de comprendre les types et leur signification. Par exemple, "42" est une chaîne de caractères, alors que 42 est un entier. false est bool alors que "false" est une chaîne de caractères.

Note:

Les formulaires HTML ne connaissent pas les entiers, nombres à virgules et autres booléens. Pour savoir si une structure est un entier, utilisez is_numeric().

Note:

La ligne if ($x) génère une erreur de niveau E_NOTICE lorsque $x est indéfini. Alternativement, utilisez plutôt les fonctions empty() ou isset(), ou encore, initialisez toutes vos variables.

Note:

Des opérations numériques peuvent donner une valeur représentée par la constante NAN. Toutes les comparaisons de cette valeur avec une autre valeur, y compris cette même valeur, à l'exception de true auront comme résultat false (i.e. NAN != NAN et NAN !== NAN). Exemples d'opérations qui produisent la valeur NAN : sqrt(-1), asin(2), et acosh(0).

Comparaisons de $x avec des fonctions PHP
Expression | gettype() | empty() | is_null() | isset() | bool : if($x)
$x = ""; | chaîne de caractères | true | false | true | false
$x = null; | NULL | true | true | false | false
var $x; | NULL | true | true | false | false
$x est indéfini | NULL | true | true | false | false
$x = []; | array | true | false | true | false
$x = ['a', 'b']; | array | false | false | true | true
$x = false; | bool | true | false | true | false
$x = true; | bool | false | false | true | true
$x = 1; | entier | false | false | true | true
$x = 42; | entier | false | false | true | true
$x = 0; | entier | true | false | true | false
$x = -1; | entier | false | false | true | true
$x = "1"; | chaîne de caractères | false | false | true | true
$x = "0"; | chaîne de caractères | true | false | true | false
$x = "-1"; | chaîne de caractères | false | false | true | true
$x = "php"; | chaîne de caractères | false | false | true | true
$x = "true"; | chaîne de caractères | false | false | true | true
$x = "false"; | string | false | false | true | true

Comparaison large avec ==
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | [] | "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 | false* | false*
-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
[] | false | true | false | false | false | false | false | false | true | true | false | false
"php" | true | false | false | false* | false | false | false | false | false | false | true | false
"" | false | true | false | false* | false | false | false | false | true | false | false | true
* true antérieur à PHP 8.0.0.

Comparaison stricte avec ===
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | [] | "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
[] | 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

Jeroen 14-Jul-2023 04:26
Be aware of the difference between checking the *value* of an array item, and checking the *existence* of an array item:
<?php
$arr = [
  'x' => 0,
  'y' => null,
];

isset($arr['x']); // true, same as isset(0)
isset($arr['y']); // false, same as isset(null)

array_key_exists('y', $arr); // true, though the value is null
array_key_exists('z', $arr); // false
ray dot paseur at SometimesUsesGmail dot com 14-Feb-2023 11:37
A colorized version of the loose comparison table is here (no copyright, nor attribution required)
https://iconoun.com/php_type_comparisons.php
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.


Liste des jetons de l'analyseur

Diverses parties du langage PHP sont représentées en interne par des jetons. Un morceau de code qui contient une séquence invalide de jetons peut mener à des erreurs telles que Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10." où le jeton == est représenté en interne par T_IS_EQUAL.

Le tableau suivant liste tous les jetons. Ils sont aussi disponibles en tant que constantes PHP.

Note: Utilisation des constantes T_*

Les valeurs des constantes T_* sont générées automatiquement en fonction de l'infrastructure sous-jacente de l'analyseur PHP. Ceci signifie que la valeur concrète d'un jeton peut changer entre deux versions de PHP. Ceci signifie que votre code ne doit jamais utiliser la valeur littérale des constantes T_* d'une version PHP X.Y.Z, pour fournir une certaine compatibilité entre plusieurs versions de PHP.

Pour utiliser les constantes T_* à travers plusieurs versions de PHP, les constantes indéfinies peuvent être définies par l'utilisateur (en utilisant des nombres larges tels que 10000) avec une stratégie approprié qui fonctionnera avec les deux versions de PHP et les valeurs de T_*.

<?php
// Antérieur à PHP 7.4.0, T_FN n'est pas définie.
defined('T_FN') || define('T_FN', 10001);

Jetons
Jeton | Syntaxe | Référence
T_ABSTRACT | abstract | Abstraction de classes
T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG | & | Déclarations de type (disponible à partir de PHP 8.1.0)
T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG | & | Déclarations de type (disponible à partir de PHP 8.1.0)
T_AND_EQUAL | &= | opérateurs d'assignation
T_ARRAY | array() | array(), syntaxe de tableau
T_ARRAY_CAST | (array) | transtypage
T_AS | as | foreach
T_ATTRIBUTE | #[ | attributs (disponible à partir de PHP 8.0.0)
T_BAD_CHARACTER |  | Tous les caractères en dessous de ASCII 32 exceptés \t (0x09), \n (0x0a) et \r (0x0d) (disponible à partir de PHP 7.4.0)
T_BOOLEAN_AND | && | opérateurs logiques
T_BOOLEAN_OR | || | opérateurs logiques
T_BOOL_CAST | (bool) ou (boolean) | transtypage
T_BREAK | break; | break
T_CALLABLE | callable | callable
T_CASE | case | switch
T_CATCH | catch | Les exceptions
T_CLASS | class | classes et objets
T_CLASS_C | __CLASS__ | constantes magiques
T_CLONE | clone | classes et objets
T_CLOSE_TAG | ?> or %> | échapper depuis le HTML
T_COALESCE | ?? | opérateurs de comparaison
T_COALESCE_EQUAL | ??= | opérateurs d'assignation (disponible à partir de PHP 7.4.0)
T_COMMENT | // ou #, et /* */ | commentaires
T_CONCAT_EQUAL | .= | opérateurs d'assignation
T_CONST | const | constantes de classe
T_CONSTANT_ENCAPSED_STRING | "foo" ou 'bar' | syntaxe chaîne de caractères
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | syntaxe d'analyse de variable complexe
T_DEC | -- | opérateurs d'incrémentation/décrémentation
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | constantes magiques
T_DIV_EQUAL | /= | opérateurs d'assignation
T_DNUMBER | 0.12, etc. | nombres à virgule flottante
T_DO | do | do..while
T_DOC_COMMENT | /** */ | style de commentaire dans la PHPDoc
T_DOLLAR_OPEN_CURLY_BRACES | ${ | syntaxe de variable complexe analysée
T_DOUBLE_ARROW | => | syntaxe de tableau
T_DOUBLE_CAST | (real), (double) ou (float) | transtypage
T_DOUBLE_COLON | :: | Voyez T_PAAMAYIM_NEKUDOTAYIM plus bas
T_ECHO | echo | echo
T_ELLIPSIS | ... | les arguments de fonction
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | partie des constantes d'une chaîne de caractères contenant des variables
T_ENDDECLARE | enddeclare | declare, syntaxe alternative
T_ENDFOR | endfor | for, syntaxe alternative
T_ENDFOREACH | endforeach | foreach, syntaxe alternative
T_ENDIF | endif | if, syntaxe alternative
T_ENDSWITCH | endswitch | switch, syntaxe alternative
T_ENDWHILE | endwhile | while, syntaxe alternative
T_ENUM | enum | Énumérations (disponible à partir de PHP 8.1.0)
T_END_HEREDOC |  | syntaxe heredoc
T_EVAL | eval() | eval()
T_EXIT | exit ou die | exit(), die()
T_EXTENDS | extends | extends, classes et objets
T_FILE | __FILE__ | constantes magiques
T_FINAL | final | Mot-clé "final"
T_FINALLY | finally | Les exceptions
T_FN | fn | fonctions fléchées (disponible à partir de PHP 7.4.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function | fonctions
T_FUNC_C | __FUNCTION__ | constantes magiques
T_GLOBAL | global | scope de variable
T_GOTO | goto | goto
T_HALT_COMPILER | __halt_compiler() | __halt_compiler
T_IF | if | if
T_IMPLEMENTS | implements | Interfaces
T_INC | ++ | opérateurs d'incrémentation/décrémentation
T_INCLUDE | include | include
T_INCLUDE_ONCE | include_once | include_once
T_INLINE_HTML |  | texte en dehors de PHP
T_INSTANCEOF | instanceof | opérateurs de type
T_INSTEADOF | insteadof | Traits
T_INTERFACE | interface | Interfaces
T_INT_CAST | (int) ou (integer) | transtypage
T_ISSET | isset() | isset()
T_IS_EQUAL | == | opérateurs de comparaison
T_IS_GREATER_OR_EQUAL | >= | opérateurs de comparaison
T_IS_IDENTICAL | === | opérateurs de comparaison
T_IS_NOT_EQUAL | != ou <> | opérateurs de comparaison
T_IS_NOT_IDENTICAL | !== | opérateurs de comparaison
T_IS_SMALLER_OR_EQUAL | <= | opérateurs de comparaison
T_LINE | __LINE__ | constantes magiques
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc. | entiers
T_LOGICAL_AND | and | opérateurs logiques
T_LOGICAL_OR | or | opérateurs logiques
T_LOGICAL_XOR | xor | opérateurs logiques
T_MATCH | match | match (disponible à partir de PHP 8.0.0)
T_METHOD_C | __METHOD__ | constantes magiques
T_MINUS_EQUAL | -= | opérateurs d'assignation
T_MOD_EQUAL | %= | opérateurs d'assignation
T_MUL_EQUAL | *= | opérateurs d'assignation
T_NAMESPACE | namespace | espaces de noms
T_NAME_FULLY_QUALIFIED | \App\Namespace | espaces de noms (disponible à partir de PHP 8.0.0)
T_NAME_QUALIFIED | App\Namespace | namespaces (disponible à partir de PHP 8.0.0)
T_NAME_RELATIVE | namespace\Namespace | namespaces (disponible à partir de PHP 8.0.0)
T_NEW | new | classes et objets
T_NS_C | __NAMESPACE__ | espaces de noms
T_NS_SEPARATOR | \ | espaces de noms
T_NUM_STRING | "$a[0]" | index d'un tableau numérique se trouvant dans une chaîne de caractères
T_OBJECT_CAST | (object) | transtypage
T_OBJECT_OPERATOR | -> | classes et objets
T_NULLSAFE_OBJECT_OPERATOR | ?-> | classes et objets
T_OPEN_TAG | <?php, <? or <% | sortie du mode HTML
T_OPEN_TAG_WITH_ECHO | <?= ou <%= | sortie du mode HTML
T_OR_EQUAL | |= | opérateurs d'assignation
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Définie également en tant que T_DOUBLE_COLON.
T_PLUS_EQUAL | += | opérateurs d'assignation
T_POW | ** | les opérateurs arithmétiques
T_POW_EQUAL | **= | les opérateurs d'affectation
T_PRINT | print | print
T_PRIVATE | private | classes et objets
T_PROTECTED | protected | classes et objets
T_PUBLIC | public | classes et objets
T_READONLY | readonly | classes et objets (disponible à partir de PHP 8.1.0)
T_REQUIRE | require | require
T_REQUIRE_ONCE | require_once | require_once
T_RETURN | return | valeurs retournées
T_SL | << | opérateurs sur les bits
T_SL_EQUAL | <<= | opérateurs d'assignation
T_SPACESHIP | <=> | opérateurs de comparaisons
T_SR | >> | opérateurs sur les bits
T_SR_EQUAL | >>= | opérateurs d'assignation
T_START_HEREDOC | <<< | syntaxe heredoc
T_STATIC | static | scope de variable
T_STRING | parent, self, etc. | identifiants, e.g. mots-clés comme parent et self, noms de fonctions, classes et autres, correspondent. Voir aussi T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST | (string) | transtypage
T_STRING_VARNAME | "${a | syntaxe d'analyse d'une variable complexe
T_SWITCH | switch | switch
T_THROW | throw | Les exceptions
T_TRAIT | trait | Traits
T_TRAIT_C | __TRAIT__ | __TRAIT__
T_TRY | try | Les exceptions
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | type-casting
T_USE | use | namespaces
T_VAR | var | classes et objets
T_VARIABLE | $foo | variables
T_WHILE | while | while, do...while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | opérateurs d'assignation
T_YIELD | yield | générateurs
T_YIELD_FROM | yield from | générateurs

Voir aussi 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.


Guide de nommage de l'espace utilisateur

Sommaire

  • Espace de noms global
  • Règles
  • Astuces

Ce guide permet de choisir de la meilleure façon possible les noms pour les identifiants dans le code PHP de l'espace utilisateur. Lors du choix des noms pour n'importe quel code qui crée des symboles dans l'espace de noms global, il est important de prendre en compte ce guide afin d'éviter d'éventuels problèmes avec les futures versions de PHP et vos symboles.

User Contributed Notes

There are no user contributed notes for this page.


Espace de noms global

Ceci est une vue de la construction du code qui ira dans l'espace de noms global :

  • fonctions

  • classes

  • interfaces

  • constantes (et non les constantes de classe)

  • variables définies à l'extérieur des fonctions/méthodes

User Contributed Notes

There are no user contributed notes for this page.


Règles

La liste suivante fournit un aperçu global des règles réservées au projet PHP lors du choix des noms pour les nouveaux identifiants internes. Le guide définitif est l'officiel » CODING STANDARDS :

  • PHP possède l'espace de noms de haut niveau mais tente de trouver des noms descriptifs cohérents.

  • Les noms des fonctions utilisent un underscore entre les mots, tandis que les noms des classes utilisent les notations camelCase et PascalCase.

  • PHP préfixe tous les symboles globaux d'une extension avec le nom de l'extension. (Dans le passé, il y avait quelques exceptions à cette règle) Exemples :

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (exemple d'une erreur du passé)

    • new SplFileObject()

  • Les itérateurs et les exceptions sont cependant simplement suffixés par respectivement, "Iterator" et "Exception." Exemples :

    • ArrayIterator

    • LogicException

  • PHP réserve tous les symboles commençant par un __ comme étant magique. Il est recommandé de ne pas créer de symboles commençant par un __ en PHP sauf si vous voulez utiliser les fonctionnalités magiques documentées. Exemple :

    • __get()

    • __autoload()

User Contributed Notes

There are no user contributed notes for this page.


Astuces

Si vous voulez écrire du code portable, il est recommandé de ne pas placer de nombreuses variables, fonctions ou classes dans l'espace de noms global. Cela empêchera les conflits de nommage avec le code tiers ainsi que des ajouts possibles au langage.

Une façon commune de prévenir les conflits de noms de fonctions et de classes est de les ajouter à leur propre namespace.

<?php

namespace MyProject;

function my_function() {
return true;
}

\MyProject\my_function();

Cela a encore besoin de vous pour garder une trace des espaces de noms déjà utilisés, mais une fois que vous avez décidé sur un espace de noms que vous allez utiliser, vous pouvez ajouter toutes les fonctions et les classes à elle sans avoir à penser à nouveau les conflits.

Il est considéré comme la meilleure pratique pour limiter le nombre de variables ajoutées à la portée globale afin d'éviter les conflits de nommage avec le code tiers.

Note: Portée des variables

En raison des règles de portée de PHP, les variables définies à l'intérieur des fonctions et des méthodes ne sont pas dans la portée globale et, en tant que telles, ne peuvent pas entrer en conflit avec d'autres variables définies dans la portée globale.

User Contributed Notes

There are no user contributed notes for this page.


À propos du manuel

Sommaire

  • Formats
  • À propos des notes utilisateurs
  • Comment lire la définition d'une fonction (prototype)
  • Versions de PHP documentées dans ce manuel
  • Où trouver plus d'informations sur PHP ?
  • Comment aider à l'amélioration de la documentation ?
  • Comment sont générées les documentations
  • Traductions

User Contributed Notes

There are no user contributed notes for this page.


Formats

Le manuel PHP est fourni en différents formats. Ces formats sont divisés en deux groupes : ceux qui sont disponibles en ligne et les téléchargeables.

Note:

Certains éditeurs ont fourni des versions imprimées de ce manuel. Nous n'en recommandons aucune, car elles sont rapidement obsolètes.

Le manuel peut être lu en ligne sur le site » php.net. La version en ligne du manuel PHP a actuellement deux rendus CSS : un rendu agréable à l'œil et un pratique pour l'impression.

Deux avantages du manuel en ligne sur la plupart des formats téléchargeables, sont l'intégration des notes des utilisateurs et les » URL de raccourci que vous pouvez utiliser pour accéder rapidement à une partie du manuel. Un inconvénient évident est que vous devez être en ligne pour profiter de ce format.

Il y a de nombreux formats du manuel pour la consultation hors ligne, et le format le plus approprié dépend de votre OS et de vos goûts personnels. Pour savoir comment le manuel est généré, lisez la section 'Comment le manuel est généré' de cet appendice.

Le format le plus portable est le HTML. Le manuel est fourni dans un format en une seule page HTML, ou comme un ensemble de fichiers de tailles réduites (mais un bon millier de fichiers tout de même). Nous fournissons ce format sous une forme compressée, vous aurez donc besoin d'un utilitaire de décompression pour extraire les fichiers de l'archive.

Pour les plates-formes Windows, le format Windows HTML Help fournit une version HTML du manuel à utiliser avec l'application Windows HTML Help : il intègre un moteur de recherche complet, un index et des signets. De nombreux IDE sous Windows fournissent des liens avec ce format pour une meilleure intégration. Il existe aussi des visualiseurs de CHM pour Linux. Visitez » xCHM ou » GnoCHM.

Il existe aussi une » version CHM étendue, qui est mise à jour moins souvent mais qui fournit plus de fonctionnalités. Elle ne fonctionnera que sur Microsoft Windows à cause des technologies utilisées pour construire ces pages.

User Contributed Notes

There are no user contributed notes for this page.


À propos des notes utilisateurs

Les notes des utilisateurs jouent un rôle très important dans le développement de ce manuel. En permettant aux lecteurs de contribuer par des exemples, des remarques et critiques, ou encore des clarifications, nous intégrons des aspects très importants du langage dans le manuel. Jusqu'à ce que les notes les plus importantes soient intégrées dans la documentation, elles sont disponibles sur le site lui-même, et dans certains formats hors ligne.

Note:

Les notes des utilisateurs ne sont pas modérées avant d'apparaître sur le site, et même si elles le sont, leur véracité ne peut être garantie, pas plus qu'il n'existe de garantie quand à l'exactitude du manuel lui-même.

Note:

Pour des questions de portée de licence, les notes utilisateurs sont considérées comme faisant partie du manuel PHP, et sont donc couvertes par la même licence qui couvre cette documentation (Creative Commons Attribution à ce jour). Pour plus de détails, lisez la page Manual's Copyright.

User Contributed Notes

There are no user contributed notes for this page.


Comment lire la définition d'une fonction (prototype)

Chaque fonction dans le manuel est documentée pour permettre une compréhension rapide. Savoir décoder le texte rendra votre apprentissage plus facile. Plutôt que de dépendre d'exemples prêts à copier/coller, il est plus utile de savoir lire la définition d'une fonction (prototype). Voici comment :

Note: Pré-requis : Connaissances de base des types.

Bien que PHP soit un langage sans typage fort, une connaissance de base des types est essentielle, car ils ont quand même des sens importants.

Les définitions de fonctions vous indiquent quel type de données est retourné. Examinons la fonction strlen() comme exemple :

strlen

(PHP 4, PHP 5, PHP 7)
strlen -- Retourne la taille de la chaîne

Description
strlen ( string $string ) : int

Retourne la taille de la chaîne $string.

Explications de la définition de la fonction
Partie | Description
strlen | Le nom de la fonction.
(PHP 4, PHP 5, PHP 7) | strlen() est présente dans toutes les versions de PHP 4, 5 et 7.
( string $string ) | Le premier (et ici le seul) paramètre à fournir à cette fonction est le paramètre string, qui doit être du type chaîne de caractères.
int | Type de valeur retournée par cette fonction, qui est, en l'occurrence, un entier (i.e. la taille d'une chaîne est mesurée par un nombre).

Nous pourrions réécrire ce prototype avec une version plus générique :

      nom de la fonction    ( type du paramètre   nom du paramètre ) : type de retour

Plusieurs fonctions ont besoin de plusieurs paramètres, comme in_array(). Son prototype est le suivant :

      in_array ( mixed $needle, array $haystack , bool $strict = false ) : bool

Qu'est ce que cela signifie ? in_array() retourne un booléen true en cas de réussite (le paramètre needle a été trouvé dans le tableau haystack) ou false si une erreur survient (le paramètre needle n'a pas été trouvé dans le tableau haystack). Le premier paramètre s'appelle needle et il peut être de différents types : il porte donc la mention mixed. Le paramètre needle (ce que nous recherchons) peut être une valeur scalaire ( chaîne de caractères, entier, ou float), ou encore un array. haystack (le array, dans lequel nous recherchons) est le second paramètre. Le troisième paramètre, optionnel, strict, est optionnel. Tous les paramètres optionnels ont une valeur par défaut ; si la valeur par défaut est inconnue, elle est affichée en tant que ?. Le manuel indique que le paramètre strict vaut par défaut false. Reportez-vous au manuel de chaque fonction pour savoir comment elle fonctionne.

De plus, le signe & (é commercial) ajouté au début du paramètre d'une fonction permet de passer ce paramètre par référence, comme ceci :

       preg_match ( string $pattern , string $subject , array &$matches = null,
       int $flags = 0 , int $offset = 0 ) : int|false

Dans cet exemple, nous pouvons voir que le troisième paramètre optionnel &$matches va être passé par référence.

Il y a aussi des fonctions avec des informations plus complexes concernant les versions de PHP. Prenons html_entity_decode() comme exemple :

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

Cela signifie que cette fonction n'est disponible que depuis PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Versions de PHP documentées dans ce manuel

Ce manuel contient des informations sur les anciennes, actuelles et futures versions de PHP. Les modifications de comportement sont documentées sous la forme de notes, d'historiques de version, mais aussi dans les pages du manuel. La version documentée la plus ancienne est la version 7.0.0.

Lorsque la documentation existe pour les dernières versions de développement (non publiées) de PHP, elle sera intitulée "disponible dans Git" ou "version de développement." Ces changements sont prévus, mais peuvent encore évoluer dans de rares cas.

Tous les développements sont versionnés dans le dépot Git et peuvent être récupérés comme décrit dans » accès anonyme Git.

Et par souci de clarté, le manuel fera référence aux versions majeures, mineures et révisions de PHP. Par exemple PHP 7.3.1, le 7 est la version majeure, 3 la mineure, et 1 la révision. Typiquement PHP n'ajoute de nouvelles fonctionnalités que dans les versions majeures ou mineures, et corrige des bugs dans les révisions. Cependant, cette convention n'est pas toujours vérifiée.

Notez aussi que le manuel concerne PHP présent et non futur, même pour les fonctionnalités documentées et qui ne sont pas encore disponibles. Ainsi le manuel peut perdurer dans le temps et ne requiert pas de mises à jour importantes à chaque sortie de PHP.

À plusieurs reprises, le manuel de PHP liste les valeurs par défaut des directives PHP. Ces valeurs sont basées sur le comportement de PHP sans fichier de configuration php.ini, ainsi ceci peut changer des valeurs trouvées dans les fichiers distribués php.ini-development et php.ini-production . Les valeurs indiquées sont aussi celles de la dernière version de PHP, un changelog indique les valeurs précédemment employées. Voyez l'appendice sur les directives PHP pour plus de détails sur ces valeurs et leurs évolutions.

User Contributed Notes

There are no user contributed notes for this page.


Où trouver plus d'informations sur PHP ?

Ce manuel n'a pas pour objectif de fournir des présentations sur les pratiques de programmation. Si vous êtes un néophyte total, ou même un programmeur débutant, vous pouvez trouver difficile d'apprendre la programmation PHP avec uniquement ce manuel : il serait mieux de trouver des ressources plus orientées vers l'apprentissage.

Il y a un bon nombre de listes de diffusion actives, traitant de tous les aspects du langage et de la programmation PHP. Si vous êtes bloqué par un problème, vous pourrez sûrement trouver de l'aide auprès de ces listes. Il existe un recensement des listes de diffusion sur » la page de support de php.net.

User Contributed Notes

There are no user contributed notes for this page.


Comment aider à l'amélioration de la documentation ?

Il y a plusieurs façons de participer à l'amélioration de la documentation.

Si une erreur est trouvée, dans n'importe quelle traduction de la documentation, veuillez rapporter le bogue sur le gestionnaire d'issue du dépôt de langue respectif à » https://github.com/php; par exemple, les erreurs dans le manuel anglais doivent être rapporté à » https://github.com/php/doc-en/issues; Toutes les issues en rapport avec la documentation, ainsi que ses formats, devraient être soumis comme des bogues.

Note:

N'abusez pas du gestionnaire d'issues pour envoyer des demandes d'aide. Utilisez plutôt une des options proposées par le » support.

En contribuant aux notes, vous pouvez fournir de nouveaux exemples, mettre en lumière des effets de bords et apporter des clarifications pour les autres lecteurs. Mais ne prenez pas le système d'annotation pour un système de soumission de bogues. Vous pouvez en savoir plus sur les annotations dans la section 'À propos des notes utilisateurs'

Il est aussi possible de soumettre des pull requests au » miroir Github du repository de la documentation.

Le manuel PHP est traduit en de nombreux langages. La connaissance de l'anglais ainsi que d'une autre langue peut vous permettre d'aider la documentation de PHP en travaillant avec une équipe de traduction. Pour plus d'informations sur le commencement d'une traduction, ou sur l'aide d'une version déjà traduite, commencez par lire » http://doc.php.net/tutorial/.

Le projet de documentation de PHP a un canal IRC où vous pouvez venir et parler avec les auteurs du manuel ou trouver un certain aspect du manuel avec lequel vous pourriez aider. Les coordonnées : #php.doc sur irc.efnet.org.

User Contributed Notes

There are no user contributed notes for this page.


Comment sont générées les documentations

Ce manuel est écrit en XML, en utilisant la » DTD de DocBook XML, et » PhD (Le moteur [PH]P d'affichage [D]ocBook) pour la maintenance et le formatage.

Grâce au format XML comme source, nous avons la possibilité de générer de nombreux formats tout en ayant une seule source pour tous les formats. L'outil utilisé pour formater le manuel en ligne est » PhD. Nous utilisons » Microsoft HTML Help Workshop pour générer le format Windows HTML Help du manuel, et, bien sûr, PHP lui-même pour effectuer des conversions et du formatage.

Le manuel PHP est généré en de nombreux langages et formats, lisez » https://www.php.net/docs.php pour plus d'informations. Le code source XML peut être téléchargé depuis git et visualisé sur » https://github.com/php/doc-en.

User Contributed Notes

There are no user contributed notes for this page.


Traductions

La manuel PHP est disponible non seulement en anglais, mais aussi dans différentes langues. Le texte du manuel est écrit d'abord en anglais, puis des équipes à travers le monde assurent la traduction du manuel dans leur langue natale. Si la traduction d'une section n'est pas encore disponible, le système de création de la documentation présentera alors la version anglaise.

Les contributeurs aux documentations partent des codes sources XML disponibles à partir de » https://github.com/php/doc-en. puis traduisent dans leur langue. Ils n'utilisent pas les versions générées (comme le HTML ou le texte plein) car c'est le système d'édition qui se charge de faire les conversions du format XML vers un format lisible.

Note:

Si vous voulez aider à la traduction de la documentation, entrez en contact avec l'équipe de documentation en vous inscrivant à la liste de diffusion : » phpdoc-subscribe@lists.php.net. L'adresse de la liste de diffusion est phpdoc@lists.php.net. Indiquez dans le message que vous êtes intéressé par la traduction de la documentation dans une nouvelle langue, et quelqu'un viendra vous aider à démarrer une nouvelle traduction, ou rejoindre l'équipe qui a pris en charge cette traduction.

Actuellement, le manuel est disponible, partiellement ou en totalité, dans plus de 10 langues.

Ils peuvent tous être téléchargés ici : » 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.


Liste de l'index

Sommaire

  • Liste des fonctions et des méthodes
  • Liste d'exemples

User Contributed Notes

There are no user contributed notes for this page.


Liste des fonctions et des méthodes

Liste de toutes les fonctions et méthodes du manuel

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 - Valeur absolue
    • acos - Arc cosinus
    • acosh - Arc cosinus hyperbolique
    • addcslashes - Ajoute des slash dans une chaîne, à la mode du langage C
    • addslashes - Ajoute des antislashs dans une chaîne
    • AllowDynamicProperties::__construct - Construit une nouvelle instance d'attribut AllowDynamicProperties
    • apache_child_terminate - Termine le processus Apache après cette requête
    • apache_getenv - Lit une variable de processus Apache
    • apache_get_modules - Retourne la liste des modules Apache chargés
    • apache_get_version - Récupère la version d'Apache
    • apache_lookup_uri - Effectue une requête partielle pour l'URI spécifiée et renvoie toutes les informations la concernant
    • apache_note - Affiche ou affecte la table des notes d'Apache
    • apache_request_headers - Récupère tous les en-têtes HTTP de la requête
    • apache_response_headers - Récupère tous les en-têtes de réponse HTTP
    • apache_setenv - Modifie une variable de processus Apache
    • APCUIterator::current - Retourne l'élément courant
    • APCUIterator::getTotalCount - Retourne le compte total
    • APCUIterator::getTotalHits - Retourne le nombre total d'accès au cache
    • APCUIterator::getTotalSize - Retourne la taille totale du cache
    • APCUIterator::key - Retourne la clé de l'élément courant
    • APCUIterator::next - Déplace le pointeur sur l'élément suivant
    • APCUIterator::rewind - Replace l'itérateur sur le premier élément
    • APCUIterator::valid - Vérifie si la position courante est valide
    • APCUIterator::__construct - Construit un objet itérateur de la classe APCUIterator
    • apcu_add - Met en cache une nouvelle variable dans le dépôt de données
    • apcu_cache_info - Récupère les informations mises en cache dans le dépôt de données d'APCu
    • apcu_cas - Remplace une ancienne valeur par une nouvelle
    • apcu_clear_cache - Efface le cache APCu
    • apcu_dec - Décrémente un nombre stocké
    • apcu_delete - Retire une variable stockée du cache
    • apcu_enabled - Vérifie si APCu est utilisable dans l'environnement courant
    • apcu_entry - Récupère atomiquement ou génère une entrée de cache
    • apcu_exists - Vérifie si une entrée existe
    • apcu_fetch - Récupère une variable stockée dans le cache
    • apcu_inc - Incrémente un nombre stocké
    • apcu_key_info - Retourne des informations détaillées sur la clé de cache
    • apcu_sma_info - Retourne des informations sur l'Allocation de Mémoire Partagée d'APCu
    • apcu_store - Met en cache une variable dans le dépôt de données
    • AppendIterator::append - Ajoute un itérateur à la fin
    • AppendIterator::current - Lit la valeur courante
    • AppendIterator::getArrayIterator - Récupère le ArrayIterator
    • AppendIterator::getIteratorIndex - Lit l'index d'un itérateur
    • AppendIterator::key - Lit la clé courante
    • AppendIterator::next - Passe à l'élément suivant
    • AppendIterator::rewind - Remet l'itérateur au début
    • AppendIterator::valid - Vérifie la validité de l'élément courant
    • AppendIterator::__construct - Construit un objet AppendIterator
    • array - Crée un tableau
    • ArrayAccess::offsetExists - Indique si une position existe dans un tableau
    • ArrayAccess::offsetGet - Position à lire
    • ArrayAccess::offsetSet - Assigne une valeur à une position donnée
    • ArrayAccess::offsetUnset - Supprime un élément à une position donnée
    • ArrayIterator::append - Ajoute un élément
    • ArrayIterator::asort - Trie les entrées par les valeurs
    • ArrayIterator::count - Compte les éléments
    • ArrayIterator::current - Retourne l'entrée courante du tableau
    • ArrayIterator::getArrayCopy - Récupère la copie d'un tableau
    • ArrayIterator::getFlags - Récupère les drapaux de comportement
    • ArrayIterator::key - Retourne la clé courante du tableau
    • ArrayIterator::ksort - Trie les entrées par les clés
    • ArrayIterator::natcasesort - Trie naturellement les entrées, en ne tenant pas compte de la casse
    • ArrayIterator::natsort - Trie naturellement les entrées
    • ArrayIterator::next - Se déplace vers la prochaine entrée
    • ArrayIterator::offsetExists - Vérifie si une position existe
    • ArrayIterator::offsetGet - Récupère la valeur pour une position
    • ArrayIterator::offsetSet - Définit la valeur d'une position
    • ArrayIterator::offsetUnset - Efface la valeur d'une position
    • ArrayIterator::rewind - Revient à la position initiale
    • ArrayIterator::seek - Avance à une position donnée
    • ArrayIterator::serialize - Sérialisation
    • ArrayIterator::setFlags - Définie les drapeaux de comportements
    • ArrayIterator::uasort - Trier avec une fonction de comparaison définie par l'utilisateur et maintient l'association de l'index
    • ArrayIterator::uksort - Trier par clés à l'aide d'une fonction de comparaison définie par l'utilisateur
    • ArrayIterator::unserialize - Désérialisation
    • ArrayIterator::valid - Vérifie si un tableau contient d'autres entrées
    • ArrayIterator::__construct - Construit un ArrayIterator
    • ArrayObject::append - Ajoute la valeur à la fin d'un tableau
    • ArrayObject::asort - Trie les éléments par valeur
    • ArrayObject::count - Retourne le nombre de propriétés publiques dans l'objet ArrayObject
    • ArrayObject::exchangeArray - Remplace un tableau par un autre
    • ArrayObject::getArrayCopy - Crée une copie de l'objet ArrayObject
    • ArrayObject::getFlags - Lit les options de comportement
    • ArrayObject::getIterator - Crée un nouvel itérateur à partir d'un objet ArrayObject
    • ArrayObject::getIteratorClass - Lit le nom de la classe de ArrayObject
    • ArrayObject::ksort - Trie un tableau par clé
    • ArrayObject::natcasesort - Trie un tableau en utilisant le tri naturel sans la casse
    • ArrayObject::natsort - Trie les éléments avec un tri naturel
    • ArrayObject::offsetExists - Vérifie si un index existe
    • ArrayObject::offsetGet - Retourne la valeur de l'index spécifié
    • ArrayObject::offsetSet - Définie $newval comme valeur à l'$index spécifié
    • ArrayObject::offsetUnset - Efface la valeur à l'$index spécifié
    • ArrayObject::serialize - Sérialise un ArrayObject
    • ArrayObject::setFlags - Configure les options de comportement
    • ArrayObject::setIteratorClass - Définit le nom de la classe de l'itérateur pour l'objet ArrayObject
    • ArrayObject::uasort - Trie les éléments avec une fonction utilisateur
    • ArrayObject::uksort - Trie les éléments par clé avec une fonction utilisateur
    • ArrayObject::unserialize - Désérialisation d'un ArrayObject
    • ArrayObject::__construct - Construit un nouvel objet tableau
    • array_change_key_case - Change la casse de toutes les clés d'un tableau
    • array_chunk - Sépare un tableau en tableaux de taille inférieure
    • array_column - Retourne les valeurs d'une colonne d'un tableau d'entrée
    • array_combine - Crée un tableau à partir de deux autres tableaux
    • array_count_values - Compte les occurrences de chaque valeur distincte dans un tableau
    • array_diff - Calcule la différence entre des tableaux
    • array_diff_assoc - Calcule la différence de deux tableaux, en prenant aussi en compte les clés
    • array_diff_key - Calcule la différence de deux tableaux en utilisant les clés pour comparaison
    • array_diff_uassoc - Calcule la différence entre deux tableaux associatifs, à l'aide d'une fonction de rappel
    • array_diff_ukey - Calcule la différence entre deux tableaux en utilisant une fonction de rappel sur les clés pour comparaison
    • array_fill - Remplit un tableau avec une même valeur
    • array_fill_keys - Remplit un tableau avec des valeurs, en spécifiant les clés
    • array_filter - Filtre les éléments d'un tableau grâce à une fonction de rappel
    • array_flip - Remplace les clés par les valeurs, et les valeurs par les clés
    • array_intersect - Calcule l'intersection de tableaux
    • array_intersect_assoc - Calcule l'intersection de deux tableaux avec des tests sur les index
    • array_intersect_key - Calcule l'intersection de deux tableaux en utilisant les clés pour comparaison
    • array_intersect_uassoc - Calcule l'intersection de deux tableaux avec des tests sur les index, compare les index en utilisant une fonction de rappel
    • array_intersect_ukey - Calcule l'intersection de deux tableaux en utilisant une fonction de rappel sur les clés pour comparaison
    • array_is_list - Vérifie si un array donné est une liste
    • array_keys - Retourne toutes les clés ou un ensemble des clés d'un tableau
    • array_key_exists - Vérifie si une clé existe dans un tableau
    • array_key_first - Récupère la première clé d'un tableau
    • array_key_last - Récupère la dernière clé d'un tableau
    • array_map - Applique une fonction sur les éléments d'un tableau
    • array_merge - Fusionne plusieurs tableaux en un seul
    • array_merge_recursive - Combine un ou plusieurs tableaux ensemble, récursivement
    • array_multisort - Trie les tableaux multidimensionnels
    • array_pad - Complète un tableau avec une valeur jusqu'à la longueur spécifiée
    • array_pop - Dépile un élément de la fin d'un tableau
    • array_product - Calcule le produit des valeurs du tableau
    • array_push - Empile un ou plusieurs éléments à la fin d'un tableau
    • array_rand - Prend une ou plusieurs clés, au hasard dans un tableau
    • array_reduce - Réduit itérativement un tableau
    • array_replace - Remplace les éléments d'un tableau par ceux d'autres tableaux
    • array_replace_recursive - Remplace récursivement dans le premier tableau les éléments des autres tableaux fournis
    • array_reverse - Inverse l'ordre des éléments d'un tableau
    • array_search - Recherche dans un tableau la première clé associée à la valeur
    • array_shift - Dépile un élément au début d'un tableau
    • array_slice - Extrait une portion de tableau
    • array_splice - Efface et remplace une portion de tableau
    • array_sum - Calcule la somme des valeurs du tableau
    • array_udiff - Calcule la différence entre deux tableaux en utilisant une fonction rappel
    • array_udiff_assoc - Calcule la différence entre des tableaux avec vérification des index, compare les données avec une fonction de rappel
    • array_udiff_uassoc - Calcule la différence de deux tableaux associatifs, compare les données et les index avec une fonction de rappel
    • array_uintersect - Calcule l'intersection de deux tableaux, compare les données en utilisant une fonction de rappel
    • array_uintersect_assoc - Calcule l'intersection de deux tableaux avec des tests sur l'index, compare les données en utilisant une fonction de rappel
    • array_uintersect_uassoc - Calcule l'intersection de deux tableaux avec des tests sur l'index, compare les données et les index des deux tableaux en utilisant une fonction de rappel séparée
    • array_unique - Dédoublonne un tableau
    • array_unshift - Empile un ou plusieurs éléments au début d'un tableau
    • array_values - Retourne toutes les valeurs d'un tableau
    • array_walk - Exécute une fonction fournie par l'utilisateur sur chacun des éléments d'un tableau
    • array_walk_recursive - Applique une fonction de rappel récursivement à chaque membre d'un tableau
    • arsort - Trie un tableau en ordre décroissant et conserve l'association des index
    • asin - Arc sinus
    • asinh - Arc sinus hyperbolique
    • asort - Trie un tableau en ordre croissant et conserve l'association des index
    • assert - Vérifie une assertion
    • assert_options - Définit/récupère différentes options d'assertions
    • atan - Arc tangente
    • atan2 - Arc tangent de deux variables
    • atanh - Arc tangente hyperbolique
    • Attribute::__construct - Construit une nouvelle instance de Attribute
  • b
    • BackedEnum::from - Convertit un scalaire en une instance d'enum
    • BackedEnum::tryFrom - Associe un scalaire à une instance d'enum ou à null
    • base64_decode - Décode une chaîne en MIME base64
    • base64_encode - Encode une chaîne en MIME base64
    • basename - Retourne le nom de la composante finale d'un chemin
    • BaseResult::getWarnings - Fetch warnings from last operation
    • BaseResult::getWarningsCount - Fetch warning count from last operation
    • base_convert - Convertit un nombre entre des bases arbitraires
    • bcadd - Additionne deux nombres de grande taille
    • bccomp - Compare deux nombres de grande taille
    • bcdiv - Divise deux nombres de grande taille
    • bcmod - Retourne le reste d'une division entre nombres de grande taille
    • bcmul - Multiplie deux nombres de grande taille
    • bcpow - Élève un nombre à une puissance donnée
    • bcpowmod - Calcule le reste modulo d'un nombre élevé à une puissance
    • bcscale - Définit ou récupère la précision par défaut pour toutes les fonctions bc math
    • bcsqrt - Récupère la racine carrée d'un nombre de grande taille
    • bcsub - Soustrait un nombre de grande taille d'un autre
    • bin2hex - Convertit des données binaires en représentation hexadécimale
    • bindec - Convertit de binaire en décimal
    • bindtextdomain - Spécifie ou récupère le chemin d'un domaine
    • bind_textdomain_codeset - Spécifie ou récupère le jeu de caractères utilisé pour les messages du domaine DOMAIN
    • boolval - Récupère la valeur booléenne d'une variable
    • bzclose - Ferme un fichier bzip2
    • bzcompress - Compresse une chaîne avec bzip2
    • bzdecompress - Décompresse une chaîne bzip2
    • bzerrno - Retourne le code d'erreur bzip2
    • bzerror - Retourne le numéro et le message d'erreur bzip2 dans un tableau
    • bzerrstr - Retourne le message d'erreur bzip2
    • bzflush - Ne fait rien
    • bzopen - Ouvre un fichier compressé avec bzip2
    • bzread - Lecture binaire d'un fichier bzip2
    • bzwrite - Écriture binaire dans un fichier bzip2
  • c
    • CachingIterator::count - Le nombre d'éléments de l'itérateur
    • CachingIterator::current - Retourne l'élément courant
    • CachingIterator::getCache - Lit le contenu du cache
    • CachingIterator::getFlags - Lit les options utilisées
    • CachingIterator::hasNext - Vérifie si l'itérateur interne a un élément suivant valide
    • CachingIterator::key - Retourne l'index de l'élément courant
    • CachingIterator::next - Déplace l'itérateur à la position suivante
    • CachingIterator::offsetExists - Vérifie l'existence d'un offset
    • CachingIterator::offsetGet - L'élément à lire à la position donnée
    • CachingIterator::offsetSet - Affecte un nouvel élément à la position donnée
    • CachingIterator::offsetUnset - Détruit un élément à l'offset indiqué
    • CachingIterator::rewind - Replace l'itérateur au début
    • CachingIterator::setFlags - Modifie les options du CachingIterator
    • CachingIterator::valid - Vérifie si l'élément courant est valide
    • CachingIterator::__construct - Construit un nouvel objet CachingIterator pour l'itérateur
    • CachingIterator::__toString - Retourne la représentation de l'élément courant sous forme de chaîne
    • CallbackFilterIterator::accept - Appel la fonction de rappel avec la valeur courante, la clé courante, et l'itérateur interne comme arguments
    • CallbackFilterIterator::__construct - Crée un itérateur filtré depuis un autre itérateur
    • call_user_func - Appelle une fonction de rappel fournie par le premier argument
    • call_user_func_array - Appelle une fonction de rappel avec les paramètres rassemblés en tableau
    • cal_days_in_month - Retourne le nombre de jours dans un mois, pour une année et un calendrier donné
    • cal_from_jd - Convertit le nombre de jours Julien en un calendrier spécifique
    • cal_info - Retourne des détails sur un calendrier
    • cal_to_jd - Convertit un calendrier en nombre de jours Julien
    • ceil - Arrondit au nombre supérieur
    • chdir - Change de dossier
    • checkdate - Valide une date grégorienne
    • checkdnsrr - Résolution DNS d'une adresse IP
    • chgrp - Change le groupe d'un fichier
    • chmod - Change le mode du fichier
    • chop - Alias de rtrim
    • chown - Change le propriétaire du fichier
    • chr - Générer une chaîne d'un octet à partir d'un nombre
    • chroot - Change le dossier racine
    • chunk_split - Scinde une chaîne
    • class_alias - Crée un alias de classe
    • class_exists - Vérifie si une classe a été définie
    • class_implements - Retourne les interfaces implémentées par une classe ou une interface donnée
    • class_parents - Retourne les classes parentes d'une classe
    • class_uses - Retourne les traits utilisés par une classe donnée.
    • clearstatcache - Efface le cache de stat
    • Client::getClient - Get client session
    • Client::__construct - Client constructor
    • cli_get_process_title - Retourne le titre du processus courant
    • cli_set_process_title - Définit le titre du processus
    • closedir - Ferme le pointeur sur le dossier
    • closelog - Ferme la connexion à l'historique système
    • Closure::bind - Duplique une fermeture avec un nouvel objet lié et un nouveau contexte de classe.
    • Closure::bindTo - Duplique la fermeture avec un nouvel objet lié et un nouveau contexte de classe.
    • Closure::call - Lie et appelle la fermeture
    • Closure::fromCallable - Convertis un callable en une fermeture
    • Closure::__construct - Constructeur empêchant l'instanciation
    • Collator::asort - Tri un tableau en conservant les clés, avec une collation
    • Collator::compare - Compare deux chaînes Unicode
    • Collator::create - Création d'un collator
    • Collator::getAttribute - Lit un attribut de collation
    • Collator::getErrorCode - Lit la dernière erreur du collator
    • Collator::getErrorMessage - Lit le dernier message d'erreur du collator
    • Collator::getLocale - Lit le nom de la locale d'un collator
    • Collator::getSortKey - Récupère la clé de tri pour une chaine
    • Collator::getStrength - Récupère la dureté de classement utilisé
    • Collator::setAttribute - Configure l'attribut de collation
    • Collator::setStrength - Set collation strength
    • Collator::sort - Trie un tableau avec une collation
    • Collator::sortWithSortKeys - Tri un tableau et ses clés avec une collation
    • Collator::__construct - Création d'un collator
    • Collectable::isGarbage - Détermine si un objet a été marqué comme obsolète
    • 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 - Constructeur de la classe com
    • 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 - Crée un tableau à partir de variables et de leur valeur
    • 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 - Génère un identifiant unique global (GUID)
    • com_event_sink - Connecte des événements d'un objet COM sur un objet PHP
    • com_get_active_object - Retourne un objet représentant l'instance actuelle d'un objet COM
    • com_load_typelib - Charge un Typelib
    • com_message_pump - Traite un message COM dans un délai donné
    • com_print_typeinfo - Affiche une définition de classe PHP pour une interface répartissable
    • connection_aborted - Indique si l'internaute a abandonné la connexion HTTP
    • connection_status - Retourne les bits de statut de la connexion HTTP
    • constant - Retourne la valeur d'une constante
    • convert_cyr_string - Convertit une chaîne d'un jeu de caractères cyrillique à l'autre
    • convert_uudecode - Décode une chaîne au format uuencode
    • convert_uuencode - Encode une chaîne de caractères en utilisant l'algorithme uuencode
    • copy - Copie un fichier
    • cos - Cosinus
    • cosh - Cosinus hyperbolique
    • count - Compte tous les éléments d'un tableau ou dans un objet Countable
    • Countable::count - Compte le nombre d'éléments d'un objet
    • count_chars - Retourne des statistiques sur les caractères utilisés dans une chaîne
    • crc32 - Calcule la somme de contrôle CRC32
    • create_function - Crée une fonction anonyme
    • CrudOperationBindable::bind - Bind value to placeholder
    • CrudOperationLimitable::limit - Set result limit
    • CrudOperationSkippable::skip - Number of operations to skip
    • CrudOperationSortable::sort - Sort results
    • crypt - Hachage à sens unique (indéchiffrable)
    • ctype_alnum - Vérifie qu'une chaîne est alphanumérique
    • ctype_alpha - Vérifie qu'une chaîne est alphabétique
    • ctype_cntrl - Vérifie qu'un caractère est un caractère de contrôle
    • ctype_digit - Vérifie qu'une chaîne est un entier
    • ctype_graph - Vérifie qu'une chaîne est imprimable
    • ctype_lower - Vérifie qu'une chaîne est en minuscules
    • ctype_print - Vérifie qu'une chaîne est imprimable
    • ctype_punct - Vérifie qu'une chaîne contient de la ponctuation
    • ctype_space - Vérifie qu'une chaîne n'est faite que de caractères blancs
    • ctype_upper - Vérifie qu'une chaîne est en majuscules
    • ctype_xdigit - Vérifie qu'un caractère représente un nombre hexadécimal
    • cubrid_affected_rows - Récupère le nombre de lignes affectées par la dernière requête SQL
    • cubrid_bind - Lie des valeurs à une requête préparée
    • cubrid_client_encoding - Retourne le jeu de caractères utilisé sur la connexion CUBRID courante
    • cubrid_close - Ferme une connexion CUBRID
    • cubrid_close_prepare - Ferme le gestionnaire de requête
    • cubrid_close_request - Ferme le gestionnaire de requête
    • cubrid_column_names - Récupère les noms de colonnes du résultat
    • cubrid_column_types - Récupère les types de colonnes du résultat
    • cubrid_col_get - Récupère le contenu des éléments d'un type de collection en utilisant l'OID
    • cubrid_col_size - Récupère le nombre d'éléments dans un type de colonne d'une collection en utilisant l'OID
    • cubrid_commit - Commit une transaction
    • cubrid_connect - Ouvre une connexion au serveur CUBRID
    • cubrid_connect_with_url - Établit l'environnement pour une connexion au serveur CUBRID
    • cubrid_current_oid - Récupère l'OID de la localisation du curseur courant
    • cubrid_data_seek - Déplace le pointeur de lignes interne du résultat CUBRID
    • cubrid_db_name - Récupère le nom de la base de données depuis les résultats de cubrid_list_dbs
    • cubrid_disconnect - Ferme la connexion à la base de données
    • cubrid_drop - Supprime une instance en utilisant son OID
    • cubrid_errno - Retourne la valeur numérique d'un message d'erreur
    • cubrid_error - Récupère le message de l'erreur
    • cubrid_error_code - Récupère le code erreur de la dernière erreur survenue
    • cubrid_error_code_facility - Récupère le niveau du code erreur
    • cubrid_error_msg - Récupère le message d'erreur de la dernière erreur survenue
    • cubrid_execute - Exécute une requête SQL préparée
    • cubrid_fetch - Récupère la prochaine ligne du jeu de résultats
    • cubrid_fetch_array - Récupère une ligne de résultat sous forme de tableau associatif, de tableau numérique, ou les deux
    • cubrid_fetch_assoc - Retourne un tableau associatif correspondant à la ligne récupérée
    • cubrid_fetch_field - Récupère des informations sur une colonne et les retourne sous la forme d'un objet
    • cubrid_fetch_lengths - Retourne un tableau contenant les longueurs des valeurs de chaque champ de la ligne courante
    • cubrid_fetch_object - Récupère la prochaine ligne et la retourne sous la forme d'un objet
    • cubrid_fetch_row - Retourne un tableau numérique avec les valeurs de la ligne courante
    • cubrid_field_flags - Retourne une chaîne avec les drapeaux de la position du champ fourni
    • cubrid_field_len - Récupère la longueur maximale du champ spécifié
    • cubrid_field_name - Retourne le nom du champ spécifié
    • cubrid_field_seek - Déplace le curseur du jeu de résultats à une position spécifiée
    • cubrid_field_table - Retourne le nom de la table d'un champ spécifié
    • cubrid_field_type - Retourne le type de la colonne correspondant à la position du champ fourni
    • cubrid_free_result - Libère la mémoire occupée par les données de résultat
    • cubrid_get - Récupère une colonne en utilisant son OID
    • cubrid_get_autocommit - Récupère le mode auto-commit de la connexion
    • cubrid_get_charset - Retourne le jeu de caractères utilisé sur la connexion CUBRID courante
    • cubrid_get_class_name - Récupère le nom de la classe en utilisant son OID
    • cubrid_get_client_info - Retourne la version de la bibliothèque cliente
    • cubrid_get_db_parameter - Retourne les paramètres de la base de données CUBRID
    • cubrid_get_query_timeout - Récupère la valeur du délai d'attente maximal d'une requête
    • cubrid_get_server_info - Retourne la version du serveur CUBRID
    • cubrid_insert_id - Retourne l'identifiant généré pour la dernière mise à jour de la colonne AUTO_INCREMENT
    • cubrid_is_instance - Vérifie si une instance existe
    • cubrid_list_dbs - Retourne un tableau contenant la liste de toutes les bases de données CUBRID existantes
    • cubrid_load_from_glo - Lie une donnée
    • cubrid_lob2_bind - Lie un objet LOB ou une chaîne de caractères à un objet LOB comme paramètre d'une requête préparée
    • cubrid_lob2_close - Ferme un objet LOB
    • cubrid_lob2_export - Exporte un objet LOB vers un fichier
    • cubrid_lob2_import - Importe des données BLOB/CLOB depuis un fichier
    • cubrid_lob2_new - Crée un nouvel objet LOB
    • cubrid_lob2_read - Lit des données BLOB/CLOB
    • cubrid_lob2_seek - Déplace le curseur d'un objet LOB
    • cubrid_lob2_seek64 - Déplace le curseur d'un objet LOB
    • cubrid_lob2_size - Récupère la taille d'un objet LOB
    • cubrid_lob2_size64 - Récupère la taille d'un objet LOB
    • cubrid_lob2_tell - Récupère la position du curseur dans un objet LOB
    • cubrid_lob2_tell64 - Récupère la position du curseur dans l'objet LOB
    • cubrid_lob2_write - Ecrit dans un objet LOB
    • cubrid_lob_close - Ferme un BLOB/CLOB
    • cubrid_lob_export - Exporte des données BLOB/CLOB vers un fichier
    • cubrid_lob_get - Récupère les données BLOB/CLOB
    • cubrid_lob_send - Lit les données BLOB/CLOB et les envoye au navigateur
    • cubrid_lob_size - Récupère la taille des données BLOB/CLOB
    • cubrid_lock_read - Place un verrou de lecture sur l'OID fourni
    • cubrid_lock_write - Place un verrou d'écriture sur l'OID fourni
    • cubrid_move_cursor - Déplace le curseur dans le résultat
    • cubrid_new_glo - Crée une instance glo
    • cubrid_next_result - Récupère le résultat de la prochaine requête lors de l'exécution de requêtes SQL multiples
    • cubrid_num_cols - Récupère le nombre de colonnes du jeu de résultats
    • cubrid_num_fields - Retourne le nombre de colonnes dans le jeu de résultats
    • cubrid_num_rows - Récupère le nombre de lignes d'un jeu de résultats
    • cubrid_pconnect - Ouvre une connexion persistante vers un serveur CUBRID
    • cubrid_pconnect_with_url - Ouvre une connexion persistante vers un serveur CUBRID
    • cubrid_ping - Ping une connexion au serveur ou se reconnecte s'il n'y a plus de connexion active
    • cubrid_prepare - Prépare une requête SQL pour son exécution
    • cubrid_put - Met à jour une colonne suivant son OID
    • cubrid_query - Envoi une requête CUBRID
    • cubrid_real_escape_string - Échappe les caractères spéciaux d'une chaîne pour l'utiliser dans une requête SQL
    • cubrid_result - Retourne la valeur d'un champ d'une ligne spécifique
    • cubrid_rollback - Annule une transaction
    • cubrid_save_to_glo - Sauvegarde un fichier dans une instance glo
    • cubrid_schema - Récupère des informations sur un schéma
    • cubrid_send_glo - Lit les données depuis une instance glo
    • cubrid_seq_drop - Supprime un élément d'une séquence
    • cubrid_seq_insert - Insère un élément dans une séquence
    • cubrid_seq_put - Met à jour la valeur d'un élément d'une séquence
    • cubrid_set_add - Insère un seul élément pour définir le type d'une colonne
    • cubrid_set_autocommit - Définit le mode auto-commit pour la connexion
    • cubrid_set_db_parameter - Définit les paramètres de base de données CUBRID
    • cubrid_set_drop - Supprime un élément
    • cubrid_set_query_timeout - Définit le délai maximal d'exécution d'une requête
    • cubrid_unbuffered_query - Exécute une requête sans placer les résultats en mémoire vive
    • cubrid_version - Récupère la version du module PHP CUBRID
    • CURLFile::getFilename - Récupère le nom du fichier
    • CURLFile::getMimeType - Récupère le type MIME
    • CURLFile::getPostFilename - Récupère le nom de fichier pour POST
    • CURLFile::setMimeType - Définit le type MIME
    • CURLFile::setPostFilename - Définit le nom du fichier pour POST
    • CURLFile::__construct - Crée un objet CURLFile
    • CURLStringFile::__construct - Crée un objet CURLStringFile
    • curl_close - Ferme une session CURL
    • curl_copy_handle - Copie une ressource cURL avec toutes ses préférences
    • curl_errno - Retourne le dernier message d'erreur cURL
    • curl_error - Retourne une chaîne contenant le dernier message d'erreur cURL
    • curl_escape - Encode URL la chaîne fournie
    • curl_exec - Exécute une session cURL
    • curl_getinfo - Lit les informations détaillant un transfert cURL
    • curl_init - Initialise une session cURL
    • curl_multi_add_handle - Ajoute une ressource cURL à un cURL multiple
    • curl_multi_close - Termine un jeu de sessions cURL
    • curl_multi_errno - Retourne le dernier numéro d'erreur multiple cURL
    • curl_multi_exec - Exécute les sous-requêtes de la session cURL
    • curl_multi_getcontent - Retourne le contenu obtenu avec l'option CURLOPT_RETURNTRANSFER
    • curl_multi_info_read - Lit les informations sur les transferts actuels
    • curl_multi_init - Retourne un nouveau cURL multiple
    • curl_multi_remove_handle - Retire une ressource cURL d'un cURL multiple
    • curl_multi_select - Attend une activité sur n'importe quelle connexion curl_multi
    • curl_multi_setopt - Définit une option multiple cURL
    • curl_multi_strerror - Retourne la description d'un code erreur
    • curl_pause - Met en pause, ou sort de la pause une connexion
    • curl_reset - Ré-initialise toutes les options d'un gestionnaire de session libcurl
    • curl_setopt - Définit une option de transmission cURL
    • curl_setopt_array - Fixe plusieurs options pour un transfert cURL
    • curl_share_close - Ferme un gestionnaire partagé cURL
    • curl_share_errno - Retourne le dernier numéro d'erreur du gestionnaire partagé cURL
    • curl_share_init - Initialise un gestionnaire partagé cURL
    • curl_share_setopt - Définit une option du gestionnaire partagé cURL
    • curl_share_strerror - Retourne une chaîne qui décrit le code d'erreur fournit
    • curl_strerror - Retourne la chaîne descriptive du code erreur fourni
    • curl_unescape - Décode l'URL fourni
    • curl_upkeep - Effectue les contrôles de maintenance de la connexion
    • curl_version - Retourne la version courante de cURL
    • current - Retourne l'élément courant du tableau
  • d
    • data:// - Données (RFC 2397)
    • DatabaseObject::existsInDatabase - Check if object exists in database
    • DatabaseObject::getName - Get object name
    • DatabaseObject::getSession - Get session name
    • date - Formate un horodatage Unix
    • DateInterval::createFromDateString - Configure un objet DateInterval à partir des parties d'une chaîne
    • DateInterval::format - Formate l'intervalle
    • DateInterval::__construct - Crée un nouvel objet DateInterval
    • DatePeriod::createFromISO8601String - Creates a new DatePeriod object from an ISO8601 string
    • DatePeriod::getDateInterval - Retourne l'intervalle
    • DatePeriod::getEndDate - Retourne la date de fin
    • DatePeriod::getRecurrences - Récupère le nombre de récurrences
    • DatePeriod::getStartDate - Obtient la date de début
    • DatePeriod::__construct - Crée un nouvel objet DatePeriod
    • DateTime::add - Modifie un objet un objet DateTime, avec le nombre de jours, mois, années, heures, minutes et secondes ajouté
    • DateTime::createFromFormat - Analyse une heure au format texte selon le format spécifié.
    • DateTime::createFromImmutable - Retourne une nouvelle instance d'objet DateTime encapsulant l'objet DateTimeImmutable fourni
    • DateTime::createFromInterface - Retourne un nouvel objet DateTime encapsulant l'objet DateTimeInterface fourni
    • DateTime::getLastErrors - Alias de DateTimeImmutable::getLastErrors
    • DateTime::modify - Modifie le timestamp
    • DateTime::setDate - Assigne la date
    • DateTime::setISODate - Configure une date ISO
    • DateTime::setTime - Assigne l'heure
    • DateTime::setTimestamp - Assigne la date et l'heure à l'aide d'un horodatage Unix
    • DateTime::setTimezone - Configure le fuseau horaire de l'objet DateTime
    • DateTime::sub - Soustrait une durée à un objet DateTime
    • DateTime::__construct - Retourne un nouvel objet DateTime
    • DateTime::__set_state - Le gestionnaire __set_state
    • DateTime::__wakeup - Le gestionnaire __wakeup
    • DateTimeImmutable::add - Retourne un nouvel object, avec le nombre de jours, mois, années, heures, minutes et secondes ajouté
    • DateTimeImmutable::createFromFormat - Analyse une heure au format texte selon le format spécifié.
    • DateTimeImmutable::createFromInterface - Retourne un nouvel objet DateTimeImmutable encapsulant l'objet DateTimeInterface fourni
    • DateTimeImmutable::createFromMutable - Retourne une nouvelle instance de DateTimeImmutable encapsulant l'objet DateTime fournit
    • DateTimeImmutable::getLastErrors - Retourne les alertes et erreurs
    • DateTimeImmutable::modify - Créée un nouvel objet avec l'horodatage modifié
    • DateTimeImmutable::setDate - Définit la date
    • DateTimeImmutable::setISODate - Définit la date ISO
    • DateTimeImmutable::setTime - Définit l'horaire
    • DateTimeImmutable::setTimestamp - Définit la date et l'heure basé sur un horodatage Unix
    • DateTimeImmutable::setTimezone - Définit le fuseau horaire
    • DateTimeImmutable::sub - Soustrait un nombre de jours, mois, années, heures et secondes
    • DateTimeImmutable::__construct - Retourne un nouvel objet DateTimeImmutable
    • DateTimeImmutable::__set_state - Le gestionnaire __set_state
    • DateTimeInterface::diff - Retourne la différence entre deux objets DateTime
    • DateTimeInterface::format - Retourne une date formatée suivant le format fourni
    • DateTimeInterface::getOffset - Retourne le décalage horaire
    • DateTimeInterface::getTimestamp - Récupère le timestamp Unix
    • DateTimeInterface::getTimezone - Retourne le fuseau horaire relatif au DateTime fourni
    • DateTimeZone::getLocation - Retourne les informations géographiques d'un fuseau horaire
    • DateTimeZone::getName - Retourne le nom du fuseau horaire
    • DateTimeZone::getOffset - Retourne le décalage GMT d'un fuseau horaire
    • DateTimeZone::getTransitions - Retourne toutes les transitions d'un fuseau horaire
    • DateTimeZone::listAbbreviations - Retourne un tableau associatif, décrivant un fuseau horaire
    • DateTimeZone::listIdentifiers - Retourne un tableau numérique contenant tous les identifiants de fuseaux horaires définis
    • DateTimeZone::__construct - Crée un nouvel objet DateTimeZone
    • date_add - Alias de DateTime::add
    • date_create - Création d'un objet DateTime
    • date_create_from_format - Alias de DateTime::createFromFormat
    • date_create_immutable - Crée un nouvel objet DateTimeImmutable
    • date_create_immutable_from_format - Alias de DateTimeImmutable::createFromFormat
    • date_date_set - Alias de DateTime::setDate
    • date_default_timezone_get - Récupère le décalage horaire par défaut utilisé par toutes les fonctions date/heure d'un script
    • date_default_timezone_set - Définit le décalage horaire par défaut de toutes les fonctions date/heure
    • date_diff - Alias de DateTime::diff
    • date_format - Alias de DateTime::format
    • date_get_last_errors - Alias de DateTimeImmutable::getLastErrors
    • date_interval_create_from_date_string - Alias de DateInterval::createFromDateString
    • date_interval_format - Alias de DateInterval::format
    • date_isodate_set - Alias de DateTime::setISODate
    • date_modify - Alias de DateTime::modify
    • date_offset_get - Alias de DateTime::getOffset
    • date_parse - Retourne un tableau associatif avec des informations détaillées sur une date/moment donnée
    • date_parse_from_format - Récupère les informations d'une date donnée suivant un format spécifique
    • date_sub - Alias de DateTime::sub
    • date_sunrise - Retourne l'heure de lever du soleil pour un jour et un endroit donnés
    • date_sunset - Retourne l'heure de coucher du soleil pour un jour et un endroit donnés
    • date_sun_info - Retourne un tableau avec les informations sur le lever/coucher du soleil ainsi que le début et la fin de l'aube
    • date_timestamp_get - Alias de DateTime::getTimestamp
    • date_timestamp_set - Alias de DateTime::setTimestamp
    • date_timezone_get - Alias de DateTime::getTimezone
    • date_timezone_set - Alias de DateTime::setTimezone
    • date_time_set - Alias de DateTime::setTime
    • db2_autocommit - Retourne ou modifie l'état AUTOCOMMIT de la connexion à la base de données
    • db2_bind_param - Associe une variable PHP à un paramètre d'une requête SQL
    • db2_client_info - Retourne un objet avec des propriétés qui décrivent le client de base de données DB2
    • db2_close - Ferme une connexion de base de données
    • db2_columns - Retourne un jeu de résultats listant les colonnes et ses métadonnées d'une table
    • db2_column_privileges - Retourne un jeu de résultats listant les colonnes et ses privilèges d'une table
    • db2_commit - Valide la transaction
    • db2_connect - Retourne une connexion à une base de données
    • db2_conn_error - Retourne une chaîne contenant la valeur de SQLSTATE retournée par la dernière tentative de connexion
    • db2_conn_errormsg - Retourne le dernier message d'erreur de connexion ainsi que la valeur de SQLCODE
    • db2_cursor_type - Retourne le type de curseur utilisé par une ressource
    • db2_escape_string - Utilisé pour échapper certains caractères
    • db2_exec - Exécute une requête SQL directement
    • db2_execute - Exécute une requête SQL préparée
    • db2_fetch_array - Retourne un tableau, indexé par la position des colonnes, représentant une ligne du jeu de résultats
    • db2_fetch_assoc - Retourne un tableau, indexé par nom de colonne, représentant une ligne du jeu de résultats
    • db2_fetch_both - Retourne un tableau, indexé par nom de colonne et position, représentant une ligne du jeu de résultats
    • db2_fetch_object - Retourne un objet avec les propriétés représentant des colonnes dans la ligne extraite
    • db2_fetch_row - Modifie le pointeur du jeu de résultat à la prochaine ligne ou à la ligne demandée
    • db2_field_display_size - Retourne le maximum d'octets requis pour afficher une colonne
    • db2_field_name - Retourne le nom de la colonne du jeu de résultats
    • db2_field_num - Retourne la position du nom de la colonne du jeu de résultats
    • db2_field_precision - Retourne la précision de la colonne indiquée du jeu de résultats
    • db2_field_scale - Retourne l'échelle de la colonne indiquée du jeu de résultats
    • db2_field_type - Retourne le type de donnée de la colonne indiquée du jeu de résultats
    • db2_field_width - Retourne la largeur de la valeur courante de la colonne indiquée du jeu de résultats
    • db2_foreign_keys - Retourne un jeu de résultats listant les clés étrangères d'une table
    • db2_free_result - Libère la mémoire associée à un jeu de résultats
    • db2_free_stmt - Libère la mémoire associée à la ressource indiquée
    • db2_get_option - Récupère la valeur d'une option pour une requête ou une connexion
    • db2_last_insert_id - Retourne le dernier ID généré par la dernière requête d'insertion
    • db2_lob_read - Récupère de grands objets binaires de tailles prédéfinies à chaque invocation
    • db2_next_result - Demande le prochain jeu de résultats de la ressource indiquée
    • db2_num_fields - Retourne le nombre de champs contenu du jeu de résultats
    • db2_num_rows - Retourne le nombre de lignes affectées par une requête SQL
    • db2_pclose - Ferme une connexion persistante à la base de données
    • db2_pconnect - Retourne une connexion persistante à une base de données
    • db2_prepare - Prépare une requête SQL à être exécutée
    • db2_primary_keys - Retourne un jeu de résultats listant les clés d'une table
    • db2_procedures - Retourne un jeu de résultats listant les procédures d'enregistrement enregistrées dans la base de données
    • db2_procedure_columns - Retourne un jeu de résultats listant les paramètres de procédure d'enregistrement
    • db2_result - Retourne une colonne d'une ligne d'un jeu de résultats
    • db2_rollback - Annule une transaction
    • db2_server_info - Retourne un objet avec des propriétés qui décrivent le serveur de base de données DB2
    • db2_set_option - Fixe des options pour une connexion ou des ressources
    • db2_special_columns - Retourne un jeu de résultats listant les identifiants uniques des lignes d'une table
    • db2_statistics - Retourne un jeu de résultats listant les index et statistiques d'une table
    • db2_stmt_error - Retourne une chaîne contenant la valeur de SQLSTATE retournée par une requête SQL
    • db2_stmt_errormsg - Retourne le dernier message d'erreur d'une requête SQL
    • db2_tables - Retourne la liste des tables et leurs métadonnées
    • db2_table_privileges - Retourne un jeu de résultats listant les tables et leurs privilèges qui leur sont associées d'une base de données
    • dbase_add_record - Ajoute un enregistrement dans une base de données dBase
    • dbase_close - Ferme une base dBase
    • dbase_create - Crée une base de données dBase
    • dbase_delete_record - Efface un enregistrement dans une base dBase
    • dbase_get_header_info - Récupère des informations d'en-tête d'une base de données dBase
    • dbase_get_record - Lit un enregistrement dans une base dBase
    • dbase_get_record_with_names - Lit un enregistrement dans une base dBase, sous la forme d'un tableau associatif
    • dbase_numfields - Compte le nombre de champs d'une base dBase
    • dbase_numrecords - Compte le nombre d'enregistrements dans une base dBase
    • dbase_open - Ouvre une base dBase
    • dbase_pack - Compacte une base dBase
    • dbase_replace_record - Remplace un enregistrement dans une base dBase
    • dba_close - Ferme une base DBA
    • dba_delete - Efface une ligne dans une base DBA
    • dba_exists - Vérifie qu'une clé DBA existe
    • dba_fetch - Lit les données liées à une clé DBA
    • dba_firstkey - Lit la première clé DBA
    • dba_handlers - Liste les gestionnaires DBA disponibles
    • dba_insert - Insère une entrée DBA
    • dba_key_split - Transforme une représentation de clé DBA par chaîne en une représentation par tableau
    • dba_list - Liste tous les fichiers de bases de données DBA ouverts
    • dba_nextkey - Lit la clé DBA suivante
    • dba_open - Ouvre une base de données DBA
    • dba_optimize - Optimise une base DBA
    • dba_popen - Ouvre une connexion persistante à une base de données DBA
    • dba_replace - Remplace ou insère une ligne DBA
    • dba_sync - Synchronise une base de données DBA
    • dcgettext - Remplace le domaine lors d'une recherche
    • dcngettext - Version plurielle de dcgettext
    • debug_backtrace - Génère le contexte de débogage
    • debug_print_backtrace - Affiche la pile d'exécution PHP
    • debug_zval_dump - Extrait une représentation sous forme de chaîne de la structure interne d'une zval pour affichage
    • decbin - Convertit de décimal en binaire
    • dechex - Convertit de décimal en hexadécimal
    • decoct - Convertit de décimal en octal
    • define - Définit une constante
    • defined - Vérifie l'existence d'une constante
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - Convertit un nombre de degrés en radians
    • delete - Voir unlink ou unset
    • dgettext - Remplace le domaine courant
    • die - Alias de la fonction exit
    • dio_close - Ferme l'accès au fichier
    • dio_fcntl - Exécute une fonction fichier de langage C
    • dio_open - Ouvre un nouveau fichier avec les permissions spécifiées
    • dio_read - Lit les octets dans un fichier
    • dio_seek - Déplace le pointeur interne de fichier
    • dio_stat - Lit des informations sur le fichier
    • dio_tcsetattr - Modifie les attributs du terminal et le taux de baud du port série
    • dio_truncate - Tronque un fichier
    • dio_write - Écrit des données dans le fichier avec la possibilité de tronquer sa longueur
    • dir - Retourne une instance de la classe Directory
    • Directory::close - Ferme le gestionnaire de dossier
    • Directory::read - Lit une entrée depuis le gestionnaire de dossier
    • Directory::rewind - Réinitialise le gestionnaire de dossier
    • DirectoryIterator::current - Retourne l'élément courant du DirectoryIterator
    • DirectoryIterator::getBasename - Lit le nom de dossier de l'élément DirectoryIterator
    • DirectoryIterator::getExtension - Récupère l'extension du fichier
    • DirectoryIterator::getFilename - Retourne le nom de l'entrée courante du dossier
    • DirectoryIterator::isDot - Retourne true si l'entrée courante est '.' ou '..'
    • DirectoryIterator::key - Retourne l'entrée courante du dossier
    • DirectoryIterator::next - Se déplace vers la prochaine entrée
    • DirectoryIterator::rewind - Revient au début du dossier
    • DirectoryIterator::seek - Déplace le pointeur dans un itérateur DirectoryIterator
    • DirectoryIterator::valid - Vérifie si le répertoire contient encore des entrées
    • DirectoryIterator::__construct - Construit un nouvel itérateur de dossier à partir d'un chemin
    • DirectoryIterator::__toString - Lit le nom du fichier
    • dirname - Renvoie le chemin du dossier parent
    • diskfreespace - Alias de disk_free_space
    • disk_free_space - Renvoie l'espace disque disponible sur le système de fichiers ou la partition
    • disk_total_space - Retourne la taille d'un dossier ou d'une partition
    • dl - Charge une extension PHP à la volée
    • dngettext - Version plurielle de dgettext
    • dns_check_record - Alias de checkdnsrr
    • dns_get_mx - Alias de getmxrr
    • dns_get_record - Lit les données DNS associées à un hôte
    • 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 - Vérifie si l'attribut est un identifiant défini
    • DOMAttr::__construct - Crée un nouvel objet DOMAttr
    • DOMCdataSection::__construct - Construit un nouvel objet DOMCdataSection
    • DOMCharacterData::after - Adds nodes after the character data
    • DOMCharacterData::appendData - Ajoute la chaîne à la fin des données dans le nœud
    • DOMCharacterData::before - Adds nodes before the node
    • DOMCharacterData::deleteData - Supprime une sous-chaîne dans le nœud
    • DOMCharacterData::insertData - Insère une chaîne à la position spécifiée d'unité 16-bit
    • DOMCharacterData::remove - Removes the character data
    • DOMCharacterData::replaceData - Remplace une sous-chaîne dans le nœud DOMCharacterData
    • DOMCharacterData::replaceWith - Replaces the character data with new nodes
    • DOMCharacterData::substringData - Extrait un morceau de données dans le nœud
    • DOMChildNode::after - Ajoute des nœuds après le nœud
    • DOMChildNode::before - Ajoute des nœuds avant le nœud
    • DOMChildNode::remove - Supprime le nœud
    • DOMChildNode::replaceWith - Remplace le nœud par de nouveaux nœuds
    • DOMComment::__construct - Crée un nouvel objet DOMComment
    • DOMDocument::adoptNode - Transfer a node from another document
    • DOMDocument::append - Appends nodes after the last child node
    • DOMDocument::createAttribute - Crée un nouvel attribut
    • DOMDocument::createAttributeNS - Crée un nouvel attribut avec un espace de noms associé
    • DOMDocument::createCDATASection - Crée un nouveau nœud cdata
    • DOMDocument::createComment - Crée un nouveau nœud de commentaire
    • DOMDocument::createDocumentFragment - Crée un nouveau fragment de document
    • DOMDocument::createElement - Crée un nouveau nœud
    • DOMDocument::createElementNS - Crée un nouveau nœud avec un espace de noms associé
    • DOMDocument::createEntityReference - Crée un nouveau nœud de référence d'entité
    • DOMDocument::createProcessingInstruction - Crée un nouveau nœud PI
    • DOMDocument::createTextNode - Crée un nouveau nœud de texte
    • DOMDocument::getElementById - Cherche un élément avec un certain identifiant
    • DOMDocument::getElementsByTagName - Cherche tous les éléments qui ont le nom de la balise locale donné
    • DOMDocument::getElementsByTagNameNS - Recherche tous les éléments avec un nom de balise donné dans un espace de noms spécifié
    • DOMDocument::importNode - Importe un nœud dans le document courant
    • DOMDocument::load - Charge du XML depuis un fichier
    • DOMDocument::loadHTML - Charge du code HTML à partir d'une chaîne de caractères
    • DOMDocument::loadHTMLFile - Charge du HTML à partir d'un fichier
    • DOMDocument::loadXML - Charge du XML depuis une chaîne de caractères
    • DOMDocument::normalizeDocument - Normalise le document
    • DOMDocument::prepend - Prepends nodes before the first child node
    • DOMDocument::registerNodeClass - Enregistre la classe étendue utilisée pour créer un type de base de nœud
    • DOMDocument::relaxNGValidate - Effectue une validation relaxNG sur le document
    • DOMDocument::relaxNGValidateSource - Effectue une validation relaxNG sur le document
    • DOMDocument::replaceChildren - Replace children in document
    • DOMDocument::save - Sauvegarde l'arbre interne XML dans un fichier
    • DOMDocument::saveHTML - Sauvegarde le document interne dans une chaîne en utilisant un formatage HTML
    • DOMDocument::saveHTMLFile - Sauvegarde un document interne dans un fichier en utilisant un formatage HTML
    • DOMDocument::saveXML - Sauvegarde l'arbre interne XML dans une chaîne de caractères
    • DOMDocument::schemaValidate - Valide un document selon un schéma. Seuls les schémas XML 1.0 sont supportés.
    • DOMDocument::schemaValidateSource - Valide un document selon un schéma
    • DOMDocument::validate - Valide un document en se basant sur sa DTD
    • DOMDocument::xinclude - Remplace les XIncludes dans un objet DOMDocument
    • DOMDocument::__construct - Crée un nouvel objet DOMDocument
    • DOMDocumentFragment::append - Appends nodes after the last child node
    • DOMDocumentFragment::appendXML - Ajoute des données XML
    • DOMDocumentFragment::prepend - Prepends nodes before the first child node
    • DOMDocumentFragment::replaceChildren - Replace children in fragment
    • DOMDocumentFragment::__construct - Construit un objet DOMDocumentFragment
    • DOMElement::after - Adds nodes after the element
    • DOMElement::append - Appends nodes after the last child node
    • DOMElement::before - Adds nodes before the element
    • DOMElement::getAttribute - Retourne la valeur d'un attribut
    • DOMElement::getAttributeNames - Get attribute names
    • DOMElement::getAttributeNode - Retourne le nœud d'attribut
    • DOMElement::getAttributeNodeNS - Retourne le nœud d'attribut
    • DOMElement::getAttributeNS - Retourne la valeur de l'attribut
    • DOMElement::getElementsByTagName - Retourne les éléments par leur nom de balise
    • DOMElement::getElementsByTagNameNS - Récupère les éléments par leur espace de noms et leur localName
    • DOMElement::hasAttribute - Vérifie si un attribut existe
    • DOMElement::hasAttributeNS - Vérifie si un attribut existe
    • DOMElement::insertAdjacentElement - Insert adjacent element
    • DOMElement::insertAdjacentText - Insert adjacent text
    • DOMElement::prepend - Prepends nodes before the first child node
    • DOMElement::remove - Removes the element
    • DOMElement::removeAttribute - Efface un attribut
    • DOMElement::removeAttributeNode - Efface un attribut
    • DOMElement::removeAttributeNS - Efface un attribut
    • DOMElement::replaceChildren - Replace children in element
    • DOMElement::replaceWith - Replaces the element with new nodes
    • DOMElement::setAttribute - Ajoute un nouvel attribut, ou modifie un attribut existant
    • DOMElement::setAttributeNode - Ajoute un nouvel attribut à l'élément
    • DOMElement::setAttributeNodeNS - Ajoute un nouvel attribut à l'élément
    • DOMElement::setAttributeNS - Ajoute un nouvel attribut
    • DOMElement::setIdAttribute - Déclare l'attribut spécifié par son nom à être de type ID
    • DOMElement::setIdAttributeNode - Déclare l'attribut spécifié par le nœud à être de type ID
    • DOMElement::setIdAttributeNS - Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID
    • DOMElement::toggleAttribute - Toggle attribute
    • DOMElement::__construct - Crée un nouvel objet DOMElement
    • DOMEntityReference::__construct - Crée un nouvel objet DOMEntityReference
    • DOMImplementation::createDocument - Crée un objet DOM Document du type spécifié avec ses éléments
    • DOMImplementation::createDocumentType - Crée un objet DOMDocumentType vide
    • DOMImplementation::hasFeature - Teste si l'implémentation DOM implémente une fonctionnalité spécifique
    • DOMImplementation::__construct - Crée un nouvel objet DOMImplementation
    • DOMNamedNodeMap::count - Récupère le nombre de nœuds dans la collection non triée (map)
    • DOMNamedNodeMap::getIterator - Retrieve an external iterator
    • DOMNamedNodeMap::getNamedItem - Retourne un nœud spécifié par son nom
    • DOMNamedNodeMap::getNamedItemNS - Retourne un nœud spécifié par son nom local et son espace de noms
    • DOMNamedNodeMap::item - Retourne un nœud selon son index
    • DOMNode::appendChild - Ajoute un nouveau fils à la fin des fils
    • DOMNode::C14N - Canonise des nœuds en une chaîne
    • DOMNode::C14NFile - Canonise des nœuds en fichier
    • DOMNode::cloneNode - Clone un nœud
    • DOMNode::contains - Checks if node contains other node
    • DOMNode::getLineNo - Lit le numéro de ligne d'un nœud
    • DOMNode::getNodePath - Récupère un XPath pour un nœud
    • DOMNode::getRootNode - Get root node
    • DOMNode::hasAttributes - Vérifie si le nœud possède un attribut
    • DOMNode::hasChildNodes - Vérifie si le nœud possède des enfants
    • DOMNode::insertBefore - Ajoute un nouveau fils avant un nœud de référence.
    • DOMNode::isDefaultNamespace - Vérifie si l'espace de nom spécifié est l'espace de noms par défaut ou non
    • DOMNode::isEqualNode - Checks that both nodes are equal
    • DOMNode::isSameNode - Indique si deux nœuds sont identiques
    • DOMNode::isSupported - Vérifie si la fonctionnalité est disponible pour la version spécifiée
    • DOMNode::lookupNamespaceURI - Retourne l'URI de l'espace de noms selon le préfixe
    • DOMNode::lookupPrefix - Retourne le préfixe de l'espace de noms selon l'URI de l'espace de noms
    • DOMNode::normalize - Normalise le nœud
    • DOMNode::removeChild - Supprime un fils de la liste des enfants
    • DOMNode::replaceChild - Remplace un fils
    • DOMNodeList::count - Récupère le nombre de nœuds dans la collection triée (list)
    • DOMNodeList::getIterator - Retrieve an external iterator
    • DOMNodeList::item - Retourne un nœud spécifié par son index
    • DOMParentNode::append - Ajoute des nœuds après le dernier nœud enfant
    • DOMParentNode::prepend - Ajoute des nœuds avant le premier nœud enfant
    • DOMParentNode::replaceChildren - Replace children in node
    • DOMProcessingInstruction::__construct - Crée un nouvel objet DOMProcessingInstruction
    • DOMText::isElementContentWhitespace - Rapporte si le nœud textuel contient des caractères d'espacement blanc
    • DOMText::isWhitespaceInElementContent - Indique si ce nœud de texte contient des espaces blancs
    • DOMText::splitText - Coupe le nœud en deux nœuds à l'endroit spécifié
    • DOMText::__construct - Crée un nouvel objet DOMText
    • DOMXPath::evaluate - Évalue une expression XPath donnée et retourne un résultat typé si possible
    • DOMXPath::query - Évalue l'expression XPath donnée
    • DOMXPath::registerNamespace - Enregistre l'espace de noms avec l'objet DOMXPath
    • DOMXPath::registerPhpFunctions - Enregistre une fonction PHP comme fonction XPath
    • DOMXPath::__construct - Crée un nouvel objet DOMXPath
    • dom_import_simplexml - Transforme un objet SimpleXMLElement en un objet DOMElement
    • dotnet::__construct - Constructeur de la classe dotnet
    • doubleval - Alias de floatval
    • DSN PDO_CUBRID - Connexion aux bases de données CUBRID
    • Ds\Collection::clear - Supprimer toutes les valeurs
    • Ds\Collection::copy - Retourne une copie superficielle de la collection
    • Ds\Collection::isEmpty - Indique si la collection est vide
    • Ds\Collection::toArray - Convertit la collection en un tableau
    • 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 tableau
    • 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 tableau
    • 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 tableau
    • 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 tableau
    • 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 tableau
    • 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 tableau
    • 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 tableau
    • 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 tableau
    • Ds\Vector::unshift - Adds values to the front of the vector
    • Ds\Vector::__construct - Creates a new instance
  • e
    • each - Retourne chaque paire clé/valeur d'un tableau
    • easter_date - Retourne un timestamp UNIX pour Pâques, à minuit pour une année donnée
    • easter_days - Retourne le nombre de jours entre le 21 Mars et Pâques, pour une année donnée
    • echo - Affiche une chaîne de caractères
    • eio_busy - Augmente artificiellement la charge. Utile dans le cadre de tests
    • eio_cancel - Annule une requête
    • eio_chmod - Modifie les permissions d'un fichier/dossier
    • eio_chown - Modifie les permissions d'un fichier/dossier
    • eio_close - Ferme un fichier
    • eio_custom - Exécute une demande personnalisée comme l'appel à une des fonctions eio_*
    • eio_dup2 - Duplique un descripteur de fichier
    • eio_event_loop - Boucle libeio tant que les requêtes s'exécutent
    • eio_fallocate - Autorise l'appelant à manipuler directement l'espace disque alloué pour un fichier
    • eio_fchmod - Modifie les permissions sur un fichier
    • eio_fchown - Modifie le propriétaire du fichier
    • eio_fdatasync - Synchronise le statut interne d'un fichier avec le périphérique de stockage
    • eio_fstat - Récupère le statut d'un fichier
    • eio_fstatvfs - Récupère des statistiques sur le système de fichiers
    • eio_fsync - Synchronise le statut interne d'un fichier avec le périphérique de stockage
    • eio_ftruncate - Tronque un fichier
    • eio_futime - Modifie l'heure du dernier accès et de la dernière modification d'un fichier
    • eio_get_event_stream - Récupère le flux représentant une variable utilisée dans les communications internes avec libeio
    • eio_get_last_error - Retourne une chaîne décrivant la dernière erreur associée avec la ressource demandée
    • eio_grp - Crée un groupe de requêtes
    • eio_grp_add - Ajoute une requête au groupe de requêtes
    • eio_grp_cancel - Annule un groupe de requêtes
    • eio_grp_limit - Définit la limite d'un groupe
    • eio_init - (Re-)initialise Eio
    • eio_link - Crée un lien fort sur un fichier
    • eio_lstat - Récupère le statut d'un fichier
    • eio_mkdir - Crée un dossier
    • eio_mknod - Crée un fichier spécial ou ordinaire
    • eio_nop - Ne fait rien, mis à part le fait de parcourir l'ensemble du cycle des requêtes
    • eio_npending - Retourne le nombre de requêtes terminées
    • eio_nready - Retourne le nombre de requêtes pas encore gérées
    • eio_nreqs - Retourne le nombre de requêtes restant à exécuter
    • eio_nthreads - Retourne le nombre de threads actuellement utilisés
    • eio_open - Ouvre un fichier
    • eio_poll - Vérifie s'il reste des requêtes en cours d'exécution
    • eio_read - Lit un descripteur de fichier à une position donnée
    • eio_readahead - Effectue un readahead sur le fichier dans le cache d'une page
    • eio_readdir - Lit le contenu d'un dossier
    • eio_readlink - Lit la valeur d'un lien symbolique
    • eio_realpath - Récupère le nom du chemin absolu canonisé
    • eio_rename - Modifie le nom ou le chemin d'un fichier
    • eio_rmdir - Supprime un dossier
    • eio_seek - Repositionne le curseur d'un fichier ouvert
    • eio_sendfile - Transfère des données entre des descripteurs de fichiers
    • eio_set_max_idle - Définit le nombre maximal de threads inactifs
    • eio_set_max_parallel - Définit le nombre maximal de threads en parallèle
    • eio_set_max_poll_reqs - Définit le nombre maximal de requêtes à exécuter dans une file d'attente
    • eio_set_max_poll_time - Définit la durée maximale de la file d'attente
    • eio_set_min_parallel - Définit le nombre minimum de threads parallèles
    • eio_stat - Récupère le statut d'un fichier
    • eio_statvfs - Récupère les statistiques du système de fichiers
    • eio_symlink - Crée un lien symbolique
    • eio_sync - Valide le cache du buffer sur le disque
    • eio_syncfs - Appel la fonction système Linux syncfs, si disponible
    • eio_sync_file_range - Synchronise un segment de fichier avec le disque
    • eio_truncate - Tronque un fichier
    • eio_unlink - Supprime un nom et éventuellement, le fichier qui s'y réfère
    • eio_utime - Modifie l'heure du dernier accès et de la dernière modification d'un fichier
    • eio_write - Ecrit dans un fichier
    • empty - Détermine si une variable est vide
    • EmptyIterator::current - La méthode EmptyIterator::current
    • EmptyIterator::key - The key() method
    • EmptyIterator::next - La méthode EmptyIterator::next
    • EmptyIterator::rewind - La méthode EmptyIterator::rewind
    • EmptyIterator::valid - La méthode EmptyIterator::valid
    • enchant_broker_describe - Énumère les fournisseurs Enchant
    • enchant_broker_dict_exists - Vérifie si un dictionnaire existe
    • enchant_broker_free - Libère la ressource de sponsor ainsi que ses dictionnaires
    • enchant_broker_free_dict - Libère une ressource de dictionnaire
    • enchant_broker_get_dict_path - Récupère le chemin du dossier pour un backend fournit
    • enchant_broker_get_error - Retourne la dernière erreur d'un sponsor
    • enchant_broker_init - Crée un nouvel objet sponsor
    • enchant_broker_list_dicts - Retourne une liste de tous les dictionnaires disponibles
    • enchant_broker_request_dict - Crée un nouveau dictionnaire
    • enchant_broker_request_pwl_dict - Crée un dictionnaire en utilisant un fichier PWL
    • enchant_broker_set_dict_path - Définit le chemin du dossier pour un backend fournit
    • enchant_broker_set_ordering - Déclare une préférence pour un dictionnaire d'une langue
    • enchant_dict_add - Ajoute un mot à une liste de mot personnelle
    • enchant_dict_add_to_personal - Alias de enchant_dict_add
    • enchant_dict_add_to_session - Ajoute un mot à la session courante
    • enchant_dict_check - Vérifie si un mot est correctement orthographié
    • enchant_dict_describe - Décrit un dictionnaire
    • enchant_dict_get_error - Retourne la dernière erreur de la session courante
    • enchant_dict_is_added - Que le 'mot' existe ou non dans cette session d'orthographe
    • enchant_dict_is_in_session - Alias de enchant_dict_is_added
    • enchant_dict_quick_check - Vérifie si le mot est correctement orthographié et fournit des suggestions
    • enchant_dict_store_replacement - Ajoute une orthographe pour un mot
    • enchant_dict_suggest - Retourne une liste de valeurs si aucunes des conditions ne sont réunies
    • end - Positionne le pointeur de tableau en fin de tableau
    • enum_exists - Vérifie si l'énumération est définie
    • Error::getCode - Récupère le code d'erreur
    • Error::getFile - Récupère le fichier où l'erreur s'est produite
    • Error::getLine - Récupère le numéro de ligne où l'erreur s'est produite
    • Error::getMessage - Récupère le message d'erreur
    • Error::getPrevious - Retourne Throwable précédent
    • Error::getTrace - Récupère la trace d'appels
    • Error::getTraceAsString - Récupère la trace d'appels en tant que chaîne de caractères
    • Error::__clone - Cloner l'erreur
    • Error::__construct - Constructeur de l'objet Error
    • Error::__toString - Représentation sous forme de chaîne de caractère de l'erreur
    • ErrorException::getSeverity - Récupère la sévérité de l'exception
    • ErrorException::__construct - Construit l'exception
    • error_clear_last - Enlève l'erreur la plus récente
    • error_get_last - Récupère la dernière erreur survenue
    • error_log - Envoi un message d'erreur vers le gestionnaire d'erreurs défini
    • error_reporting - Fixe le niveau de rapport d'erreurs PHP
    • escapeshellarg - Protège une chaîne de caractères pour utilisation en ligne de commande
    • escapeshellcmd - Protège les caractères spéciaux du Shell
    • Ev::backend - Retourne un entier décrivant le backend utilisé par libev
    • Ev::depth - Retourne la profondeur de récursion
    • Ev::embeddableBackends - Retourne le jeu de backends qui sont encapsulés dans les autres boucles d'événements
    • Ev::feedSignal - Simule la réception d'un signal
    • Ev::feedSignalEvent - Simule un événement de signal dans la boucle par défaut
    • Ev::iteration - Retourne le nombre de fois que la boucle d'événement par défaut a été sollicitée pour un nouvel événement
    • Ev::now - Retourne le temps de démarrage de la dernière itération de la boucle d'événement par défaut
    • Ev::nowUpdate - Etablit le temps courant en demandant au kernel ; met à jour le temps retourné par Ev::now pendant l'exécution
    • Ev::recommendedBackends - Retourne un masque d'octets de backends recommandés pour la plateforme courante
    • Ev::resume - Reprend la boucle d'événement par défaut précédemment stoppée
    • Ev::run - Commence la vérification des événements et appelle les fonctions de rappels pour la boucle par défaut
    • Ev::sleep - Bloque le processus pendant un nombre de secondes fourni
    • Ev::stop - Arrête la boucle d'événements par défaut
    • Ev::supportedBackends - Retourne le jeu de backends supportés par la configuration courant de libev
    • Ev::suspend - Suspend la boucle par défaut d'événements
    • Ev::time - Retourne le temps courant depuis l'époque Unix
    • Ev::verify - Effectue des vérifications internes de consistence (pour le débogage)
    • eval - Exécute une chaîne comme un script PHP
    • EvCheck::createStopped - Crée une instance d'un observateur stoppé EvCheck
    • EvCheck::__construct - Construit l'objet d'observation EvCheck
    • EvChild::createStopped - Crée une instance de l'observateur stoppé EvCheck
    • EvChild::set - Configure l'observateur
    • EvChild::__construct - Construit l'objet d'observation EvChild
    • EvEmbed::createStopped - Crée un objet EvEmbed watcher stoppé
    • EvEmbed::set - Configure le watcher
    • EvEmbed::sweep - Balaye, une seule fois, et de façon non bloquante la boucle interne
    • EvEmbed::__construct - Construit un objet EvEmbed
    • Event::add - Bascule un évènement en attente
    • Event::addSignal - Alias de Event::add
    • Event::addTimer - Alias de Event::add
    • Event::del - Supprime un événement de la liste des événements surveillés
    • Event::delSignal - Alias de Event::del
    • Event::delTimer - Alias de Event::del
    • Event::free - Supprime une événement de la liste des événements surveillés et libère les ressources associées
    • Event::getSupportedMethods - Retourne un tableau contenant les noms des méthodes supportées par cette version de Libevent
    • Event::pending - Détecte si l'événement est en attente ou programmé
    • Event::set - Re-configure l'événement
    • Event::setPriority - Défini la priorité de l'événement
    • Event::setTimer - Re-configure un événement timer
    • Event::signal - Construit un objet d'événement signal
    • Event::timer - Construit un objet d'événement timer
    • Event::__construct - Construit un objet Event
    • EventBase::dispatch - Distribut les événements en attente
    • EventBase::exit - Stoppe la distribution des événements
    • EventBase::free - Libère les ressources allouées pour l'événement de base
    • EventBase::getFeatures - Retourne un masque des fonctionnalités supportées
    • EventBase::getMethod - Retourne la méthode d'événement utilisée
    • EventBase::getTimeOfDayCached - Retourne le temps de l'événement courant
    • EventBase::gotExit - Vérifie s'il a été demandé à la boucle d'événements de sortir
    • EventBase::gotStop - Vérifie s'il a été demandé à la boucle d'événements de s'arrêter
    • EventBase::loop - Distribue les événements en attente
    • EventBase::priorityInit - Défini le nombre de propriétés par événement de base
    • EventBase::reInit - Re-initialise l'événement de base (après un fork)
    • EventBase::stop - Demande à event_base de stopper la distribution d'événements
    • EventBase::__construct - Construit un objet EventBase
    • EventBuffer::add - Ajoute des données à la fin du tampon d'événement
    • EventBuffer::addBuffer - Déplace toutes les données du tampon fourni dans l'instance courante EventBuffer
    • EventBuffer::appendFrom - Déplace le nombre d'octets fourni depuis un tampon source vers la fin du tampon courant
    • EventBuffer::copyout - Copie le nombre d'octets spécifié depuis le début du tampon
    • EventBuffer::drain - Supprime un nombre spécifié d'octets depuis le début du tampon sans copier les données
    • EventBuffer::enableLocking - Description
    • EventBuffer::expand - Réserve de l'espace dans le tampon
    • EventBuffer::freeze - Permet d'empécher les appels qui tentent de modifier un tampon d'événements de réussir
    • EventBuffer::lock - Acquière un verrou sur le buffer
    • EventBuffer::prepend - Ajoute des données au début du buffer
    • EventBuffer::prependBuffer - Déplace toutes les données depuis le buffer source vers le début du buffer courant
    • EventBuffer::pullup - Sérialise les données du buffer et retourne le contenu du buffer sous la forme d'une chaîne
    • EventBuffer::read - Lit les données d'un evbuffer, et vide les octets lus
    • EventBuffer::readFrom - Lit des données depuis un fichier et les place à la fin du tampon
    • EventBuffer::readLine - Extrait une ligne depuis le début du tampon
    • EventBuffer::search - Recherche dans le tampon une occurrence d'une chaîne
    • EventBuffer::searchEol - Cherche dans le tampon une occurrence de fin de ligne
    • EventBuffer::substr - Soustrait une portion des données du tampon
    • EventBuffer::unfreeze - Ré-active les appels qui permettent de modifier un buffer d'événements
    • EventBuffer::unlock - Libère un verrou acquis avec EventBuffer::lock
    • EventBuffer::write - Ecrit le contenu du buffer dans un fichier ou dans un socket
    • EventBuffer::__construct - Construit un objet EventBuffer
    • EventBufferEvent::close - Ferme le descripteur de fichier associé avec le buffer d'événements courant
    • EventBufferEvent::connect - Connecte le descripteur de fichier du tampon d'événement à l'adresse fournie, ou au socket UNIX
    • EventBufferEvent::connectHost - Connexion à un hôte
    • EventBufferEvent::createPair - Crée deux événements de tampon connectés l'un à l'autre
    • EventBufferEvent::disable - Désactive les événements de lecture, d'écriture ou des deux sur un événement de tampon
    • EventBufferEvent::enable - Active les événements de lecture, d'écriture, ou des deux, sur un événement de tampon
    • EventBufferEvent::free - Libère un événement de tampon
    • EventBufferEvent::getDnsErrorString - Retourne une chaîne décrivant la dernière erreur DNS
    • EventBufferEvent::getEnabled - Retourne un masque d'événements actuellement actifs sur le tampon d'événements
    • EventBufferEvent::getInput - Retourne le tampon d'entrée associé avec le tampon d'événements courant
    • EventBufferEvent::getOutput - Retourne le tampon de sortie associé avec le tampon d'événement courant
    • EventBufferEvent::read - Lit les données du tampon
    • EventBufferEvent::readBuffer - Vide le contenu entier du tampon d'entrée et le place dans le tampon
    • EventBufferEvent::setCallbacks - Assigne les fonctions de rappel pour la lecture, l'écriture, et les statuts d'événements
    • EventBufferEvent::setPriority - Assigne une priorité pour un tampon d'événements
    • EventBufferEvent::setTimeouts - Défini le mode lecture et écriture pour le délai d'attente maximal d'un tampon d'événement
    • EventBufferEvent::setWatermark - Active la lecture, et/ou l'écriture des filigranes
    • EventBufferEvent::sslError - Retourne l'erreur OpenSSL la plus récente rapportée par le tampon d'événement
    • EventBufferEvent::sslFilter - Crée un nouveau tampon d'événement SSL, dont les données seront envoyées via un autre tampon d'événement
    • EventBufferEvent::sslGetCipherInfo - Retourne une description textuelle d'un cipher
    • EventBufferEvent::sslGetCipherName - Retourne le nom du cipher courant pour la connexion SSL
    • EventBufferEvent::sslGetCipherVersion - Retourne la version du cipher utilisé pour la connexion SSL courante
    • EventBufferEvent::sslGetProtocol - Retourne le nom du protocole utilisé pour la connexion SSL courante
    • EventBufferEvent::sslRenegotiate - Demande au tampon d'événement de commencer une renégociation SSL
    • EventBufferEvent::sslSocket - Crée un nouveau tampon SSL dont ces données seront envoyées via un socket SSL
    • EventBufferEvent::write - Ajoute des données dans un tampon d'événement de sortie
    • EventBufferEvent::writeBuffer - Ajoute le contenu entier d'un tampon dans un tampon d'événement de sortie
    • EventBufferEvent::__construct - Construit un objet EventBufferEvent
    • EventConfig::avoidMethod - Demande à libevent d'ignorer une méthode d'événement spécifique
    • EventConfig::requireFeatures - Entre dans une fonctionnalité de méthode d'événement demandée par l'application
    • EventConfig::setFlags - Sets one or more flags to configure the eventual EventBase will be initialized
    • EventConfig::setMaxDispatchInterval - Evite l'inversion des priorités
    • EventConfig::__construct - Construit un objet EventConfig
    • EventDnsBase::addNameserverIp - Ajoute un serveur de noms à la base DNS
    • EventDnsBase::addSearch - Ajoute un domaine à la liste des domaines utilisés pour la recherche
    • EventDnsBase::clearSearch - Supprime tous les suffixes courants de recherche
    • EventDnsBase::countNameservers - Récupère le nombre de serveurs de noms configurés
    • EventDnsBase::loadHosts - Charge un fichier hosts (au même format que /etc/hosts)
    • EventDnsBase::parseResolvConf - Analyse le fichier resolv.conf
    • EventDnsBase::setOption - Définit la valeur d'une option de configuration
    • EventDnsBase::setSearchNdots - Définit le paramètre 'ndots' pour les recherches
    • EventDnsBase::__construct - Construit un objet EventDnsBase
    • EventHttp::accept - Autorise un serveur HTTP à accepter les connexions sur le socket ou la ressource spécifiée
    • EventHttp::addServerAlias - Ajoute un alias du serveur pour l'objet serveur HTTP
    • EventHttp::bind - Lie un serveur HTTP sur une adresse et un port spécifiés
    • EventHttp::removeServerAlias - Supprime un alias sur le serveur
    • EventHttp::setAllowedMethods - Définit les méthodes HTTP supportées et acceptées dans les requêtes sur ce serveur, et passées aux fonctions de rappel utilisateurs
    • EventHttp::setCallback - Définit une fonction de rapppel pour une URI spécifique
    • EventHttp::setDefaultCallback - Définit la fonction de rappel par défaut pour gérer les requêtes qui ne sont pas attrappées par des fonctions de rappel spécifiques
    • EventHttp::setMaxBodySize - Définit la taille maximale du corps de la demande
    • EventHttp::setMaxHeadersSize - Définit la taille maximale des en-têtes HTTP
    • EventHttp::setTimeout - Définit le délai d'attente maximal pour une requête HTTP
    • EventHttp::__construct - Construit un objet EventHttp (le serveur HTTP)
    • EventHttpConnection::getBase - Retourne la base d'événement associée avec la connexion
    • EventHttpConnection::getPeer - Récupère l'adresse et le port distant associés avec la connexion
    • EventHttpConnection::makeRequest - Effectue une requête HTTP sur la connexion spécifiée
    • EventHttpConnection::setCloseCallback - Défini une fonction de rappel lors de la fermeture de la connexion
    • EventHttpConnection::setLocalAddress - Définit l'adresse IP depuis laquelle les connexions HTTP sont effectuées
    • EventHttpConnection::setLocalPort - Définit le port local depuis lequel les connexions sont effectuées
    • EventHttpConnection::setMaxBodySize - Définit la taille maximale du corps pour la connexion
    • EventHttpConnection::setMaxHeadersSize - Définit la taille maximale des en-têtes
    • EventHttpConnection::setRetries - Définit le nombre de tentatives pour la connexion
    • EventHttpConnection::setTimeout - Définit le délai d'attente maximal pour la connexion
    • EventHttpConnection::__construct - Construit un objet EventHttpConnection
    • EventHttpRequest::addHeader - Ajoute un en-tête HTTP aux en-têtes de la requête
    • EventHttpRequest::cancel - Annule une requête HTTP en attente
    • EventHttpRequest::clearHeaders - Supprime tous les en-têtes depuis la liste des en-têtes de la requête
    • EventHttpRequest::closeConnection - Ferme les connexions HTTP associées
    • EventHttpRequest::findHeader - Cherche la valeur d'un en-tête
    • EventHttpRequest::free - Libère l'objet et supprime les événements associés
    • EventHttpRequest::getBufferEvent - Retourne l'objet EventBufferEvent
    • EventHttpRequest::getCommand - Retourne la commande de la requête (méthode)
    • EventHttpRequest::getConnection - Retourne un objet EventHttpConnection
    • EventHttpRequest::getHost - Retourne l'hôte demandé
    • EventHttpRequest::getInputBuffer - Retourne le buffer d'entrée
    • EventHttpRequest::getInputHeaders - Retourne le tableau associatif contenant les en-têtes d'entrée
    • EventHttpRequest::getOutputBuffer - Retourne le buffer de sortie de la requête
    • EventHttpRequest::getOutputHeaders - Retourne un tableau associatif contenant les en-têtes de sortie
    • EventHttpRequest::getResponseCode - Retourne le code de la réponse
    • EventHttpRequest::getUri - Retourne l'URI de la requête
    • EventHttpRequest::removeHeader - Supprime un en-tête HTTP depuis les en-têtes de la requête
    • EventHttpRequest::sendError - Envoi un message d'erreur HTML au client
    • EventHttpRequest::sendReply - Envoi une réponse HTML au client
    • EventHttpRequest::sendReplyChunk - Envoi un autre bloc de données comme partie d'un bloc de réponse entrant
    • EventHttpRequest::sendReplyEnd - Complète un bloc de réponse, en libérant la requête
    • EventHttpRequest::sendReplyStart - Initialise un bloc de réponse
    • EventHttpRequest::__construct - Construit un objet EventHttpRequest
    • EventListener::disable - Désactive un objet d'écoute d'événement de connexion
    • EventListener::enable - Active un objet d'écoute d'événement de connexion
    • EventListener::getBase - Retourne la base d'événement associée avec l'écouteur d'événements
    • EventListener::getSocketName - Récupère l'adresse courant pour laquelle le socket d'écoute est lié
    • EventListener::setCallback - Le but de setCallback
    • EventListener::setErrorCallback - Définit la fonction de rappel sur l'évènement d'erreur
    • EventListener::__construct - Crée un nouvel écouteur de connexion associé avec la base d'événement
    • EventSslContext::__construct - Construit un contexte OpenSSL à utiliser avec les classes Event
    • EventUtil::getLastSocketErrno - Retourne le numéro d'erreur le plus récemment survenu sur le socket
    • EventUtil::getLastSocketError - Retourne l'erreur la plus récemment survenue sur le socket
    • EventUtil::getSocketFd - Retourne le descripteur de fichier d'un socket ou d'un flux
    • EventUtil::getSocketName - Récupère l'adresse courant liée au socket
    • EventUtil::setSocketOption - Définit les options du socket
    • EventUtil::sslRandPoll - Génère l'entropie via OpenSSL RAND_poll()
    • EventUtil::__construct - Le constructeur
    • EvFork::createStopped - Crée un instance arrêté de la classe de l'observateur EvFork
    • EvFork::__construct - Construit l'objet observateur EvFork
    • EvIdle::createStopped - Crée une instance d'un objet observateur EvIdle
    • EvIdle::__construct - Construit l'objet observateur EvIdle
    • EvIo::createStopped - Crée un objet d'observateur EvIo arrêté
    • EvIo::set - Configure l'observateur
    • EvIo::__construct - Construit un nouvel objet EvIo
    • EvLoop::backend - Retourne un entier décrivant le backend utilisé par libev
    • EvLoop::check - Crée un objet EvCheck associé avec l'instance de la boucle d'événements courante
    • EvLoop::child - Crée un objet EvChild associé avec la boucle d'événements courante
    • EvLoop::defaultLoop - Retourne ou crée la boucle d'événements par défaut
    • EvLoop::embed - Crée une instance de l'observateur EvEmbed associé avec l'objet de l'EvLoop courant
    • EvLoop::fork - Crée un objet EvFork watcher associé avec l'instance de la boucle de l'événement courant
    • EvLoop::idle - Crée un objet EvIdle watcher associé avec l'instance de la boucle de l'événement courant
    • EvLoop::invokePending - Invoque tous les watchers en attente pendant que leurs statuts de file d'attente ne soient réinitialisés
    • EvLoop::io - Crée un objet EvIo watcher associé avec l'instance de la boucle de l'événement courant
    • EvLoop::loopFork - Doit être appelé après un fork
    • EvLoop::now - Retourne le "event loop time" courant
    • EvLoop::nowUpdate - Etablit le temps courant en demandant au kernel, et mise à jour du temps retourné par EvLoop::now pendant l'exécution
    • EvLoop::periodic - Crée un objet EvPeriodic watcher associé avec l'instance de la boucle d'événement courant
    • EvLoop::prepare - Crée un objet EvPrepare watcher associé avec l'instance de la boucle d'événement courant
    • EvLoop::resume - Reprend une boucle d'évément précédemment stoppée
    • EvLoop::run - Commence à vérifier les événements et à appeler les fonctions de rappel de la boucle
    • EvLoop::signal - Crée un objet EvSignal watcher associé avec l'instance de la boucle d'événement courant
    • EvLoop::stat - Crée un objet EvStat watcher associé avec l'instance de la boucle d'événement courant
    • EvLoop::stop - Stoppe la boucle d'événement
    • EvLoop::suspend - Suspend la boucle
    • EvLoop::timer - Crée un objet EvTimer watcher associé avec l'instance de la boucle d'événement courant
    • EvLoop::verify - Effectue des vérifications de consistence interne (pour le débogage)
    • EvLoop::__construct - Construit un objet de boucle d'événements
    • EvPeriodic::again - Arrête et re-démarre le watcher périodique
    • EvPeriodic::at - Retourne le temps absolu auquel ce watcher sera appelé la prochaine fois
    • EvPeriodic::createStopped - Crée un watcher EvPeriodic stoppé
    • EvPeriodic::set - Configure le watcher
    • EvPeriodic::__construct - Construit un objet watcher EvPeriodic
    • EvPrepare::createStopped - Crée une instance stoppée du watcher EvPrepare
    • EvPrepare::__construct - Construit un objet de watcher EvPrepare
    • EvSignal::createStopped - Crée un objet watcher EvSignal stoppé
    • EvSignal::set - Configure le watcher
    • EvSignal::__construct - Construit un objet watcher EvSignal
    • EvStat::attr - Retourne la valeur la plus récente détectée par Ev
    • EvStat::createStopped - Crée un objet EvStat watcher stoppé
    • EvStat::prev - Retourne le jeu précédent retourné par EvStat::attr
    • EvStat::set - Configure le watcher
    • EvStat::stat - Initialise l'appel à stat
    • EvStat::__construct - Construit un objet EvStat watcher
    • EvTimer::again - Re-démarre le watcher Timer
    • EvTimer::createStopped - Crée un objet EvTimer watcher stoppé
    • EvTimer::set - Configure le watcher
    • EvTimer::__construct - Construit un objet EvTimer watcher
    • EvWatcher::clear - Efface le statut d'attente de l'observateur
    • EvWatcher::feed - Alimente les revents fournis dans la boucle d'événements
    • EvWatcher::getLoop - Retourne la boucle responsable de l'observateur
    • EvWatcher::invoke - Invoque la fonction de rappel de l'observateur avec le masque de bits des événements reçus fournis
    • EvWatcher::keepalive - Garde la boucle active
    • EvWatcher::setCallback - Définit une nouvelle fonction de rappel pour le watcher
    • EvWatcher::start - Démarre le Watcher
    • EvWatcher::stop - Arrête le Watcher
    • EvWatcher::__construct - Constructeur d'objet observateur
    • Exception::getCode - Récupère le code de l'exception
    • Exception::getFile - Récupère le fichier dans lequel l'exception a été créée
    • Exception::getLine - Récupère la ligne dans laquelle l'exception a été créée
    • Exception::getMessage - Récupère le message de l'exception
    • Exception::getPrevious - Retourne le Throwable précédent
    • Exception::getTrace - Récupère la trace de la pile
    • Exception::getTraceAsString - Récupère la trace de la pile en tant que chaîne
    • Exception::__clone - Clone l'exception
    • Exception::__construct - Construit l'exception
    • Exception::__toString - Représente l'exception sous la forme d'une chaîne
    • exec - Exécute un programme externe
    • Executable::execute - Execute statement
    • ExecutionStatus::__construct - ExecutionStatus constructor
    • exif_imagetype - Détermine le type d'une image
    • exif_read_data - Lit les en-têtes EXIF dans les images
    • exif_tagname - Lit le nom d'en-tête EXIF d'un index
    • exif_thumbnail - Récupère la miniature d'une image
    • exit - Affiche un message et termine le script courant
    • exp - Calcul l'exponentielle de e
    • expect:// - Flux d'interactions de processus
    • expect_expectl - Attend jusqu'à ce que la sortie d'un processus corresponde à un des motifs, un période de temps spécifique est passée ou un EOF est vu
    • expect_popen - Exécute une commande via le shell Bourne, et ouvre le flux PTY au processus
    • explode - Scinde une chaîne de caractères en segments
    • expm1 - Retourne exp($num) - 1, calculé de manière précise même lorsque la valeur du nombre est proche de zéro
    • expression - Bind prepared statement variables as parameters
    • Expression::__construct - Expression constructor
    • extension_loaded - Détermine si une extension est chargée ou non
    • extract - Importe les variables dans la table des symboles
    • ezmlm_hash - Calcule le hachage demandé par EZMLM
  • f
    • FANNConnection::getFromNeuron - Retourne la position du neurone de départ
    • FANNConnection::getToNeuron - Retourne la position du neurone de fin
    • FANNConnection::getWeight - Retourne le poids de la connexion
    • FANNConnection::setWeight - Défini le poids de la connexion
    • FANNConnection::__construct - Le constructeur de connexion
    • fann_cascadetrain_on_data - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm
    • fann_clear_scaling_params - Clears scaling parameters
    • fann_copy - Crée une copie d'une structure fann
    • fann_create_from_file - Consruit une propagation de retour du réseau neuronal depuis un fichier de configuration
    • fann_create_shortcut - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut_array - Crée une propagation de retour standart de réseau neuronal qui n'est pas totalement connecté, et a des connexions raccourcies
    • fann_create_sparse - Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_sparse_array - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_standard - Creates a standard fully connected backpropagation neural network
    • fann_create_standard_array - Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_train - Crée une structure vide de données d'entrainement
    • fann_create_train_from_callback - Crée la structure de données d'entrainement depuis une fonction fournie par l'utilisateur
    • fann_descale_input - Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output - Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train - Descale input and output data based on previously calculated parameters
    • fann_destroy - Détruit le réseau en entier, et libère proprement toute la mémoire associée
    • fann_destroy_train - Détruit les données d'entrainement
    • fann_duplicate_train_data - Retourne une copie exact des données d'entrainement fann
    • fann_get_activation_function - Returns the activation function
    • fann_get_activation_steepness - Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array - Get the number of bias in each layer in the network
    • fann_get_bit_fail - The number of fail bits
    • fann_get_bit_fail_limit - Returns the bit fail limit used during training
    • fann_get_cascade_activation_functions - Returns the cascade activation functions
    • fann_get_cascade_activation_functions_count - Returns the number of cascade activation functions
    • fann_get_cascade_activation_steepnesses - Returns the cascade activation steepnesses
    • fann_get_cascade_activation_steepnesses_count - The number of activation steepnesses
    • fann_get_cascade_candidate_change_fraction - Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit - Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs - Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs - Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs - Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs - Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs - Returns the minimum out epochs
    • fann_get_cascade_num_candidates - Returns the number of candidates used during training
    • fann_get_cascade_num_candidate_groups - Returns the number of candidate groups
    • fann_get_cascade_output_change_fraction - Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs - Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier - Returns the weight multiplier
    • fann_get_connection_array - Récupère les connexions dans le réseau
    • fann_get_connection_rate - Récupère le taux de connexion lorsque le réseau a été créé
    • fann_get_errno - Retourne le numéro de la dernière erreur
    • fann_get_errstr - Retourne le dernier message d'erreur
    • fann_get_layer_array - Get the number of neurons in each layer in the network
    • fann_get_learning_momentum - Returns the learning momentum
    • fann_get_learning_rate - Returns the learning rate
    • fann_get_MSE - Reads the mean square error from the network
    • fann_get_network_type - Get the type of neural network it was created as
    • fann_get_num_input - Récupère le nombre de neurones entrants
    • fann_get_num_layers - Récupère le nombre de couches du réseau neuronal
    • fann_get_num_output - Récupère le nombre de neurones sortants
    • fann_get_quickprop_decay - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu - Retourne le facteur mu
    • fann_get_rprop_decrease_factor - Retourne le facteur d'accroissement utilisé pendant l'entrainement RPROP
    • fann_get_rprop_delta_max - Retourne la taille maximale de l'étape
    • fann_get_rprop_delta_min - Retourne la taille minimale de l'étape
    • fann_get_rprop_delta_zero - Retourne la taille initiale de l'étape
    • fann_get_rprop_increase_factor - Retourne le facteur croissant utilisé pendant l'entrainement RPROP
    • fann_get_sarprop_step_error_shift - Retourne le décalage de l'erreur lors de l'étape sarprop
    • fann_get_sarprop_step_error_threshold_factor - Retourne le facteur de seuil d'erreur lors de l'étape sarprop
    • fann_get_sarprop_temperature - Retourne la température sarprop
    • fann_get_sarprop_weight_decay_shift - Retourne le changement décroissant du poids sarprop
    • fann_get_total_connections - Récupère le nombre total de connexions dans la totalité du réseau
    • fann_get_total_neurons - Récupère le nombre total de neurones dans la totalité du réseau
    • fann_get_training_algorithm - Retourne l'algorithme d'entrainement
    • fann_get_train_error_function - Retourne la fonction d'erreur utilisée pendant l'entrainement
    • fann_get_train_stop_function - Retourne la fonction d'arrêt utilisée pendant l'entrainement
    • fann_init_weights - Initialise les poids en utilisant les algorythme Widrow et Nguyen
    • fann_length_train_data - Retourne le nombre de masques d'entrainement dans les données d'entrainement
    • fann_merge_train_data - Fusionne les données d'entrainement
    • fann_num_input_train_data - Retourne le nombre d'entrées dans chaque masque d'entrainement dans les données d'entrainement
    • fann_num_output_train_data - Retourne le nombre de sortie dans chaque masque d'entrainement dans les données d'entrainement
    • fann_print_error - Affiche le message d'erreur
    • fann_randomize_weights - Donne à chaque connexion un poids aléatoire compris entre min_weight et max_weight
    • fann_read_train_from_file - Lit un fichier contenant les données d'entrainement
    • fann_reset_errno - Réinitialise le numéro de la dernière erreur
    • fann_reset_errstr - Réinitialise le message de la dernière erreur
    • fann_reset_MSE - Réinitialise l'erreur quadratique moyenne du réseau
    • fann_run - Exécute les entrées via le réseau neuronal
    • fann_save - Sauvegarde le réseau complet dans un fichier de configuration
    • fann_save_train - Sauvegarde la structure d'entrainement dans un fichier
    • fann_scale_input - Met à l'échelle les données dans le vecteur d'entrée avant de les donner à ANN, en se basant sur les paramètres précédemment calculés
    • fann_scale_input_train_data - Met à l'échelle les entrées dans les données d'entrainement à l'intervalle spécifié
    • fann_scale_output - Met à l'échelle les données dans le vecteur de sortie avant de les passer à ANN, en se basant sur les paramètres précédemment calculés
    • fann_scale_output_train_data - Met à l'échelle les sorties dans les données d'entrainement à l'intervalle spécifié
    • fann_scale_train - Met à l'échelle les données d'entrée et de sortie en se basant sur les paramètres précédemment calculés
    • fann_scale_train_data - Met à l'échelle les entrées et les sorties dans les données d'entrainement à l'intervalle spécifié
    • fann_set_activation_function - Défini la fonction d'activation pour le neurone et la couche spécifiés
    • fann_set_activation_function_hidden - Défini la fonction d'activation pour toutes les couches cachées
    • fann_set_activation_function_layer - Défini la fonction d'activation pour tous les neurones de la couche spécifiée
    • fann_set_activation_function_output - Défini la fonction d'activation pour la couche d'entrée
    • fann_set_activation_steepness - Défini la pente d'activation pour le neurone et le numéro de couche donnés
    • fann_set_activation_steepness_hidden - Défini la raideur de la pente d'activation pour tous les neurones des couches cachées
    • fann_set_activation_steepness_layer - Défini la pente d'activation pour tous les neurones dans la couche dont le numéro est fourni
    • fann_set_activation_steepness_output - Défini la raideur de la pente d'activation dans la couche de sortie
    • fann_set_bit_fail_limit - Défini le bit sûr limite, utilisé pendant l'entrainement
    • fann_set_callback - Défini la fonction de rappel à utiliser pendant l'entrainement
    • fann_set_cascade_activation_functions - Défini le tableau des fonctions d'activation candidate en cascade
    • fann_set_cascade_activation_steepnesses - Défini le tableaux des raideurs d'activation candidate en cascade
    • fann_set_cascade_candidate_change_fraction - Défini la fraction de modification candidate en cascade
    • fann_set_cascade_candidate_limit - Défini la limite candidate
    • fann_set_cascade_candidate_stagnation_epochs - Défini le nombre d'époques de stagnation candidates en cascade
    • fann_set_cascade_max_cand_epochs - Défini l'époque maximale candidate
    • fann_set_cascade_max_out_epochs - Défini l'époque maximale de sortie
    • fann_set_cascade_min_cand_epochs - Défini l'époque minimale candidate
    • fann_set_cascade_min_out_epochs - Défini l'époque minimale de sortie
    • fann_set_cascade_num_candidate_groups - Défini le nombre de groupes candidats
    • fann_set_cascade_output_change_fraction - Défini la fraction de modification de sortie en cascade
    • fann_set_cascade_output_stagnation_epochs - Défini le nombre d'époques de stagnation en cascade de sortie
    • fann_set_cascade_weight_multiplier - Défini le multiplicateur de poids
    • fann_set_error_log - Défini l'endroit où les erreurs seront historisées
    • fann_set_input_scaling_params - Calcule les paramètres d'échelle d'entrée pour une utilisation future, en se basant sur les données d'entrainement
    • fann_set_learning_momentum - Défini la dynamique d'apprentissage
    • fann_set_learning_rate - Défini le taux d'apprentissage
    • fann_set_output_scaling_params - Calcule les paramètres d'échelle de sortie pour une utilisation future, en se basant sur les données d'entrainement
    • fann_set_quickprop_decay - Défini le facteur décroissant quickprop
    • fann_set_quickprop_mu - Défini le facteur quickprop mu
    • fann_set_rprop_decrease_factor - Défini le facteur de diminution utilisé pendant l'entrainement RPROP
    • fann_set_rprop_delta_max - Défini la taille maximale de l'étape
    • fann_set_rprop_delta_min - Défini la taille minimale de l'étape
    • fann_set_rprop_delta_zero - Défini la taille de l'étape initiale
    • fann_set_rprop_increase_factor - Défini le facteur d'augmentation utilisé pendant l'entrainement RPROP
    • fann_set_sarprop_step_error_shift - Défini le changement de l'étape d'erreur sarprop
    • fann_set_sarprop_step_error_threshold_factor - Défini le facteur de seuil de l'étape d'erreur sarprop
    • fann_set_sarprop_temperature - Défini la températeur sarprop
    • fann_set_sarprop_weight_decay_shift - Défini le changement décroissant du poids de sarprop
    • fann_set_scaling_params - Calcule les paramètres d'échelles d'entrée et de sortie utilisés en se basant sur les données d'entrainement
    • fann_set_training_algorithm - Défini l'algorithme d'entrainement
    • fann_set_train_error_function - Défini la fonction d'erreur utilisée pendant l'entrainement
    • fann_set_train_stop_function - Défini la fonction d'arrêt à utiliser durant l'entrainement
    • fann_set_weight - Défini une connexion dans le réseau
    • fann_set_weight_array - Défini les connexions dans le réseau
    • fann_shuffle_train_data - Mélange les données d'entrainement, et rend aléaloire leurs ordres
    • fann_subset_train_data - Retourne une copie d'un sous-jeu de données d'entrainement
    • fann_test - Effectue un test avec un jeu d'entrées et un jeu de sorties désirées
    • fann_test_data - Effectue un test sur un jeu de données d'entrainement et calcule le MSE pour ces données
    • fann_train - Effectue un entrainement sur une itération avec un jeu d'entrées, et un jeu de sorties désirées
    • fann_train_epoch - Effectue un entrainement avec un jeu de données d'entrainement
    • fann_train_on_data - Effectue un entrainement sur un jeu de données complet pour une période de temps
    • fann_train_on_file - Effectue un entrainement sur un jeu complet de données, qui peut être lu depuis un fichier, pour une période de temps
    • fastcgi_finish_request - Affiche toutes les données de la réponse au client
    • fbird_add_user - Alias de ibase_add_user
    • fbird_affected_rows - Alias de ibase_affected_rows
    • fbird_backup - Alias de ibase_backup
    • fbird_blob_add - Alias de ibase_blob_add
    • fbird_blob_cancel - Annule la création d'un blob
    • fbird_blob_close - Alias de ibase_blob_close
    • fbird_blob_create - Alias de ibase_blob_create
    • fbird_blob_echo - Alias de ibase_blob_echo
    • fbird_blob_get - Alias de ibase_blob_get
    • fbird_blob_import - Alias de ibase_blob_import
    • fbird_blob_info - Alias de ibase_blob_info
    • fbird_blob_open - Alias de ibase_blob_open
    • fbird_close - Alias de ibase_close
    • fbird_commit - Alias de ibase_commit
    • fbird_commit_ret - Alias de ibase_commit_ret
    • fbird_connect - Alias de ibase_connect
    • fbird_db_info - Alias de ibase_db_info
    • fbird_delete_user - Alias de ibase_delete_user
    • fbird_drop_db - Alias de ibase_drop_db
    • fbird_errcode - Alias de ibase_errcode
    • fbird_errmsg - Alias de ibase_errmsg
    • fbird_execute - Alias de ibase_execute
    • fbird_fetch_assoc - Alias de ibase_fetch_assoc
    • fbird_fetch_object - Alias de ibase_fetch_object
    • fbird_fetch_row - Alias de ibase_fetch_row
    • fbird_field_info - Alias de ibase_field_info
    • fbird_free_event_handler - Alias de ibase_free_event_handler
    • fbird_free_query - Alias de ibase_free_query
    • fbird_free_result - Alias de ibase_free_result
    • fbird_gen_id - Alias de ibase_gen_id
    • fbird_maintain_db - Alias de ibase_maintain_db
    • fbird_modify_user - Alias de ibase_modify_user
    • fbird_name_result - Alias de ibase_name_result
    • fbird_num_fields - Alias de ibase_num_fields
    • fbird_num_params - Alias de ibase_num_params
    • fbird_param_info - Alias de ibase_param_info
    • fbird_pconnect - Alias de ibase_pconnect
    • fbird_prepare - Alias de ibase_prepare
    • fbird_query - Alias de ibase_query
    • fbird_restore - Alias de ibase_restore
    • fbird_rollback - Alias de ibase_rollback
    • fbird_rollback_ret - Alias de ibase_rollback_ret
    • fbird_server_info - Alias de ibase_server_info
    • fbird_service_attach - Alias de ibase_service_attach
    • fbird_service_detach - Alias de ibase_service_detach
    • fbird_set_event_handler - Alias de ibase_set_event_handler
    • fbird_trans - Alias de ibase_trans
    • fbird_wait_event - Alias de ibase_wait_event
    • fclose - Ferme un fichier
    • fdatasync - Synchronise les données (mais pas les métadonnées) avec le fichier
    • fdf_add_doc_javascript - Ajoute du code javascript dans un document FDF
    • fdf_add_template - Ajoute un template dans le document FDF
    • fdf_close - Ferme un document FDF
    • fdf_create - Crée un nouveau document FDF
    • fdf_enum_values - Appelle une fonction utilisateur à chaque valeur FDF
    • fdf_errno - Retourne le code d'erreur de la dernière opération FDF
    • fdf_error - Retourne le message d'erreur FDF
    • fdf_get_ap - Lit l'apparence d'un champ
    • fdf_get_attachment - Extrait un fichier intégré dans un document FDF
    • fdf_get_encoding - Lit la valeur de la clé /Encoding
    • fdf_get_file - Lit la valeur de la clé /F
    • fdf_get_flags - Lit les attributs d'un champ FDF
    • fdf_get_opt - Lit une valeur dans un tableau de valeur d'un champ FDF
    • fdf_get_status - Lit la valeur de la clé /STATUS
    • fdf_get_value - Retourne la valeur d'un champ FDF
    • fdf_get_version - Lit le numéro de version de l'API FDF
    • fdf_header - Émet les en-têtes HTTP spécifiques à FDF
    • fdf_next_field_name - Lit le nom du champ FDF suivant
    • fdf_open - Ouvre un document FDF
    • fdf_open_string - Lit un document FDF à partir d'une chaîne de caractères
    • fdf_remove_item - Configure le cadre FDF de destination pour le formulaire
    • fdf_save - Sauvegarde un document FDF
    • fdf_save_string - Retourne un document FDF sous forme d'une chaîne de caractères
    • fdf_set_ap - Fixe l'apparence d'un champ FDF
    • fdf_set_encoding - Modifie l'encodage des caractères
    • fdf_set_file - Crée un document PDF pour y afficher des données FDF
    • fdf_set_flags - Modifie une option d'un champ
    • fdf_set_javascript_action - Modifie l'action javascript d'un champ
    • fdf_set_on_import_javascript - Ajoute du code Javascript à être exécuté lorsque Acrobat ouvre un FDF
    • fdf_set_opt - Modifie une option d'un champ
    • fdf_set_status - Fixe la valeur de la clé /STATUS
    • fdf_set_submit_form_action - Modifie l'action d'un formulaire
    • fdf_set_target_frame - Configure le cadre de destination pour l'affichage du formulaire
    • fdf_set_value - Modifie la valeur d'un champ FDF
    • fdf_set_version - Modifie le numéro de version du fichier FDF
    • fdiv - Divides two numbers, according to IEEE 754
    • feof - Teste la fin du fichier
    • FFI::addr - Crée un pointeur non géré vers des données C
    • FFI::alignof - Récupère l'alignement
    • FFI::arrayType - Construit dynamiquement un nouveau type de tableau C
    • FFI::cast - Effectue une conversion de type C
    • FFI::cdef - Crée un nouvel objet FFI
    • FFI::free - Libère une structure de données non gérée
    • FFI::isNull - Vérifie si un objet FFI\CData est un pointeur null
    • FFI::load - Charge les déclarations C à partir d'un fichier d'en-tête C
    • FFI::memcmp - Comparaison des zones de mémoire
    • FFI::memcpy - Copie d'une zone de mémoire dans une autre
    • FFI::memset - Remplit une zone de mémoire
    • FFI::new - Crée une structure de données C
    • FFI::scope - Instancie un objet FFI avec les déclarations C analysées lors du préchargement
    • FFI::sizeof - Récupère la taille des données ou des types C
    • FFI::string - Crée une chaîne PHP à partir d'une zone de mémoire
    • FFI::type - Crée un objet FFI\CType à partir d'une déclaration C
    • FFI::typeof - Récupère le FFI\CType de FFI\CData
    • FFI\CType::getAlignment - Description
    • FFI\CType::getArrayElementType - Description
    • FFI\CType::getArrayLength - Description
    • FFI\CType::getAttributes - Description
    • FFI\CType::getEnumKind - Description
    • FFI\CType::getFuncABI - Description
    • FFI\CType::getFuncParameterCount - Description
    • FFI\CType::getFuncParameterType - Description
    • FFI\CType::getFuncReturnType - Description
    • FFI\CType::getKind - Description
    • FFI\CType::getName - Description
    • FFI\CType::getPointerType - Description
    • FFI\CType::getSize - Description
    • FFI\CType::getStructFieldNames - Description
    • FFI\CType::getStructFieldOffset - Description
    • FFI\CType::getStructFieldType - Description
    • fflush - Envoie tout le contenu généré dans un fichier
    • fgetc - Lit un caractère dans un fichier
    • fgetcsv - Obtient une ligne depuis un pointeur de fichier et l'analyse pour des champs CSV
    • fgets - Récupère la ligne courante à partir de l'emplacement du pointeur sur fichier
    • fgetss - Renvoie la ligne courante du fichier et élimine les balises HTML
    • Fiber::getCurrent - Obtient l'instance de Fibre en cours d'exécution
    • Fiber::getReturn - Obtient la valeur retournée par la fibre
    • Fiber::isRunning - Détermine si la fibre est en cours d'exécution
    • Fiber::isStarted - Détermine si la fibre a démarrée
    • Fiber::isSuspended - Détermine si la fibre est suspendue
    • Fiber::isTerminated - Détermine si la fibre est terminée
    • Fiber::resume - Reprend l'exécution de la fibre avec une valeur
    • Fiber::start - Démarre l'exécution de la fibre
    • Fiber::suspend - Suspend l'exécution de la fibre en cours
    • Fiber::throw - Reprend l'exécution de la fibre avec une exception
    • Fiber::__construct - Crée une nouvelle instance de Fibre
    • FiberError::__construct - Constructeur pour empêcher l'instanciation directe
    • file - Lit le fichier et renvoie le résultat dans un tableau
    • file:// - Accès au système de fichiers local
    • fileatime - Renvoie la date à laquelle le fichier a été accédé pour la dernière fois
    • filectime - Renvoie la date de dernière modification de l'inode d'un fichier
    • filegroup - Lire le nom du groupe
    • fileinode - Lit le numéro d'inode du fichier
    • filemtime - Lit la date de dernière modification du fichier
    • fileowner - Lit l'identifiant du propriétaire d'un fichier
    • fileperms - Lit les droits d'un fichier
    • filesize - Lit la taille d'un fichier
    • FilesystemIterator::current - Lit le fichier courant
    • FilesystemIterator::getFlags - Lit les options activées
    • FilesystemIterator::key - Lit le nom du fichier
    • FilesystemIterator::next - Passe au fichier suivant
    • FilesystemIterator::rewind - Recommence à lire le dossier
    • FilesystemIterator::setFlags - Configure les options
    • FilesystemIterator::__construct - Construit un objet FilesystemIterator
    • filetype - Retourne le type de fichier
    • file_exists - Vérifie si un fichier ou un dossier existe
    • file_get_contents - Lit tout un fichier dans une chaîne
    • file_put_contents - Écrit des données dans un fichier
    • FilterIterator::accept - Vérifie si l'élément courant de l'itérateur est acceptable
    • FilterIterator::current - Récupère la valeur de l'élément courant
    • FilterIterator::key - Récupère la clé courante
    • FilterIterator::next - Déplace l'itérateur à la position suivante
    • FilterIterator::rewind - Replace l'itérateur au début
    • FilterIterator::valid - Vérifie si l'élément courant est valide
    • FilterIterator::__construct - Construit un filterIterator
    • filter_has_var - Vérifie si une variable d'un type spécifique existe
    • filter_id - Retourne l'identifiant d'un filtre nommé
    • filter_input - Récupère une variable externe et la filtre
    • filter_input_array - Récupère plusieurs valeurs externes et les filtre
    • filter_list - Retourne une liste de tous les filtres supportés
    • filter_var - Filtre une variable avec un filtre spécifique
    • filter_var_array - Récupère plusieurs variables et les filtre
    • finfo::buffer - Alias de finfo_buffer()
    • finfo::file - Alias de finfo_file()
    • finfo::set_flags - Alias de finfo_set_flags()
    • finfo::__construct - Alias de finfo_open
    • finfo_close - Ferme une instance finfo
    • finfo_open - Crée une nouvelle instance finfo
    • floatval - Convertit une chaîne en nombre à virgule flottante
    • flock - Verrouille le fichier
    • floor - Arrondit à l'entier inférieur
    • flush - Vide les tampons de sortie du système
    • fmod - Retourne le reste de la division
    • fnmatch - Teste un nom de fichier au moyen d'un masque de recherche
    • fopen - Ouvre un fichier ou une URL
    • forward_static_call - Appelle une méthode statique
    • forward_static_call_array - Appelle une méthode statique et passe les arguments en tableau
    • fpassthru - Affiche le reste du fichier
    • fpm_get_status - Retourne l'état actuel du pool FPM
    • fprintf - Écrit une chaîne formatée dans un flux
    • fputcsv - Formate une ligne en CSV et l'écrit dans un fichier
    • fputs - Alias de fwrite
    • fread - Lecture du fichier en mode binaire
    • frenchtojd - Convertit une date du calendrier français républicain en nombre de jours du calendrier Julien
    • fscanf - Analyse un fichier en fonction d'un format
    • fseek - Modifie la position du pointeur de fichier
    • fsockopen - Ouvre un socket de connexion Internet ou Unix
    • fstat - Lit les informations sur un fichier à partir d'un pointeur de fichier
    • fsync - Synchronise les modifications apportées au fichier (y compris les métadonnées)
    • ftell - Renvoie la position courante du pointeur de fichier
    • ftok - Convertit un chemin et un identifiant de projet en une clé System V IPC
    • ftp:// - Accès aux URLs FTP(s)
    • ftp_alloc - Alloue de l'espace pour un téléchargement de fichier
    • ftp_append - Ajoute le contenu d'un fichier à un autre fichier sur le serveur FTP
    • ftp_cdup - Change de dossier et passe au dossier parent
    • ftp_chdir - Modifie le dossier FTP courant
    • ftp_chmod - Modifie les droits d'un fichier via FTP
    • ftp_close - Ferme une connexion FTP
    • ftp_connect - Ouvre une connexion FTP
    • ftp_delete - Efface un fichier sur un serveur FTP
    • ftp_exec - Exécute une commande sur un serveur FTP
    • ftp_fget - Télécharge un fichier via FTP dans un fichier local
    • ftp_fput - Téléverse un fichier sur un serveur FTP
    • ftp_get - Télécharge un fichier depuis un serveur FTP
    • ftp_get_option - Lit différentes options pour la connexion FTP courante
    • ftp_login - Identification sur un serveur FTP
    • ftp_mdtm - Retourne la date de dernière modification d'un fichier sur un serveur FTP
    • ftp_mkdir - Crée un dossier sur un serveur FTP
    • ftp_mlsd - Retourne la liste des fichiers d'un dossier donné
    • ftp_nb_continue - Reprend le téléchargement d'un fichier (non bloquant)
    • ftp_nb_fget - Lit un fichier sur un serveur FTP, et l'écrit dans un fichier (non bloquant)
    • ftp_nb_fput - Écrit un fichier sur un serveur FTP, et le lit depuis un fichier (non bloquant)
    • ftp_nb_get - Lit un fichier sur un serveur FTP, et l'écrit dans un fichier (non bloquant)
    • ftp_nb_put - Envoie un fichier sur un serveur FTP (non-bloquant)
    • ftp_nlist - Retourne la liste des fichiers d'un dossier
    • ftp_pasv - Active ou désactive le mode passif
    • ftp_put - Charge un fichier sur un serveur FTP
    • ftp_pwd - Retourne le nom du dossier courant
    • ftp_quit - Alias de ftp_close
    • ftp_raw - Envoie une commande FTP brute
    • ftp_rawlist - Fait une liste détaillée des fichiers d'un dossier
    • ftp_rename - Renomme un fichier sur un serveur FTP
    • ftp_rmdir - Efface un dossier FTP
    • ftp_set_option - Modifie les options de la connexion FTP
    • ftp_site - Exécute la commande SITE sur un serveur FTP
    • ftp_size - Retourne la taille d'un fichier
    • ftp_ssl_connect - Ouvre une connexion FTP sécurisée avec SSL
    • ftp_systype - Retourne un identifiant de type de serveur FTP
    • ftruncate - Tronque un fichier
    • function_exists - Indique si une fonction est définie
    • func_get_arg - Retourne un élément de la liste des arguments
    • func_get_args - Retourne les arguments d'une fonction sous la forme d'un tableau
    • func_num_args - Retourne le nombre d'arguments passés à la fonction
    • fwrite - Écrit un fichier en mode binaire
  • g
    • gc_collect_cycles - Force le passage du collecteur de mémoire
    • gc_disable - Désactive le collecteur de références circulaires
    • gc_enable - Active le collecteur de références circulaires
    • gc_enabled - Retourne le statut du collecteur de références circulaires
    • gc_mem_caches - Récupère de la mémoire utilisé par le gestionaire de mémoire de Zend Engine
    • gc_status - Récupère les informations à propos du ramasse-miettes
    • gd_info - Retourne des informations à propos de la bibliothèque GD installée
    • GearmanClient::addOptions - Ajoute des options au client
    • GearmanClient::addServer - Ajoute un serveur de tâches au client
    • GearmanClient::addServers - Ajoute une liste de serveurs de tâches au client
    • GearmanClient::addTask - Ajoute une tâche à exécuter en parallèle
    • GearmanClient::addTaskBackground - Ajoute une tâche d'arrière-plan pour une exécution en parallèle
    • GearmanClient::addTaskHigh - Ajoute une tâche de forte priorité à effectuer en parallèle
    • GearmanClient::addTaskHighBackground - Ajoute une tâche de fond de forte priorité à effectuer en parallèle
    • GearmanClient::addTaskLow - Ajoute une tâche de faible priorité à effectuer en parallèle
    • GearmanClient::addTaskLowBackground - Ajoute une tâche de fond de faible priorité à effectuer en parallèle
    • GearmanClient::addTaskStatus - Ajoute une tâche pour obtenir le statut
    • GearmanClient::clearCallbacks - Efface toutes les fonctions de rappel des tâches
    • GearmanClient::clone - Crée une copie de l'objet GearmanClient
    • GearmanClient::context - Récupère le contexte de l'application
    • GearmanClient::data - Récupère les données de l'application (obsolète)
    • GearmanClient::do - Exécute une seule tâche et retourne le résultat (obsolète)
    • GearmanClient::doBackground - Exécute une tâche en arrière-plan
    • GearmanClient::doHigh - Exécute une seule tâche en priorité haute
    • GearmanClient::doHighBackground - Exécute une tâche en priorité haute en arrière plan
    • GearmanClient::doJobHandle - Récupère le gestionnaire de travaux pour la tâche en cours
    • GearmanClient::doLow - Exécute une seule tâche en priorité basse
    • GearmanClient::doLowBackground - Exécute une tâche en priorité basse en arrière-plan
    • GearmanClient::doNormal - Exécute une tâche et retourne le résultat
    • GearmanClient::doStatus - Récupère le statut de la tâche en cours
    • GearmanClient::echo - Envoi des données à tous les serveurs de travaux afin de vérifier qu'ils les affichent en retour (obsolète)
    • GearmanClient::error - Retourne la dernière erreur rencontrée sous forme de chaîne de caractères
    • GearmanClient::getErrno - Récupère la valeur d'errno
    • GearmanClient::jobStatus - Récupère le statut d'un travail en arrière-plan
    • GearmanClient::ping - Envoi des données à tous les serveurs de tâches pour s'assurer qu'ils sont toujours en fonctionnement
    • GearmanClient::removeOptions - Supprime les options du client
    • GearmanClient::returnCode - Récupère le dernier code Gearman retourné
    • GearmanClient::runTasks - Exécute une liste de tâches en parallèle
    • GearmanClient::setClientCallback - Définit une fonction de rappel lorsqu'un paquet de données est reçu pour une tâche (obsolète)
    • GearmanClient::setCompleteCallback - Définit une fonction à appeler une fois la tâche terminée
    • GearmanClient::setContext - Définit le contexte d'une application
    • GearmanClient::setCreatedCallback - Définit une fonction de rappel à appeler lorsqu'une tâche est placée dans la file d'attente
    • GearmanClient::setData - Définit les données de l'application (obsolète)
    • GearmanClient::setDataCallback - Définit une fonction de rappel à appeler lorsqu'un paquet de données est reçu pour une tâche
    • GearmanClient::setExceptionCallback - Définit une fonction de rappel pour les exceptions émises par l'agent
    • GearmanClient::setFailCallback - Définit une fonction de rappel à appeler lorsqu'un travail échoue
    • GearmanClient::setOptions - Définit les options du client
    • GearmanClient::setStatusCallback - Définit une fonction de rappel pour collecter les statuts d'une tâche
    • GearmanClient::setTimeout - Définit le délai d'attente d'une activité du socket I/O
    • GearmanClient::setWarningCallback - Définit une fonction de rappel lors de l'émission d'alerte depuis l'agent
    • GearmanClient::setWorkloadCallback - Définit une fonction de rappel lors de la réception de mises à jour de données incrémentales
    • GearmanClient::timeout - Récupère la valeur du délai d'activité du socket I/O
    • GearmanClient::wait - Wait for I/O activity on all connections in a client
    • GearmanClient::__construct - Crée une instance GearmanClient
    • GearmanJob::complete - Envoie les résultats ainsi que le statut complet (obsolète)
    • GearmanJob::data - Envoie des données pour un travail en cours d'exécution (obsolète)
    • GearmanJob::exception - Envoie une exception pour un travail en cours d'exécution (obsolète)
    • GearmanJob::fail - Envoie un statut d'échec (obsolète)
    • GearmanJob::functionName - Récupère le nom de la fonction
    • GearmanJob::handle - Récupère le gestionnaire de travaux
    • GearmanJob::returnCode - Récupère le dernier code retourné
    • GearmanJob::sendComplete - Envoie le résultat ainsi que le statut complet
    • GearmanJob::sendData - Envoie les données pour un travail en cours d'exécution
    • GearmanJob::sendException - Envoie une exception pour un travail en cours d'exécution
    • GearmanJob::sendFail - Envoie un statut d'échec
    • GearmanJob::sendStatus - Envoie un statut
    • GearmanJob::sendWarning - Envoie une alerte
    • GearmanJob::setReturn - Définit une valeur de retour
    • GearmanJob::status - Envoie un statut (obsolète)
    • GearmanJob::unique - Récupère l'identifiant unique
    • GearmanJob::warning - Envoie une alerte (obsolète)
    • GearmanJob::workload - Récupère la charge de travail
    • GearmanJob::workloadSize - Récupère la taille de la charge de travail
    • GearmanJob::__construct - Crée une nouvelle instance GearmanJob
    • GearmanTask::create - Crée une tâche (obsolète)
    • GearmanTask::data - Récupère les données retournées par une tâche
    • GearmanTask::dataSize - Récupère la taille des données retournées
    • GearmanTask::function - Récupère le nom de la fonction associée (obsolète)
    • GearmanTask::functionName - Récupère le nom de la fonction associée
    • GearmanTask::isKnown - Vérifie si une tâche est connue
    • GearmanTask::isRunning - Vérifie si la tâche est actuellement en fonctionnement
    • GearmanTask::jobHandle - Récupère le gestionnaire de travaux
    • GearmanTask::recvData - Lit le travail ou les données retournées par une tâche dans un buffer
    • GearmanTask::returnCode - Récupère le dernier code retourné
    • GearmanTask::sendData - Envoie des données pour une tâche (obsolète)
    • GearmanTask::sendWorkload - Envoie les données pour une tâche
    • GearmanTask::taskDenominator - Récupère le dénominateur du taux de réalisation
    • GearmanTask::taskNumerator - Récupère le numérateur du taux de réalisation
    • GearmanTask::unique - Récupère l'identifiant unique de la tâche
    • GearmanTask::uuid - Récupère l'identifiant unique pour une tâche (obsolète)
    • GearmanTask::__construct - Crée une instance GearmanTask
    • GearmanWorker::addFunction - Enregistre et ajoute une fonction de rappel
    • GearmanWorker::addOptions - Ajout des options à l'agent
    • GearmanWorker::addServer - Ajoute un serveur de travaux
    • GearmanWorker::addServers - Ajoute plusieurs serveurs de travaux
    • GearmanWorker::clone - Crée une copie d'un agent
    • GearmanWorker::echo - Test la réponse d'un serveur de travaux
    • GearmanWorker::error - Récupère la dernière erreur survenue
    • GearmanWorker::getErrno - Récupère la errno
    • GearmanWorker::options - Récupère les options de l'agent
    • GearmanWorker::register - Enregistre une fonction sur un serveur de travaux
    • GearmanWorker::removeOptions - Supprime des options de l'agent
    • GearmanWorker::returnCode - Récupère le dernier code Gearman retourné
    • GearmanWorker::setId - Définit un identifiant au worker
    • GearmanWorker::setOptions - Définit les options de l'agent
    • GearmanWorker::setTimeout - Définit le délai d'attente maximal d'activité du socket I/O
    • GearmanWorker::timeout - Récupère le délai d'attente de l'activité du socket I/O
    • GearmanWorker::unregister - Supprime une fonction des serveurs de travaux
    • GearmanWorker::unregisterAll - Supprime toutes les fonctions des serveurs de travaux
    • GearmanWorker::wait - Attente une activité d'un ou plusieurs serveurs de travaux
    • GearmanWorker::work - Attend et exécute un travail
    • GearmanWorker::__construct - Crée une instance GearmanWorker
    • Gender\Gender::connect - Connexion à un dictionnaire externe
    • Gender\Gender::country - Récupère la représentation textuelle d'un pays
    • Gender\Gender::get - Récupère le sexe d'un prénom
    • Gender\Gender::isNick - Vérifie si name0 est un alias de name1
    • Gender\Gender::similarNames - Récupère des noms similaires
    • Gender\Gender::__construct - Construit un objet Gender
    • Generator::current - Récupère la valeur cédée
    • Generator::getReturn - Obtenir la valeur de retour d'un générateur
    • Generator::key - Récupère la clé cédée
    • Generator::next - Reprend l'exécution du générateur
    • Generator::rewind - Ré-initialise l'itérateur
    • Generator::send - Envoi une valeur au générateur
    • Generator::throw - Lance une exception dans le générateur
    • Generator::valid - Vérifie si l'itérateur a été fermé
    • Generator::__wakeup - Fonction de rappel de sérialisation
    • geoip_asnum_by_name - Récupère l'ASN (Autonomous System Numbers)
    • geoip_continent_code_by_name - Lit de code de continent d'une IP
    • geoip_country_code3_by_name - Récupère les trois lettres du code pays
    • geoip_country_code_by_name - Récupère les deux lettres du code pays
    • geoip_country_name_by_name - Récupère le nom complet du pays
    • geoip_database_info - Récupère les informations de la base de données GeoIP
    • geoip_db_avail - Vérifie si la base de données GeoIP est disponible
    • geoip_db_filename - Retourne le nom du fichier contenant la base de données GeoIP spécifiée
    • geoip_db_get_all_info - Retourne des informations détaillées sur tous les types de bases de données GeoIP
    • geoip_domain_by_name - Récupère le second niveau du nom de domaine
    • geoip_id_by_name - Récupère le type de la connexion Internet
    • geoip_isp_by_name - Récupère le nom du fournisseur d'accès
    • geoip_netspeedcell_by_name - Récupère la vitesse de la connexion Internet
    • geoip_org_by_name - Récupère le nom de l'organisation
    • geoip_record_by_name - Récupère les informations enregistrées correspondant au nom de l'hôte ou à l'adresse IP, trouvées dans la base de données GeoIP
    • geoip_region_by_name - Récupère le code pays et la région
    • geoip_region_name_by_code - Retourne le nom de la région pour un pays et un code de région
    • geoip_setup_custom_directory - Défini un dossier personnalisé pour la base de données GeoIP
    • geoip_time_zone_by_country_and_region - Retourne le fuseau horaire de certains pays et région du globe
    • getallheaders - Récupère tous les en-têtes de la requête HTTP
    • getcwd - Retourne le dossier de travail courant
    • getdate - Retourne la date/heure
    • getenv - Retourne la valeur d'une seule ou toutes les variables d'environnement
    • gethostbyaddr - Retourne le nom d'hôte correspondant à une IP
    • gethostbyname - Retourne l'adresse IPv4 correspondant à un hôte
    • gethostbynamel - Retourne la liste d'IPv4 correspondante à un hôte
    • gethostname - Lit le nom de l'hôte
    • getimagesize - Retourne la taille d'une image
    • getimagesizefromstring - Récupère la taille d'une image depuis une chaîne
    • getlastmod - Retourne la date de dernière modification de la page
    • getmxrr - Retourne les enregistrements MX d'un hôte
    • getmygid - Retourne le GID du propriétaire du script
    • getmyinode - Retourne l'inode du script
    • getmypid - Retourne le numéro de processus courant de PHP
    • getmyuid - Retourne l'UID du propriétaire du script actuel
    • getopt - Lit des options passées dans la ligne de commande
    • getprotobyname - Retourne le numéro de protocole associé à un nom de protocole
    • getprotobynumber - Retourne le nom de protocole associé à un numéro de protocole
    • getrandmax - Plus grande valeur aléatoire possible
    • getrusage - Retourne le niveau d'utilisation des ressources
    • getservbyname - Retourne le numéro de port associé à un service Internet et un protocole
    • getservbyport - Retourne le service Internet qui correspond au port et protocole
    • getSession - Connect to a MySQL server
    • gettext - Recherche un message dans le domaine courant
    • gettimeofday - Retourne l'heure actuelle
    • gettype - Retourne le type de la variable
    • get_browser - Indique les capacités du navigateur client
    • get_called_class - Le nom de la classe en "Late Static Binding"
    • get_cfg_var - Retourne la valeur d'une option de PHP
    • get_class - Retourne le nom de la classe d'un objet
    • get_class_methods - Retourne les noms des méthodes d'une classe
    • get_class_vars - Retourne les valeurs par défaut des propriétés d'une classe
    • get_current_user - Retourne le nom du possesseur du script courant
    • get_debug_type - Gets the type name of a variable in a way that is suitable for debugging
    • get_declared_classes - Liste toutes les classes définies dans PHP
    • get_declared_interfaces - Retourne un tableau avec toutes les interfaces déclarées
    • get_declared_traits - Retourne un tableau contenant tous les traits déclarés
    • get_defined_constants - Retourne la liste des constantes et leurs valeurs
    • get_defined_functions - Liste toutes les fonctions définies
    • get_defined_vars - Liste toutes les variables définies
    • get_extension_funcs - Liste les fonctions d'une extension
    • get_headers - Retourne tous les en-têtes envoyés par le serveur en réponse à une requête HTTP
    • get_html_translation_table - Retourne la table de traduction des entités utilisée par htmlspecialchars et htmlentities
    • get_included_files - Retourne un tableau avec les noms des fichiers qui sont inclus dans un script
    • get_include_path - Lit la valeur de la directive de configuration include_path
    • get_loaded_extensions - Retourne la liste de tous les modules compilés et chargés
    • get_magic_quotes_gpc - Retourne la configuration actuelle de l'option magic_quotes_gpc
    • get_magic_quotes_runtime - Retourne la configuration actuelle de l'option magic_quotes_runtime
    • get_mangled_object_vars - Retourne un tableau de propriétés de l'objet manipulé
    • get_meta_tags - Extrait toutes les balises méta d'un fichier HTML
    • get_object_vars - Retourne les propriétés d'un objet
    • get_parent_class - Retourne le nom de la classe parente d'un objet
    • get_required_files - Alias de get_included_files
    • get_resources - Retourne les ressources active
    • get_resource_id - Retourne un entier identifiant une ressource
    • get_resource_type - Retourne le type de ressource
    • glob - Recherche des chemins qui vérifient un masque
    • glob:// - Trouve des noms de fichiers correspondant à un masque donné
    • GlobIterator::count - Lit le nombre de dossiers et fichiers
    • GlobIterator::__construct - Construit un itérateur de type glob
    • Gmagick::addimage - Ajoute une nouvelle image à la liste des images de l'objet Gmagick
    • Gmagick::addnoiseimage - Ajoute du bruit aléatoirement dans l'image
    • Gmagick::annotateimage - Annote une image avec du texte
    • Gmagick::blurimage - Ajoute un filtre flou à l'image
    • Gmagick::borderimage - Ajoute une bordure à l'image
    • Gmagick::charcoalimage - Simule un dessin au fusain
    • Gmagick::chopimage - Supprime une région de l'image
    • Gmagick::clear - Efface toutes les ressources associées à l'objet Gmagick
    • Gmagick::commentimage - Ajoute un commentaire à l'image
    • Gmagick::compositeimage - Assemble 2 images
    • Gmagick::cropimage - Extrait une portion d'une image
    • Gmagick::cropthumbnailimage - Crée une miniature recadrée
    • Gmagick::current - Le contexte courante
    • Gmagick::cyclecolormapimage - Déplace la carte des couleurs d'une image
    • Gmagick::deconstructimages - Retourne les pixels différents entre des images
    • Gmagick::despeckleimage - Le but de despeckleimage
    • Gmagick::destroy - Le but de la méthode destroy
    • Gmagick::drawimage - Fait un rendu de l'objet GmagickDraw sur l'image courante
    • Gmagick::edgeimage - Améliore les bords intérieurs de l'image
    • Gmagick::embossimage - Retourne une image en niveau de gris avec un effet à 3 dimensions
    • Gmagick::enhanceimage - Améliore la qualité d'une image contenant du bruit
    • Gmagick::equalizeimage - Égalise l'histogramme de l'image
    • Gmagick::flipimage - Crée une image miroir verticale
    • Gmagick::flopimage - Crée une image miroir horizontale
    • Gmagick::frameimage - Ajoute une bordure afin de simuler un effet 3D
    • Gmagick::gammaimage - Corrige le gamma d'une image
    • Gmagick::getcopyright - Retourne le copyright de l'API GraphicsMagick
    • Gmagick::getfilename - Retourne le nom du fichier associé avec une séquence d'image
    • Gmagick::getimagebackgroundcolor - Retourne la couleur d'arrière plan de l'image
    • Gmagick::getimageblueprimary - Retourne le point bleu primaire chromatique
    • Gmagick::getimagebordercolor - Retourne la couleur du bord de l'image
    • Gmagick::getimagechanneldepth - Récupère la profondeur d'un canal particulier de l'image
    • Gmagick::getimagecolors - Retourne la couleur de l'indice de la carte des couleurs spécifiée
    • Gmagick::getimagecolorspace - Récupère l'espace colorimétrique de l'image
    • Gmagick::getimagecompose - Retourne l'opérateur de composition associé avec l'image
    • Gmagick::getimagedelay - Récupère le délai de l'image
    • Gmagick::getimagedepth - Récupère la profondeur de l'image
    • Gmagick::getimagedispose - Récupère la méthode de disposition de l'image
    • Gmagick::getimageextrema - Récupère les extrémités de l'image
    • Gmagick::getimagefilename - Récupère le nom du fichier d'une image particulière dans une séquence
    • Gmagick::getimageformat - Récupère le format d'une image particulière dans une séquence
    • Gmagick::getimagegamma - Récupère le gamma de l'image
    • Gmagick::getimagegreenprimary - Récupère le point chromatique primaire vert
    • Gmagick::getimageheight - Récupère la hauteur de l'image
    • Gmagick::getimagehistogram - Récupère l'histogramme de l'image
    • Gmagick::getimageindex - Récupère l'indice de l'image active courante
    • Gmagick::getimageinterlacescheme - Récupère le schéma d'entrelacement de l'image
    • Gmagick::getimageiterations - Récupère les itérations de l'image
    • Gmagick::getimagematte - Vérifie si l'image a un canal mate
    • Gmagick::getimagemattecolor - Récupère la couleur mate de l'image
    • Gmagick::getimageprofile - Récupère le nom du profile de l'image
    • Gmagick::getimageredprimary - Récupère le point chromatique primaire rouge
    • Gmagick::getimagerenderingintent - Récupère l'image de rendu
    • Gmagick::getimageresolution - Récupère la résolution de l'image
    • Gmagick::getimagescene - Récupère la scène de l'image
    • Gmagick::getimagesignature - Génère la signature SHA-256 de l'image
    • Gmagick::getimagetype - Récupère le type potentiel d'une image
    • Gmagick::getimageunits - Récupère les unités utilisées pour la résolution de l'image
    • Gmagick::getimagewhitepoint - Récupère le point chromatique blanc
    • Gmagick::getimagewidth - Récupère la largeur de l'image
    • Gmagick::getpackagename - Récupère le nom du paquet GraphicsMagick
    • Gmagick::getquantumdepth - Récupère la profondeur du quantum Gmagick
    • Gmagick::getreleasedate - Récupère la date de sortie de la version courante de GraphicsMagick
    • Gmagick::getsamplingfactors - Récupère le facteur d'échantillonnage horizontal et vertical
    • Gmagick::getsize - Récupère la taille associée avec l'objet Gmagick
    • Gmagick::getversion - Récupère la version de l'API GraphicsMagick
    • Gmagick::hasnextimage - Vérifie si l'objet contient au moins une autre image
    • Gmagick::haspreviousimage - Vérifie si l'objet contient une image précédente
    • Gmagick::implodeimage - Crée une image à partir d'une copie
    • Gmagick::labelimage - Ajoute un libellé à une image
    • Gmagick::levelimage - Ajuste les niveaux d'une image
    • Gmagick::magnifyimage - Retaille par 2 une image en conservant les proportions
    • Gmagick::mapimage - Remplace les couleurs d'une image avec les couleurs les plus proches d'une image de référence
    • Gmagick::medianfilterimage - Applique un filtre digital
    • Gmagick::minifyimage - Réduit une image de moitié en gardant les proportions
    • Gmagick::modulateimage - Contrôle la luminosité, la saturation et la teinte
    • Gmagick::motionblurimage - Simule un flou cinétique
    • Gmagick::newimage - Crée une nouvelle image
    • Gmagick::nextimage - Se déplace sur l'image suivante
    • Gmagick::normalizeimage - Améliore le contraste de la couleur de l'image
    • Gmagick::oilpaintimage - Simule une peinture à l'huile
    • Gmagick::previousimage - Se déplace vers l'image précédente de l'objet
    • Gmagick::profileimage - Ajoute ou supprime un profile d'une image
    • Gmagick::quantizeimage - Analyse les couleurs d'une image de référence
    • Gmagick::quantizeimages - Le but de quantizeimages
    • Gmagick::queryfontmetrics - Retourne un tableau représentant la métrique pour la police de caractères
    • Gmagick::queryfonts - Retourne les polices de caractères configurées
    • Gmagick::queryformats - Retourne les formats supportés par Gmagick
    • Gmagick::radialblurimage - Brouille une image suivant un rayon
    • Gmagick::raiseimage - Crée un un bouton avec un effet 3D
    • Gmagick::read - Lit une image depuis un fichier
    • Gmagick::readimage - Lit une image depuis un fichier
    • Gmagick::readimageblob - Lit une image depuis une chaîne binaire
    • Gmagick::readimagefile - Le but de readimagefile
    • Gmagick::reducenoiseimage - Lisse les contours de l'image
    • Gmagick::removeimage - Supprime une image depuis la liste des images
    • Gmagick::removeimageprofile - Supprime un profil nommé de l'image
    • Gmagick::resampleimage - Échantillonne l'image à la résolution désirée
    • Gmagick::resizeimage - Redimensionne une image
    • Gmagick::rollimage - Repositionne une image
    • Gmagick::rotateimage - Effectue une rotation de l'image
    • Gmagick::scaleimage - Met à l'échelle une image
    • Gmagick::separateimagechannel - Sépare un canal depuis une image
    • Gmagick::setCompressionQuality - Définit la qualité de compression par défaut de l'objet
    • Gmagick::setfilename - Définit le nom de fichier avant la lecture ou l'écriture d'une image
    • Gmagick::setimagebackgroundcolor - Définit la couleur d'arrière-plan de l'image
    • Gmagick::setimageblueprimary - Définit le point bleu primaire de l'image chromatique
    • Gmagick::setimagebordercolor - Définit la couleur de la bordure de l'image
    • Gmagick::setimagechanneldepth - Définit la profondeur d'un canal particulier de l'image
    • Gmagick::setimagecolorspace - Définit l'espace de couleurs de l'image
    • Gmagick::setimagecompose - Définit l'opérateur de composition de l'image
    • Gmagick::setimagedelay - Définit le délai de l'image
    • Gmagick::setimagedepth - Définit la profondeur de l'image
    • Gmagick::setimagedispose - Définit la méthode de disposition de l'image
    • Gmagick::setimagefilename - Définit le nom du fichier pour une image particulière d'une séquence
    • Gmagick::setimageformat - Définit le format d'une image
    • Gmagick::setimagegamma - Définit le gamma de l'image
    • Gmagick::setimagegreenprimary - Définit le point vert sur l'image chromatique primaire
    • Gmagick::setimageindex - Définit l'itérateur à la position spécifiée dans l'image de la liste pointée par son index
    • Gmagick::setimageinterlacescheme - Définit le schéma d'entrelacement de l'image
    • Gmagick::setimageiterations - Définit les itérations de l'image
    • Gmagick::setimageprofile - Ajoute un profile nommé à l'objet Gmagick
    • Gmagick::setimageredprimary - Définit le point rouge sur l'image chromatique primaire
    • Gmagick::setimagerenderingintent - Définit l'image de rendu
    • Gmagick::setimageresolution - Définit la résolution de l'image
    • Gmagick::setimagescene - Définit l'image de scène
    • Gmagick::setimagetype - Définit le type de l'image
    • Gmagick::setimageunits - Définit les unités à utiliser pour la résolution de l'image
    • Gmagick::setimagewhitepoint - Définit le point blanc sur l'image chromatique primaire
    • Gmagick::setsamplingfactors - Définit les facteurs d'échantillonnage de l'image
    • Gmagick::setsize - Définit la taille de l'objet Gmagick
    • Gmagick::shearimage - Crée un parallélogramme
    • Gmagick::solarizeimage - Applique un effet de solarisation à l'image
    • Gmagick::spreadimage - Déplace aléatoirement chaque pixel d'un bloc
    • Gmagick::stripimage - Supprime d'une image tous les profiles et tous les commentaires
    • Gmagick::swirlimage - Remous les pixels du centre de l'image
    • Gmagick::thumbnailimage - Modifie la taille d'une image
    • Gmagick::trimimage - Supprime les coins de l'image
    • Gmagick::write - Alias de Gmagick::writeimage
    • Gmagick::writeimage - Écrit une image dans un fichier
    • Gmagick::__construct - Le constructeur Gmagick
    • GmagickDraw::annotate - Dessine un texte sur l'image
    • GmagickDraw::arc - Dessine un arc
    • GmagickDraw::bezier - Dessine une courbe de Bézier
    • GmagickDraw::ellipse - Dessine une ellipse sur l'image
    • GmagickDraw::getfillcolor - Retourne la couleur de remplissage
    • GmagickDraw::getfillopacity - Retourne l'opacité utilisée lors d'un dessin
    • GmagickDraw::getfont - Retourne la police de caractères
    • GmagickDraw::getfontsize - Retourne la taille du point d'une police de caractères
    • GmagickDraw::getfontstyle - Retourne le style de la police de caractères
    • GmagickDraw::getfontweight - Retourne le poids de la police de caractères
    • GmagickDraw::getstrokecolor - Retourne la couleur utilisée pour tracer les contours de l'objet
    • GmagickDraw::getstrokeopacity - Retourne l'opacité du tracé des contours de l'objet
    • GmagickDraw::getstrokewidth - Retourne la largeur utilisée pour les contours de l'objet
    • GmagickDraw::gettextdecoration - Retourne la décoration du texte
    • GmagickDraw::gettextencoding - Retourne le code du jeu de caractères à utiliser pour les annotations
    • GmagickDraw::line - Trace une ligne
    • GmagickDraw::point - Dessine un point
    • GmagickDraw::polygon - Dessine un polygone
    • GmagickDraw::polyline - Dessine une polyligne
    • GmagickDraw::rectangle - Dessine un rectangle
    • GmagickDraw::rotate - Applique une rotation
    • GmagickDraw::roundrectangle - Dessine un rectangle arrondi
    • GmagickDraw::scale - Ajuste le facteur d'échelle
    • GmagickDraw::setfillcolor - Définit la couleur de remplissage à utiliser pour dessiner des objets pleins
    • GmagickDraw::setfillopacity - Le but de la méthode setfillopacity
    • GmagickDraw::setfont - Définit la police de caractère à utiliser lors d'une annotation
    • GmagickDraw::setfontsize - Définit la taille, en points, de la police de caractère utilisée lors d'une annotation
    • GmagickDraw::setfontstyle - Définit le style de police de caractères à utiliser lors d'une annotation
    • GmagickDraw::setfontweight - Définit le poids de la police de caractères
    • GmagickDraw::setstrokecolor - Définit la couleur à utiliser pour tracer les contours de l'objet
    • GmagickDraw::setstrokeopacity - Spécifie l'opacité pour les contours de l'objet
    • GmagickDraw::setstrokewidth - Définit la largeur des contours de l'objet
    • GmagickDraw::settextdecoration - Spécifie une décoration
    • GmagickDraw::settextencoding - Spécifie le code du jeu de caractères à utiliser
    • GmagickPixel::getcolor - Retourne la couleur
    • GmagickPixel::getcolorcount - Retourne le nombre de couleurs associées avec cette couleur
    • GmagickPixel::getcolorvalue - Récupère la valeur normalisée du canal de la couleur fournie
    • GmagickPixel::setcolor - Définit la couleur
    • GmagickPixel::setcolorvalue - Définit la valeur normalisée d'un des canaux
    • GmagickPixel::__construct - Le constructeur GmagickPixel
    • gmdate - Formate une date/heure GMT/CUT
    • gmmktime - Retourne le timestamp UNIX d'une date GMT
    • GMP::__construct - Crée un nombre GMP
    • GMP::__serialize - Sérialise l'objet GMP
    • GMP::__unserialize - Désérialise le paramètre data en un objet GMP
    • gmp_abs - Valeur absolue GMP
    • gmp_add - Addition de 2 nombres GMP
    • gmp_and - ET logique
    • gmp_binomial - Calcul le coefficient binomial
    • gmp_clrbit - Annule un octet
    • gmp_cmp - Compare des nombres GMP
    • gmp_com - Calcule le complémentaire d'un nombre
    • gmp_div - Alias de gmp_div_q
    • gmp_divexact - Division exacte de nombres GMP
    • gmp_div_q - Divisions de 2 nombres GMP
    • gmp_div_qr - Divise deux nombres GMP
    • gmp_div_r - Reste de la division de deux nombres GMP
    • gmp_export - Exportation vers une chaîne binaire
    • gmp_fact - Factorielle GMP
    • gmp_gcd - Calcule le PGCD
    • gmp_gcdext - PGCD étendu
    • gmp_hamdist - Distance de Hamming
    • gmp_import - Importation depuis une chaîne binaire
    • gmp_init - Crée un nombre GMP
    • gmp_intval - Convertit un nombre GMP en entier
    • gmp_invert - Modulo inversé
    • gmp_jacobi - Symbole de Jacobi
    • gmp_kronecker - Symbole Kronecker
    • gmp_lcm - Calcul le PPCM
    • gmp_legendre - Symbole de Legendre
    • gmp_mod - Modulo GMP
    • gmp_mul - Multiplication de 2 nombres GMP
    • gmp_neg - Opposé de nombre GMP
    • gmp_nextprime - Trouve le prochain nombre premier
    • gmp_or - OU logique
    • gmp_perfect_power - Vérifie si un nombre est une puissance parfaite
    • gmp_perfect_square - Carré parfait GMP
    • gmp_popcount - Comptage de population
    • gmp_pow - Puissance
    • gmp_powm - Puissance et modulo
    • gmp_prob_prime - Nombre GMP probablement premier
    • gmp_random - Nombre GMP aléatoire
    • gmp_random_bits - Génère un nombre aléatoire
    • gmp_random_range - Récupérer un entier uniformément sélectionné
    • gmp_random_seed - Définit la graine RNG (Générateur de Nombres Aléatoire)
    • gmp_root - Récupère la partie entière de la n-ème racine
    • gmp_rootrem - Récupère la partie entière et le reste de la n-ème racine
    • gmp_scan0 - Recherche 0
    • gmp_scan1 - Recherche 1
    • gmp_setbit - Modifie un bit
    • gmp_sign - Signe du nombre GMP
    • gmp_sqrt - Racine carrée GMP
    • gmp_sqrtrem - Racine carrée avec reste GMP
    • gmp_strval - Convertit un nombre GMP en chaîne
    • gmp_sub - Soustraction de 2 nombres GMP
    • gmp_testbit - Teste si un octet est défini
    • gmp_xor - OU exclusif logique
    • gmstrftime - Formate une date/heure GMT/CUT en fonction de la configuration locale
    • gnupg_adddecryptkey - Ajoute une clé pour déchiffrement
    • gnupg_addencryptkey - Ajoute une clé pour chiffrement
    • gnupg_addsignkey - Ajoute une clé pour signer
    • gnupg_cleardecryptkeys - Supprime toutes les clés qui étaient fixées pour déchiffrement auparavant
    • gnupg_clearencryptkeys - Supprime toutes les clés qui étaient fixées pour chiffrement auparavant
    • gnupg_clearsignkeys - Supprime toutes les clés qui étaient fixées pour signature auparavant
    • gnupg_decrypt - Déchiffre un texte donné
    • gnupg_decryptverify - Déchiffre et vérifie un texte donné
    • gnupg_deletekey - Delete a key from the keyring
    • gnupg_encrypt - Chiffre un texte donné
    • gnupg_encryptsign - Chiffre et signe un texte donné
    • gnupg_export - Exporte une clé
    • gnupg_getengineinfo - Returns the engine info
    • gnupg_geterror - Retourne le texte d'erreur, si une fonction échoue
    • gnupg_geterrorinfo - Returns the error info
    • gnupg_getprotocol - Retourne le protocole actif courant pour toutes les opérations
    • gnupg_gettrustlist - Search the trust items
    • gnupg_import - Importe une clé
    • gnupg_init - Initialise une connexion
    • gnupg_keyinfo - Retourne un tableau avec les informations à propos de toutes les clés qui correspondent au motif donné
    • gnupg_listsignatures - List key signatures
    • gnupg_setarmor - Change la sortie blindée
    • gnupg_seterrormode - Fixe le mode pour error_reporting
    • gnupg_setsignmode - Fixe le mode pour signer
    • gnupg_sign - Signe un texte donné
    • gnupg_verify - Vérifie un texte signé
    • grapheme_extract - Extrait un groupe de graphème d'une chaîne UTF-8
    • grapheme_stripos - Trouve la position en graphème de la première occurrence dans une chaîne, insensible à la casse
    • grapheme_stristr - Retourne la partie d'une chaîne à partir d'une occurrence
    • grapheme_strlen - Lit la taille d'une chaîne en nombre de graphème
    • grapheme_strpos - Trouve la position du premier graphème
    • grapheme_strripos - Trouve la position du dernier graphème, insensible à la casse
    • grapheme_strrpos - Trouve la position du dernier graphème
    • grapheme_strstr - Retourne la partie d'une chaîne à partir d'une occurrence, insensible à la casse
    • grapheme_substr - Retourne une partie d'une chaîne
    • gregoriantojd - Convertit une date grégorienne en nombre de jours du calendrier Julien
    • gzclose - Ferme un pointeur sur un fichier gz ouvert
    • gzcompress - Compresse une chaîne
    • gzdecode - Décode une chaîne de caractères compressée gzip
    • gzdeflate - Compresse une chaîne
    • gzencode - Crée une chaîne compressée gzip
    • gzeof - Indique si la fin d'un fichier (EOF) compressé est atteinte
    • gzfile - Lit la totalité d'un fichier compressé
    • gzgetc - Lit un caractère dans un fichier compressé
    • gzgets - Lit une ligne dans un fichier compressé
    • gzgetss - Lit une ligne dans un fichier compressé, et supprime les balises HTML
    • gzinflate - Décompresse une chaîne
    • gzopen - Ouvre un fichier compressé avec gzip
    • gzpassthru - Affiche toutes les données qui restent dans un pointeur gz
    • gzputs - Alias de gzwrite
    • gzread - Lecture de fichier compressé binaire
    • gzrewind - Replace le pointeur au début du fichier
    • gzseek - Déplace le pointeur de lecture
    • gztell - Lit la position courante du pointeur de lecture
    • gzuncompress - Décompresse une chaîne compressée
    • gzwrite - Écrit dans un fichier compressé gzip
  • h
    • hash - Génère une valeur de hachage (empreinte numérique)
    • HashContext::__construct - Constructeur privé pour interdire l'instanciation directe
    • HashContext::__serialize - Sérialise l'objet HashContext
    • HashContext::__unserialize - Désérialise le paramètre data en un objet HashContext
    • hash_algos - Retourne une liste des algorithmes de hachage enregistrés
    • hash_copy - Copie un contexte de hachage
    • hash_equals - Comparaison de chaînes résistante aux attaques temporelles
    • hash_file - Génère une valeur de hachage en utilisant le contenu d'un fichier donné
    • hash_final - Finalise un hachage incrémental et retourne le résultat de l'empreinte numérique
    • hash_hkdf - Génère une dérivation de clé HKDF depuis une clé fournie
    • hash_hmac - Génère une valeur de clé de hachage en utilisant la méthode HMAC
    • hash_hmac_algos - Return a list of registered hashing algorithms suitable for hash_hmac
    • hash_hmac_file - Génère une valeur de clé de hachage en utilisant la méthode HMAC et le contenu d'un fichier donné
    • hash_init - Initialise un contexte de hachage incrémental
    • hash_pbkdf2 - Génère une clé PBKDF2 dérivée du mot de passe fourni
    • hash_update - Ajoute des données dans le contexte de hachage actif
    • hash_update_file - Ajoute des données dans un contexte de hachage actif provenant d'un fichier
    • hash_update_stream - Ajoute des données dans un contexte de hachage actif d'un flux ouvert
    • header - Envoie un en-tête HTTP brut
    • headers_list - Retourne la liste des en-têtes de réponse du script courant
    • headers_sent - Indique si les en-têtes HTTP ont déjà été envoyés
    • header_register_callback - Enregistre une fonction de rappel pour l'envoi des en-têtes
    • header_remove - Supprime un en-tête HTTP
    • hebrev - Convertit un texte logique hébreux en texte visuel
    • hebrevc - Convertit un texte logique hébreux en texte visuel, avec retours à la ligne
    • hex2bin - Convertit une chaîne encodée en hexadécimal vers du binaire
    • hexdec - Convertit de hexadécimal en décimal
    • highlight_file - Colorisation syntaxique d'un fichier
    • highlight_string - Applique la syntaxe colorisée à du code PHP
    • hrtime - Get the system's high resolution time
    • HRTime\PerformanceCounter::getFrequency - Fréquence du timer en ticks par seconde
    • HRTime\PerformanceCounter::getTicks - Ticks courrant depuis le système
    • HRTime\PerformanceCounter::getTicksSince - Ticks écoulés depuis la valeur fournie
    • HRTime\StopWatch::getElapsedTicks - Récupère les ticks écoulés pour toutes les intervalles
    • HRTime\StopWatch::getElapsedTime - Récupère le temps écoulé pour tous les intervalles
    • HRTime\StopWatch::getLastElapsedTicks - Récupère les ticks écoulés pour la dernière intervalle
    • HRTime\StopWatch::getLastElapsedTime - Récupère le temps écoulé pour la dernière intervalle
    • HRTime\StopWatch::isRunning - Vérifie si la mesure du temps est en cours
    • HRTime\StopWatch::start - Démarre la mesure du temps
    • HRTime\StopWatch::stop - Arrête la mesure du temps
    • htmlentities - Convertit tous les caractères éligibles en entités HTML
    • htmlspecialchars - Convertit les caractères spéciaux en entités HTML
    • htmlspecialchars_decode - Convertit les entités HTML spéciales en caractères
    • html_entity_decode - Convertit les entités HTML à leurs caractères correspondant
    • http:// - Accès aux URLs HTTP(s)
    • http_build_query - Génère une chaîne de requête en encodage URL
    • http_response_code - Récupère ou définit le code de réponse HTTP
    • hypot - Calcul la longueur de l'hypoténuse d'un triangle à angle droit
  • i
    • ibase_add_user - Ajoute un utilisateur à une base de données de sécurité
    • ibase_affected_rows - Retourne le nombre de lignes affectées par la dernière requête iBase
    • ibase_backup - Lance une tâche de sauvegarde dans le gestionnaire de services et retourne immédiatement
    • ibase_blob_add - Ajoute des données dans un BLOB iBase fraîchement créé
    • ibase_blob_cancel - Annule la création d'un BLOB iBase
    • ibase_blob_close - Ferme un BLOB iBase
    • ibase_blob_create - Crée un BLOB iBase pour ajouter des données
    • ibase_blob_echo - Affiche le contenu d'un BLOB iBase au navigateur
    • ibase_blob_get - Lit len octets de données dans un BLOB iBase ouvert
    • ibase_blob_import - Crée un BLOB iBase, y copie un fichier et le referme
    • ibase_blob_info - Retourne la taille d'un BLOB iBase et d'autres informations utiles
    • ibase_blob_open - Ouvre un BLOB iBase pour récupérer des parties de données
    • ibase_close - Ferme une connexion à une base de données Interbase
    • ibase_commit - Valide une transaction iBase
    • ibase_commit_ret - Valide une transaction iBase sans la refermer
    • ibase_connect - Ouvre une connexion à une base de données
    • ibase_db_info - Demande des statistiques sur une base de données Interbase
    • ibase_delete_user - Efface un utilisateur d'une base de données de sécurité
    • ibase_drop_db - Supprime une base de données iBase
    • ibase_errcode - Retourne le code d'erreur iBase
    • ibase_errmsg - Retourne un message d'erreur
    • ibase_execute - Exécute une requête iBase préparée
    • ibase_fetch_assoc - Récupère une ligne du résultat d'une requête dans un tableau associatif
    • ibase_fetch_object - Lit une ligne dans une base Interbase dans un objet
    • ibase_fetch_row - Lit une ligne d'une base Interbase
    • ibase_field_info - Lit les informations sur un champ iBase
    • ibase_free_event_handler - Libère un gestionnaire d'événements iBase
    • ibase_free_query - Libère la mémoire réservée par une requête préparée
    • ibase_free_result - Libère un résultat iBase
    • ibase_gen_id - Incrémente le générateur donné et retourne sa nouvelle valeur
    • ibase_maintain_db - Exécute une commande de maintenance sur une base de données Interbase
    • ibase_modify_user - Modifie un utilisateur dans une base de données de sécurité
    • ibase_name_result - Assigne un nom à un jeu de résultats iBase
    • ibase_num_fields - Retourne le nombre de colonnes dans un résultat iBase
    • ibase_num_params - Retourne le nombre de paramètres dans une requête préparée iBase
    • ibase_param_info - Retourne des informations à propos d'un paramètre dans une requête préparée iBase
    • ibase_pconnect - Ouvre une connexion persistante à une base de données InterBase
    • ibase_prepare - Prépare une requête iBase pour lier les paramètres et l'exécuter ultérieurement
    • ibase_query - Exécute une requête sur une base iBase
    • ibase_restore - Lance une tâche de restauration dans le gestionnaire de services et retourne immédiatement
    • ibase_rollback - Annule une transaction interBase
    • ibase_rollback_ret - Annule une transaction sans la fermer
    • ibase_server_info - Sollicite des informations à propos d'un serveur de base de donnée
    • ibase_service_attach - Connexion au gestionnaire de service
    • ibase_service_detach - Déconnexion du gestionnaire de service
    • ibase_set_event_handler - Enregistre une fonction de rappel sur un événement interBase
    • ibase_trans - Prépare une transaction interBase
    • ibase_wait_event - Attend un événement interBase
    • iconv - Convertit une chaîne de caractères à partir d'un encodage vers un autre
    • iconv_get_encoding - Lit le jeu de caractères courant
    • iconv_mime_decode - Décode un champ d’en-tête MIME
    • iconv_mime_decode_headers - Décode des en-têtes MIME multiples
    • iconv_mime_encode - Construit un en-tête MIME avec les champs field_name et field_value
    • iconv_set_encoding - Modifie le jeu courant de caractères d'encodage
    • iconv_strlen - Retourne le nombre de caractères d'une chaîne
    • iconv_strpos - Trouve la position de la première occurrence d'une chaîne dans une autre
    • iconv_strrpos - Trouve la position de la dernière occurrence d'un élément dans une chaîne
    • iconv_substr - Coupe une partie de chaîne
    • idate - Formate une partie de l'heure/date locale en tant qu'entier
    • idn_to_ascii - Convertit un nom de domaine au format IDNA ASCII
    • idn_to_utf8 - Convertit le nom de domaine IDNA ASCII en Unicode
    • igbinary_serialize - Génère une représentation binaire stockable et compacte d'une valeur
    • igbinary_unserialize - Crée une variable PHP à partir d'une valeur sérialisée par igbinary_serialize
    • ignore_user_abort - Active l'interruption de script sur déconnexion du visiteur
    • image2wbmp - Affichage de l'image vers le navigateur ou dans un fichier
    • imageaffine - Retourne une image contenant l'image source transformée, en utilisant optionnellement une zone de découpe
    • imageaffinematrixconcat - Concatène deux matrices de transformation affine
    • imageaffinematrixget - Obtenir une matrice de transformation affine
    • imagealphablending - Modifie le mode de blending d'une image
    • imageantialias - Utiliser ou non les fonctions d'antialias
    • imagearc - Dessine une ellipse partielle
    • imageavif - Affichage de l'image vers le navigateur ou dans un fichier
    • imagebmp - Affiche ou enregistre une image BMP au navigateur ou dans un fichier
    • imagechar - Dessine un caractère horizontalement
    • imagecharup - Dessine un caractère verticalement
    • imagecolorallocate - Alloue une couleur pour une image
    • imagecolorallocatealpha - Alloue une couleur à une image
    • imagecolorat - Retourne l'index de la couleur d'un pixel donné
    • imagecolorclosest - Retourne l'index de la couleur la plus proche d'une couleur donnée
    • imagecolorclosestalpha - Retourne la couleur la plus proche, en tenant compte du canal alpha
    • imagecolorclosesthwb - Lit l'index de la couleur spécifiée avec sa teinte, blanc et noir
    • imagecolordeallocate - Supprime une couleur d'une image
    • imagecolorexact - Retourne l'index de la couleur donnée
    • imagecolorexactalpha - Retourne l'index d'une couleur avec son canal alpha
    • imagecolormatch - Fait correspondre un peu plus les couleurs de la version palette d'une image aux couleurs de sa version truecolor
    • imagecolorresolve - Retourne l'index de la couleur donnée, ou la plus proche possible
    • imagecolorresolvealpha - Retourne un index de couleur ou son alternative la plus proche, y compris le canal alpha
    • imagecolorset - Change la couleur dans une palette à l'index donné
    • imagecolorsforindex - Retourne la couleur associée à un index
    • imagecolorstotal - Calcule le nombre de couleurs d'une palette
    • imagecolortransparent - Définit la couleur transparente
    • imageconvolution - Applique une matrice de la convolution 3x3, en utilisant le coefficient et l'excentrage
    • imagecopy - Copie une partie d'une image
    • imagecopymerge - Copie et fusionne une partie d'une image
    • imagecopymergegray - Copie et fusionne une partie d'une image en niveaux de gris
    • imagecopyresampled - Copie, redimensionne, rééchantillonne une image
    • imagecopyresized - Copie et redimensionne une partie d'une image
    • imagecreate - Crée une nouvelle image à palette
    • imagecreatefromavif - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefrombmp - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefromgd - Crée une nouvelle image à partir d'un fichier GD ou d'une URL
    • imagecreatefromgd2 - Crée une nouvelle image à partir d'un fichier GD2 ou d'une URL
    • imagecreatefromgd2part - Crée une nouvelle image à partir d'une partie de fichier GD2 ou d'une URL
    • imagecreatefromgif - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefromjpeg - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefrompng - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefromstring - Crée une image à partir d'une chaîne
    • imagecreatefromtga - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefromwbmp - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefromwebp - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefromxbm - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatefromxpm - Crée une nouvelle image depuis un fichier ou une URL
    • imagecreatetruecolor - Crée une nouvelle image en couleurs vraies
    • imagecrop - Recadre une image sur le rectangle donné
    • imagecropauto - Recadre une image automatiquement en utilisant un des modes disponibles
    • imagedashedline - Dessine une ligne pointillée
    • imagedestroy - Détruit une image
    • imageellipse - Dessine une ellipse
    • imagefill - Remplissage
    • imagefilledarc - Dessine un arc partiel et le remplit
    • imagefilledellipse - Dessine une ellipse pleine
    • imagefilledpolygon - Dessine un polygone rempli
    • imagefilledrectangle - Dessine un rectangle rempli
    • imagefilltoborder - Remplit une région avec une couleur spécifique
    • imagefilter - Applique un filtre à une image
    • imageflip - Retourne une image en utilisant le mode fourni
    • imagefontheight - Retourne la hauteur de la police
    • imagefontwidth - Retourne la largeur de la police
    • imageftbbox - Calcule le rectangle d'encadrement pour un texte, en utilisant la police courante et freetype2
    • imagefttext - Écrit du texte dans une image avec la police courante FreeType 2
    • imagegammacorrect - Applique une correction gamma à l'image GD
    • imagegd - Génère une image au format GD, vers le navigateur ou un fichier
    • imagegd2 - Génère une image au format GD2, vers le navigateur ou un fichier
    • imagegetclip - Récupère le rectangle de coupure
    • imagegetinterpolation - Récupère la méthode d'interpolation
    • imagegif - Affichage de l'image vers le navigateur ou dans un fichier
    • imagegrabscreen - Capture l'écran complet
    • imagegrabwindow - Capture une fenêtre
    • imageinterlace - Active ou désactive l'entrelacement
    • imageistruecolor - Détermine si une image est une image truecolor
    • imagejpeg - Affichage de l'image vers le navigateur ou dans un fichier
    • imagelayereffect - Active l'option d'alpha blending, pour utiliser les effets de libgd
    • imageline - Dessine une ligne
    • imageloadfont - Charge une nouvelle police
    • imageopenpolygon - Dessine un polygone ouvert
    • imagepalettecopy - Copie la palette d'une image à l'autre
    • imagepalettetotruecolor - Convertit une image basée sur une palette en couleur vraie
    • imagepng - Envoie une image PNG vers un navigateur ou un fichier
    • imagepolygon - Dessine un polygone
    • imagerectangle - Dessine un rectangle
    • imageresolution - Récupère ou définit la résoltion de l'image
    • imagerotate - Fait tourner une image d'un angle
    • imagesavealpha - Détermine si les informations complètes du canal alpha doivent être conservées lors de la sauvegardes d'images
    • imagescale - Met à l'échelle une image en utilisant une hauteur et une largeur fournies
    • imagesetbrush - Modifie la brosse pour le dessin des lignes
    • imagesetclip - Définit le rectangle de coupure
    • imagesetinterpolation - Défini la méthode d'interpolation
    • imagesetpixel - Dessine un pixel
    • imagesetstyle - Configure le style pour le dessin des lignes
    • imagesetthickness - Modifie l'épaisseur d'un trait
    • imagesettile - Modifie l'image utilisée pour le carrelage
    • imagestring - Dessine une chaîne horizontale
    • imagestringup - Dessine une chaîne verticale
    • imagesx - Retourne la largeur d'une image
    • imagesy - Retourne la hauteur de l'image
    • imagetruecolortopalette - Convertit une image en couleurs vraies en image à palette
    • imagettfbbox - Retourne le rectangle entourant un texte et dessiné avec une police TrueType
    • imagettftext - Dessine un texte avec une police TrueType
    • imagetypes - Retourne les types d'images supportés par la version courante de PHP
    • imagewbmp - Affichage de l'image vers le navigateur ou dans un fichier
    • imagewebp - Affiche une image WebP vers un navigateur ou un fichier
    • imagexbm - Génère une image au format XBM
    • image_type_to_extension - Retourne l'extension du fichier pour le type d'image
    • image_type_to_mime_type - Lit le Mime-Type d'un type d'image
    • Imagick::adaptiveBlurImage - Ajout un flou adaptatif à l'image
    • Imagick::adaptiveResizeImage - Redimensionne adaptativement une image par triangulation
    • Imagick::adaptiveSharpenImage - Augmente le contraste de l'image
    • Imagick::adaptiveThresholdImage - Sélectionne le niveau de chaque pixel, à partir d'un intervalle d'intensité
    • Imagick::addImage - Ajoute une nouvelle image à la liste d'image Imagick
    • Imagick::addNoiseImage - Ajoute un bruit blanc à une image
    • Imagick::affineTransformImage - Transforme une image
    • Imagick::animateImages - Anime une ou plusieurs images
    • Imagick::annotateImage - Annote une image avec un texte
    • Imagick::appendImages - Ajoute un jeu d'images
    • Imagick::autoLevelImage - Adjusts the levels of a particular image channel
    • Imagick::averageImages - Moyenne d'un jeu d'images
    • Imagick::blackThresholdImage - Force tous les pixels au-delà d'un seuil à noir
    • Imagick::blueShiftImage - Mutes the colors of the image
    • Imagick::blurImage - Ajoute un filtre de flou à une image
    • Imagick::borderImage - Encadre une image avec un bord
    • Imagick::brightnessContrastImage - Change the brightness and/or contrast of an image
    • Imagick::charcoalImage - Simule un dessin au fusain
    • Imagick::chopImage - Supprime une région d'une image et retaille
    • Imagick::clampImage - Restricts the color range from 0 to the quantum depth.
    • Imagick::clear - Libère toutes les ressources associées à un objet Imagick
    • Imagick::clipImage - S'aligne sur le premier chemin d'un profil 8BIM
    • Imagick::clipImagePath - Clips along the named paths from the 8BIM profile, if present
    • Imagick::clipPathImage - Suit le chemin d'un profil 8BIM
    • Imagick::clone - Fait une copie exacte d'un objet Imagick
    • Imagick::clutImage - Remplace les couleurs d'une image
    • Imagick::coalesceImages - Compose un jeu d'images
    • Imagick::colorFloodfillImage - Change les pixels qui sont d'une couleur
    • Imagick::colorizeImage - Mélange la couleur de remplissage avec l'image
    • Imagick::colorMatrixImage - Apply color transformation to an image
    • Imagick::combineImages - Combine plusieurs images en une seule
    • Imagick::commentImage - Ajoute un commentaire à une image
    • Imagick::compareImageChannels - Retourne la différence entre plusieurs images
    • Imagick::compareImageLayers - Retourne la région d'encadrement maximale entre deux images
    • Imagick::compareImages - Compare une image avec une image reconstituée
    • Imagick::compositeImage - Compose une image avec une autre
    • Imagick::contrastImage - Change le contraste de l'image
    • Imagick::contrastStretchImage - Améliore le contraste d'une image
    • Imagick::convolveImage - Applique un noyau de convolution à une image
    • Imagick::count - Get the number of images
    • Imagick::cropImage - Extrait une région d'une image
    • Imagick::cropThumbnailImage - Crée une miniature par retaillage
    • Imagick::current - Retourne une référence sur l'objet imagick courant
    • Imagick::cycleColormapImage - Déplace la carte des couleurs d'une image
    • Imagick::decipherImage - Déchiffre une image
    • Imagick::deconstructImages - Retourne les différences de certains pixels entre deux images
    • Imagick::deleteImageArtifact - Supprime l'artefact d'une image
    • Imagick::deleteImageProperty - Deletes an image property
    • Imagick::deskewImage - Supprime le biais de l'image
    • Imagick::despeckleImage - Réduit le bruit speckle d'une image
    • Imagick::destroy - Détruit un objet Imagick
    • Imagick::displayImage - Affiche une image
    • Imagick::displayImages - Affiche une image ou une séquence
    • Imagick::distortImage - Déforme une image avec différentes méthodes
    • Imagick::drawImage - Affiche un objet ImagickDraw dans l'image courante
    • Imagick::edgeImage - Renforce les bords dans l'image
    • Imagick::embossImage - Retourne une image en niveau de gris, avec un effet 3D
    • Imagick::encipherImage - Chiffre une image
    • Imagick::enhanceImage - Améliore la qualité d'une image bruitée
    • Imagick::equalizeImage - Égalise l'histogramme d'une image
    • Imagick::evaluateImage - Applique une expression à une image
    • Imagick::exportImagePixels - Exporte les pixels bruts de l'image
    • Imagick::extentImage - Définit la taille de l'image
    • Imagick::filter - Applies a custom convolution kernel to the image
    • Imagick::flattenImages - Fusionne une séquence d'images
    • Imagick::flipImage - Crée une image par miroir vertical
    • Imagick::floodFillPaintImage - Modifie la valeur de la couleur de chaque pixel correspondant à la cible
    • Imagick::flopImage - Crée une image par miroir horizontal
    • Imagick::forwardFourierTransformImage - Implements the discrete Fourier transform (DFT)
    • Imagick::frameImage - Ajoute un bord 3D
    • Imagick::functionImage - Applique une fonction sur l'image
    • Imagick::fxImage - Évalue une expression pour chaque pixel d'une image
    • Imagick::gammaImage - Applique une correction gamma à l'image
    • Imagick::gaussianBlurImage - Ajoute du flou à image
    • Imagick::getColorspace - Récupère l'espace de couleurs
    • Imagick::getCompression - Lit le type de compression
    • Imagick::getCompressionQuality - Lit la qualité de la compression
    • Imagick::getCopyright - Retourne le copyright de l'API ImageMagick API
    • Imagick::getFilename - Lit le nom du fichier associé à une séquence
    • Imagick::getFont - Récupère la police de caractères
    • Imagick::getFormat - Retourne le format de l'image Imagick
    • Imagick::getGravity - Récupère la gravité
    • Imagick::getHomeURL - Retourne l'URL de ImageMagick
    • Imagick::getImage - Retourne un nouvel objet Imagick
    • Imagick::getImageAlphaChannel - Vérifie si l'image a un canal alpha
    • Imagick::getImageArtifact - Récupère l'artefact de l'image
    • Imagick::getImageAttribute - Returns a named attribute
    • Imagick::getImageBackgroundColor - Retourne la couleur de fond
    • Imagick::getImageBlob - Retourne la séquence d'images comme un blob
    • Imagick::getImageBluePrimary - Retourne la chromacité de la couleur bleue
    • Imagick::getImageBorderColor - Retourne la couleur de bordure de l'image
    • Imagick::getImageChannelDepth - Lit la profondeur d'un des canaux de l'image
    • Imagick::getImageChannelDistortion - Compare les canaux d'une image reconstituée
    • Imagick::getImageChannelDistortions - Récupère les distorsions d'un canal
    • Imagick::getImageChannelExtrema - Lit les extrêmes pour les canaux de l'image
    • Imagick::getImageChannelKurtosis - Le but de getImageChannelKurtosis
    • Imagick::getImageChannelMean - Lit la moyenne et la déviation standard
    • Imagick::getImageChannelRange - Récupère l'intervalle du canal
    • Imagick::getImageChannelStatistics - Retourne des statistiques sur chaque canal de l'image
    • Imagick::getImageClipMask - Récupère le masque du clip de l'image
    • Imagick::getImageColormapColor - Retourne la couleur à l'index de la carte de couleurs
    • Imagick::getImageColors - Lit le nombre de couleurs uniques de l'image
    • Imagick::getImageColorspace - Lit l'espace de couleurs de l'image
    • Imagick::getImageCompose - Retourne l'opérateur de composition associé à une image
    • Imagick::getImageCompression - Lit le type de compression de l'image
    • Imagick::getImageCompressionQuality - Lit la qualité de compression de l'image
    • Imagick::getImageDelay - Lit le délai de l'image
    • Imagick::getImageDepth - Lit la profondeur de l'image
    • Imagick::getImageDispose - Lit la méthode de récupération
    • Imagick::getImageDistortion - Compare une image à une image reconstituée
    • Imagick::getImageExtrema - Lit les extrêmes d'une image
    • Imagick::getImageFilename - Retourne le nom d'un fichier pour une image dans une séquence
    • Imagick::getImageFormat - Retourne le format d'une image dans une séquence
    • Imagick::getImageGamma - Lit le gamma de l'image
    • Imagick::getImageGeometry - Lit les dimensions de l'image dans un tableau
    • Imagick::getImageGravity - Récupère la gravité de l'image
    • Imagick::getImageGreenPrimary - Retourne la chromacité de la couleur verte
    • Imagick::getImageHeight - Retourne la hauteur de l'image
    • Imagick::getImageHistogram - Retourne l'histogramme de l'image
    • Imagick::getImageIndex - Lit l'index de l'image courante
    • Imagick::getImageInterlaceScheme - Lit le schéma d'entrelacement de l'image
    • Imagick::getImageInterpolateMethod - Retourne la méthode d'interpolation
    • Imagick::getImageIterations - Lit les itérations de l'image
    • Imagick::getImageLength - Retourne la taille de l'image en octets
    • Imagick::getImageMatte - Indique si l'image a un canal mat
    • Imagick::getImageMatteColor - Retourne la couleur mate de l'image
    • Imagick::getImageMimeType - Returns the image mime-type
    • Imagick::getImageOrientation - Lit l'orientation de l'image
    • Imagick::getImagePage - Retourne la géométrie de la page
    • Imagick::getImagePixelColor - Retourne la couleur d'un pixel
    • Imagick::getImageProfile - Retourne un profil d'une image
    • Imagick::getImageProfiles - Retourne les profils de l'image
    • Imagick::getImageProperties - Retourne les propriétés EXIF de l'image
    • Imagick::getImageProperty - Retourne une propriété d'une image
    • Imagick::getImageRedPrimary - Retourne la chromacité du point rouge
    • Imagick::getImageRegion - Extrait une région d'une image
    • Imagick::getImageRenderingIntent - Lit la méthode de rendu de l'image
    • Imagick::getImageResolution - Lit les résolutions en X et Y d'une image
    • Imagick::getImagesBlob - Retourne toutes les images de la séquence en un BLOB
    • Imagick::getImageScene - Retourne la scène de l'image
    • Imagick::getImageSignature - Génère une signature SHA-256
    • Imagick::getImageSize - Retourne la taille de l'image en octets
    • Imagick::getImageTicksPerSecond - Lit les ticks-par-seconde de l'image
    • Imagick::getImageTotalInkDensity - Lit la densité totale d'encre de l'image
    • Imagick::getImageType - Lit le type possible d'image
    • Imagick::getImageUnits - Retourne les unités de résolution de l'image
    • Imagick::getImageVirtualPixelMethod - Retourne la méthode du pixel virtuel
    • Imagick::getImageWhitePoint - Retourne la chromacité du point blanc
    • Imagick::getImageWidth - Retourne la largeur de l'image
    • Imagick::getInterlaceScheme - Lit le schéma d'entrelacement de l'objet
    • Imagick::getIteratorIndex - Lit l'index de l'image active courante
    • Imagick::getNumberImages - Retourne le nombre d'images d'un objet
    • Imagick::getOption - Retourne la valeur d'une option
    • Imagick::getPackageName - Retourne le nom du paquet ImageMagick
    • Imagick::getPage - Retourne la géométrie de la page
    • Imagick::getPixelIterator - Retourne un MagickPixelIterator
    • Imagick::getPixelRegionIterator - Lit un objet ImagickPixelIterator pour une section d'image
    • Imagick::getPointSize - Récupère la taille du point
    • Imagick::getQuantum - Returns the ImageMagick quantum range
    • Imagick::getQuantumDepth - Lit la profondeur quantique
    • Imagick::getQuantumRange - Retourne l'intervalle quantique de Imagick
    • Imagick::getRegistry - Get a StringRegistry entry
    • Imagick::getReleaseDate - Retourne la date de publication de ImageMagick
    • Imagick::getResource - Retourne la consommation de mémoire de la ressource
    • Imagick::getResourceLimit - Retourne la limite de la ressource
    • Imagick::getSamplingFactors - Lit le facteur d'échantillonnage horizontal et vertical
    • Imagick::getSize - Retourne la taille associée avec un objet Imagick
    • Imagick::getSizeOffset - Retourne la taille de la position
    • Imagick::getVersion - Retourne l'API de ImageMagick API
    • Imagick::haldClutImage - Remplace les couleurs de l'image
    • Imagick::hasNextImage - Vérifie si un objet a une image suivante
    • Imagick::hasPreviousImage - Vérifie si un objet a une image précédente
    • Imagick::identifyFormat - Formats a string with image details
    • Imagick::identifyImage - Identifie une image et lit ses attributs
    • Imagick::implodeImage - Crée une nouvelle copie d'image
    • Imagick::importImagePixels - Importe des pixels dans une image
    • Imagick::inverseFourierTransformImage - Implements the inverse discrete Fourier transform (DFT)
    • Imagick::labelImage - Ajoute un libelle à une image
    • Imagick::levelImage - Ajuste les niveaux de l'image
    • Imagick::linearStretchImage - Étire la saturation de l'intensité de l'image
    • Imagick::liquidRescaleImage - Anime une ou plusieurs images
    • Imagick::listRegistry - List all the registry settings
    • Imagick::magnifyImage - Double la taille d'une image, proportionnellement
    • Imagick::mapImage - Remplace la couleur d'une image par celle d'une image de référence
    • Imagick::matteFloodfillImage - Change la transparence d'une couleur
    • Imagick::medianFilterImage - Applique un filtre numérique
    • Imagick::mergeImageLayers - Fusionne les calques de l'image
    • Imagick::minifyImage - Met à l'échelle une image proportionnellement pour la réduire de moitié de taille
    • Imagick::modulateImage - Contrôle la saturation, l'intensité et la teinte
    • Imagick::montageImage - Crée une image composite
    • Imagick::morphImages - Réalise un morphing entre deux images
    • Imagick::morphology - Applies a user supplied kernel to the image according to the given morphology method.
    • Imagick::mosaicImages - Forme une mosaïque d'images
    • Imagick::motionBlurImage - Ajout un flou de déplacement
    • Imagick::negateImage - Effectue la négation des couleurs d'une image de référence
    • Imagick::newImage - Crée une nouvelle image
    • Imagick::newPseudoImage - Crée une nouvelle image
    • Imagick::nextImage - Passe à la prochaine image
    • Imagick::normalizeImage - Améliore le contraste de l'image
    • Imagick::oilPaintImage - Simule une peinture à l'huile
    • Imagick::opaquePaintImage - Modifie la valeur de la couleur de tous les pixels correspondant à la cible
    • Imagick::optimizeImageLayers - Supprime les portions récurrents d'images à optimiser
    • Imagick::orderedPosterizeImage - Effectue un dither ordonné
    • Imagick::paintOpaqueImage - Change les pixels qui sont d'une couleur
    • Imagick::paintTransparentImage - Remplit les pixels avec une couleur
    • Imagick::pingImage - Lit des attributs simples sans ouvrir une image
    • Imagick::pingImageBlob - Lit rapidement les attributs
    • Imagick::pingImageFile - Lit les attributs simples d'une image
    • Imagick::polaroidImage - Simule une photo Polaroid
    • Imagick::posterizeImage - Réduit une image à un nombre limité de couleurs
    • Imagick::previewImages - Teste rapidement différents paramètres pour un traitement d'images
    • Imagick::previousImage - Passe à l'image précédente dans une séquence d'images
    • Imagick::profileImage - Ajoute ou retire un profil d'une image
    • Imagick::quantizeImage - Analyse les couleurs dans une référence d'image
    • Imagick::quantizeImages - Analyse les couleurs d'une séquence d'images
    • Imagick::queryFontMetrics - Retourne un tableau représentant les dimensions de la police
    • Imagick::queryFonts - Retourne la liste de polices configurés
    • Imagick::queryFormats - Retourne les formats supportés par Imagick
    • Imagick::radialBlurImage - Flou radial d'une image
    • Imagick::raiseImage - Crée un effet 3D de bouton
    • Imagick::randomThresholdImage - Crée une image en deux couleurs, à haut contraste
    • Imagick::readImage - Lit une image depuis un fichier
    • Imagick::readImageBlob - Lit une image depuis une chaîne binaire
    • Imagick::readImageFile - Lit une image à partir d'une ressource fichier
    • Imagick::readimages - Reads image from an array of filenames
    • Imagick::recolorImage - Recolore l'image
    • Imagick::reduceNoiseImage - Adoucit les contours d'une image
    • Imagick::remapImage - Reconfigure les couleurs de l'image
    • Imagick::removeImage - Retire une image de la liste
    • Imagick::removeImageProfile - Supprime le profil de l'image et le retourne
    • Imagick::render - Affiche toute les commandes de dessins précédentes
    • Imagick::resampleImage - Rééchantillonne l'image
    • Imagick::resetImagePage - Réinitialise la page de l'image
    • Imagick::resizeImage - Redimensionne une image
    • Imagick::rollImage - Décale une image
    • Imagick::rotateImage - Tourne une image
    • Imagick::rotationalBlurImage - Rotational blurs an image
    • Imagick::roundCorners - Arrondit les coins d'un image
    • Imagick::sampleImage - Met à l'échelle une image avec échantillonnage de pixels
    • Imagick::scaleImage - Met à l'échelle la taille de l'image
    • Imagick::segmentImage - Segmente une image
    • Imagick::selectiveBlurImage - Selectively blur an image within a contrast threshold
    • Imagick::separateImageChannel - Sépare un canal d'une image
    • Imagick::sepiaToneImage - Passe une image en tons sépia
    • Imagick::setBackgroundColor - Configure la couleur de fond par défaut
    • Imagick::setColorspace - Définit l'espace de couleurs
    • Imagick::setCompression - Configure le type de compression de l'objet
    • Imagick::setCompressionQuality - Configure la compression par défaut de l'objet
    • Imagick::setFilename - Configure le nom du fichier d'image avant d'y accéder
    • Imagick::setFirstIterator - Place l'itérateur de Imagick sur la première image
    • Imagick::setFont - Configure la police
    • Imagick::setFormat - Configure le format de l'objet Imagick
    • Imagick::setGravity - Définit la gravité
    • Imagick::setImage - Remplace l'image dans l'objet
    • Imagick::setImageAlphaChannel - Définit le canal alpha de l'image
    • Imagick::setImageArtifact - Définit l'artefact de l'image
    • Imagick::setImageAttribute - Sets an image attribute
    • Imagick::setImageBackgroundColor - Configure la couleur de fond d'image
    • Imagick::setImageBias - Configure le biais pour les convolutions
    • Imagick::setImageBiasQuantum - Sets the image bias
    • Imagick::setImageBluePrimary - Configure la chromacité du point bleu
    • Imagick::setImageBorderColor - Configure la couleur de bordure
    • Imagick::setImageChannelDepth - Configure la profondeur d'un canal
    • Imagick::setImageClipMask - Définit le masque du clip de l'image
    • Imagick::setImageColormapColor - Configure une couleur de la carte
    • Imagick::setImageColorspace - Configure l'espace de couleurs de l'image
    • Imagick::setImageCompose - Configure l'opérateur de composition de l'image
    • Imagick::setImageCompression - Configure la compression de l'image
    • Imagick::setImageCompressionQuality - Spécifie la qualité de compression de l'image
    • Imagick::setImageDelay - Configure le délai de l'image
    • Imagick::setImageDepth - Configure la profondeur de l'image
    • Imagick::setImageDispose - Configure la méthode de récupération
    • Imagick::setImageExtent - Configure la taille d'une image
    • Imagick::setImageFilename - Configure le nom de fichier d'une image dans une séquence
    • Imagick::setImageFormat - Configure le format d'une image dans une séquence
    • Imagick::setImageGamma - Configure la correction gamma
    • Imagick::setImageGravity - Définit la gravité de l'image
    • Imagick::setImageGreenPrimary - Configure la chromacité du point vert
    • Imagick::setImageIndex - Modifie la position de l'itérateur
    • Imagick::setImageInterlaceScheme - Configure la méthode d'entrelacement de l'image
    • Imagick::setImageInterpolateMethod - Configure la méthode d'interpolation de l'image
    • Imagick::setImageIterations - Configure les itérations de l'image
    • Imagick::setImageMatte - Configure le canal mate de l'image
    • Imagick::setImageMatteColor - Configure la couleur mate
    • Imagick::setImageOpacity - Configure le niveau d'opacité de l'image
    • Imagick::setImageOrientation - Configure l'orientation de l'image
    • Imagick::setImagePage - Configure la géométrie de la page de l'image
    • Imagick::setImageProfile - Ajoute un profil à un objet Imagick
    • Imagick::setImageProperty - Configure une propriété d'image
    • Imagick::setImageRedPrimary - Configure la chromacité du point rouge
    • Imagick::setImageRenderingIntent - Configure le type de rendu de l'image
    • Imagick::setImageResolution - Configure la résolution de l'image
    • Imagick::setImageScene - Configure la scène de l'image
    • Imagick::setImageTicksPerSecond - Configure le nombre e tick par seconde de l'image
    • Imagick::setImageType - Configure le type d'image
    • Imagick::setImageUnits - Configure les unités de résolutions de l'image
    • Imagick::setImageVirtualPixelMethod - Configure la méthode du point virtuel de l'image
    • Imagick::setImageWhitePoint - Configure la chromacité du point blanc
    • Imagick::setInterlaceScheme - Configure la compression de l'image
    • Imagick::setIteratorIndex - Déplace l'itérateur
    • Imagick::setLastIterator - Positionne l'itérateur Imagick à la dernière image
    • Imagick::setOption - Configure une option d'un objet Imagick
    • Imagick::setPage - Configure la géométrie de la page de l'objet Imagick
    • Imagick::setPointSize - Définit la taille du point
    • Imagick::setProgressMonitor - Set a callback to be called during processing
    • Imagick::setRegistry - Sets the ImageMagick registry entry named key to value
    • Imagick::setResolution - Configure la résolution de l'image
    • Imagick::setResourceLimit - Définit la limite pour une ressource particulière
    • Imagick::setSamplingFactors - Configure les facteurs d'échantillonnage de l'image
    • Imagick::setSize - Configure la taille de l'objet Imagick
    • Imagick::setSizeOffset - Configure la taille et la position de l'objet Imagick
    • Imagick::setType - Configure l'attribut de l'image
    • Imagick::shadeImage - Crée un effet 3D
    • Imagick::shadowImage - Simule une ombre sur l'image
    • Imagick::sharpenImage - Aiguise une image
    • Imagick::shaveImage - Supprime les pixels du bord de l'image
    • Imagick::shearImage - Crée un parallélogramme
    • Imagick::sigmoidalContrastImage - Ajuste le contraste de l'image
    • Imagick::sketchImage - Simule un crayon à main levée
    • Imagick::smushImages - Takes all images from the current image pointer to the end of the image list and smushs them
    • Imagick::solarizeImage - Applique un effet de solarisation à l'image
    • Imagick::sparseColorImage - Interpole les couleurs
    • Imagick::spliceImage - Joint une couleur solide dans l'image
    • Imagick::spreadImage - Bouge aléatoirement chaque pixel d'un bloc
    • Imagick::statisticImage - Modifies image using a statistics function
    • Imagick::steganoImage - Cache un filigrane digital dans l'image
    • Imagick::stereoImage - Fusionne 2 images
    • Imagick::stripImage - Supprime d'une image tous les profiles et les commentaires
    • Imagick::subImageMatch - Searches for a subimage in the current image and returns a similarity image
    • Imagick::swirlImage - Tourbillonne les pixels du centre de l'image
    • Imagick::textureImage - Répète les carreaux de la texture d'une image
    • Imagick::thresholdImage - Modifie la valeur des pixels individuels, basée sur un seuil
    • Imagick::thumbnailImage - Modifie la taille d'une image
    • Imagick::tintImage - Applique un vecteur de couleur à chaque pixel de l'image
    • Imagick::transformImage - Méthode de convenance pour définir la taille de rognage et la géométrie de l'image
    • Imagick::transformImageColorspace - Transforms an image to a new colorspace
    • Imagick::transparentPaintImage - Colorise les pixels transparents
    • Imagick::transposeImage - Applique une symétrie verticale
    • Imagick::transverseImage - Crée un miroir horizontal de l'image
    • Imagick::trimImage - Supprime les bords de l'image
    • Imagick::uniqueImageColors - Ne conserve qu'une couleur de pixel
    • Imagick::unsharpMaskImage - Rend une image plus nette
    • Imagick::valid - Vérifie si l'élément courant est valide
    • Imagick::vignetteImage - Ajout un filtre vignette à l'image
    • Imagick::waveImage - Ajoute un filtre de vagues à l'image
    • Imagick::whiteThresholdImage - Force tous les pixels en dessous du seuil en blanc
    • Imagick::writeImage - Écrit une image dans le fichier spécifié
    • Imagick::writeImageFile - Écrit une image dans un descripteur de fichier
    • Imagick::writeImages - Écrit une image ou une séquence d'images
    • Imagick::writeImagesFile - Écrits des frames dans un descripteur de fichiers
    • Imagick::__construct - Le constructeur Imagick
    • Imagick::__toString - Returns the image as a string
    • ImagickDraw::affine - Ajuste la matrice de transformation affine courante
    • ImagickDraw::annotation - Dessine un texte sur une image
    • ImagickDraw::arc - Dessine un arc
    • ImagickDraw::bezier - Dessine une courbe de Bézier
    • ImagickDraw::circle - Dessine un cercle
    • ImagickDraw::clear - Efface tout l'objet ImagickDraw
    • ImagickDraw::clone - Fait une copie exacte de l'objet ImagickDraw
    • ImagickDraw::color - Dessine une couleur sur une image
    • ImagickDraw::comment - Ajoute un commentaire
    • ImagickDraw::composite - Compose une image avec une autre
    • ImagickDraw::destroy - Libère toutes les ressources associées à un objet ImageDraw
    • ImagickDraw::ellipse - Dessine une ellipse sur une image
    • ImagickDraw::getClipPath - Retourne l'identifiant du chemin courant
    • ImagickDraw::getClipRule - Retourne la règle de remplissage courante pour les polygones
    • ImagickDraw::getClipUnits - Retourne l'unité d'interprétation des chemins
    • ImagickDraw::getFillColor - Retourne la couleur de remplissage
    • ImagickDraw::getFillOpacity - Retourne l'opacité de dessin
    • ImagickDraw::getFillRule - Retourne la règle de remplissage
    • ImagickDraw::getFont - Retourne la police
    • ImagickDraw::getFontFamily - Retourne la famille de police
    • ImagickDraw::getFontSize - Retourne la taille de la police
    • ImagickDraw::getFontStretch - Gets the font stretch to use when annotating with text
    • ImagickDraw::getFontStyle - Retourne le style de la police
    • ImagickDraw::getFontWeight - Retourne le poids de la police
    • ImagickDraw::getGravity - Retourne la gravité de placement de texte
    • ImagickDraw::getStrokeAntialias - Retourne la configuration d'anti-aliasing de trait
    • ImagickDraw::getStrokeColor - Retourne la couleur des contours d'objets
    • ImagickDraw::getStrokeDashArray - Retourne un tableau représentant le motif de pointillés
    • ImagickDraw::getStrokeDashOffset - Retourne l'offset du pointillé dans le motif
    • ImagickDraw::getStrokeLineCap - Retourne la forme à utiliser pour dessiner les bouts de sous-chemins
    • ImagickDraw::getStrokeLineJoin - Retourne la forme à utiliser pour dessiner les coins d'un chemin
    • ImagickDraw::getStrokeMiterLimit - Retourne la 'miterLimit'
    • ImagickDraw::getStrokeOpacity - Retourne l'opacité des contours d'un objet
    • ImagickDraw::getStrokeWidth - Retourne la largeur du trait utilisé
    • ImagickDraw::getTextAlignment - Retourne l'alignement du texte
    • ImagickDraw::getTextAntialias - Retourne la configuration de l'anti-aliasing de texte
    • ImagickDraw::getTextDecoration - Retourne la décoration du texte
    • ImagickDraw::getTextEncoding - Retourne le jeu de caractères utilisé pour les annotations de texte
    • ImagickDraw::getTextInterlineSpacing - Récupère l'espace entre les mots d'un texte.
    • ImagickDraw::getTextInterwordSpacing - Récupère l'espace entre les mots d'un texte.
    • ImagickDraw::getTextKerning - Récupère le crénage d'un texte.
    • ImagickDraw::getTextUnderColor - Retourne la couleur sous le texte
    • ImagickDraw::getVectorGraphics - Retourne une chaîne contenant le vecteur graphique
    • ImagickDraw::line - Dessine une ligne
    • ImagickDraw::matte - Dessine sur le canal d'opacité de l'image
    • ImagickDraw::pathClose - Ajoute un élément de chemin au chemin courant
    • ImagickDraw::pathCurveToAbsolute - Dessine une courbe de Bézier cubique, en coordonnées absolues
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute - Dessine une courbe de Bézier quadratique, en coordonnées absolues
    • ImagickDraw::pathCurveToQuadraticBezierRelative - Dessine une courbe de Bézier quadratique, en coordonnées relatives
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute - Dessine une courbe de Bézier de puissance 4, en coordonnées absolues
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative - Dessine une courbe de Bézier de puissance 4, en coordonnées relatives
    • ImagickDraw::pathCurveToRelative - Dessine une courbe de Bézier cubique, en coordonnées relatives
    • ImagickDraw::pathCurveToSmoothAbsolute - Dessine une courbe de Bézier, en coordonnées absolues
    • ImagickDraw::pathCurveToSmoothRelative - Dessine une courbe de Bézier, en coordonnées relatives
    • ImagickDraw::pathEllipticArcAbsolute - Dessine un arc d'ellipse, en coordonnées absolues
    • ImagickDraw::pathEllipticArcRelative - Dessine un arc d'ellipse, en coordonnées relatives
    • ImagickDraw::pathFinish - Termine le chemin courant
    • ImagickDraw::pathLineToAbsolute - Dessine une ligne de chemin, en coordonnées absolues
    • ImagickDraw::pathLineToHorizontalAbsolute - Dessine une ligne de chemin horizontale, en coordonnées absolues
    • ImagickDraw::pathLineToHorizontalRelative - Dessine une ligne de chemin horizontale, en coordonnées relatives
    • ImagickDraw::pathLineToRelative - Dessine une ligne de chemin, en coordonnées relatives
    • ImagickDraw::pathLineToVerticalAbsolute - Dessine une ligne de chemin verticale, en coordonnées absolues
    • ImagickDraw::pathLineToVerticalRelative - Dessine une ligne de chemin verticale, en coordonnées relatives
    • ImagickDraw::pathMoveToAbsolute - Commence un nouveau sous-chemin, en coordonnées absolues
    • ImagickDraw::pathMoveToRelative - Commence un nouveau sous-chemin, en coordonnées relatives
    • ImagickDraw::pathStart - Déclare le début d'une chemin de dessin
    • ImagickDraw::point - Dessine un point
    • ImagickDraw::polygon - Dessine un polygone
    • ImagickDraw::polyline - Dessine une ligne brisée
    • ImagickDraw::pop - Détruit l'objet ImagickDraw courant dans la pile, et retourne son précédent
    • ImagickDraw::popClipPath - Termine la définition d'un chemin
    • ImagickDraw::popDefs - Termine une définition de liste
    • ImagickDraw::popPattern - Termine une définition de motif
    • ImagickDraw::push - Clone l'objet ImagickDraw courant et le pousse dans la pile
    • ImagickDraw::pushClipPath - Commence la définition d'un chemin
    • ImagickDraw::pushDefs - Indique que la commande suivante créée des éléments nommés pour pré-traitement
    • ImagickDraw::pushPattern - Configure un espace de dessin
    • ImagickDraw::rectangle - Dessine un rectangle
    • ImagickDraw::render - Effectue le rendu de tous les dessins à l'image
    • ImagickDraw::resetVectorGraphics - Resets the vector graphics
    • ImagickDraw::rotate - Applique une rotation
    • ImagickDraw::roundRectangle - Dessine un rectangle aux coins arrondis
    • ImagickDraw::scale - Ajuste le facteur de mise à l'échelle
    • ImagickDraw::setClipPath - Associe un chemin avec une image
    • ImagickDraw::setClipRule - Configure la règle de remplissage du polygone à utiliser avec les chemins
    • ImagickDraw::setClipUnits - Configure le mode d'interprétation des unités de chemin
    • ImagickDraw::setFillAlpha - Configure l'opacité de la couleur de remplissage
    • ImagickDraw::setFillColor - Configure la couleur de dessin des objets remplis
    • ImagickDraw::setFillOpacity - Configure l'opacité à utiliser pour le remplissage
    • ImagickDraw::setFillPatternURL - Configure l'URL du motif de remplissage des surfaces
    • ImagickDraw::setFillRule - Configure la règle de remplissage des polygones
    • ImagickDraw::setFont - Configure la police complète pour les textes
    • ImagickDraw::setFontFamily - Configure la famille de police pour les textes
    • ImagickDraw::setFontSize - Configure la taille de point pour les textes
    • ImagickDraw::setFontStretch - Configure l'étirement du texte
    • ImagickDraw::setFontStyle - Configure le style de police
    • ImagickDraw::setFontWeight - Configure le poids de la police
    • ImagickDraw::setGravity - Configure la gravité de placement de texte
    • ImagickDraw::setResolution - Définie la résolution
    • ImagickDraw::setStrokeAlpha - Spécifie l'opacité des contours d'objets
    • ImagickDraw::setStrokeAntialias - Contrôle l'anti-aliasing des pointillés
    • ImagickDraw::setStrokeColor - Configure la couleur utilisée pour dessiner les objets
    • ImagickDraw::setStrokeDashArray - Spécifie le motif de pointillé
    • ImagickDraw::setStrokeDashOffset - Spécifie la position dans le motif pour commencer le pointillé
    • ImagickDraw::setStrokeLineCap - Spécifie la forme à utiliser à la fin des sous-chemins
    • ImagickDraw::setStrokeLineJoin - Spécifie la forme à utiliser pour dessiner les fins de lignes
    • ImagickDraw::setStrokeMiterLimit - Spécifie la limiter miter
    • ImagickDraw::setStrokeOpacity - Spécifie l'opacité pour dessiner les contours
    • ImagickDraw::setStrokePatternURL - Configure le motif utilisé pour dessiner les contours
    • ImagickDraw::setStrokeWidth - Configure la largeur du trait pour dessiner les contours
    • ImagickDraw::setTextAlignment - Spécifie l'alignement du texte
    • ImagickDraw::setTextAntialias - Contrôle l'anti-alisasing du texte
    • ImagickDraw::setTextDecoration - Spécifie les ornements de texte
    • ImagickDraw::setTextEncoding - Spécifie le jeu de caractères
    • ImagickDraw::setTextInterlineSpacing - Défine l'espace entre les lignes d'un texte
    • ImagickDraw::setTextInterwordSpacing - Définie l'espace entre les mots d'un texte
    • ImagickDraw::setTextKerning - Définie le crénage d'un texte
    • ImagickDraw::setTextUnderColor - Spécifie la couleur de fond d'une rectangle
    • ImagickDraw::setVectorGraphics - Configure le vecteur graphique
    • ImagickDraw::setViewbox - Configure la taille du canevas
    • ImagickDraw::skewX - Biaise les coordonnées dans la direction horizontale
    • ImagickDraw::skewY - Incline les coordonnées dans la direction verticale
    • ImagickDraw::translate - Applique une translation
    • ImagickDraw::__construct - Le constructeur ImagickDraw
    • ImagickKernel::addKernel - Attach another kernel to a kernel list
    • ImagickKernel::addUnityKernel - Adds a Unity Kernel to the kernel list
    • ImagickKernel::fromBuiltIn - Create a kernel from a builtin in kernel
    • ImagickKernel::fromMatrix - Create a kernel from a 2d matrix of values
    • ImagickKernel::getMatrix - Get the 2d matrix of values used in this kernel
    • ImagickKernel::scale - Scales a kernel list by the given amount
    • ImagickKernel::separate - Separates a linked set of kernels and returns an array of ImagickKernels
    • ImagickPixel::clear - Supprime toutes les ressources associées avec l'objet
    • ImagickPixel::destroy - Libère les ressources associées avec l'objet
    • ImagickPixel::getColor - Retourne la couleur
    • ImagickPixel::getColorAsString - Retourne une couleur
    • ImagickPixel::getColorCount - Retourne le nombre de couleurs associé avec une couleur
    • ImagickPixel::getColorQuantum - Returns the color of the pixel in an array as Quantum values
    • ImagickPixel::getColorValue - Récupère la valeur normalisée du canal de la couleur fournie
    • ImagickPixel::getColorValueQuantum - Gets the quantum value of a color in the ImagickPixel
    • ImagickPixel::getHSL - Retourne la couleur HSL normalisée de l'objet ImagickPixel
    • ImagickPixel::getIndex - Gets the colormap index of the pixel wand
    • ImagickPixel::isPixelSimilar - Vérifie la distance entre cette couleur et une autre
    • ImagickPixel::isPixelSimilarQuantum - Returns whether two colors differ by less than the specified distance
    • ImagickPixel::isSimilar - Vérifie la distance entre 2 couleurs
    • ImagickPixel::setColor - Définit la couleur
    • ImagickPixel::setColorCount - Sets the color count associated with this color
    • ImagickPixel::setColorValue - Définit la valeur normalisée d'un des canaux
    • ImagickPixel::setColorValueQuantum - Sets the quantum value of a color element of the ImagickPixel
    • ImagickPixel::setHSL - Définit la couleur HSL normalisée
    • ImagickPixel::setIndex - Sets the colormap index of the pixel wand
    • ImagickPixel::__construct - Le constructeur ImagickPixel
    • ImagickPixelIterator::clear - Efface toutes les ressources associées à PixelIterator
    • ImagickPixelIterator::destroy - Libère les ressources associées à PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow - Retourne la ligne courante des objets ImagickPixel
    • ImagickPixelIterator::getIteratorRow - Retourne la ligne courante de l'itérateur de pixel
    • ImagickPixelIterator::getNextIteratorRow - Retourne la prochaine ligne de l'itérateur de pixel
    • ImagickPixelIterator::getPreviousIteratorRow - Retourne la ligne précédente
    • ImagickPixelIterator::newPixelIterator - Retourne un nouveau pixel de l'itérateur
    • ImagickPixelIterator::newPixelRegionIterator - Retourne un nouveau pixel de l'itérateur
    • ImagickPixelIterator::resetIterator - Réinitialise l'itérateur de pixel
    • ImagickPixelIterator::setIteratorFirstRow - Définit l'itérateur de pixel sur la première ligne de pixels
    • ImagickPixelIterator::setIteratorLastRow - Définit l'itérateur de pixel sur la dernière ligne de pixels
    • ImagickPixelIterator::setIteratorRow - Définit la ligne de l'itérateur de pixel
    • ImagickPixelIterator::syncIterator - Synchronise l'itérateur de pixel
    • ImagickPixelIterator::__construct - Le constructeur ImagickPixelIterator
    • imap_8bit - Convertit une chaîne à 8 bits en une chaîne encodée en Quoted-Printable
    • imap_alerts - Retourne toutes les alertes
    • imap_append - Ajoute un message dans une boîte aux lettres
    • imap_base64 - Décode un texte encodé en BASE64
    • imap_binary - Convertit une chaîne à 8 bits en une chaîne à base64
    • imap_body - Lit le corps d'un message
    • imap_bodystruct - Lit la structure d'une section du corps d'un mail
    • imap_check - Vérifie la boîte aux lettres courante
    • imap_clearflag_full - Supprime un flag (drapeau) sur un message
    • imap_close - Termine un flux IMAP
    • imap_create - Alias de imap_createmailbox
    • imap_createmailbox - Crée une nouvelle boîte aux lettres
    • imap_delete - Marque le fichier pour l'effacement, dans la boîte aux lettres courante
    • imap_deletemailbox - Efface une boîte aux lettres
    • imap_errors - Retourne toutes les erreurs IMAP survenues
    • imap_expunge - Efface tous les messages marqués pour l'effacement
    • imap_fetchbody - Retourne une section extraite du corps d'un message
    • imap_fetchheader - Retourne l'en-tête d'un message
    • imap_fetchmime - Récupère les en-têtes MIME pour une section particulière du message
    • imap_fetchstructure - Lit la structure d'un message
    • imap_fetchtext - Alias de imap_body
    • imap_fetch_overview - Lit le sommaire des en-têtes de messages
    • imap_gc - Efface le cache IMAP
    • imap_getacl - Retourne le ACL pour la boîte aux lettres
    • imap_getmailboxes - Liste les boîtes aux lettres, et retourne les détails de chacune
    • imap_getsubscribed - Liste toutes les boîtes aux lettres souscrites
    • imap_get_quota - Lit les quotas des boîtes aux lettres ainsi que des statistiques sur chacune d'elles
    • imap_get_quotaroot - Lit les quotas de chaque utilisateur
    • imap_header - Alias de imap_headerinfo
    • imap_headerinfo - Lit l'en-tête du message
    • imap_headers - Retourne les en-têtes de tous les messages d'une boîte aux lettres
    • imap_is_open - Vérifier si le flux IMAP est toujours valide
    • imap_last_error - Retourne la dernière erreur survenue
    • imap_list - Lit la liste des boîtes aux lettres
    • imap_listmailbox - Alias de imap_list
    • imap_listscan - Lit la liste des boîtes aux lettres, et y recherche une chaîne
    • imap_listsubscribed - Alias de imap_lsub
    • imap_lsub - Liste toutes les boîtes aux lettres enregistrées
    • imap_mail - Envoie un message mail
    • imap_mailboxmsginfo - Lit les informations à propos de la boîte aux lettres courante
    • imap_mail_compose - Crée un message MIME
    • imap_mail_copy - Copie les messages spécifiés dans une boîte aux lettres
    • imap_mail_move - Déplace des messages dans une boîte aux lettres
    • imap_mime_header_decode - Décode les éléments MIME d'un en-tête
    • imap_msgno - Retourne le numéro de séquence du message pour un UID donné
    • imap_mutf7_to_utf8 - Décode une chaîne de caractère UTF-7 modifié en UTF-8
    • imap_num_msg - Retourne le nombre de messages dans la boîte aux lettres courante
    • imap_num_recent - Retourne le nombre de messages récents dans la boîte aux lettres courante
    • imap_open - Ouvre un flux IMAP vers une boîte aux lettres
    • imap_ping - Vérifie que le flux IMAP est toujours actif
    • imap_qprint - Convertit une chaîne à guillemets en une chaîne à 8 bits
    • imap_rename - Alias de imap_renamemailbox
    • imap_renamemailbox - Renomme une boîte aux lettres
    • imap_reopen - Réouvre un flux IMAP vers une nouvelle boîte aux lettres
    • imap_rfc822_parse_adrlist - Analyse une adresse email
    • imap_rfc822_parse_headers - Analyse un en-tête mail
    • imap_rfc822_write_address - Retourne une adresse email formatée correctement
    • imap_savebody - Sauvegarde une partie spécifique du corps dans un fichier
    • imap_scan - Alias de imap_listscan
    • imap_scanmailbox - Alias de imap_listscan
    • imap_search - Retourne un tableau de messages après recherche
    • imap_setacl - Modifie le ACL de la boîte aux lettres
    • imap_setflag_full - Positionne un drapeau sur un message
    • imap_set_quota - Modifie le quota d'une boîte aux lettres
    • imap_sort - Trie des messages
    • imap_status - Retourne les informations de statut sur une boîte aux lettres
    • imap_subscribe - Souscrit à une boîte aux lettres
    • imap_thread - Retourne l'arbre des messages organisés par thread
    • imap_timeout - Configure ou retourne le timeout
    • imap_uid - Retourne l'UID d'un message
    • imap_undelete - Enlève la marque d'effacement d'un message
    • imap_unsubscribe - Termine la souscription à une boîte aux lettres
    • imap_utf7_decode - Décode une chaîne encodée en UTF-7 modifié
    • imap_utf7_encode - Convertit une chaîne ISO-8859-1 en texte UTF-7 modifié
    • imap_utf8 - Convertit du texte au format MIME en UTF-8
    • imap_utf8_to_mutf7 - Encode une chaîne de caractère UTF-8 en UTF-7 modifié
    • implode - Rassemble les éléments d'un tableau en une chaîne
    • inet_ntop - Convertit un paquet d'adresses internet en une représentation humainement lisible
    • inet_pton - Convertit une adresse IP lisible en sa représentation in_addr
    • InfiniteIterator::next - Avance l'itérateur ou le replace au début
    • InfiniteIterator::__construct - Construit un 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
    • ini_alter - Alias de ini_set
    • ini_get - Lit la valeur d'une option de configuration
    • ini_get_all - Lit toutes les valeurs de configuration
    • ini_parse_quantity - Get interpreted size from ini shorthand syntax
    • ini_restore - Restaure la valeur de l'option de configuration
    • ini_set - Modifie la valeur d'une option de configuration
    • inotify_add_watch - Ajoute un point de surveillance à une instance inotify
    • inotify_init - Initialise une instance inotify
    • inotify_queue_len - Retourne le nombre d'événements qui sont survenus
    • inotify_read - Lit les événements dans une instance inotify
    • inotify_rm_watch - Supprime un point de surveillance d'une instance inotify
    • intdiv - Division d'Entier
    • interface_exists - Vérifie si une interface a été définie
    • InternalIterator::current - Retourne l'élément courant
    • InternalIterator::key - Retourne la clé de l'élément courant
    • InternalIterator::next - Passe à l'élément suivant
    • InternalIterator::rewind - Replace l'itérateur sur le premier élément
    • InternalIterator::valid - Vérifie si la position actuelle est valide
    • InternalIterator::__construct - Constructeur privé pour empêcher l'instanciation directe
    • IntlBreakIterator::createCharacterInstance - Crée un itérateur pour les limites des séquences de caractères combinés
    • IntlBreakIterator::createCodePointInstance - Crée un itérateur pour les limites de points de code
    • IntlBreakIterator::createLineInstance - Crée un itérateur pour les coupures de lignes
    • IntlBreakIterator::createSentenceInstance - Crée un itérateur pour les coupures de phrase
    • IntlBreakIterator::createTitleInstance - Crée un itérateur
    • IntlBreakIterator::createWordInstance - Crée un itérateur pour les coupures de mot
    • IntlBreakIterator::current - Récupère l'index de la position courante
    • IntlBreakIterator::first - Définit la position au premier caractère du texte
    • IntlBreakIterator::following - Avance l'itérateur à la première limite suivant la position spécifiée
    • IntlBreakIterator::getErrorCode - Récupère le code de la dernière erreur survenue sur l'objet
    • IntlBreakIterator::getErrorMessage - Récupère le message de la dernière erreur survenue sur l'objet
    • IntlBreakIterator::getLocale - Récupère la locale associée avec l'objet
    • IntlBreakIterator::getPartsIterator - Crée un itérateur pour naviguer dans les fragments entre les limites
    • IntlBreakIterator::getText - Récupère le texte analysé
    • IntlBreakIterator::isBoundary - Indique si une position est une position limite
    • IntlBreakIterator::last - Définit la position de l'itérateur à l'index après le dernier caractère
    • IntlBreakIterator::next - Avance l'itérateur à la prochaine limite
    • IntlBreakIterator::preceding - Définit la position de l'itérateur à la première limite avant la position
    • IntlBreakIterator::previous - Définit la position de l'itérateur à la limite immédiate avant la courante
    • IntlBreakIterator::setText - Définit le texte à analyser
    • IntlBreakIterator::__construct - Constructeur privé pour désactiver l'instantiation
    • IntlCalendar::add - Ajoute une durée (signée) à un champ
    • IntlCalendar::after - Vérifie si l'objet temps courant est dans le futur par rapport à l'objet temps passé
    • IntlCalendar::before - Vérifie si l'objet temps est dans le passé par rapport à l'objet fourni
    • IntlCalendar::clear - Vide un ou tous les champs
    • IntlCalendar::createInstance - Crée un nouvel objet IntlCalendar
    • IntlCalendar::equals - Vérifie si deux objets IntlCalendar sont égaux
    • IntlCalendar::fieldDifference - Calcule la différence entre le temps donné et le temps de l'objet
    • IntlCalendar::fromDateTime - Create an IntlCalendar from a DateTime object or string
    • IntlCalendar::get - Récupère la valeur d'une propriété
    • 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 - Récupère le nombre représentant la date courante
    • 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 - Récupère le fuseau horaire de l'objet
    • IntlCalendar::getType - Récupère le type de calendrier
    • 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::setDate - Set a date fields
    • IntlCalendar::setDateTime - Set a date and time fields
    • IntlCalendar::setFirstDayOfWeek - Défini le jour de début de la semaine
    • 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 - Défini le temps du calendrier en milliseconde depuis l'époque
    • IntlCalendar::setTimeZone - Défini le fuseau horaire utilisé par ce calendrier
    • IntlCalendar::toDateTime - Converti un objet IntlCalendar en un objet DateTime
    • IntlCalendar::__construct - Constructeur privé pour la désactivation de l'instanciation
    • 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 - Récupère le dernier point de code après avoir avancé ou reculé dans l'itérateur
    • IntlDateFormatter::create - Crée un formateur de date
    • IntlDateFormatter::format - Formate la date et l'heure sous forme de chaîne
    • IntlDateFormatter::formatObject - Formate un objet
    • IntlDateFormatter::getCalendar - Lit le calendrier utilisé par l'objet IntlDateFormatter
    • IntlDateFormatter::getCalendarObject - Récupère une copie de l'objet formateur du calendrier
    • IntlDateFormatter::getDateType - Lit le type de date utilisé par IntlDateFormatter
    • IntlDateFormatter::getErrorCode - Lit le code d'erreur de la dernière opération
    • IntlDateFormatter::getErrorMessage - Lit le dernier message d'erreur
    • IntlDateFormatter::getLocale - Lit la locale utilisée par le formateur
    • IntlDateFormatter::getPattern - Lit le modèle utilisé par IntlDateFormatter
    • IntlDateFormatter::getTimeType - Lit le type de temps pour IntlDateFormatter
    • IntlDateFormatter::getTimeZone - Récupère le formateur du décalage horaire
    • IntlDateFormatter::getTimeZoneId - Lit le fuseau horaire de IntlDateFormatter
    • IntlDateFormatter::isLenient - Retourne la sévérité utilisée pour IntlDateFormatter
    • IntlDateFormatter::localtime - Analyse une chaîne et la convertie en temps
    • IntlDateFormatter::parse - Analyse une chaîne vers un timestamp
    • IntlDateFormatter::setCalendar - Définit le type de calendrier utilisé par le formateur
    • IntlDateFormatter::setLenient - Configure la souplesse de l'analyseur
    • IntlDateFormatter::setPattern - Configure le modèle utilisé par le IntlDateFormatter
    • IntlDateFormatter::setTimeZone - Définit le formateur pour le décalage horaire
    • IntlDatePatternGenerator::create - Creates a new IntlDatePatternGenerator instance
    • IntlDatePatternGenerator::getBestPattern - Determines the most suitable date/time format
    • IntlGregorianCalendar::createFromDate - Create a new IntlGregorianCalendar instance from date
    • IntlGregorianCalendar::createFromDateTime - Create a new IntlGregorianCalendar instance from date and time
    • 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 - Récupère l'élément courant
    • IntlIterator::key - Récupère la clé courante
    • IntlIterator::next - Se déplace sur l'élément suivant
    • IntlIterator::rewind - Re-positionne l'itérateur au premier élément
    • IntlIterator::valid - Vérifie si la position courant est valide
    • IntlPartsIterator::getBreakIterator - Récupère IntlBreakIterator, sauvegardant ainsi cette partie de l'itérateur
    • IntlRuleBasedBreakIterator::getBinaryRules - Récupère la forme binaire des règles compilées
    • IntlRuleBasedBreakIterator::getRules - Récupère le jeu de règles utilisé pour créer cet objet
    • IntlRuleBasedBreakIterator::getRuleStatus - Récupère la valeur de statut la plus grande depuis les règles qui déterminent la position courante d'arrêt
    • IntlRuleBasedBreakIterator::getRuleStatusVec - Récupère les valeurs de statut depuis les règles d'arrêt qui déterminent la position d'arrêt courante
    • IntlRuleBasedBreakIterator::__construct - Crée un itérateur depuis un jeu de règles
    • IntlTimeZone::countEquivalentIDs - Récupère le nombre d'IDs dans le groupe d'équivalence qui inclut l'ID fourni
    • IntlTimeZone::createDefault - Crée une nouvelle copie du fuseau horaire par défaut pour cet hôte
    • IntlTimeZone::createEnumeration - Récupère une énumération d'IDs de fuseau horaire associés avec le pays fourni
    • IntlTimeZone::createTimeZone - Crée un objet de fuseau horaire pour l'ID fourni
    • IntlTimeZone::createTimeZoneIDEnumeration - Get an enumeration over system time zone IDs with the given filter conditions
    • IntlTimeZone::fromDateTimeZone - Crée un objet fuseau horaire depuis DateTimeZone
    • IntlTimeZone::getCanonicalID - Récupère l'identifiant du fuseau horaire système ou l'identifiant normalisé du fuseau horaire personnalisé pour l'ID du fuseau horaire fourni
    • IntlTimeZone::getDisplayName - Récupère un nom du fuseau horaire aux fins de présentation à l'utilisateur
    • IntlTimeZone::getDSTSavings - Récupère la durée à ajouter à l'heure locale pour récupérer l'heure murale locale
    • IntlTimeZone::getEquivalentID - Récupère un identifiant d'un groupe d'équivalence qui inclut l'identifiant fourni
    • IntlTimeZone::getErrorCode - Récupère le code de la dernière erreur survenue sur l'objet
    • IntlTimeZone::getErrorMessage - Récupère le message de la dernière erreur survenue sur l'objet
    • IntlTimeZone::getGMT - Crée un fuseau horaire GMT (UTC)
    • IntlTimeZone::getID - Récupère l'ID d'un fuseau horaire
    • IntlTimeZone::getIDForWindowsID - Translate a Windows timezone into a system timezone
    • IntlTimeZone::getOffset - Récupère le fuseau horaire brute, et la position GMT pour un moment dans le temps donné
    • IntlTimeZone::getRawOffset - Récupère la position brute GMT (avant de prendre en compte l'heure d'été)
    • IntlTimeZone::getRegion - Get the region code associated with the given system time zone ID
    • IntlTimeZone::getTZDataVersion - Récupère la version du fuseau horaire actuellement utilisé par ICU
    • IntlTimeZone::getUnknown - Get the "unknown" time zone
    • IntlTimeZone::getWindowsID - Translate a system timezone into a Windows timezone
    • IntlTimeZone::hasSameRules - Vérifie si cette zone a les mêmes règles qu'une autre
    • IntlTimeZone::toDateTimeZone - Convertit un objet DateTimeZone
    • IntlTimeZone::useDaylightTime - Vérifie si ce fuseau horaire utilise l'heure d'étét
    • IntlTimeZone::__construct - Private constructor to disallow direct instantiation
    • intl_error_name - Lit le nom symbolique d'un code d'erreur donné
    • intl_get_error_code - Lit le dernier code d'erreur
    • intl_get_error_message - Lit la description de la dernière erreur
    • intl_is_failure - Vérifie si un code d'erreur indique un échec
    • intval - Retourne la valeur numérique entière équivalente d'une variable
    • in_array - Indique si une valeur appartient à un tableau
    • ip2long - Convertit une chaîne contenant une adresse (IPv4) en notation décimale à point en une adresse entier long
    • iptcembed - Intègre des données binaires IPTC dans une image JPEG
    • iptcparse - Analyse un bloc binaire IPTC et recherche les balises simples
    • isset - Détermine si une variable est déclarée et est différente de null
    • is_a - Vérifie si l'objet est d'un certain type ou sous-type.
    • is_array - Détermine si une variable est un tableau
    • is_bool - Détermine si une variable est un booléen
    • is_callable - Détermine si une valeur peut être appelé comme une fonction dans la portée courante.
    • is_countable - Vérifie si le contenu de la variable est une valeur dénombrable
    • is_dir - Indique si le fichier est un dossier
    • is_double - Alias de is_float
    • is_executable - Indique si le fichier est exécutable
    • is_file - Indique si le fichier est un véritable fichier
    • is_finite - Vérifie si un nombre flottant est fini
    • is_float - Détermine si une variable est de type nombre décimal
    • is_infinite - Vérifie si un nombre flottant est infini
    • is_int - Détermine si une variable est de type nombre entier
    • is_integer - Alias de is_int
    • is_iterable - Détermine si le contenu de la variable est itérable.
    • is_link - Indique si le fichier est un lien symbolique
    • is_long - Alias de is_int
    • is_nan - Vérifie si un nombre flottant est NAN
    • is_null - Indique si une variable vaut null
    • is_numeric - Détermine si une variable est un nombre ou une chaîne numérique
    • is_object - Détermine si une variable est de type objet
    • is_readable - Indique si un fichier existe et est accessible en lecture
    • is_real - Alias de is_float
    • is_resource - Détermine si une variable est une ressource
    • is_scalar - Indique si une variable est un scalaire
    • is_soap_fault - Vérifie si SOAP retourne une erreur
    • is_string - Détermine si une variable est de type chaîne de caractères
    • is_subclass_of - Détermine si un objet est une sous-classe d'une classe donnée ou l'implémente
    • is_tainted - Vérifie si une chaîne est nettoyée
    • is_uploaded_file - Indique si le fichier a été téléchargé par HTTP POST
    • is_writable - Indique si un fichier est accessible en écriture
    • is_writeable - Alias de is_writable
    • Iterator::current - Retourne l'élément courant
    • Iterator::key - Retourne la clé de l'élément courant
    • Iterator::next - Se déplace sur l'élément suivant
    • Iterator::rewind - Replace l'itérateur sur le premier élément
    • Iterator::valid - Vérifie si la position courante est valide
    • IteratorAggregate::getIterator - Retourne un itérateur externe
    • IteratorIterator::current - Lit la valeur courante
    • IteratorIterator::getInnerIterator - Retourne l'itérateur interne
    • IteratorIterator::key - Lit la clé de l'élément courant
    • IteratorIterator::next - Avance au prochain élément
    • IteratorIterator::rewind - Retourne au premier élément
    • IteratorIterator::valid - Vérifie si un itérateur est valide
    • IteratorIterator::__construct - Crée un itérateur à partir d'un objet traversable
    • iterator_apply - Appelle une fonction pour tous les éléments d'un itérateur
    • iterator_count - Compte de nombre d'éléments dans un itérateur
    • iterator_to_array - Copie un itérateur dans un tableau
  • j
    • jddayofweek - Retourne le numéro du jour de la semaine
    • jdmonthname - Retourne le nom du mois
    • jdtofrench - Convertit le nombre de jours du calendrier Julien en date du calendrier français républicain
    • jdtogregorian - Convertit le nombre de jours du calendrier Julien en date grégorienne
    • jdtojewish - Convertit le nombre de jours du calendrier Julien en date du calendrier juif
    • jdtojulian - Convertit le nombre de jours du calendrier Julien en date du calendrier Julien
    • jdtounix - Convertit un jour Julien en timestamp UNIX
    • jewishtojd - Convertit une date du calendrier Juif en nombre de jours du calendrier Julien
    • join - Alias de implode
    • jpeg2wbmp - Convertit une image JPEG en image WBMP
    • JsonSerializable::jsonSerialize - Spécifie les données qui doivent être sérialisées en JSON
    • json_decode - Décode une chaîne JSON
    • json_encode - Retourne la représentation JSON d'une valeur
    • json_last_error - Retourne la dernière erreur JSON
    • json_last_error_msg - Retourne le message de la dernière erreur survenue lors de l'appel à la fonction json_encode() ou json_decode()
    • json_validate - Checks if a string contains valid JSON
    • juliantojd - Convertit un jours du calendrier Julien en un nombre de jours du calendrier Julien
  • k
    • key - Retourne une clé d'un tableau associatif
    • key_exists - Alias de array_key_exists
    • krsort - Trie un tableau en fonction des clés en ordre décroissant
    • ksort - Trie un tableau en fonction des clés en ordre croissant
  • l
    • lcfirst - Met le premier caractère en minuscule
    • lcg_value - Générateur de congruence combinée linéaire
    • lchgrp - Change l'appartenance du groupe d'un lien symbolique
    • lchown - Change le propriétaire d'un lien symbolique
    • ldap_8859_to_t61 - Convertit les caractères 8859 en caractères t61
    • ldap_add - Ajoute une entrée dans un dossier LDAP
    • ldap_add_ext - Ajoute une entrée dans un dossier LDAP
    • ldap_bind - Authentification au serveur LDAP
    • ldap_bind_ext - Lie un dossier LDAP
    • ldap_close - Alias de ldap_unbind
    • ldap_compare - Compare une entrée avec des valeurs d'attributs
    • ldap_connect - Connexion à un serveur LDAP
    • ldap_connect_wallet - Connect to an LDAP server
    • ldap_control_paged_result - Envoi un contrôle de pagination LDAP
    • ldap_control_paged_result_response - Récupère le cookie de pagination LDAP
    • ldap_count_entries - Compte le nombre d'entrées après une recherche
    • ldap_count_references - Counts the number of references in a search result
    • ldap_delete - Efface une entrée dans un dossier
    • ldap_delete_ext - Supprime une entrée d'un dossier
    • ldap_dn2ufn - Convertit un DN en format UFN (User Friendly Naming)
    • ldap_err2str - Convertit un numéro d'erreur LDAP en message d'erreur
    • ldap_errno - Retourne le numéro d'erreur LDAP de la dernière commande exécutée
    • ldap_error - Retourne le message LDAP de la dernière commande LDAP
    • ldap_escape - Échappe une chaîne pour l'utiliser dans un filtre LDAP ou un DN
    • ldap_exop - Performs an extended operation
    • ldap_exop_passwd - PASSWD extended operation helper
    • ldap_exop_refresh - Refresh extended operation helper
    • ldap_exop_sync - Performs an extended operation
    • ldap_exop_whoami - WHOAMI extended operation helper
    • ldap_explode_dn - Sépare les différents composants d'un DN
    • ldap_first_attribute - Retourne le premier attribut
    • ldap_first_entry - Retourne la première entrée
    • ldap_first_reference - Retourne la première référence
    • ldap_free_result - Libère la mémoire du résultat
    • ldap_get_attributes - Lit les attributs d'une entrée
    • ldap_get_dn - Lit le DN d'une entrée
    • ldap_get_entries - Lit toutes les entrées du résultat
    • ldap_get_option - Lit/écrit la valeur courante d'une option
    • ldap_get_values - Lit toutes les valeurs d'une entrée LDAP
    • ldap_get_values_len - Lit toutes les valeurs binaires d'une entrée
    • ldap_list - Recherche dans un niveau
    • ldap_modify - Alias de ldap_mod_replace
    • ldap_modify_batch - Mets en lot des modifications et les exécute sur une entrée LDAP
    • ldap_mod_add - Ajoute un attribut à l'entrée courante
    • ldap_mod_add_ext - Add attribute values to current attributes
    • ldap_mod_del - Efface un attribut à l'entrée courante
    • ldap_mod_del_ext - Delete attribute values from current attributes
    • ldap_mod_replace - Remplace un attribut dans l'entrée courante
    • ldap_mod_replace_ext - Replace attribute values with new ones
    • ldap_next_attribute - Lit l'attribut suivant
    • ldap_next_entry - Lit la prochaine entrée
    • ldap_next_reference - Lit la référence suivante
    • ldap_parse_exop - Parse result object from an LDAP extended operation
    • ldap_parse_reference - Extrait les informations d'une référence d'entrée
    • ldap_parse_result - Extrait des informations d'un résultat
    • ldap_read - Lit une entrée
    • ldap_rename - Modifie le nom d'une entrée
    • ldap_rename_ext - Modify the name of an entry
    • ldap_sasl_bind - Authentification au serveur LDAP en utilisant SASL
    • ldap_search - Recherche sur le serveur LDAP
    • ldap_set_option - Modifie la valeur d'une option LDAP
    • ldap_set_rebind_proc - Configure une fonction de retour pour refaire des liaisons lors de recherche de référants
    • ldap_sort - Trie les entrées d'un résultat LDAP côté client
    • ldap_start_tls - Démarre TLS
    • ldap_t61_to_8859 - Convertit les caractères t61 en caractères 8859
    • ldap_unbind - Déconnecte d'un serveur LDAP
    • Les options du contexte Phar - Liste des options du contexte Phar
    • levenshtein - Calcule la distance Levenshtein entre deux chaînes
    • libxml_clear_errors - Vide le buffer d'erreur libxml
    • libxml_disable_entity_loader - Désactive le chargement des entités externes
    • libxml_get_errors - Lit le tableau d'erreurs
    • libxml_get_external_entity_loader - Get the current external entity loader
    • libxml_get_last_error - Lit la dernière erreur libxml
    • libxml_set_external_entity_loader - Change le chargeur d'entités externes par défaut
    • libxml_set_streams_context - Configure le contexte de flux pour la prochaine opération libxml
    • libxml_use_internal_errors - Désactive le rapport d'erreur libxml et les stocke pour lecture ultérieure
    • LimitIterator::current - Récupère l'élément courant
    • LimitIterator::getPosition - Retourne la position courante
    • LimitIterator::key - Récupère la clé courante
    • LimitIterator::next - Déplace l'itérateur à la position suivante
    • LimitIterator::rewind - Replace l'itérateur au début
    • LimitIterator::seek - Place l'itérateur à une position donnée
    • LimitIterator::valid - Vérifie si l'élément courant est valide
    • LimitIterator::__construct - Construit un nouvel objet LimitIterator
    • link - Crée un lien
    • linkinfo - Renvoie les informations d'un lien
    • list - Assigne des variables comme si elles étaient un tableau
    • Locale::acceptFromHttp - Devine la meilleure locale à partir de l'en-tête HTTP "Accept-Language"
    • Locale::canonicalize - Canonise la chaîne représentant la locale
    • Locale::composeLocale - Retourne un identifiant de locale correct
    • Locale::filterMatches - Vérifie si le tag de langue correspond à une locale
    • Locale::getAllVariants - Liste toutes les variantes d'une locale
    • Locale::getDefault - Lit la valeur par défaut d'une locale pour la variable globale 'default_locale'
    • Locale::getDisplayLanguage - Retourne un nom approprié pour l'affichage d'un nom de langue
    • Locale::getDisplayName - Retourne un nom d'affichage correct pour une locale
    • Locale::getDisplayRegion - Retourne un nom pour la région de la locale
    • Locale::getDisplayScript - Retourne le nom du script de la locale
    • Locale::getDisplayVariant - Retourne un nom pour la variante de la locale
    • Locale::getKeywords - Lit les mots-clé de la locale
    • Locale::getPrimaryLanguage - Lit la langue principale de la locale
    • Locale::getRegion - Retourne un code pour la région de la locale
    • Locale::getScript - Retourne un code pour le script de la locale
    • Locale::lookup - Recherche dans la liste la meilleure langue
    • Locale::parseLocale - Retourne les sous-éléments de la locale
    • Locale::setDefault - Configure la locale par défaut
    • localeconv - Lit la configuration locale
    • localtime - Récupère l'heure locale
    • log - Logarithme naturel (népérien)
    • log1p - Calcule précisément log(1 + nombre)
    • log10 - Logarithme en base 10
    • long2ip - Convertit une adresse entier long (IPv4) en sa notation décimale à point
    • lstat - Retourne les informations sur un fichier ou un lien symbolique
    • ltrim - Supprime les espaces (ou d'autres caractères) de début de chaîne
    • Lua::assign - Assigne une variable PHP à Lua
    • Lua::call - Appelle les fonctions Lua
    • Lua::eval - Évalue une chaîne comme du code Lua
    • Lua::getVersion - Le but de getversion
    • Lua::include - Analyse un fichier de script Lua
    • Lua::registerCallback - Enregistre une fonction PHP en Lua
    • Lua::__construct - Constructeur Lua
    • LuaClosure::__invoke - Appelle 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 - Compression LZF
    • lzf_decompress - Décompression LZF
    • lzf_optimized_for - Détermine le mode d'optimisation de l'extension LZF
  • m
    • mail - Envoi de mail
    • mailparse_determine_best_xfer_encoding - Détermine le meilleur encodage pour un fichier
    • mailparse_msg_create - Crée une ressource email mime
    • mailparse_msg_extract_part - Extrait et décode une section de message
    • mailparse_msg_extract_part_file - Extrait et décode une section de message
    • mailparse_msg_extract_whole_part_file - Extrait une section de message incluant les en-têtes sans décoder l'encodage de transfert
    • mailparse_msg_free - Libère une ressource MIME
    • mailparse_msg_get_part - Retourne une ressource sur une section d'un message MIME
    • mailparse_msg_get_part_data - Retourne un tableau associatif avec des informations sur le message
    • mailparse_msg_get_structure - Retourne un tableau avec les différentes sections MIME du message
    • mailparse_msg_parse - Analyse incrémentalement des données dans un buffer
    • mailparse_msg_parse_file - Analyse un fichier
    • mailparse_rfc822_parse_addresses - Analyse des adresses
    • mailparse_stream_encode - Lit les données dans un fichier, applique l'encodage et envoie le résultat à destfp
    • mailparse_uudecode_all - Scanne les données du fichier et extrait tous les fichiers encodés qui s'y trouvent
    • max - La plus grande valeur
    • mb_check_encoding - Vérifie si les chaînes sont valide pour l'encodage spécifié
    • mb_chr - Retourne un caractère par sa valeur de point de code Unicode
    • mb_convert_case - Modifie la casse d'une chaîne
    • mb_convert_encoding - Convertir une chaîne d'un codage de caractères à un autre
    • mb_convert_kana - Convertit un "kana" en un autre ("zen-kaku", "han-kaku" et plus)
    • mb_convert_variables - Convertit l'encodage de variables
    • mb_decode_mimeheader - Décode un en-tête MIME
    • mb_decode_numericentity - Décode les entités HTML en caractères
    • mb_detect_encoding - Détecte un encodage
    • mb_detect_order - Lit/modifie l'ordre de détection des encodages
    • mb_encode_mimeheader - Encode une chaîne pour un en-tête MIME
    • mb_encode_numericentity - Encode les caractères en référence numérique HTML
    • mb_encoding_aliases - Récupère les aliases d'un type d'encodage connu
    • mb_ereg - Recherche par expression rationnelle avec support des caractères multioctets
    • mb_eregi - Expression rationnelle insensible à la casse avec le support des caractères multioctets
    • mb_eregi_replace - Expression rationnelle avec support des caractères multioctets, sans tenir compte de la casse
    • mb_ereg_match - Expression rationnelle POSIX pour les chaînes multioctets
    • mb_ereg_replace - Remplace des segments de chaîne à l'aide des expressions régulières
    • mb_ereg_replace_callback - Rechercher et remplacer par expression régulière avec support multi octets utilisant une fonction de callback
    • mb_ereg_search - Recherche par expression rationnelle multioctets
    • mb_ereg_search_getpos - Retourne la position du début du prochain segment repéré par une expression rationnelle
    • mb_ereg_search_getregs - Lit le dernier segment de chaîne multioctets qui correspond au masque
    • mb_ereg_search_init - Configure les chaînes et les expressions régulières pour le support des caractères multioctets
    • mb_ereg_search_pos - Retourne la position et la longueur du segment de chaîne qui vérifie le masque de l'expression rationnelle
    • mb_ereg_search_regs - Retourne le segment de chaîne trouvé par une expression rationnelle multioctets
    • mb_ereg_search_setpos - Choisit le point de départ de la recherche par expression rationnelle
    • mb_get_info - Lit la configuration interne de l'extension mbstring
    • mb_http_input - Détecte le type d'encodage d'un caractère HTTP
    • mb_http_output - Lit/modifie l'encodage d'affichage
    • mb_internal_encoding - Lit/modifie l'encodage interne
    • mb_language - Définit/Récupère le langage courant
    • mb_list_encodings - Retourne un tableau contenant tous les encodages supportés
    • mb_ord - Récupère le point de code Unicode d'un caractère
    • mb_output_handler - Fonction de traitement des affichages
    • mb_parse_str - Analyse les données HTTP GET/POST/COOKIE et assigne les variables globales
    • mb_preferred_mime_name - Détecte l'encodage MIME
    • mb_regex_encoding - Définit/Récupère l'encodage des caractères pour les expressions régulières multioctets
    • mb_regex_set_options - Lit et modifie les options des fonctions d'expression rationnelle à support de caractères multioctets
    • mb_scrub - Remplacez les séquences d'octets mal formées par le caractère de substitution.
    • mb_send_mail - Envoie un mail encodé
    • mb_split - Scinde une chaîne en tableau avec une expression rationnelle multioctets
    • mb_strcut - Coupe une partie de chaîne
    • mb_strimwidth - Tronque une chaîne
    • mb_stripos - Trouve la première occurrence d'une chaîne dans une autre, sans tenir compte de la casse
    • mb_stristr - Trouve la première occurrence d'une chaîne dans une autre, sans tenir compte de la casse
    • mb_strlen - Retourne la taille d'une chaîne
    • mb_strpos - Repère la première occurrence d'un caractère dans une chaîne
    • mb_strrchr - Trouve la dernière occurrence d'un caractère d'une chaîne dans une autre
    • mb_strrichr - Trouve la dernière occurrence d'un caractère d'une chaîne dans une autre, insensible à la casse
    • mb_strripos - Trouve la position de la dernière occurrence d'une chaîne dans une autre, en ne tenant pas compte de la casse
    • mb_strrpos - Repère la dernière occurrence d'un caractère dans une chaîne
    • mb_strstr - Trouve la première occurrence d'une chaîne dans une autre
    • mb_strtolower - Met tous les caractères en minuscules
    • mb_strtoupper - Met tous les caractères en majuscules
    • mb_strwidth - Retourne la taille d'une chaîne
    • mb_str_pad - Pad a multibyte string to a certain length with another multibyte string
    • mb_str_split - Pour une chaîne multi-octets donnée, renvoie un tableau de ses caractères
    • mb_substitute_character - Définit/Récupère les caractères de substitution
    • mb_substr - Lit une sous-chaîne
    • mb_substr_count - Compte le nombre d'occurrences d'une sous-chaîne
    • mcrypt_create_iv - Crée un vecteur d'initialisation (IV) à partir d'une source aléatoire
    • mcrypt_decrypt - Déchiffre un texte avec les paramètres donnés
    • mcrypt_encrypt - Chiffre un texte
    • mcrypt_enc_get_algorithms_name - Retourne le nom de l'algorithme de chiffrement
    • mcrypt_enc_get_block_size - Retourne la taille du bloc d'un algorithme
    • mcrypt_enc_get_iv_size - Retourne la taille du VI d'un algorithme
    • mcrypt_enc_get_key_size - Retourne la taille maximale de la clé pour un mode
    • mcrypt_enc_get_modes_name - Retourne le nom du mode
    • mcrypt_enc_get_supported_key_sizes - Retourne un tableau contenant les tailles de clés acceptées par un algorithme
    • mcrypt_enc_is_block_algorithm - Teste le chiffrement par blocs d'un algorithme
    • mcrypt_enc_is_block_algorithm_mode - Teste le chiffrement par blocs d'un mode
    • mcrypt_enc_is_block_mode - Teste si le mode retourne les données par blocs
    • mcrypt_enc_self_test - Teste un module ouvert
    • mcrypt_generic - Chiffre les données
    • mcrypt_generic_deinit - Prépare le module pour le déchargement
    • mcrypt_generic_init - Initialise tous les buffers nécessaires
    • mcrypt_get_block_size - Retourne la taille de blocs d'un chiffrement
    • mcrypt_get_cipher_name - Lit le nom du chiffrement utilisé
    • mcrypt_get_iv_size - Retourne la taille du VI utilisé par un couple chiffrement/mode
    • mcrypt_get_key_size - Retourne la taille de la clé de chiffrement
    • mcrypt_list_algorithms - Liste tous les algorithmes de chiffrement supportés
    • mcrypt_list_modes - Liste tous les modes de chiffrement supportés
    • mcrypt_module_close - Décharge le module de chiffrement
    • mcrypt_module_get_algo_block_size - Retourne la taille de blocs d'un algorithme
    • mcrypt_module_get_algo_key_size - Retourne la taille maximale de clé
    • mcrypt_module_get_supported_key_sizes - Retourne un tableau contenant les tailles de clés supportées par l'algorithme ouvert
    • mcrypt_module_is_block_algorithm - Indique si un algorithme fonctionne par blocs
    • mcrypt_module_is_block_algorithm_mode - Indique si un mode fonctionne par blocs
    • mcrypt_module_is_block_mode - Indique si un mode travaille par blocs
    • mcrypt_module_open - Ouvre le module de l'algorithme et du mode à utiliser
    • mcrypt_module_self_test - Teste un mode
    • md5 - Calcule le md5 d'une chaîne
    • md5_file - Calcule le md5 d'un fichier
    • mdecrypt_generic - Déchiffre les données
    • Memcache::add - Ajoute un élément dans le server
    • Memcache::addServer - Ajoute un serveur memcache à la liste de connexion
    • Memcache::close - Ferme la connexion avec le serveur Memcache
    • Memcache::connect - Ouvre une connexion avec le serveur Memcache
    • Memcache::decrement - Décrémente la valeur d'un élément
    • Memcache::delete - Efface un élément du serveur de cache
    • Memcache::flush - Efface tous les éléments existant sur le serveur de cache
    • Memcache::get - Récupère un élément du serveur de cache
    • Memcache::getExtendedStats - Récupère des statistiques de tous les serveurs dans la liste
    • Memcache::getServerStatus - Retourne le statut du serveur
    • Memcache::getStats - Lit les statistiques du serveur
    • Memcache::getVersion - Retourne le numéro de version du serveur
    • Memcache::increment - Incrément la valeur d'un élément
    • Memcache::pconnect - Ouvre un connexion persistante à un serveur de cache
    • Memcache::replace - Remplace une valeur d'un élément existant
    • Memcache::set - Stocke des données dans le serveur de cache
    • Memcache::setCompressThreshold - Active la compression automatique des valeurs larges
    • Memcache::setServerParams - Modifit les paramètres et les statuts du serveur pendant l'exécution
    • Memcached::add - Ajoute un nouvel élément sous une nouvelle clé
    • Memcached::addByKey - Ajoute un élément sur un serveur désigné
    • Memcached::addServer - Ajoute un serveur au pool
    • Memcached::addServers - Ajoute plusieurs serveurs au pool
    • Memcached::append - Ajoute des données à un élément
    • Memcached::appendByKey - Ajoute des données à un élément
    • Memcached::cas - Compare et échange un élément
    • Memcached::casByKey - Compare et échange un élément sur un serveur
    • Memcached::decrement - Décrémente une valeur numérique
    • Memcached::decrementByKey - Décrémente une valeur numérique d'un élément, stocké sur un serveur spécifique
    • Memcached::delete - Efface un élément
    • Memcached::deleteByKey - Supprime un élément d'un serveur spécifique
    • Memcached::deleteMulti - Supprime plusieurs éléments
    • Memcached::deleteMultiByKey - Supprime plusieurs éléments depuis un serveur spécifique
    • Memcached::fetch - Lit le prochain résultat
    • Memcached::fetchAll - Lit tous les autres éléments
    • Memcached::flush - Invalide tous les éléments du cache
    • Memcached::get - Lit un élément
    • Memcached::getAllKeys - Récupère toutes les clés stockés sur tous les serveurs
    • Memcached::getByKey - Lit un élément sur un serveur spécifique
    • Memcached::getDelayed - Lit plusieurs éléments
    • Memcached::getDelayedByKey - Lit plusieurs éléments sur un serveur
    • Memcached::getMulti - Lit plusieurs éléments
    • Memcached::getMultiByKey - Lit plusieurs éléments d'un serveur spécifique
    • Memcached::getOption - Lit une option Memcached
    • Memcached::getResultCode - Retourne le code de résultat de la dernière opération
    • Memcached::getResultMessage - Retourne un message décrivant le résultat de la dernière opération
    • Memcached::getServerByKey - Dirige une clé sur un serveur
    • Memcached::getServerList - Liste les serveurs du pool memcached
    • Memcached::getStats - Lit des statistiques du pool de serveurs
    • Memcached::getVersion - Lit les informations de version du pool serveur
    • Memcached::increment - Incrémente numériquement un élément
    • Memcached::incrementByKey - Incrémente une valeur numérique d'un élément, stocké sur un serveur spécifique
    • Memcached::isPersistent - Vérifie si une connexion persistente vers memcache est en cours d'utilisation
    • Memcached::isPristine - Vérifie si l'instance a été créée récemment
    • Memcached::prepend - Préfixe des données à un élément existant
    • Memcached::prependByKey - Préfixe un élément existant
    • Memcached::quit - Ferme toutes les connexions ouvertes
    • Memcached::replace - Remplace un élément sous une clé
    • Memcached::replaceByKey - Remplace un élément spécifique sur un serveur désigné
    • Memcached::resetServerList - Supprime tous les serveurs depuis la liste des serveurs
    • Memcached::set - Stocke un élément
    • Memcached::setByKey - Stocke un élément sur un serveur spécifique
    • Memcached::setMulti - Stocke plusieurs éléments
    • Memcached::setMultiByKey - Stocke plusieurs éléments sur un serveur
    • Memcached::setOption - Configure une option Memcached
    • Memcached::setOptions - Définit des options Memcache
    • Memcached::setSaslAuthData - Définit les informations à utiliser pour l'authentification
    • Memcached::touch - Définit une nouvelle expiration sur un élément
    • Memcached::touchByKey - Définit une nouvelle expiration sur un élément d'un serveur spécifique
    • Memcached::__construct - Crée un objet Memcached
    • memcache_debug - Active ou non l'affichage des informations de déboguage
    • memory_get_peak_usage - Retourne la quantité de mémoire maximale allouée par PHP
    • memory_get_usage - Indique la quantité de mémoire utilisée par PHP
    • memory_reset_peak_usage - Reset the peak memory usage
    • MessageFormatter::create - Construit un nouveau formateur de messages
    • MessageFormatter::format - Formate un message
    • MessageFormatter::formatMessage - Formate rapidement un message
    • MessageFormatter::getErrorCode - Lit le dernier code d'erreur de la dernière opération
    • MessageFormatter::getErrorMessage - Lit le message d'erreur de la dernière opération
    • MessageFormatter::getLocale - Lit la locale avec la quelle le formateur a été créé
    • MessageFormatter::getPattern - Lit le modèle utilisé par le formateur de messages
    • MessageFormatter::parse - Analyse une chaîne en fonction du modèle
    • MessageFormatter::parseMessage - Analyse rapidement une chaîne
    • MessageFormatter::setPattern - Configure le modèle utilisé par le formateur
    • metaphone - Calcule la clé metaphone
    • method_exists - Vérifie si la méthode existe pour une classe
    • mhash - Calcule un hash
    • mhash_count - Récupère l'identifiant maximal de hash
    • mhash_get_block_size - Retourne la taille de bloc du hash
    • mhash_get_hash_name - Retourne le nom du hash
    • mhash_keygen_s2k - Génère une clé
    • microtime - Retourne le timestamp UNIX actuel avec les microsecondes
    • mime_content_type - Détecte le type de contenu d'un fichier
    • min - La plus petite valeur
    • mkdir - Crée un dossier
    • mktime - Retourne l'horodatage UNIX d'une date
    • money_format - Met un nombre au format monétaire
    • MongoDB\BSON\Binary::getData - Retourne les données de Binary
    • MongoDB\BSON\Binary::getType - Retourne le type de Binary
    • MongoDB\BSON\Binary::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Binary::serialize - Sérialise un Binary
    • MongoDB\BSON\Binary::unserialize - Désérialise un Binary
    • MongoDB\BSON\Binary::__construct - Construit un nouveau binaire
    • MongoDB\BSON\Binary::__toString - Retourne les données de Binary
    • MongoDB\BSON\BinaryInterface::getData - Retourne les données de BinaryInterface
    • MongoDB\BSON\BinaryInterface::getType - Retourne le type de BinaryInterface
    • MongoDB\BSON\BinaryInterface::__toString - Retourne les données de BinaryInterface
    • MongoDB\BSON\DBPointer::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\DBPointer::serialize - Sérialise un DBPointer
    • MongoDB\BSON\DBPointer::unserialize - Désérialisé un DBPointer
    • MongoDB\BSON\DBPointer::__construct - Construit un nouveau DBPointer (inutilisé)
    • MongoDB\BSON\DBPointer::__toString - Retourne une chaîne vide
    • MongoDB\BSON\Decimal128::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Decimal128::serialize - Sérialise un Decimal128
    • MongoDB\BSON\Decimal128::unserialize - Désérialisé un Decimal128
    • MongoDB\BSON\Decimal128::__construct - Construit un nouveau Decimal128
    • MongoDB\BSON\Decimal128::__toString - Retourne la représentation sous forme de chaîne de caractère de Decimal128
    • MongoDB\BSON\Decimal128Interface::__toString - Retourne une représentation sous chaîne de caractères de Decimal128Interface
    • MongoDB\BSON\Document::fromBSON - Construct a new document instance from a BSON string
    • MongoDB\BSON\Document::fromJSON - Construct a new document instance from a JSON string
    • MongoDB\BSON\Document::fromPHP - Construct a new document instance from PHP data
    • MongoDB\BSON\Document::get - Returns the value of a key in the document
    • MongoDB\BSON\Document::getIterator - Returns an iterator for the BSON document
    • MongoDB\BSON\Document::has - Returns whether a key is present in the document
    • MongoDB\BSON\Document::serialize - Serialize a Document
    • MongoDB\BSON\Document::toCanonicalExtendedJSON - Returns the Canonical Extended JSON representation of the BSON document
    • MongoDB\BSON\Document::toPHP - Returns the PHP representation of the BSON document
    • MongoDB\BSON\Document::toRelaxedExtendedJSON - Returns the Relaxed Extended JSON representation of the BSON document
    • MongoDB\BSON\Document::unserialize - Unserialize a BSON document
    • MongoDB\BSON\Document::__construct - Construct a new BSON document (unused)
    • MongoDB\BSON\Document::__toString - Returns the string representation of this BSON Document
    • MongoDB\BSON\fromJSON - Retourne la représentation BSON d'une valeur JSON
    • MongoDB\BSON\fromPHP - Retourne la représentation BSON d'une valeur PHP
    • MongoDB\BSON\Int64::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Int64::serialize - Sérialise un Int64
    • MongoDB\BSON\Int64::unserialize - Désérialisé un Int64
    • MongoDB\BSON\Int64::__construct - Construit un nouveau Int64
    • MongoDB\BSON\Int64::__toString - Retourne la représentation sous forme de chaîne de caractère de Int64
    • MongoDB\BSON\Iterator::current - Returns the current element
    • MongoDB\BSON\Iterator::key - Returns the key of the current element
    • MongoDB\BSON\Iterator::next - Advances the iterator to next element
    • MongoDB\BSON\Iterator::rewind - Rewinds the Iterator to the first element
    • MongoDB\BSON\Iterator::valid - Checks if current position is valid
    • MongoDB\BSON\Iterator::__construct - Construct a new BSON iterator (unused)
    • MongoDB\BSON\Javascript::getCode - Retourne le code Javascript
    • MongoDB\BSON\Javascript::getScope - Retourne le document de portée de Javascript
    • MongoDB\BSON\Javascript::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Javascript::serialize - Sérialise un Javascript
    • MongoDB\BSON\Javascript::unserialize - Désérialisé un Javascript
    • MongoDB\BSON\Javascript::__construct - Construit un nouvel objet Javascript
    • MongoDB\BSON\Javascript::__toString - Retourne le code Javascript
    • MongoDB\BSON\JavascriptInterface::getCode - Retourne le code de JavascriptInterface
    • MongoDB\BSON\JavascriptInterface::getScope - Retourne le document de portée de JavascriptInterface
    • MongoDB\BSON\JavascriptInterface::__toString - Retourne le code de JavascriptInterface
    • MongoDB\BSON\MaxKey::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\MaxKey::serialize - Sérialise un MaxKey
    • MongoDB\BSON\MaxKey::unserialize - Désérialisé un MaxKey
    • MongoDB\BSON\MaxKey::__construct - Construit un nouveau MaxKey
    • MongoDB\BSON\MinKey::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\MinKey::serialize - Sérialise un MinKey
    • MongoDB\BSON\MinKey::unserialize - Désérialisé un MinKey
    • MongoDB\BSON\MinKey::__construct - Construit un nouveau MinKey
    • MongoDB\BSON\ObjectId::getTimestamp - Retourne le composant d'horodatage de ObjectId
    • MongoDB\BSON\ObjectId::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\ObjectId::serialize - Sérialise un ObjectId
    • MongoDB\BSON\ObjectId::unserialize - Désérialisé un ObjectId
    • MongoDB\BSON\ObjectId::__construct - Construit un nouvel ObjectId
    • MongoDB\BSON\ObjectId::__toString - Retourne la représentation hexadécimale de cet ObjectId
    • MongoDB\BSON\ObjectIdInterface::getTimestamp - Retourne le composant d'horodatage de ObjectIdInterface
    • MongoDB\BSON\ObjectIdInterface::__toString - Retourne la représentation hexadécimale de ObjectIdInterface
    • MongoDB\BSON\PackedArray::fromPHP - Construct a new BSON array instance from PHP data
    • MongoDB\BSON\PackedArray::get - Returns the value of an index in the array
    • MongoDB\BSON\PackedArray::getIterator - Returns an iterator for the BSON array
    • MongoDB\BSON\PackedArray::has - Returns whether a index is present in the array
    • MongoDB\BSON\PackedArray::serialize - Serialize a BSON array
    • MongoDB\BSON\PackedArray::toPHP - Returns the PHP representation of the BSON array
    • MongoDB\BSON\PackedArray::unserialize - Unserialize a BSON array
    • MongoDB\BSON\PackedArray::__construct - Construct a new BSON array (unused)
    • MongoDB\BSON\PackedArray::__toString - Returns the string representation of this BSON array
    • MongoDB\BSON\Persistable::bsonSerialize - Provides an array or document to serialize as BSON
    • MongoDB\BSON\Regex::getFlags - Retourne les drapeux de la REGEX
    • MongoDB\BSON\Regex::getPattern - Retourne le masque du REGEX
    • MongoDB\BSON\Regex::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Regex::serialize - Sérialise un Regex
    • MongoDB\BSON\Regex::unserialize - Désérialisé un Regex
    • MongoDB\BSON\Regex::__construct - Construit une nouvelle REGEX
    • MongoDB\BSON\Regex::__toString - Retourne la chaîne représentant cette REGEX
    • MongoDB\BSON\RegexInterface::getFlags - Retourne les drapeaux de RegexInterface
    • MongoDB\BSON\RegexInterface::getPattern - Retourne le masque de RegexInterface
    • MongoDB\BSON\RegexInterface::__toString - Retourne la représentation sous forme de chaîne de caractère de cette RegexInterface
    • MongoDB\BSON\Serializable::bsonSerialize - Fournit un tableau ou un document à sérialiser en tant que BSON
    • MongoDB\BSON\Symbol::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Symbol::serialize - Sérialise un Symbol
    • MongoDB\BSON\Symbol::unserialize - Désérialisé un Symbol
    • MongoDB\BSON\Symbol::__construct - Construit un nouveau Symbol (inutilisé)
    • MongoDB\BSON\Symbol::__toString - Retourne la représentation sous forme de chaîne de caractère de Symbol
    • MongoDB\BSON\Timestamp::getIncrement - Retourne le composant d'incrémentation de ce Timestamp
    • MongoDB\BSON\Timestamp::getTimestamp - Retourne le composant d'horodatage de Timestamp
    • MongoDB\BSON\Timestamp::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Timestamp::serialize - Sérialise un Timestamp
    • MongoDB\BSON\Timestamp::unserialize - Désérialisé un Timestamp
    • MongoDB\BSON\Timestamp::__construct - Contruit un nouveau Timestamp
    • MongoDB\BSON\Timestamp::__toString - Retourne la représentation sous forme de chaîne de cet horodatage
    • MongoDB\BSON\TimestampInterface::getIncrement - Retourne le composant d'incrémentation de ce TimestampInterface
    • MongoDB\BSON\TimestampInterface::getTimestamp - Retourne le composant d'horodatage de TimestampInterface
    • MongoDB\BSON\TimestampInterface::__toString - Retourne la représentation sous forme de chaîne de caractère de TimestampInterface
    • MongoDB\BSON\toCanonicalExtendedJSON - Returns the Canonical Extended JSON representation of a BSON value
    • MongoDB\BSON\toJSON - Retourne la représentation JSON étendue héritée d'une valeur BSON
    • 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 - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\Undefined::serialize - Sérialise un Undefined
    • MongoDB\BSON\Undefined::unserialize - Désérialisé un Undefined
    • MongoDB\BSON\Undefined::__construct - Construit un nouveau Undefined (inutilisé)
    • MongoDB\BSON\Undefined::__toString - Retourne une chaîne vide
    • MongoDB\BSON\Unserializable::bsonUnserialize - Construit l'objet à partir d'un tableau ou d'un document BSON
    • MongoDB\BSON\UTCDateTime::jsonSerialize - Retourne une représentation qui peut être convertie en JSON
    • MongoDB\BSON\UTCDateTime::serialize - Sérialise un UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime - Retourne la représentation DateTime de ce UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize - Désérialisé un UTCDateTime
    • MongoDB\BSON\UTCDateTime::__construct - Construit un nouveau UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString - Retourne la représentation sous forme de chaîne de ce UTCDateTime
    • MongoDB\BSON\UTCDateTimeInterface::toDateTime - Retourne la représentation DateTime de UTCDateTimeInterface
    • MongoDB\BSON\UTCDateTimeInterface::__toString - Retourne la représentation sous forme de chaîne de caractère de 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\ClientEncryption::addKeyAltName - Adds an alternate name to a key document
    • MongoDB\Driver\ClientEncryption::createDataKey - Creates a key document
    • MongoDB\Driver\ClientEncryption::decrypt - Decrypt a value
    • MongoDB\Driver\ClientEncryption::deleteKey - Deletes a key document
    • MongoDB\Driver\ClientEncryption::encrypt - Encrypt a value
    • MongoDB\Driver\ClientEncryption::encryptExpression - Encrypts a match or aggregate expression
    • MongoDB\Driver\ClientEncryption::getKey - Gets a key document
    • MongoDB\Driver\ClientEncryption::getKeyByAltName - Gets a key document by an alternate name
    • MongoDB\Driver\ClientEncryption::getKeys - Gets all key documents
    • MongoDB\Driver\ClientEncryption::removeKeyAltName - Removes an alternate name from a key document
    • MongoDB\Driver\ClientEncryption::rewrapManyDataKey - Rewraps data keys
    • MongoDB\Driver\ClientEncryption::__construct - Create a new ClientEncryption object
    • MongoDB\Driver\Command::__construct - Crée une nouvelle commande
    • MongoDB\Driver\Cursor::current - Returns the current element
    • MongoDB\Driver\Cursor::getId - Retourne l'ID de ce curseur
    • MongoDB\Driver\Cursor::getServer - Retourne le serveur associé à ce curseur
    • MongoDB\Driver\Cursor::isDead - Vérifie si le curseur est épuisé ou peut avoir des résultats supplémentaires
    • 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 - Défini un type de carte à utiliser pour la désérialisation BSON
    • MongoDB\Driver\Cursor::toArray - Retourne un tableau contenant tous les résultats pour ce curseur
    • MongoDB\Driver\Cursor::valid - Checks if the current position in the cursor is valid
    • MongoDB\Driver\Cursor::__construct - Créer un nouveau curseur (non utilisé)
    • MongoDB\Driver\CursorId::serialize - Serialize a CursorId
    • MongoDB\Driver\CursorId::unserialize - Unserialize a CursorId
    • MongoDB\Driver\CursorId::__construct - Créer un nouveau CursorId (non utilisé)
    • MongoDB\Driver\CursorId::__toString - Représentation sous forme de chaîne de l'ID de curseur
    • MongoDB\Driver\CursorInterface::getId - Returns the ID for this cursor
    • MongoDB\Driver\CursorInterface::getServer - Returns the server associated with this cursor
    • MongoDB\Driver\CursorInterface::isDead - Checks if the cursor may have additional results
    • MongoDB\Driver\CursorInterface::setTypeMap - Sets a type map to use for BSON unserialization
    • MongoDB\Driver\CursorInterface::toArray - Returns an array containing all results for this cursor
    • MongoDB\Driver\Exception\CommandException::getResultDocument - Retourne le document résultant pour la commande échoué
    • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel - Retourne si un label d'erreur est associé avec une exception
    • MongoDB\Driver\Exception\WriteException::getWriteResult - Retourne le WriteResult pour l'opération d'écriture qui a échoué
    • MongoDB\Driver\Manager::addSubscriber - Registers a monitoring event subscriber with this Manager
    • 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::getEncryptedFieldsMap - Return the encryptedFieldsMap auto encryption option for the Manager
    • MongoDB\Driver\Manager::getReadConcern - Return the ReadConcern for the Manager
    • MongoDB\Driver\Manager::getReadPreference - Return the ReadPreference for the Manager
    • MongoDB\Driver\Manager::getServers - Retourner les serveurs auxquels ce gestionnaire est connecté
    • MongoDB\Driver\Manager::getWriteConcern - Return the WriteConcern for the Manager
    • MongoDB\Driver\Manager::removeSubscriber - Unregisters a monitoring event subscriber with this 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 - Enregistre un abonnement de surveillance d'événement
    • 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\CommandFailedEvent::getServerConnectionId - Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId - Returns the load balancer service ID for the command
    • 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\CommandStartedEvent::getServerConnectionId - Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId - Returns the load balancer service ID for the command
    • 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\CommandSucceededEvent::getServerConnectionId - Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId - Returns the load balancer service ID for the command
    • MongoDB\Driver\Monitoring\LogSubscriber::log - Notification method for a log message
    • MongoDB\Driver\Monitoring\removeSubscriber - Retire un abonnement de surveillance d'événement global
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged - Notification method for a server description change
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed - Notification method for closing a server
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed - Notification method for a failed server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted - Notification method for a started server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded - Notification method for a successful server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening - Notification method for opening a server
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged - Notification method for a topology description change
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed - Notification method for closing the topology
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening - Notification method for opening the topology
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription - Returns the new description for the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription - Returns the previous description for the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId - Returns the topology ID associated with this server
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId - Returns the topology ID associated with this server
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros - Returns the heartbeat's duration in microseconds
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError - Returns the Exception associated with the failed heartbeat
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited - Returns whether the heartbeat used a streaming protocol
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited - Returns whether the heartbeat used a streaming protocol
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros - Returns the heartbeat's duration in microseconds
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply - Returns the heartbeat reply document
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited - Returns whether the heartbeat used a streaming protocol
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId - Returns the topology ID associated with this server
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription - Returns the new description for the topology
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription - Returns the previous description for the topology
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId - Returns the topology ID
    • MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId - Returns the topology ID
    • MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId - Returns the topology ID
    • 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 - Créer un nouveau ReadPreference
    • MongoDB\Driver\Server::executeBulkWrite - Exécute une ou plusieurs opérations d'écriture sur ce serveur
    • MongoDB\Driver\Server::executeCommand - Exécute une commande de base de données sur ce serveur
    • MongoDB\Driver\Server::executeQuery - Exécute une requête de base de données sur ce serveur
    • 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 - Retourne le nom d'hôte du serveur
    • MongoDB\Driver\Server::getInfo - Retourne un tableau d'informations décrivant ce serveur
    • MongoDB\Driver\Server::getLatency - Retourne la latence de ce serveur en millisecondes
    • MongoDB\Driver\Server::getPort - Retourne le port sur lequel le serveur écoute
    • MongoDB\Driver\Server::getServerDescription - Returns a ServerDescription for this server
    • MongoDB\Driver\Server::getTags - Returns an array of tags describing this server in a replica set
    • MongoDB\Driver\Server::getType - Retourne un entier représentant le type du serveur
    • 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 - Vérifie si le serveur est un membre passif du jeu de réplication
    • 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 - Créer un nouveau serveur (non utilisé)
    • MongoDB\Driver\ServerApi::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ServerApi::serialize - Serialize a ServerApi
    • MongoDB\Driver\ServerApi::unserialize - Unserialize a ServerApi
    • MongoDB\Driver\ServerApi::__construct - Create a new ServerApi instance
    • MongoDB\Driver\ServerDescription::getHelloResponse - Returns the server's most recent "hello" response
    • MongoDB\Driver\ServerDescription::getHost - Returns the hostname of this server
    • MongoDB\Driver\ServerDescription::getLastUpdateTime - Returns the server's last update time in microseconds
    • MongoDB\Driver\ServerDescription::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\ServerDescription::getRoundTripTime - Returns the server's round trip time in milliseconds
    • MongoDB\Driver\ServerDescription::getType - Returns a string denoting the type of this server
    • MongoDB\Driver\Session::abortTransaction - Aborts a transaction
    • MongoDB\Driver\Session::advanceClusterTime - Advances the cluster time for this session
    • MongoDB\Driver\Session::advanceOperationTime - Advances the operation time for this session
    • MongoDB\Driver\Session::commitTransaction - Commits a transaction
    • MongoDB\Driver\Session::endSession - Terminates a session
    • MongoDB\Driver\Session::getClusterTime - Returns the cluster time for this session
    • MongoDB\Driver\Session::getLogicalSessionId - Returns the logical session ID for this session
    • MongoDB\Driver\Session::getOperationTime - Returns the operation time for this session
    • MongoDB\Driver\Session::getServer - Returns the server to which this session is pinned
    • MongoDB\Driver\Session::getTransactionOptions - Returns options for the currently running transaction
    • MongoDB\Driver\Session::getTransactionState - Returns the current transaction state for this session
    • MongoDB\Driver\Session::isDirty - Returns whether the session has been marked as dirty
    • MongoDB\Driver\Session::isInTransaction - Returns whether a multi-document transaction is in progress
    • MongoDB\Driver\Session::startTransaction - Starts a transaction
    • MongoDB\Driver\Session::__construct - Create a new Session (not used)
    • MongoDB\Driver\TopologyDescription::getServers - Returns the servers in the topology
    • MongoDB\Driver\TopologyDescription::getType - Returns a string denoting the type of this topology
    • MongoDB\Driver\TopologyDescription::hasReadableServer - Returns whether the topology has a readable server
    • MongoDB\Driver\TopologyDescription::hasWritableServer - Returns whether the topology has a writable server
    • 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 - Construit un WriteConcern
    • MongoDB\Driver\WriteConcernError::getCode - Retourne le code d'erreur de WriteConcernError
    • MongoDB\Driver\WriteConcernError::getInfo - Retourne le document de métadonnées pour WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage - Renvoie le message d'erreur du WriteConcernError
    • MongoDB\Driver\WriteError::getCode - Retourne le code d'erreur de WriteError
    • MongoDB\Driver\WriteError::getIndex - Retourne l'index de l'opération d'écriture correspondant à ce WriteError
    • MongoDB\Driver\WriteError::getInfo - Retourne le document de métadonnées pour WriteError
    • MongoDB\Driver\WriteError::getMessage - Renvoie le message d'erreur du WriteError
    • MongoDB\Driver\WriteResult::getDeletedCount - Renvoie le nombre de documents supprimés
    • MongoDB\Driver\WriteResult::getInsertedCount - Renvoie le nombre de documents insérés (à l'exception de Upserts)
    • MongoDB\Driver\WriteResult::getMatchedCount - Renvoie le nombre de documents sélectionnés pour la mise à jour
    • MongoDB\Driver\WriteResult::getModifiedCount - Renvoie le nombre de documents existants mis à jour
    • MongoDB\Driver\WriteResult::getServer - Retourne le serveur associé à ce résultat d'écriture
    • MongoDB\Driver\WriteResult::getUpsertedCount - Renvoie le nombre de documents insérés par un upsert
    • MongoDB\Driver\WriteResult::getUpsertedIds - Retourne un tableau d'identificateurs pour les documents upserted
    • MongoDB\Driver\WriteResult::getWriteConcernError - Retourne toute erreur de WriteConcern qui s'est produite
    • MongoDB\Driver\WriteResult::getWriteErrors - Retourne toutes les erreurs d'écriture qui se sont produites
    • MongoDB\Driver\WriteResult::isAcknowledged - Retourne si l'écriture a été reconnue
    • move_uploaded_file - Déplace un fichier téléchargé
    • 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 - Retourne le message d'erreur correspondant au code de résultat
    • msg_get_queue - Crée ou s'attache à une file de messages
    • msg_queue_exists - Vérifie si une file de messages existe
    • msg_receive - Reçoit un message depuis une file de messages
    • msg_remove_queue - Détruit une file de messages
    • msg_send - Envoie un message dans une file
    • msg_set_queue - Modifie des informations dans la file de messages
    • msg_stat_queue - Retourne des informations sur la file de messages
    • mt_getrandmax - La plus grande valeur aléatoire possible
    • mt_rand - Génère une valeur aléatoire via le générateur de nombre aléatoire Mersenne Twister
    • mt_srand - Initialise le générateur de nombres aléatoires Mersenne Twister
    • MultipleIterator::attachIterator - Attache un itérateur
    • MultipleIterator::containsIterator - Vérifie si un itérateur est attaché
    • MultipleIterator::countIterators - Récupère le nombre d'instances d'itérateurs attachés
    • MultipleIterator::current - Récupère les instantes des itérateurs attachés
    • MultipleIterator::detachIterator - Détache un itérateur
    • MultipleIterator::getFlags - Récupère les informations d'un drapeau
    • MultipleIterator::key - Récupère les instances des itérateurs enregistrés
    • MultipleIterator::next - Déplace vers l'avant toutes les instances des itérateurs attachés
    • MultipleIterator::rewind - Réinitialise toutes les instances d'itérateurs attachés
    • MultipleIterator::setFlags - Définit des drapeaux
    • MultipleIterator::valid - Vérifie la validité d'un sous-itérateur
    • MultipleIterator::__construct - Construit un nouvel objet MultipleIterator
    • mysqli::$affected_rows - Retourne le nombre de lignes affectées par la dernière opération MySQL
    • mysqli::$client_info - Récupère des informations sur le client MySQL
    • mysqli::$client_version - Retourne la version du client MySQL sous forme d'un entier
    • mysqli::$connect_errno - Retourne le code d'erreur du dernier appel de connexion
    • mysqli::$connect_error - Retourne une description de la dernière erreur de connexion
    • mysqli::$errno - Retourne le dernier code d'erreur produit
    • mysqli::$error - Retourne une chaîne décrivant la dernière erreur
    • mysqli::$error_list - Retourne une liste d'erreur depuis la dernière commande exécutée
    • mysqli::$field_count - Retourne le nombre de colonnes pour la dernière requête
    • mysqli::$host_info - Retourne une chaîne contenant le type de connexion utilisée
    • mysqli::$info - Retourne des informations à propos de la dernière requête exécutée
    • mysqli::$insert_id - Retourne la valeur généré pour une colonne AUTO_INCREMENT par la dernière requête
    • mysqli::$protocol_version - Retourne la version du protocole MySQL utilisé
    • mysqli::$server_info - Retourne la version du serveur MySQL
    • mysqli::$server_version - Retourne un entier représentant la version du serveur MySQL
    • mysqli::$sqlstate - Retourne l'erreur SQLSTATE de la dernière opération MySQL
    • mysqli::$thread_id - Retourne l'identifiant du thread pour la connexion courante
    • mysqli::$warning_count - Retourne le nombre d'avertissements générés par la dernière requête
    • mysqli::autocommit - Active ou désactive le mode auto-commit
    • mysqli::begin_transaction - Démarre une transaction
    • mysqli::change_user - Change l'utilisateur de la connexion spécifiée
    • mysqli::character_set_name - Retourne le jeu de caractères courant pour la connexion
    • mysqli::close - Ferme une connexion
    • mysqli::commit - Valide la transaction courante
    • mysqli::debug - Effectue des actions de débogage
    • mysqli::dump_debug_info - Écrit les informations de débogage dans les logs
    • mysqli::escape_string - Alias de mysqli_real_escape_string
    • mysqli::execute_query - Prepares, binds parameters, and executes SQL statement
    • mysqli::get_charset - Retourne un objet représentant le jeu de caractères
    • mysqli::get_connection_stats - Retourne des statistiques sur la connexion
    • mysqli::get_warnings - Lit le résultat de SHOW WARNINGS
    • mysqli::init - Initialise MySQLi et retourne un objet à utiliser avec mysqli_real_connect()
    • mysqli::kill - Demande au serveur de terminer un thread MySQL
    • mysqli::more_results - Vérifie s'il y a d'autres jeux de résultats MySQL disponibles
    • mysqli::multi_query - Exécute une ou plusieurs requêtes sur la base de donnée
    • mysqli::next_result - Prépare le prochain résultat d'une requête multiple
    • mysqli::options - Définit les options
    • mysqli::ping - Ping la connexion au serveur et reconnecte si elle n'existe plus
    • mysqli::poll - Vérifie l'état de la connexion
    • mysqli::prepare - Prépare une requête SQL pour l'exécution
    • mysqli::query - Exécute une requête sur la base de données
    • mysqli::real_connect - Ouvre une connexion à un serveur MySQL
    • mysqli::real_escape_string - Protège les caractères spéciaux d'une chaîne pour l'utiliser dans une requête SQL, en prenant en compte le jeu de caractères courant de la connexion
    • mysqli::real_query - Exécute une requête SQL
    • mysqli::reap_async_query - Lit un résultat pour une requête asynchrone
    • mysqli::refresh - Rafraîchie
    • mysqli::release_savepoint - Supprime le point de sauvegardé nommé du jeu des points de sauvegarde de la transaction courante
    • mysqli::rollback - Annule la transaction courante
    • mysqli::savepoint - Définit un point de sauvegarde nommé de la transaction
    • mysqli::select_db - Sélectionne une base de données par défaut pour les requêtes
    • mysqli::set_charset - Définit le jeu de caractères du client
    • mysqli::set_opt - Alias de mysqli_options
    • mysqli::ssl_set - Utilisée pour établir une connexion sécurisée avec SSL
    • mysqli::stat - Obtient le statut courant du système
    • mysqli::stmt_init - Initialise une commande MySQL
    • mysqli::store_result - Transfère un jeu de résultats à partir de la dernière requête
    • mysqli::thread_safe - Indique si le support des threads est activé ou pas
    • mysqli::use_result - Initialise la récupération d'un jeu de résultats
    • mysqli::__construct - Ouvre une connexion à un serveur MySQL
    • mysqli_connect - Alias de mysqli::__construct
    • mysqli_driver::$report_mode - Définit le mode du rapport d'erreur mysqli
    • mysqli_driver::embedded_server_end - Arrête le serveur embarqué
    • mysqli_driver::embedded_server_start - Initialise et démarre le serveur embarqué
    • mysqli_execute - Alias de mysqli_stmt_execute
    • mysqli_get_client_stats - Retourne les statistiques client par processus
    • mysqli_get_links_stats - Retourne des informations sur les liens ouverts et mis en cache
    • mysqli_report - Alias de mysqli_driver->report_mode
    • mysqli_result::$current_field - Récupère la position courante d'un champ dans un pointeur de résultat
    • mysqli_result::$field_count - Récupère le nombre de champs dans l'ensemble de résultats
    • mysqli_result::$lengths - Retourne la longueur des colonnes de la ligne courante du jeu de résultats
    • mysqli_result::$num_rows - Retourne le nombre de lignes dans le jeu de résultats
    • mysqli_result::data_seek - Déplace le pointeur interne de résultat
    • mysqli_result::fetch_all - Récupère toutes les lignes de résultats dans un tableau associatif, numérique, ou les deux
    • mysqli_result::fetch_array - Récupère la ligne suivante d'un ensemble de résultats sous forme de tableau associatif, numérique ou les deux
    • mysqli_result::fetch_assoc - Récupère la ligne suivante d'un ensemble de résultats sous forme de tableau associatif
    • mysqli_result::fetch_column - Fetch a single column from the next row of a result set
    • mysqli_result::fetch_field - Retourne le prochain champs dans le jeu de résultats
    • mysqli_result::fetch_fields - Retourne un tableau d'objets représentant les champs dans le résultat
    • mysqli_result::fetch_field_direct - Récupère les métadonnées d'un champ unique
    • mysqli_result::fetch_object - Retourne la ligne suivante d'un ensemble de résultats sous forme d'objet
    • mysqli_result::fetch_row - Récupère une ligne de résultat sous forme de tableau indexé
    • mysqli_result::field_seek - Déplace le pointeur de résultat sur le champ spécifié
    • mysqli_result::free - Libère la mémoire associée à un résultat
    • mysqli_result::getIterator - Retrieve an external iterator
    • mysqli_result::__construct - Constructs a mysqli_result object
    • mysqli_sql_exception::getSqlState - Returns the SQLSTATE error code
    • mysqli_stmt::$affected_rows - Retourne le nombre total de lignes modifiées, effacées insérées, ou correspondant par la dernière requête
    • mysqli_stmt::$errno - Retourne un code erreur pour la dernière requête
    • mysqli_stmt::$error - Retourne une description de la dernière erreur de traitement
    • mysqli_stmt::$error_list - Retourne une liste d'erreurs pour la dernière requête exécutée
    • mysqli_stmt::$field_count - Retourne le nombre de colonnes dans la requête donnée
    • mysqli_stmt::$insert_id - Récupère l'ID généré par la dernière requête INSERT
    • mysqli_stmt::$num_rows - Retourne le nombre de lignes extraites du serveur
    • mysqli_stmt::$param_count - Retourne le nombre de paramètres d'une commande SQL
    • mysqli_stmt::$sqlstate - Retourne le code SQLSTATE de la dernière opération MySQL
    • mysqli_stmt::attr_get - Récupère la valeur courante d'un attribut de requête
    • mysqli_stmt::attr_set - Modifie le comportement d'une requête préparée
    • mysqli_stmt::bind_param - Lie des variables à une requête MySQL
    • mysqli_stmt::bind_result - Lie des variables à un jeu de résultats
    • mysqli_stmt::close - Termine une requête préparée
    • mysqli_stmt::data_seek - Ajuste le pointeur de résultat vers une ligne arbitraire dans le résultat mis en mémoire tampon.
    • mysqli_stmt::execute - Exécute une requête préparée
    • mysqli_stmt::fetch - Lit des résultats depuis une requête MySQL préparée dans des variables liées
    • mysqli_stmt::free_result - Libère le résultat MySQL de la mémoire
    • mysqli_stmt::get_result - Récupère un jeu de résultats depuis une requête préparée en tant qu'objet mysqli_result
    • mysqli_stmt::get_warnings - Récupère le résultat de SHOW WARNINGS
    • mysqli_stmt::more_results - Vérifie s'il y a encore des résultats depuis une requête multiple
    • mysqli_stmt::next_result - Lit le résultat suivant depuis une requête multiple
    • mysqli_stmt::prepare - Prépare une requête SQL pour l'exécution
    • mysqli_stmt::reset - Annule une requête préparée
    • mysqli_stmt::result_metadata - Retourne les métadonnées de préparation de requête MySQL
    • mysqli_stmt::send_long_data - Envoie des données MySQL par paquets
    • mysqli_stmt::store_result - Stocke un ensemble de résultats dans un tampon interne
    • mysqli_stmt::__construct - Construit un nouvel objet mysqli_stmt
    • mysqli_warning::next - Récupère le prochain avertissement
    • mysqli_warning::__construct - Private constructor to disallow direct instantiation
    • mysql_affected_rows - Retourne le nombre de lignes affectées lors de la dernière opération MySQL
    • mysql_client_encoding - Retourne le nom du jeu de caractères utilisé par le client MySQL
    • mysql_close - Ferme la connexion MySQL
    • mysql_connect - Ouvre une connexion à un serveur MySQL
    • mysql_create_db - Crée une base de données MySQL
    • mysql_data_seek - Déplace le pointeur interne de résultat MySQL
    • mysql_db_name - Récupère le nom de base de données à l'appel de mysql_list_dbs
    • mysql_db_query - Sélectionne une base de données et y exécute une requête
    • mysql_drop_db - Efface une base de données MySQL
    • mysql_errno - Retourne le numéro d'erreur de la dernière commande MySQL
    • mysql_error - Retourne le texte associé avec l'erreur générée lors de la dernière requête
    • mysql_escape_string - Protège les caractères spéciaux SQL
    • mysql_fetch_array - Retourne une ligne de résultat MySQL sous la forme d'un tableau associatif, d'un tableau indexé, ou les deux
    • mysql_fetch_assoc - Lit une ligne de résultat MySQL dans un tableau associatif
    • mysql_fetch_field - Retourne les données enregistrées dans une colonne MySQL sous forme d'objet
    • mysql_fetch_lengths - Retourne la taille de chaque colonne d'une ligne de résultat MySQL
    • mysql_fetch_object - Retourne une ligne de résultat MySQL sous la forme d'un objet
    • mysql_fetch_row - Retourne une ligne de résultat MySQL sous la forme d'un tableau
    • mysql_field_flags - Retourne des détails sur une colonne MySQL
    • mysql_field_len - Retourne la taille d'un champ de résultat MySQL
    • mysql_field_name - Retourne le nom d'une colonne dans un résultat MySQL
    • mysql_field_seek - Déplace le pointeur de résultat vers une position donnée
    • mysql_field_table - Retourne le nom de la table MySQL où se trouve une colonne
    • mysql_field_type - Retourne le type d'une colonne MySQL spécifique
    • mysql_free_result - Libère le résultat de la mémoire
    • mysql_get_client_info - Lit les informations sur le client MySQL
    • mysql_get_host_info - Lit les informations sur l'hôte MySQL
    • mysql_get_proto_info - Lit les informations sur le protocole MySQL
    • mysql_get_server_info - Lit les informations sur le serveur MySQL
    • mysql_info - Lit des informations à propos de la dernière requête MySQL
    • mysql_insert_id - Retourne l'identifiant généré par la dernière requête
    • mysql_list_dbs - Liste les bases de données disponibles sur le serveur MySQL
    • mysql_list_fields - Liste les champs d'une table MySQL
    • mysql_list_processes - Liste les processus MySQL
    • mysql_list_tables - Liste les tables d'une base de données MySQL
    • mysql_num_fields - Retourne le nombre de champs d'un résultat MySQL
    • mysql_num_rows - Retourne le nombre de lignes d'un résultat MySQL
    • mysql_pconnect - Ouvre une connexion persistante à un serveur MySQL
    • mysql_ping - Vérifie la connexion au serveur MySQL, et s'y reconnecte au besoin
    • mysql_query - Envoie une requête à un serveur MySQL
    • mysql_real_escape_string - Protège une commande SQL de la présence de caractères spéciaux
    • mysql_result - Retourne un champ d'un résultat MySQL
    • mysql_select_db - Sélectionne une base de données MySQL
    • mysql_set_charset - Définit le jeu de caractères du client MySQL
    • mysql_stat - Retourne le statut courant du serveur MySQL
    • mysql_tablename - Lit le nom de la table qui contient un champ
    • mysql_thread_id - Retourne l'identifiant du thread MySQL courant
    • mysql_unbuffered_query - Exécute une requête SQL sans mobiliser les résultats MySQL
    • mysql_xdevapi\Client::close - Close client
  • n
    • natcasesort - Trie un tableau avec l'algorithme à "ordre naturel" insensible à la casse
    • natsort - Trie un tableau avec l'algorithme à "ordre naturel"
    • net_get_interfaces - Get network interfaces
    • next - Avance le pointeur interne d'un tableau
    • ngettext - Version plurielle de gettext
    • nl2br - Insère un retour à la ligne HTML à chaque nouvelle ligne
    • nl_langinfo - Rassemble des informations sur la langue et la configuration locale
    • NoRewindIterator::current - Récupère la valeur courante
    • NoRewindIterator::key - Récupère la clé courante
    • NoRewindIterator::next - Se déplace vers le prochain élément
    • NoRewindIterator::rewind - Réinitialise l'itérateur interne
    • NoRewindIterator::valid - Valide un itérateur
    • NoRewindIterator::__construct - Construit un nouvel objet NoRewindIterator
    • Normalizer::getRawDecomposition - Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
    • Normalizer::isNormalized - Vérifie si une chaîne est normalisée
    • Normalizer::normalize - Normalise une chaîne en entrée
    • NumberFormatter::create - Crée un formateur de nombre
    • NumberFormatter::format - Formate un nombre
    • NumberFormatter::formatCurrency - Formate une valeur monétaire
    • NumberFormatter::getAttribute - Lit un attribut
    • NumberFormatter::getErrorCode - Lit le dernier code d'erreur du formateur
    • NumberFormatter::getErrorMessage - Lit le dernier message d'erreur du formateur
    • NumberFormatter::getLocale - Lit la locale du formateur
    • NumberFormatter::getPattern - Lit le modèle du formateur
    • NumberFormatter::getSymbol - Lit la valeur du symbole
    • NumberFormatter::getTextAttribute - Lit un attribut textuel
    • NumberFormatter::parse - Analyse un nombre
    • NumberFormatter::parseCurrency - Analyse un nombre monétaire
    • NumberFormatter::setAttribute - Affecte un attribut du formateur
    • NumberFormatter::setPattern - Configure le modèle du formateur
    • NumberFormatter::setSymbol - Configure le symbole du formateur
    • NumberFormatter::setTextAttribute - Modifie un attribut texte
    • number_format - Formate un nombre pour l'affichage
  • o
    • OAuth::disableDebug - Désactive les messages de déboguage
    • OAuth::disableRedirects - Désactive les redirections
    • OAuth::disableSSLChecks - Désactive la vérification SSL
    • OAuth::enableDebug - Active les messages de débogage
    • OAuth::enableRedirects - Active les redirections
    • OAuth::enableSSLChecks - Active la vérification SSL
    • OAuth::fetch - Lit une ressource protégée par OAuth
    • OAuth::generateSignature - Génère une signature
    • OAuth::getAccessToken - Récupère un token d'accès
    • OAuth::getCAPath - Récupère l'information CA
    • OAuth::getLastResponse - Lit la dernière réponse
    • OAuth::getLastResponseHeaders - Récupère les en-têtes de la dernière réponse
    • OAuth::getLastResponseInfo - Lit les informations HTTP de la dernière réponse
    • OAuth::getRequestHeader - Génère une signature d'en-tête OAuth
    • OAuth::getRequestToken - Lit le token de requête
    • OAuth::setAuthType - Définit le type d'autorisation
    • OAuth::setCAPath - Définit le chemin et les informations du CA
    • OAuth::setNonce - Configure le nonce OAuth
    • OAuth::setRequestEngine - Le but de setRequestEngine
    • OAuth::setRSACertificate - Définit le certificat RSA
    • OAuth::setSSLChecks - Définit des vérifications spécifiques à SSL pour les requêtes
    • OAuth::setTimestamp - Définit le timestamp
    • OAuth::setToken - Configure le token et le secret
    • OAuth::setVersion - Configure la version OAuth
    • OAuth::__construct - Crée un nouvel objet OAuth
    • OAuth::__destruct - Le destructeur
    • OAuthProvider::addRequiredParameter - Ajoute des paramètres requis
    • OAuthProvider::callconsumerHandler - Appelle la fonction de rappel consumerNonceHandler
    • OAuthProvider::callTimestampNonceHandler - Appelle la fonction de rappel timestampNonceHandler
    • OAuthProvider::calltokenHandler - Appelle la fonction de rappel tokenNonceHandler
    • OAuthProvider::checkOAuthRequest - Vérifie une requête OAuth
    • OAuthProvider::consumerHandler - Définit la fonction de rappel consumerHandler
    • OAuthProvider::generateToken - Génère un jeton aléatoire
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - Définit isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - Supprime un paramètre
    • OAuthProvider::reportProblem - Rapporte un problème
    • OAuthProvider::setParam - Définit un paramètre
    • OAuthProvider::setRequestTokenPath - Définit le chemin du jeton demandé
    • OAuthProvider::timestampNonceHandler - Définit le gestionnaire de rappel timestampNonceHandler
    • OAuthProvider::tokenHandler - Définit le gestionnaire de rappel tokenHandler
    • OAuthProvider::__construct - Construit un nouvel objet OAuthProvider
    • oauth_get_sbs - Génère une chaîne de base de signature
    • oauth_urlencode - Encode une URI conformément à RFC 3986
    • ob_clean - Efface le tampon de sortie
    • ob_end_clean - Détruit les données du tampon de sortie et éteint la temporisation de sortie
    • ob_end_flush - Envoie les données du tampon de sortie et éteint la temporisation de sortie
    • ob_flush - Envoie le tampon de sortie
    • ob_get_clean - Lit le contenu courant du tampon de sortie puis l'efface
    • ob_get_contents - Retourne le contenu du tampon de sortie
    • ob_get_flush - Vide le tampon, le retourne en tant que chaîne et stoppe la temporisation
    • ob_get_length - Retourne la longueur du contenu du tampon de sortie
    • ob_get_level - Retourne le nombre de niveaux d'imbrications du système de temporisation de sortie
    • ob_get_status - Lit le statut du tampon de sortie
    • ob_gzhandler - Fonction de rappel pour la compression automatique des tampons
    • ob_iconv_handler - Gestionnaire de sortie pour maîtriser le jeu de caractères de sortie
    • ob_implicit_flush - Active/désactive l'envoi implicite
    • ob_list_handlers - Liste les gestionnaires d'affichage utilisés
    • ob_start - Enclenche la temporisation de sortie
    • ob_tidyhandler - Fonction de rappel ob_start pour réparer le buffer
    • ocibindbyname - Alias de oci_bind_by_name
    • ocicancel - Alias de oci_cancel
    • ocicloselob - Alias de OCILob::close
    • ocicollappend - Alias de OCICollection::append
    • ocicollassign - Alias de OCICollection::assign
    • ocicollassignelem - Alias de OCICollection::assignElem
    • OCICollection::append - Ajoute un élément à une collection Oracle
    • OCICollection::assign - Assigne une valeur à une collection depuis une autre collection Oracle
    • OCICollection::assignElem - Assigne une valeur à un élément d'une collection Oracle
    • OCICollection::free - Libère les ressources associées avec un objet de collection
    • OCICollection::getElem - Retourne la valeur d'un élément d'une collection Oracle
    • OCICollection::max - Retourne le nombre maximal de valeurs d'une collection Oracle
    • OCICollection::size - Retourne la taille d'une collection Oracle
    • OCICollection::trim - Supprime les derniers éléments d'une collection Oracle
    • ocicollgetelem - Alias de OCICollection::getElem
    • ocicollmax - Alias de OCICollection::max
    • ocicollsize - Alias de OCICollection::size
    • ocicolltrim - Alias de OCICollection::trim
    • ocicolumnisnull - Alias de oci_field_is_null
    • ocicolumnname - Alias de oci_field_name
    • ocicolumnprecision - Alias de oci_field_precision
    • ocicolumnscale - Alias de oci_field_scale
    • ocicolumnsize - Alias de oci_field_size
    • ocicolumntype - Alias de oci_field_type
    • ocicolumntyperaw - Alias de oci_field_type_raw
    • ocicommit - Alias de oci_commit
    • ocidefinebyname - Alias de oci_define_by_name
    • ocierror - Alias de oci_error
    • ociexecute - Alias de oci_execute
    • ocifetch - Alias de oci_fetch
    • ocifetchinto - Variante obsolète de la fonction oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
    • ocifetchstatement - Alias de oci_fetch_all
    • ocifreecollection - Alias de OCICollection::free
    • ocifreecursor - Alias de oci_free_statement
    • ocifreedesc - Alias de OCILob::free
    • ocifreestatement - Alias de oci_free_statement
    • ociinternaldebug - Alias de oci_internal_debug
    • ociloadlob - Alias de OCILob::load
    • OCILob::append - Ajoute des données à un LOB Oracle
    • OCILob::close - Ferme un LOB Oracle
    • OCILob::eof - Test la fin du LOB Oracle
    • OCILob::erase - Écrase une partie d'un LOB Oracle
    • OCILob::export - Exporte un LOB Oracle dans un fichier
    • OCILob::flush - Écrit les LOB Oracle sur le disque
    • OCILob::free - Détruit un pointeur de LOB Oracle
    • OCILob::getBuffering - Retourne l'état de bufferisation LOB d'Oracle
    • OCILob::import - Importe un fichier dans LOB Oracle
    • OCILob::load - Retourne le contenu d'un LOB
    • OCILob::read - Lit une partie d'un LOB Oracle
    • OCILob::rewind - Ramène le pointeur interne d'un LOB Oracle au début
    • OCILob::save - Sauvegarde des données dans un LOB Oracle
    • OCILob::saveFile - Alias de OCILob::import
    • OCILob::seek - Déplace le pointeur interne d'un LOB Oracle
    • OCILob::setBuffering - Active/désactive la bufferisation des LOB Oracle
    • OCILob::size - Retourne la taille d'un LOB Oracle
    • OCILob::tell - Retourne la position courante du pointeur de LOB
    • OCILob::truncate - Tronque un LOB Oracle
    • OCILob::write - Écrit des données dans un LOB Oracle
    • OCILob::writeTemporary - Écrit un LOB Oracle temporaire
    • OCILob::writeToFile - Alias de OCILob::export
    • ocilogoff - Alias de oci_close
    • ocilogon - Alias de oci_connect
    • ocinewcollection - Alias de oci_new_collection
    • ocinewcursor - Alias de oci_new_cursor
    • ocinewdescriptor - Alias de oci_new_descriptor
    • ocinlogon - Alias de oci_new_connect
    • ocinumcols - Alias de oci_num_fields
    • ociparse - Alias de oci_parse
    • ociplogon - Alias de oci_pconnect
    • ociresult - Alias de oci_result
    • ocirollback - Alias de oci_rollback
    • ocirowcount - Alias de oci_num_rows
    • ocisavelob - Alias de OCILob::save
    • ocisavelobfile - Alias de OCILob::import
    • ociserverversion - Alias de oci_server_version
    • ocisetprefetch - Alias de oci_set_prefetch
    • ocistatementtype - Alias de oci_statement_type
    • ociwritelobtofile - Alias de OCILob::export
    • ociwritetemporarylob - Alias de OCILob::writeTemporary
    • oci_bind_array_by_name - Lie un tableau PHP à un paramètre de tableau Oracle PL/SQL
    • oci_bind_by_name - Associe une variable PHP à un marqueur Oracle
    • oci_cancel - Termine la lecture de curseurs Oracle
    • oci_client_version - Retourne la version de la bibliothèque cliente Oracle
    • oci_close - Ferme une connexion Oracle
    • oci_commit - Valide les transactions Oracle en cours
    • oci_connect - Établit une connexion avec un serveur Oracle
    • oci_define_by_name - Associe une variable PHP avec une colonne pour une requête de récupération de données
    • oci_error - Retourne la dernière erreur Oracle
    • oci_execute - Exécute une commande SQL Oracle
    • oci_fetch - Lit la prochaine ligne d'un résultat Oracle dans un buffer interne
    • oci_fetch_all - Lit plusieurs lignes d'un résultat dans un tableau multidimensionnel
    • oci_fetch_array - Lit une ligne d'un résultat sous forme de tableau associatif ou numérique
    • oci_fetch_assoc - Lit une ligne d'un résultat sous forme de tableau associatif
    • oci_fetch_object - Lit une ligne d'un résultat sous forme d'objet
    • oci_fetch_row - Lit la prochaine ligne d'une requête sous forme de tableau numérique
    • oci_field_is_null - Test si un champ de la ligne récupérée vaut null
    • oci_field_name - Retourne le nom d'un champ Oracle
    • oci_field_precision - Lit la précision d'un champ Oracle
    • oci_field_scale - Lit l'échelle d'une colonne Oracle
    • oci_field_size - Retourne la taille d'un champ Oracle
    • oci_field_type - Retourne le type de données d'un champ Oracle
    • oci_field_type_raw - Lit les données brutes du type d'un champ
    • oci_free_descriptor - Libère un descripteur
    • oci_free_statement - Libère toutes les ressources réservées par un résultat Oracle
    • oci_get_implicit_resultset - Retourne le fils suivant d'une ressource de requête depuis une ressource de requête parent qui a un jeu de résultat implicite Oracle Database
    • oci_internal_debug - Enables or disables internal debug output
    • oci_lob_copy - Copie un LOB Oracle
    • oci_lob_is_equal - Compare deux LOB/FILE Oracle
    • oci_new_collection - Initialise une nouvelle collection Oracle
    • oci_new_connect - Connexion au serveur Oracle en utilisant une seule connexion
    • oci_new_cursor - Alloue et retourne un nouveau curseur Oracle
    • oci_new_descriptor - Initialise un nouveau pointeur vide de LOB/FILE Oracle
    • oci_num_fields - Retourne le nombre de colonnes dans un résultat Oracle
    • oci_num_rows - Retourne le nombre de lignes affectées durant la dernière commande Oracle
    • oci_parse - Prépare une requête SQL avec Oracle
    • oci_password_change - Modifie le mot de passe d'un utilisateur Oracle
    • oci_pconnect - Ouvre une connexion persistante à un serveur Oracle
    • oci_register_taf_callback - Register a user-defined callback function for Oracle Database TAF
    • oci_result - Retourne la valeur d'une colonne dans un résultat Oracle
    • oci_rollback - Annule les transactions Oracle en cours
    • oci_server_version - Retourne la version du serveur Oracle
    • oci_set_action - Définit le nom de l'action
    • oci_set_call_timeout - Sets a millisecond timeout for database calls
    • oci_set_client_identifier - Définit l'identifiant du client
    • oci_set_client_info - Définit l'information concernant le client
    • oci_set_db_operation - Sets the database operation
    • oci_set_edition - Définit l'édition de la base de données
    • oci_set_module_name - Définit le nom du module
    • oci_set_prefetch - Indique le nombre de lignes qui doivent être lues à l'avance par Oracle
    • oci_set_prefetch_lob - Sets the amount of data prefetched for each CLOB or BLOB.
    • oci_statement_type - Retourne le type de la requête Oracle
    • oci_unregister_taf_callback - Unregister a user-defined callback function for Oracle Database TAF
    • octdec - Conversion d'octal en décimal
    • odbc_autocommit - Active le mode d'autovalidation
    • odbc_binmode - Modifie la gestion des colonnes de données binaires
    • odbc_close - Ferme une connexion ODBC
    • odbc_close_all - Ferme toutes les connexions ODBC
    • odbc_columnprivileges - Liste les colonnes et leurs droits associés
    • odbc_columns - Liste les colonnes d'une table
    • odbc_commit - Valide une transaction ODBC
    • odbc_connect - Connexion à une source
    • odbc_connection_string_is_quoted - Determines if an ODBC connection string value is quoted
    • odbc_connection_string_quote - Quotes an ODBC connection string value
    • odbc_connection_string_should_quote - Determines if an ODBC connection string value should be quoted
    • odbc_cursor - Lit le nom du pointeur de résultat courant
    • odbc_data_source - Retourne des informations sur les DSNs disponibles
    • odbc_do - Alias de odbc_exec
    • odbc_error - Lit le dernier code d'erreur
    • odbc_errormsg - Lit le dernier message d'erreur
    • odbc_exec - Exécute directement une requête SQL
    • odbc_execute - Exécute une requête SQL préparée
    • odbc_fetch_array - Lit une ligne de résultat dans un tableau associatif
    • odbc_fetch_into - Lit une ligne de résultat, et la place dans un tableau
    • odbc_fetch_object - Lit une ligne de résultat dans un objet
    • odbc_fetch_row - Lit une ligne de résultat
    • odbc_field_len - Lit la longueur d'un champ
    • odbc_field_name - Lit le nom de la colonne
    • odbc_field_num - Numéro de colonne
    • odbc_field_precision - Alias de odbc_field_len
    • odbc_field_scale - Lit l'échelle d'un champ
    • odbc_field_type - Type de données d'un champ
    • odbc_foreignkeys - Liste les clés étrangères
    • odbc_free_result - Libère les ressources associées à un résultat
    • odbc_gettypeinfo - Liste les types de données supportés par une source
    • odbc_longreadlen - Gestion des colonnes de type LONG
    • odbc_next_result - Vérifie si plusieurs résultats sont disponibles
    • odbc_num_fields - Nombre de colonnes dans un résultat
    • odbc_num_rows - Nombre de lignes dans un résultat
    • odbc_pconnect - Ouvre une connexion persistante à une source de données
    • odbc_prepare - Prépare une commande pour l'exécution
    • odbc_primarykeys - Liste les colonnes utilisées dans une clé primaire
    • odbc_procedurecolumns - Liste les paramètres des procédures
    • odbc_procedures - Liste les procédures stockées
    • odbc_result - Lit un champ de résultat UODBC
    • odbc_result_all - Affiche le résultat sous la forme d'une table HTML
    • odbc_rollback - Annule une transaction
    • odbc_setoption - Modifie les paramètres ODBC
    • odbc_specialcolumns - Retourne l'ensemble optimal de colonnes
    • odbc_statistics - Calcul des statistiques sur une table
    • odbc_tableprivileges - Liste les tables et leurs privilèges
    • odbc_tables - Liste les tables d'une source
    • ogg:// - Flux Audio
    • opcache_compile_file - Compile et met en cache un script PHP sans l'exécuter
    • opcache_get_configuration - Récupère les informations de configuration du cache
    • opcache_get_status - Récupère les informations de statut du cache
    • opcache_invalidate - Invalide un script mis en cache
    • opcache_is_script_cached - Indique si un script est dans le cache d'OPCache
    • opcache_reset - Ré-initialise le contenu du cache opcode
    • openal_buffer_create - Génère un buffer OpenAL
    • openal_buffer_data - Charge un buffer avec des données
    • openal_buffer_destroy - Détruit un buffer OpenAL
    • openal_buffer_get - Récupère les propriétés du buffer OpenAL
    • openal_buffer_loadwav - Charge un fichier .wav dans le buffer
    • openal_context_create - Crée un contexte de traitement audio
    • openal_context_current - Rend courant le contexte spécifié
    • openal_context_destroy - Détruit un contexte
    • openal_context_process - Traite le contexte spécifié
    • openal_context_suspend - Suspend le contexte spécifié
    • openal_device_close - Ferme un périphérique OpenAL
    • openal_device_open - Initialise une interface audio OpenAL
    • openal_listener_get - Récupère une propriété d'auditeur
    • openal_listener_set - Définie une propriété d'auditeur
    • openal_source_create - Génère une ressource de source
    • openal_source_destroy - Détruit une ressource de source
    • openal_source_get - Récupère une propriété de source OpenAL
    • openal_source_pause - Marque une pause dans la source
    • openal_source_play - Démarre la lecture de la source
    • openal_source_rewind - Revient en arrière dans la source
    • openal_source_set - Définie une propriété de la source
    • openal_source_stop - Arrête la lecture de la source
    • openal_stream - Démarre le streaming d'une source
    • opendir - Ouvre un dossier, et récupère un pointeur dessus
    • openlog - Ouvre la connexion à l'historique système
    • openssl_cipher_iv_length - Récupère la longueur cipher iv
    • openssl_cipher_key_length - Gets the cipher key length
    • 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 - Exporte un CSR vers un fichier ou une variable
    • openssl_csr_export_to_file - Exporte une CSR vers un fichier
    • openssl_csr_get_public_key - Retourne la clé publique d'un CSR
    • openssl_csr_get_subject - Retourne le sujet d'une CSR
    • openssl_csr_new - Génère une CSR
    • openssl_csr_sign - Signe un CSR avec un autre certificat (ou lui-même) et génère un certificat
    • openssl_decrypt - Déchiffrer les données
    • openssl_dh_compute_key - Calcule un secret partagé pour une valeur publique de la clé DH publique distante et la clé DH locale
    • openssl_digest - Calcule un digest
    • openssl_encrypt - Chiffre les données
    • openssl_error_string - Retourne le message d'erreur OpenSSL
    • openssl_free_key - Libère les ressources
    • openssl_get_cert_locations - Récupère les chemins vers les certificats disponibles
    • openssl_get_cipher_methods - Récupère la liste des méthodes de chiffrements disponibles
    • openssl_get_curve_names - Récupère la liste des noms de courbes disponibles pour ECC
    • openssl_get_md_methods - Récupère la liste des méthodes digest disponibles
    • openssl_get_privatekey - Alias de openssl_pkey_get_private
    • openssl_get_publickey - Alias de openssl_pkey_get_public
    • openssl_open - Ouvre des données scellées
    • openssl_pbkdf2 - Génère une chaîne PKCS5 v2 PBKDF2
    • openssl_pkcs7_decrypt - Déchiffre un message S/MIME
    • openssl_pkcs7_encrypt - Chiffre un message S/MIME
    • openssl_pkcs7_read - Exporte le fichier PKCS7 vers un tableau de certificats PEM
    • openssl_pkcs7_sign - Signe un message S/MIME
    • openssl_pkcs7_verify - Vérifie la signature d'un message S/MIME
    • openssl_pkcs12_export - Exporte un certificat compatible PKCS#12 dans une variable
    • openssl_pkcs12_export_to_file - Exporte un certificat compatible PKCS#12
    • openssl_pkcs12_read - Lit un certificat PKCS#12 dans un tableau
    • openssl_pkey_derive - Computes shared secret for public value of remote and local DH or ECDH key
    • openssl_pkey_export - Stocke une représentation exportable de la clé dans une chaîne de caractères
    • openssl_pkey_export_to_file - Sauve une clé au format ASCII dans un fichier
    • openssl_pkey_free - Libère une clé privée
    • openssl_pkey_get_details - Retourne un tableau contenant les détails de la clé
    • openssl_pkey_get_private - Lit une clé privée
    • openssl_pkey_get_public - Extrait une clé publique d'un certificat, et la prépare
    • openssl_pkey_new - Génère une nouvelle clé privée
    • openssl_private_decrypt - Déchiffre des données avec une clé privée
    • openssl_private_encrypt - Chiffre des données avec une clé privée
    • openssl_public_decrypt - Déchiffre des données avec une clé publique
    • openssl_public_encrypt - Chiffre des données avec une clé publique
    • openssl_random_pseudo_bytes - Génère une chaine pseudo-aléatoire d'octets
    • openssl_seal - Scelle des données
    • openssl_sign - Signe les données
    • openssl_spki_export - Exporte un PEM valide formaté comme une clé publique signée
    • openssl_spki_export_challenge - Exporte le challenge associé avec la clé publique signée
    • openssl_spki_new - Génère une clé publique signée et effectue un challenge
    • openssl_spki_verify - Vérifie une clé publique signée, et effectue un challenge
    • openssl_verify - Vérifie une signature
    • openssl_x509_checkpurpose - Vérifie l'usage d'un certificat
    • openssl_x509_check_private_key - Vérifie si une clé privée correspond à un certificat
    • openssl_x509_export - Exporte un certificat vers une chaîne de caractères
    • openssl_x509_export_to_file - Exporte un certificat vers un fichier
    • openssl_x509_fingerprint - Calcule l'empreinte, ou le digest d'un certificat X.509 donné
    • openssl_x509_free - Libère les ressources prises par un certificat
    • openssl_x509_parse - Analyse un certificat X509
    • openssl_x509_read - Analyse un certificat X.509 et retourne un objet
    • openssl_x509_verify - Vérifie la signature digitale d'un certificat x509 par rapport à une clé publique
    • Options de contexte des sockets - Liste des options de contexte des sockets
    • Options de contexte FTP - Liste des options de contexte FTP
    • Options de contexte HTTP - Liste des options de contexte HTTP
    • Options de contexte SSL - Liste des options de contexte SSL
    • Options de contexte Zip - Zip context option listing
    • Options de contexte Zlib - Liste des options de contexte Zlib
    • ord - Convertit le premier octet d'une chaîne en une valeur entre 0 et 255
    • OuterIterator::getInnerIterator - Retourne l'itérateur interne pour l'entrée courante
    • output_add_rewrite_var - Ajoute une règle de réécriture d'URL
    • output_reset_rewrite_vars - Annule la réécriture d'URL
  • p
    • pack - Compacte des données dans une chaîne binaire
    • 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
    • Paramètres de contexte - Liste des paramètres de contexte
    • ParentIterator::accept - Détermine si l'élément courant a des fils
    • ParentIterator::getChildren - Retourne le fils de l'itérateur interne contenu dans ParentIterator
    • ParentIterator::hasChildren - Vérifie si l'élément courant de l'itérateur interne a un fils
    • ParentIterator::next - Déplace l'itérateur à la position suivante
    • ParentIterator::rewind - Replace l'itérateur au début
    • ParentIterator::__construct - Construit un nouvel objet 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::sigilCount - Number of elements in matched rule
    • Parle\Parser::sigilName - Retrieve a rule or token name
    • 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::sigilCount - Number of elements in matched rule
    • Parle\RParser::sigilName - Retrieve a rule or token name
    • 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 - Analyse un fichier de configuration
    • parse_ini_string - Analyse une chaîne de configuration
    • parse_str - Analyse une chaîne de caractères d'une variable
    • parse_url - Analyse une URL et retourne ses composants
    • passthru - Exécute un programme externe et affiche le résultat brut
    • password_algos - Récupère tous les identifiants des algorithmes de hachage de mots de passe disponibles
    • password_get_info - Retourne des informations à propos du hachage fourni
    • password_hash - Crée une clé de hachage pour un mot de passe
    • password_needs_rehash - Vérifie que le hachage fourni est conforme à l'algorithme et aux options spécifiées
    • password_verify - Vérifie qu'un mot de passe correspond à un hachage
    • pathinfo - Retourne des informations sur un chemin système
    • pclose - Ferme un processus de pointeur de fichier
    • pcntl_alarm - Planifie une alarme pour délivrer un signal
    • pcntl_async_signals - Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno - Alias de pcntl_get_last_error
    • pcntl_exec - Exécute le programme indiqué dans l'espace courant de processus
    • pcntl_fork - Duplique le process courant
    • pcntl_getpriority - Retourne la priorité d'un processus
    • pcntl_get_last_error - Récupère le numéro de l'erreur générée par la dernière fonction pcntl utilisée
    • pcntl_rfork - Manipulates process resources
    • pcntl_setpriority - Change la priorité d'un processus
    • pcntl_signal - Installe un gestionnaire de signaux
    • pcntl_signal_dispatch - Appelle les gestionnaires de signaux pour chaque signal en attente
    • pcntl_signal_get_handler - Récupère le gestionnaire courant pour le signal spécifié
    • pcntl_sigprocmask - Liste et configure les signaux bloqués
    • pcntl_sigtimedwait - Attend un signal dans un délai donné
    • pcntl_sigwaitinfo - Attend un signal
    • pcntl_strerror - Récupère le message d'erreur système associé avec l'errno fourni
    • pcntl_unshare - Dissociates parts of the process execution context
    • pcntl_wait - Attend ou retourne le statut d'un processus fils
    • pcntl_waitpid - Attend la fin de l'exécution d'un processus fils
    • pcntl_wexitstatus - Retourne le code d'un processus fils terminé
    • pcntl_wifexited - Vérifie si le code de retour représente une fin normale
    • pcntl_wifsignaled - Retourne true si le code statut représente une fin due à un signal
    • pcntl_wifstopped - Retourne true si le processus fils est stoppé
    • pcntl_wstopsig - Retourne le signal qui a causé l'arrêt du processus fils
    • pcntl_wtermsig - Retourne le signal qui a provoqué la fin du processus fils
    • PDO::beginTransaction - Démarre une transaction
    • PDO::commit - Valide une transaction
    • PDO::cubrid_schema - Récupère le schéma d'informations demandé
    • PDO::errorCode - Retourne le SQLSTATE associé avec la dernière opération sur la base de données
    • PDO::errorInfo - Retourne les informations associées à l'erreur lors de la dernière opération sur la base de données
    • PDO::exec - Exécute une requête SQL et retourne le nombre de lignes affectées
    • PDO::getAttribute - Récupère un attribut d'une connexion à une base de données
    • PDO::getAvailableDrivers - Retourne la liste des pilotes PDO disponibles
    • PDO::inTransaction - Vérifie si nous sommes dans une transaction
    • PDO::lastInsertId - Retourne l'identifiant de la dernière ligne insérée ou la valeur d'une séquence
    • PDO::pgsqlCopyFromArray - Copie des données d'un tableau PHP dans une table
    • PDO::pgsqlCopyFromFile - Copie des données d'un fichier dans une table
    • PDO::pgsqlCopyToArray - Copie des données d'une table de base de donnée dans un tableau PHP
    • PDO::pgsqlCopyToFile - Copie des données d'une table dans un fichier
    • PDO::pgsqlGetNotify - Récupère une notification asynchrone
    • PDO::pgsqlGetPid - Récupère le PID du serveur
    • PDO::pgsqlLOBCreate - Crée un nouvel objet large
    • PDO::pgsqlLOBOpen - Ouvre un flux existant de large objet
    • PDO::pgsqlLOBUnlink - Supprime un objet large
    • PDO::prepare - Prépare une requête à l'exécution et retourne un objet
    • PDO::query - Prépare et Exécute une requête SQL sans marque substitutive
    • PDO::quote - Protège une chaîne pour l'utiliser dans une requête SQL PDO
    • PDO::rollBack - Annule une transaction
    • PDO::setAttribute - Configure un attribut PDO
    • PDO::sqliteCreateAggregate - Référence une fonction agrégative définie par l'utilisateur pour une utilisation dans les requêtes SQL
    • PDO::sqliteCreateCollation - Enregistre une fonction PHP ou définie par l'utilisateur pour l'utiliser comme une fonction de collecte dans les requêtes SQL.
    • PDO::sqliteCreateFunction - Référence une fonction définie par l'utilisateur pour une utilisation dans les requêtes SQL
    • PDO::__construct - Crée une instance PDO qui représente une connexion à la base
    • PDOStatement::bindColumn - Lie une colonne à une variable PHP
    • PDOStatement::bindParam - Lie un paramètre à un nom de variable spécifique
    • PDOStatement::bindValue - Associe une valeur à un paramètre
    • PDOStatement::closeCursor - Ferme le curseur, permettant à la requête d'être de nouveau exécutée
    • PDOStatement::columnCount - Retourne le nombre de colonnes dans le jeu de résultats
    • PDOStatement::debugDumpParams - Détaille une commande préparée SQL
    • PDOStatement::errorCode - Récupère les informations sur l'erreur associée lors de la dernière opération sur la requête
    • PDOStatement::errorInfo - Récupère les informations sur l'erreur associée lors de la dernière opération sur la requête
    • PDOStatement::execute - Exécute une requête préparée
    • PDOStatement::fetch - Récupère la ligne suivante d'un jeu de résultats PDO
    • PDOStatement::fetchAll - Récupère les lignes restantes d'un ensemble de résultats
    • PDOStatement::fetchColumn - Retourne une colonne depuis la ligne suivante d'un jeu de résultats
    • PDOStatement::fetchObject - Récupère la prochaine ligne et la retourne en tant qu'objet
    • PDOStatement::getAttribute - Récupère un attribut de requête
    • PDOStatement::getColumnMeta - Retourne les métadonnées pour une colonne d'un jeu de résultats
    • PDOStatement::getIterator - Gets result set iterator
    • PDOStatement::nextRowset - Avance à la prochaine ligne de résultats d'un gestionnaire de lignes de résultats multiples
    • PDOStatement::rowCount - Retourne le nombre de lignes affectées par le dernier appel à la fonction PDOStatement::execute()
    • PDOStatement::setAttribute - Définit un attribut de requête
    • PDOStatement::setFetchMode - Définit le mode de récupération par défaut pour cette requête
    • PDO_DBLIB DSN - Connexion au Serveur Microsoft SQL et bases de données Sybase
    • PDO_FIREBIRD DSN - Connexion aux bases de données Firebird
    • PDO_IBM DSN - Connexion aux bases de données IBM
    • PDO_INFORMIX DSN - Connexion aux bases de données Informix
    • PDO_MYSQL DSN - Connexion aux bases de données MySQL
    • PDO_OCI DSN - Connexion aux bases de données Oracle
    • PDO_ODBC DSN - Connexion aux bases de données ODBC ou DB2
    • PDO_PGSQL DSN - Connexion aux bases de données PostgreSQL
    • PDO_SQLITE DSN - Connexion aux bases de données SQLite
    • PDO_SQLSRV DSN - Connexion à des bases de données MS SQL Server et SQL Azure
    • pfsockopen - Ouvre un socket de connexion Internet ou Unix persistante
    • pg_affected_rows - Retourne le nombre de lignes affectées
    • pg_cancel_query - Annule une requête asynchrone
    • pg_client_encoding - Lit l'encodage du client
    • pg_close - Termine une connexion PostgreSQL
    • pg_connect - Établit une connexion PostgreSQL
    • pg_connection_busy - Vérifie si la connexion PostgreSQL est occupée
    • pg_connection_reset - Relance la connexion au serveur PostgreSQL
    • pg_connection_status - Lit le statut de la connexion PostgreSQL
    • pg_connect_poll - Test le statut d'une tentative de connexion asynchrone PostgreSQL en cours
    • pg_consume_input - Lit l'entrée de la connexion
    • pg_convert - Convertit des valeurs d'un tableaux associatifs en une forme convenable pour des requêtes SQL
    • pg_copy_from - Insère des lignes dans une table à partir d'un tableau
    • pg_copy_to - Copie une table dans un tableau
    • pg_dbname - Retourne le nom de la base de données PostgreSQL
    • pg_delete - Efface des lignes PostgreSQL
    • pg_end_copy - Synchronise avec le serveur PostgreSQL
    • pg_escape_bytea - Protège une chaîne pour insertion dans un champ bytea
    • pg_escape_identifier - Protège un identifiant pour l'insertion dans un champ texte.
    • pg_escape_literal - Protège une requête SQL littérale à insérer dans un champ texte
    • pg_escape_string - Protège une chaîne de caractères pour une requête SQL
    • pg_execute - Exécute une requête préparée PostGreSQL
    • pg_fetch_all - Lit toutes les lignes d'un résultat
    • pg_fetch_all_columns - Récupère toutes les lignes d'une colonne de résultats particulière en tant que tableau
    • pg_fetch_array - Lit une ligne de résultat PostgreSQL dans un tableau
    • pg_fetch_assoc - Lit une ligne de résultat PostgreSQL sous forme de tableau associatif
    • pg_fetch_object - Lit une ligne de résultat PostgreSQL dans un objet
    • pg_fetch_result - Retourne les valeurs d'un résultat
    • pg_fetch_row - Lit une ligne dans un tableau
    • pg_field_is_null - Teste si un champ PostgreSQL est à null
    • pg_field_name - Retourne le nom d'un champ PostgreSQL
    • pg_field_num - Retourne le numéro d'une colonne
    • pg_field_prtlen - Retourne la taille imprimée
    • pg_field_size - Retourne la taille interne de stockage d'un champ donné
    • pg_field_table - Retourne le nom ou l'oid d'une table
    • pg_field_type - Retourne le type d'un champ PostgreSQL donné par index
    • pg_field_type_oid - Retourne le type ID (OID) pour le numéro du champ correspondant
    • pg_flush - Envoi les données de requête sortante sur la connexion
    • pg_free_result - Libère la mémoire
    • pg_get_notify - Lit le message SQL NOTIFY
    • pg_get_pid - Lit l'identifiant de processus du serveur PostgreSQL
    • pg_get_result - Lit un résultat PostgreSQL asynchrone
    • pg_host - Retourne le nom d'hôte
    • pg_insert - Insère un tableau dans une table
    • pg_last_error - Lit le dernier message d'erreur sur la connexion
    • pg_last_notice - Retourne la dernière note du serveur PostgreSQL
    • pg_last_oid - Retourne l'identifiant de la dernière ligne
    • pg_lo_close - Ferme un objet de grande taille PostgreSQL
    • pg_lo_create - Crée un objet de grande taille PostgreSQL
    • pg_lo_export - Exporte un objet de grande taille vers un fichier
    • pg_lo_import - Importe un objet de grande taille depuis un fichier
    • pg_lo_open - Ouvre un objet de grande taille PostgreSQL
    • pg_lo_read - Lit un objet de grande taille
    • pg_lo_read_all - Lit un objet de grande taille en totalité
    • pg_lo_seek - Modifie la position dans un objet de grande taille
    • pg_lo_tell - Retourne la position courante dans un objet de grande taille PostgreSQL
    • pg_lo_truncate - Tronque un objet large
    • pg_lo_unlink - Efface un objet de grande taille PostgreSQL
    • pg_lo_write - Écrit un objet de grande taille PostgreSQL
    • pg_meta_data - Lit les métadonnées de la table PostgreSQL
    • pg_num_fields - Retourne le nombre de champ
    • pg_num_rows - Retourne le nombre de lignes PostgreSQL
    • pg_options - Retourne les options PostgreSQL
    • pg_parameter_status - Consulte un paramètre de configuration courant du serveur
    • pg_pconnect - Établit une connexion PostgreSQL persistante
    • pg_ping - Ping la connexion à la base
    • pg_port - Retourne le numéro de port
    • pg_prepare - Envoie une requête pour créer une requête préparée avec les paramètres donnés et attend l'exécution
    • pg_put_line - Envoie une chaîne au serveur PostgreSQL
    • pg_query - Exécute une requête PostgreSQL
    • pg_query_params - Envoie une commande au serveur et attend le résultat, avec les capacités de passer des paramètres séparément de la commande texte SQL
    • pg_result_error - Lit le message d'erreur associé à un résultat
    • pg_result_error_field - Retourne un champ individuel d'un rapport d'erreur
    • pg_result_seek - Définit la position de la ligne dans un résultat
    • pg_result_status - Lit le statut du résultat
    • pg_select - Effectue une sélection PostgreSQL
    • pg_send_execute - Envoie une requête pour exécuter une requête préparée avec des paramètres donnés, sans attendre le(s) résultat(s)
    • pg_send_prepare - Envoie une requête pour créer une requête préparée avec les paramètres donnés, sans attendre la fin de son exécution
    • pg_send_query - Exécute une requête PostgreSQL asynchrone
    • pg_send_query_params - Envoie une commande et sépare les paramètres au serveur sans attendre le(s) résultat(s)
    • pg_set_client_encoding - Choisit l'encodage du client PostgreSQL
    • pg_set_error_context_visibility - Détermine la visibilité des messages d'erreur du contexte retournés par pg_last_error et pg_result_error
    • pg_set_error_verbosity - Détermine la le degré des messages retournés par pg_last_error et pg_result_error
    • pg_socket - Récupère un gestionnaire de lecture seul sur le socket sous-jacent d'une connexion PostgreSQL
    • pg_trace - Active le suivi d'une connexion PostgreSQL
    • pg_transaction_status - Retourne le statut de la transaction en cours du serveur
    • pg_tty - Retourne le nom de TTY associé à la connexion
    • pg_unescape_bytea - Supprime la protection d'une chaîne de type bytea
    • pg_untrace - Termine le suivi d'une connexion PostgreSQL
    • pg_update - Modifie les lignes d'une table
    • pg_version - Retourne un tableau avec les versions du client, du protocole et du serveur (si disponible)
    • phar:// - Archive PHP
    • Phar::addEmptyDir - Ajoute un répertoire vide à l'archive phar
    • Phar::addFile - Ajoute un fichier du système de fichiers à l'archive phar
    • Phar::addFromString - Ajoute un fichier depuis une chaîne de caractère à l'archive phar
    • Phar::apiVersion - Retourne la version de l'API
    • Phar::buildFromDirectory - Construit une archive phar à partir des fichiers d'un répertoire
    • Phar::buildFromIterator - Construit une archive phar à partir d'un itérateur
    • Phar::canCompress - Détermine si l'extension phar supporte une la compression en utilisant soit zip soit bzip2
    • Phar::canWrite - Détermine si l'extension phar supporte la création et l'écriture des phars
    • Phar::compress - Compresse l'archive Phar complète en utilisant la compression Gzip ou Bzip2
    • Phar::compressFiles - Compresse tous les fichiers de l'archive Phar courante'
    • Phar::convertToData - Convertit une archive phar en un fichier non-exécutable
    • Phar::convertToExecutable - Convertit une archive phar vers un autre format de fichier d'archive phar exécutable
    • Phar::copy - Copie un fichier appartenant à une archive vers un autre fichier de la même archive
    • Phar::count - Retourne le nombre d'entrées (fichiers) dans l'archive Phar
    • Phar::createDefaultStub - Crée un conteneur de chargement d'une archive Phar
    • Phar::decompress - Décompresse l'archive tar complète
    • Phar::decompressFiles - Décompresse tous les fichiers de l'archive Phar courante
    • Phar::delete - Efface un fichier au sein d'une archive phar
    • Phar::delMetadata - Efface les méta-données globales du phar
    • Phar::extractTo - Extrait le contenu d'une archive phar vers un répertoire
    • Phar::getAlias - Récupère l'alias pour Phar
    • Phar::getMetadata - Retourne les méta-données de l'archive phar
    • Phar::getModified - Indique si le fichier phar a été modifié
    • Phar::getPath - Récupère le chemin absolu de l'archive Phar sur le disque
    • Phar::getSignature - Retourne la signature MD5/SHA1/SHA256/SHA512 d'une archive Phar
    • Phar::getStub - Retourne le chargeur PHP ou le conteneur de chargement d'une archive Phar
    • Phar::getSupportedCompression - Retourne un tableau des algorithmes de compression supportés
    • Phar::getSupportedSignatures - Retourne un tableau des types de signature supportés
    • Phar::getVersion - Retourne les informations de version de l'archive Phar
    • Phar::hasMetadata - Détermine si le phar a ou non des méta-données
    • Phar::interceptFileFuncs - Informe phar qu'il doit intercepter les fonctions de fichiers
    • Phar::isBuffering - Détermine si les opérations d'écriture du Phar sont mises en tampons ou sont directement inscrites sur le disque
    • Phar::isCompressed - Retourne Phar::GZ ou PHAR::BZ2 si l'archive entière est compressée (.tar.gz/tar.bz, etc)
    • Phar::isFileFormat - Retourne true si l'archive phar est basée sur le formats de fichier tar/phar/zip selon le paramètre
    • Phar::isValidPharFilename - Détermine si le nom de fichier spécifié est un nom de fichier valide pour une archive phar
    • Phar::isWritable - Retourne true si l'archive phar peut être modifiée
    • Phar::loadPhar - Charge n'importe quelle archive phar avec un alias
    • Phar::mapPhar - Lit le phar exécuté et charge son manifeste
    • Phar::mount - Monte un chemin ou un fichier externe à un emplacement virtuel au sein de l'archive phar
    • Phar::mungServer - Définit une liste de maximum 4 variables $_SERVER qui doivent être modifiées lors de l'exécution
    • Phar::offsetExists - Détermine si un fichier existe dans le phar
    • Phar::offsetGet - Obtient un objet PharFileInfo à partir d'un fichier
    • Phar::offsetSet - Met le contenu d'un fichier interne à l'archive à l'identique du contenu d'un fichier externe
    • Phar::offsetUnset - Efface un fichier d'un phar
    • Phar::running - Retourne le chemin complet sur le disque ou l'URL phar complète de l'archive phar couramment exécutée
    • Phar::setAlias - Fixe l'alias de l'archive Phar
    • Phar::setDefaultStub - Utilisé pour fixer le chargeur PHP ou le conteneur de chargement d'une archive Phar en tant que chargeur par défaut
    • Phar::setMetadata - Fixe les métadonnées de l'archive phar
    • Phar::setSignatureAlgorithm - Fixe et applique l'algorithme de signature d'un phar
    • Phar::setStub - Utilisé pour spécifier le chargeur PHP ou le conteneur de chargement d'une archive Phar
    • Phar::startBuffering - Démarre la mise en tampon d'écritures Phar, ne modifie pas l'objet Phar sur le disque
    • Phar::stopBuffering - Arrête la mise en tampon des écritures Phar et provoque l'écriture que le disque
    • Phar::unlinkArchive - Efface complètement une archive phar du disque et de la mémoire
    • Phar::webPhar - Redirige une requête depuis un navigateur web à un fichier interne dans l'archive phar
    • Phar::__construct - Construit un objet d'archive Phar
    • Phar::__destruct - Destructs a Phar archive object
    • PharData::addEmptyDir - Ajoute un répertoire vide à l'archive tar/zip
    • PharData::addFile - Ajoute un fichier du système de fichiers à l'archive tar/zip
    • PharData::addFromString - Ajoutez un fichier à partir d'une chaîne de caractères à l'archive tar/zip
    • PharData::buildFromDirectory - Construit une archive tar/zip à partir des fichiers d'un répertoire
    • PharData::buildFromIterator - Construit une archive tar ou zip à partir d'un itérateur
    • PharData::compress - Compresse l'archive tar/zip complète en utilisant la compression Gzip ou Bzip2
    • PharData::compressFiles - Compresse tous les fichiers de l'archive tar/zip courante
    • PharData::convertToData - Convertit une archive phar en une archive tar ou zip non-exécutable
    • PharData::convertToExecutable - Convertit une archive tar/zip non-exécutable en une archive phar exécutable
    • PharData::copy - Copie un fichier interne à l'archive phar vers un autre fichier au sein de la même archive
    • PharData::decompress - Décompresse l'archive Phar entière
    • PharData::decompressFiles - Décompresse tous les fichiers de l'archive zip courante
    • PharData::delete - Efface un fichier au sein de l'archive tar/zip
    • PharData::delMetadata - Efface les méta-données globales d'une archive zip
    • PharData::extractTo - Extrait le contenu d'une archive tar/zip vers un répertoire
    • PharData::isWritable - Vérifie si l'archive tar/zip peut être modifiée
    • PharData::offsetSet - Remplit un fichier au sein de l'archive tar/zip avec le contenu d'un fichier externe ou d'une chaîne de caractères
    • PharData::offsetUnset - Efface un fichier d'une archive tar/zip
    • PharData::setAlias - Fonction inutile (Phar::setAlias n'est pas valide pour PharData)
    • PharData::setDefaultStub - Fonction inutile (Phar::setDefaultStub n'est pas valide pour PharData)
    • PharData::setMetadata - Fixe les méta-données de l'archive
    • PharData::setSignatureAlgorithm - Assigne l'algorithme de signature d'un phar et l'applique
    • PharData::setStub - Fonction inutile (Phar::setStub n'est pas valide pour PharData)
    • PharData::__construct - Construit un objet d'archive tar ou zip non-exécutable
    • PharData::__destruct - Destructs a non-executable tar or zip archive object
    • PharFileInfo::chmod - Fixe les bits de permission spécifiques aux fichiers
    • PharFileInfo::compress - Compresse l'entrée Phar courante avec une des compressions zlib ou bzip2
    • PharFileInfo::decompress - Décompresse l'entrée Phar courante au sein du phar
    • PharFileInfo::delMetadata - Efface les métadonnées de l'entrée
    • PharFileInfo::getCompressedSize - Retourne la taille actuelle (avec compression) du fichier au sein de l'archive Phar
    • PharFileInfo::getContent - Récupère le contenu entier du fichier de l'entrée
    • PharFileInfo::getCRC32 - Retourne le code CRC32 ou soulève une exception si le CRC n'a pas été vérifié
    • PharFileInfo::getMetadata - Retourne les méta-données spécifiques attachées à un fichier
    • PharFileInfo::getPharFlags - Retourne les drapeaux du fichier Phar
    • PharFileInfo::hasMetadata - Retourne les méta-données de l'entrée
    • PharFileInfo::isCompressed - Retourne si l'entrée est compressée
    • PharFileInfo::isCRCChecked - Détermine si le fichier a un CRC vérifié
    • PharFileInfo::setMetadata - Fixe les métadonnées spécifiques à un fichier
    • PharFileInfo::__construct - Construit un objet d'entrée Phar
    • PharFileInfo::__destruct - Destructs a Phar entry object
    • php:// - Accès aux divers flux I/O
    • phpcredits - Affiche les crédits de PHP
    • phpdbg_break_file - Insère un point d'arrêt dans une ligne d'un fichier
    • phpdbg_break_function - Insère un point d'arrêt à l'entrée d'une fonction
    • phpdbg_break_method - Insère un point d'arrêt à l'entrée d'une méthode
    • phpdbg_break_next - Insère un point d'arrêt au prochain opcode
    • phpdbg_clear - Supprime tous les points d'arrêt
    • phpdbg_color - Définie la couleur de certaines éléments
    • phpdbg_end_oplog - Description
    • phpdbg_exec - Tente de définir le contexte d'exécution
    • phpdbg_get_executable - Description
    • phpdbg_prompt - Définie l'invite de commande
    • phpdbg_start_oplog - Description
    • phpinfo - Affiche de nombreuses informations sur la configuration de 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 - Retourne le numéro de la version courante de PHP
    • php_ini_loaded_file - Récupère le chemin d'un fichier php.ini chargé
    • php_ini_scanned_files - Retourne la liste des fichiers .ini analysés dans les dossiers de configuration supplémentaires
    • php_sapi_name - Retourne le type d'interface utilisée entre le serveur web et PHP
    • php_strip_whitespace - Retourne la source sans commentaires, ni espaces blancs
    • php_uname - Retourne les informations sur le système d'exploitation
    • php_user_filter::filter - Appelé lors de l'application d'un filtre
    • php_user_filter::onClose - Appelé lors de la fermeture du filtre
    • php_user_filter::onCreate - Appelé lors de la création du filtre
    • pi - Retourne la valeur de pi
    • png2wbmp - Convertit une image PNG en image WBMP
    • Pool::collect - Collecte les références des tâches achevées
    • Pool::resize - Redimensionne le Pool
    • Pool::shutdown - Arrête tous les workers
    • Pool::submit - Soumet un objet pour exécution
    • Pool::submitTo - Soumet une tâche à un worker spécifique pour exécution
    • Pool::__construct - Crée un nouveau Pool de Workers
    • popen - Crée un processus de pointeur de fichier
    • pos - Alias de current
    • posix_access - Détermine l'accessibilité d'un fichier
    • posix_ctermid - Retourne le chemin du terminal
    • posix_eaccess - Determine accessibility of a file
    • posix_errno - Alias de posix_get_last_error
    • posix_fpathconf - Returns the value of a configurable limit
    • posix_getcwd - Chemin du dossier de travail courant
    • posix_getegid - Retourne l'ID effectif du groupe du processus courant
    • posix_geteuid - Retourne l'UID effectif de l'utilisateur du processus courant
    • posix_getgid - Retourne l'UID du groupe du processus courant
    • posix_getgrgid - Retourne des informations sur un groupe
    • posix_getgrnam - Retourne des informations sur un groupe
    • posix_getgroups - Retourne les identifiants du groupe du processus courant
    • posix_getlogin - Retourne le login
    • posix_getpgid - Retourne l'id du groupe de processus
    • posix_getpgrp - Retourne l'identifiant du groupe de processus
    • posix_getpid - Retourne l'identifiant du processus courant
    • posix_getppid - Retourne l'identifiant du processus parent
    • posix_getpwnam - Retourne des informations sur un utilisateur
    • posix_getpwuid - Retourne des informations sur un utilisateur
    • posix_getrlimit - Retourne des informations concernant les limites des ressources système
    • posix_getsid - Retourne le sid du processus
    • posix_getuid - Retourne l'ID de l'utilisateur du processus courant
    • posix_get_last_error - Lit le dernier numéro d'erreur généré par la dernière fonction POSIX qui a échoué
    • posix_initgroups - Calcule la liste des accès de groupe
    • posix_isatty - Détermine si un pointeur de fichier est un terminal interactif
    • posix_kill - Envoie un signal à un processus
    • posix_mkfifo - Crée un fichier FIFO (first in, first out) (un pipe nommé)
    • posix_mknod - Crée un fichier spécial ou ordinaire (POSIX.1)
    • posix_pathconf - Returns the value of a configurable limit
    • posix_setegid - Modifie le GID réel du processus courant
    • posix_seteuid - Modifie l'identifiant d'utilisateur réel (UID) du processus courant
    • posix_setgid - Fixe le GID effectif du processus courant
    • posix_setpgid - Fixe l'identifiant de groupe de processus
    • posix_setrlimit - Définit les limites pour une ressource système
    • posix_setsid - Fait du processus courant un chef de session
    • posix_setuid - Fixe l'UID effective du processus courant
    • posix_strerror - Lit le message d'erreur associé à un numéro d'erreur POSIX
    • posix_sysconf - Returns system runtime information
    • posix_times - Utilisation des ressources
    • posix_ttyname - Retourne le nom de device du terminal
    • posix_uname - Retourne le nom du système
    • pow - Expression exponentielle
    • preg_filter - Recherche et remplace avec une expression rationnelle
    • preg_grep - Retourne un tableau avec les résultats de la recherche
    • preg_last_error - Retourne le code erreur de la dernière expression PCRE exécutée
    • preg_last_error_msg - Returns the error message of the last PCRE regex execution
    • preg_match - Effectue une recherche de correspondance avec une expression rationnelle standard
    • preg_match_all - Expression rationnelle globale
    • preg_quote - Protection des caractères spéciaux des expressions régulières
    • preg_replace - Rechercher et remplacer par expression rationnelle standard
    • preg_replace_callback - Rechercher et remplacer par expression rationnelle standard en utilisant une fonction de callback
    • preg_replace_callback_array - Éffectue une recherche de correspondance avec une expression régulière et remplace grâce à une fonction de rappel
    • preg_split - Éclate une chaîne par expression rationnelle
    • prev - Recule le pointeur courant de tableau
    • print - Affiche une chaîne de caractères
    • printf - Affiche une chaîne de caractères formatée
    • print_r - Affiche des informations lisibles pour une variable
    • proc_close - Ferme un processus ouvert par proc_open
    • proc_get_status - Lit les informations concernant un processus ouvert par proc_open
    • proc_nice - Change la priorité d'exécution du processus courant
    • proc_open - Exécute une commande et ouvre les pointeurs de fichiers pour les entrées / sorties
    • proc_terminate - Termine un processus ouvert par proc_open
    • property_exists - Vérifie si un objet ou une classe possède une propriété
    • pspell_add_to_personal - Ajoute le mot au dictionnaire personnel
    • pspell_add_to_session - Ajoute le mot au dictionnaire personnel de la session courante
    • pspell_check - Vérifie un mot
    • pspell_clear_session - Remet à zéro la session courante
    • pspell_config_create - Crée une configuration utilisée pour ouvrir un dictionnaire
    • pspell_config_data_dir - Dossier qui contient les fichiers de données linguistiques
    • pspell_config_dict_dir - Endroit où se trouve le fichier global des mots
    • pspell_config_ignore - Ignore les mots de moins de N caractères
    • pspell_config_mode - Change le mode de suggestion
    • pspell_config_personal - Choisit le fichier qui contient le dictionnaire personnel
    • pspell_config_repl - Choisit le fichier qui contient les paires de remplacement
    • pspell_config_runtogether - Considère deux mots accolés comme un composé
    • pspell_config_save_repl - Détermine s'il faut sauver les paires de remplacement avec le dictionnaire
    • pspell_new - Charge un nouveau dictionnaire
    • pspell_new_config - Charge un nouveau dictionnaire avec les paramètres spécifiés dans une configuration
    • pspell_new_personal - Charge un nouveau dictionnaire avec un dictionnaire personnel
    • pspell_save_wordlist - Sauve le dictionnaire personnel dans un fichier
    • pspell_store_replacement - Enregistre une paire de remplacement pour un mot
    • pspell_suggest - Suggère l'orthographe d'un mot
    • ps_add_bookmark - Ajoute un signet à la page courante
    • ps_add_launchlink - Ajoute un lien qui démarre un fichier
    • ps_add_locallink - Ajoute un lien à une page dans le même document
    • ps_add_note - Ajoute une note à la page courante
    • ps_add_pdflink - Ajoute un lien à une page à un second document PDF
    • ps_add_weblink - Ajoute un lien à un emplacement web
    • ps_arc - Dessine un arc dans le sens contraire des aiguilles d'une montre
    • ps_arcn - Dessine un arc dans le sens des aiguilles d'une montre
    • ps_begin_page - Démarre une nouvelle page
    • ps_begin_pattern - Démarre un nouveau motif
    • ps_begin_template - Démarre un nouveau modèle
    • ps_circle - Dessine un cercle
    • ps_clip - Attache le dessin au chemin courant
    • ps_close - Ferme le document PostScript
    • ps_closepath - Ferme un chemin
    • ps_closepath_stroke - Ferme et trace un chemin
    • ps_close_image - Ferme l'image et libère la mémoire
    • ps_continue_text - Continue un texte à la ligne suivante
    • ps_curveto - Dessine une courbe
    • ps_delete - Supprime toutes les ressources d'un document PostScript
    • ps_end_page - Termine une page
    • ps_end_pattern - Termine un motif
    • ps_end_template - Termine un modèle
    • ps_fill - Remplit le chemin courant
    • ps_fill_stroke - Remplit et trace le chemin courant
    • ps_findfont - Charge une police
    • ps_get_buffer - Récupère le tampon complet contenant les données PS générées
    • ps_get_parameter - Récupère certains paramètres
    • ps_get_value - Récupère certaines valeurs
    • ps_hyphenate - Relie un mot
    • ps_include_file - Lit un fichier externe avec du code PostScript brut
    • ps_lineto - Dessine une ligne
    • ps_makespotcolor - Crée une tache de couleur
    • ps_moveto - Fixe le point courant
    • ps_new - Crée un nouvel objet document PostScript
    • ps_open_file - Ouvre un fichier pour écriture
    • ps_open_image - Lit une image pour placement futur
    • ps_open_image_file - Ouvre une image à partir d'un fichier
    • ps_open_memory_image - Prend une image GD et retourne une image à placer dans un document PS
    • ps_place_image - Place une image sur la page
    • ps_rect - Dessine un rectangle
    • ps_restore - Restaure un contexte précédemment sauvegardé
    • ps_rotate - Fixe le facteur de rotation
    • ps_save - Sauvegarde le contexte courant
    • ps_scale - Fixe le facteur de redimensionnement
    • ps_setcolor - Fixe la couleur courante
    • ps_setdash - Fixe l'apparence d'une ligne pointillée
    • ps_setflat - Fixe la position à plat
    • ps_setfont - Fixe la police à utiliser pour la prochaine écriture
    • ps_setgray - Fixe la valeur de gris
    • ps_setlinecap - Fixe l'apparence des fins de ligne
    • ps_setlinejoin - Fixe comment les lignes connectés sont jointes
    • ps_setlinewidth - Fixe la largeur d'une ligne
    • ps_setmiterlimit - Fixe les limites de l'anglet
    • ps_setoverprintmode - Définit le mode "overprint"
    • ps_setpolydash - Fixe l'apparence d'une ligne pointillée
    • ps_set_border_color - Fixe la couleur des bordures pour les commentaires
    • ps_set_border_dash - Fixe la grandeur des tirets pour les bordures des commentaires
    • ps_set_border_style - Fixe le style de bordure des commentaires
    • ps_set_info - Assigne les champs d'informations d'un document
    • ps_set_parameter - Fixe certains paramètres
    • ps_set_text_pos - Fixe la position l'écriture du texte
    • ps_set_value - Fixe certaines valeurs
    • ps_shading - Crée un ton pour usage futur
    • ps_shading_pattern - Crée un motif basé sur le ton
    • ps_shfill - Remplit un espace avec un ton
    • ps_show - Écrit du texte
    • ps_show2 - Affiche un texte à la position courante
    • ps_show_boxed - Écriture de texte dans une boîte
    • ps_show_xy - Écrit du texte à la position donnée
    • ps_show_xy2 - Affiche un texte à la position
    • ps_stringwidth - Récupère la largeur d'une chaîne de caractères
    • ps_string_geometry - Récupère les géométries d'une chaîne de caractères
    • ps_stroke - Dessine le chemin courant
    • ps_symbol - Écrit un glyphe
    • ps_symbol_name - Récupère le nom d'un glyphe
    • ps_symbol_width - Récupère la largeur d'un glyphe
    • ps_translate - Fixe une translation
    • putenv - Fixe la valeur d'une variable d'environnement
  • q
    • QuickHashIntHash::add - This method adds a new entry to the hash
    • QuickHashIntHash::delete - This method deletes an 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 an 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 an 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 - Convertit une chaîne quoted-printable en chaîne 8 bits
    • quoted_printable_encode - Convertit une chaîne 8 bits en une chaîne quoted-printable
    • quotemeta - Protège les métacaractères
  • r
    • rad2deg - Conversion de radians en degrés
    • radius_acct_open - Crée une ressource Radius pour les comptes
    • radius_add_server - Ajoute un serveur
    • radius_auth_open - Crée une ressource Radius pour l'identification
    • radius_close - Libère toutes les ressources Radius
    • radius_config - Demande à la bibliothèque de lire un fichier de configuration donné
    • radius_create_request - Crée une demande de compte ou d'identification
    • radius_cvt_addr - Convertit des données brutes en adresse IP
    • radius_cvt_int - Convertit des données brutes en entier
    • radius_cvt_string - Convertit des données brutes en chaîne de caractères
    • radius_demangle - Assèche des données
    • radius_demangle_mppe_key - Dérive les clés mppe depuis des données
    • radius_get_attr - Extrait un attribut
    • radius_get_tagged_attr_data - Extrait les données d'un attribut
    • radius_get_tagged_attr_tag - Extrait le tag depuis un attribut
    • radius_get_vendor_attr - Extrait un attribut spécifique au vendeur
    • radius_put_addr - Attache une adresse IP en tant qu'attribut
    • radius_put_attr - Attache un attribut binaire
    • radius_put_int - Attache un attribut entier
    • radius_put_string - Attache un attribut chaîne de caractères
    • radius_put_vendor_addr - Attache une adresse IP spécifique à un vendeur
    • radius_put_vendor_attr - Attache un attribut binaire à un vendeur spécifique
    • radius_put_vendor_int - Attache un attribut entier à un vendeur spécifique
    • radius_put_vendor_string - Attache un attribut sous la forme d'une chaîne à un vendeur spécifique
    • radius_request_authenticator - Retourne l'identifiant demandé
    • radius_salt_encrypt_attr - Chiffre une valeur en utilisant un Salt
    • radius_send_request - Envoie une requête et attend une réponse
    • radius_server_secret - Retourne le secret partagé
    • radius_strerror - Retourne un message d'erreur
    • rand - Génère une valeur aléatoire
    • Random\Engine::generate - Génère de l'aléatoire
    • Random\Engine\Mt19937::generate - Generate 32 bits of randomness
    • Random\Engine\Mt19937::__construct - Constructs a new Mt19937 engine
    • Random\Engine\Mt19937::__debugInfo - Returns the internal state of the engine
    • Random\Engine\Mt19937::__serialize - Serializes the Mt19937 object
    • Random\Engine\Mt19937::__unserialize - Deserializes the data parameter into a Mt19937 object
    • Random\Engine\PcgOneseq128XslRr64::generate - Generate 64 bits of randomness
    • Random\Engine\PcgOneseq128XslRr64::jump - Efficiently move the engine ahead multiple steps
    • Random\Engine\PcgOneseq128XslRr64::__construct - Constructs a new PCG Oneseq 128 XSL RR 64 engine
    • Random\Engine\PcgOneseq128XslRr64::__debugInfo - Returns the internal state of the engine
    • Random\Engine\PcgOneseq128XslRr64::__serialize - Serializes the PcgOneseq128XslRr64 object
    • Random\Engine\PcgOneseq128XslRr64::__unserialize - Deserializes the data parameter into a PcgOneseq128XslRr64 object
    • Random\Engine\Secure::generate - Generate cryptographically secure randomness
    • Random\Engine\Xoshiro256StarStar::generate - Generate 64 bits of randomness
    • Random\Engine\Xoshiro256StarStar::jump - Efficiently move the engine ahead by 2^128 steps
    • Random\Engine\Xoshiro256StarStar::jumpLong - Efficiently move the engine ahead by 2^192 steps
    • Random\Engine\Xoshiro256StarStar::__construct - Constructs a new xoshiro256** engine
    • Random\Engine\Xoshiro256StarStar::__debugInfo - Returns the internal state of the engine
    • Random\Engine\Xoshiro256StarStar::__serialize - Serializes the Xoshiro256StarStar object
    • Random\Engine\Xoshiro256StarStar::__unserialize - Deserializes the data parameter into a Xoshiro256StarStar object
    • Random\Randomizer::getBytes - Get random bytes
    • Random\Randomizer::getBytesFromString - Get random bytes from a source string
    • Random\Randomizer::getFloat - Get a uniformly selected float
    • Random\Randomizer::getInt - Get a uniformly selected integer
    • Random\Randomizer::nextFloat - Get a float from the right-open interval [0.0, 1.0)
    • Random\Randomizer::nextInt - Get a positive integer
    • Random\Randomizer::pickArrayKeys - Select random array keys
    • Random\Randomizer::shuffleArray - Get a permutation of an array
    • Random\Randomizer::shuffleBytes - Get a byte-wise permutation of a string
    • Random\Randomizer::__construct - Constructs a new Randomizer
    • Random\Randomizer::__serialize - Serializes the Randomizer object
    • Random\Randomizer::__unserialize - Deserializes the data parameter into a Randomizer object
    • random_bytes - Récupère des octets aléatoires cryptographiquement sécurisés
    • random_int - Récupère un entier sélectionné de manière uniforme et cryptographiquement sécurisée
    • range - Crée un tableau contenant un intervalle d'éléments
    • rar:// - RAR
    • RarArchive::close - Ferme une archive RAR et libère toutes les ressources
    • RarArchive::getComment - Récupère un commentaire depuis une archive RAR
    • RarArchive::getEntries - Récupère la liste complète depuis l'archive RAR
    • RarArchive::getEntry - Récupère une entrée depuis une archive RAR
    • RarArchive::isBroken - Test si une archive est corrompue (incomplète)
    • RarArchive::isSolid - Vérifie si l'archive RAR est solide
    • RarArchive::open - Ouvre une archive RAR
    • RarArchive::setAllowBroken - Autorise ou non l'ouverture d'archives corrompues
    • RarArchive::__toString - Récupère une représentation sous forme de texte
    • RarEntry::extract - Extrait une entrée d'une archive
    • RarEntry::getAttr - Récupère les attributs d'une entrée
    • RarEntry::getCrc - Récupère le CRC d'une entrée
    • RarEntry::getFileTime - Récupère la date de dernière modification d'une entrée
    • RarEntry::getHostOs - Récupère le code de l'hôte pour une entrée
    • RarEntry::getMethod - Récupère la méthode utilisée pour l'ajout d'une entrée
    • RarEntry::getName - Récupère le nom de l'entrée
    • RarEntry::getPackedSize - Récupère la taille compressée d'une entrée
    • RarEntry::getStream - Récupère le gestion de fichier pour une entrée
    • RarEntry::getUnpackedSize - Récupère la taille décompressée d'une entrée
    • RarEntry::getVersion - Récupère la version minimale du logiciel RAR à utiliser pour décompresser une entrée
    • RarEntry::isDirectory - Teste si l'entrée courante est un dossier
    • RarEntry::isEncrypted - Teste si une entrée est cryptée
    • RarEntry::__toString - Récupère une représentation sous forme de chaîne de caractères d'une entrée
    • RarException::isUsingExceptions - Vérifie si le gestionnaire d'erreur utilise les exceptions ou non
    • RarException::setUsingExceptions - Active ou désactive les exceptions dans le gestionnaire d'erreurs
    • rar_wrapper_cache_stats - Statistique pour le cache du gestionnaire URL
    • rawurldecode - Décode une chaîne URL
    • rawurlencode - Encode une chaîne en URL, selon la RFC 3986
    • readdir - Lit une entrée du dossier
    • readfile - Affiche un fichier
    • readgzfile - Lit tout le fichier compressé
    • readline - Lit une ligne
    • readline_add_history - Ajoute une ligne à l'historique
    • readline_callback_handler_install - Initialise l'interface et le terminal de rappel de readline, affiche le prompt et retourne immédiatement
    • readline_callback_handler_remove - Efface un gestionnaire de rappel readline
    • readline_callback_read_char - Lit un caractère et informe l'interface de rappel readline
    • readline_clear_history - Efface l'historique
    • readline_completion_function - Enregistre une fonction de complétion
    • readline_info - Lit ou modifie diverses variables internes de readline
    • readline_list_history - Liste l'historique
    • readline_on_new_line - Informe readline que le curseur est passé à une nouvelle ligne
    • readline_read_history - Lit l'historique
    • readline_redisplay - Demande à readline de refaire l'affichage
    • readline_write_history - Écrit dans l'historique
    • readlink - Renvoie le contenu d'un lien symbolique
    • read_exif_data - Alias de exif_read_data
    • realpath - Retourne le chemin canonique absolu
    • realpath_cache_get - Récupère les entrées du cache realpath
    • realpath_cache_size - Récupère la taille du cache realpath
    • recode - Alias de recode_string
    • recode_file - Recodage de fichier à fichier, en fonction de la demande
    • recode_string - Recode une chaîne en fonction de la requête
    • RecursiveArrayIterator::getChildren - Retourne un itérateur pour l'entrée courante
    • RecursiveArrayIterator::hasChildren - Vérifie si l'entrée courante est un tableau ou un objet
    • RecursiveCachingIterator::getChildren - Retourne le fils de l'itérateur interne comme un CachingRecursiveIterator
    • RecursiveCachingIterator::hasChildren - Vérifie si l'élément courant de l'itérateur interne a un fils
    • RecursiveCachingIterator::__construct - Constructeur
    • RecursiveCallbackFilterIterator::getChildren - Retourne l'itérateur fils interne contenu dans un RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Vérifie si l'élément courant de l'itérateur interne a un fils
    • RecursiveCallbackFilterIterator::__construct - Crée un objet RecursiveCallbackFilterIterator depuis une interface RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Retourne un itérateur pour l'entrée courante si c'est un dossier
    • RecursiveDirectoryIterator::getSubPath - Récupère le sous-chemin
    • RecursiveDirectoryIterator::getSubPathname - Récupère le sous-chemin et le nom du fichier
    • RecursiveDirectoryIterator::hasChildren - Vérifie si l'entrée courante est un dossier et n'est pas '.' ou '..'
    • RecursiveDirectoryIterator::key - Retourne le chemin et le nom de l'entrée courante du dossier
    • RecursiveDirectoryIterator::next - Se déplace vers la prochaine entrée
    • RecursiveDirectoryIterator::rewind - Revient à la position initiale dans le dossier
    • RecursiveDirectoryIterator::__construct - Construit un objet RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Retourne l'itérateur interne contenu dans un objet RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Vérifie si un fils existe pour l'itérateur interne de l'élément courant
    • RecursiveFilterIterator::__construct - Crée un objet RecursiveFilterIterator depuis un objet RecursiveIterator
    • RecursiveIterator::getChildren - Récupère l'itérateur de l'entrée courante
    • RecursiveIterator::hasChildren - Vérifie si un itérateur peut être créé depuis l'entrée courante
    • RecursiveIteratorIterator::beginChildren - Commence un fils
    • RecursiveIteratorIterator::beginIteration - Commence une itération
    • RecursiveIteratorIterator::callGetChildren - Récupère un fils
    • RecursiveIteratorIterator::callHasChildren - Vérifie si un fils existe
    • RecursiveIteratorIterator::current - Accède à la valeur de l'élément courant
    • RecursiveIteratorIterator::endChildren - Termine un fils
    • RecursiveIteratorIterator::endIteration - Termine un itérateur
    • RecursiveIteratorIterator::getDepth - Récupère la profondeur courante de la récursivité de l'itérateur
    • RecursiveIteratorIterator::getInnerIterator - Récupère l'itérateur interne
    • RecursiveIteratorIterator::getMaxDepth - Récupère la profondeur maximale
    • RecursiveIteratorIterator::getSubIterator - L'itérateur secondaire actif courant
    • RecursiveIteratorIterator::key - Accède à la clé courante
    • RecursiveIteratorIterator::next - Déplace l'itérateur à la position suivante
    • RecursiveIteratorIterator::nextElement - Élément suivant
    • RecursiveIteratorIterator::rewind - Replace l'itérateur au début
    • RecursiveIteratorIterator::setMaxDepth - Définit la profondeur maximale
    • RecursiveIteratorIterator::valid - Vérifie si la position courante est valide
    • RecursiveIteratorIterator::__construct - Construit un objet RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Retourne un itérateur depuis l'entrée courante
    • RecursiveRegexIterator::hasChildren - Vérifie si un itérateur peut être obtenu depuis l'entrée courante
    • RecursiveRegexIterator::__construct - Crée un nouveau RecursiveRegexIterator
    • RecursiveTreeIterator::beginChildren - Début d'un fils
    • RecursiveTreeIterator::beginIteration - Début d'une itération
    • RecursiveTreeIterator::callGetChildren - Récupère un fils
    • RecursiveTreeIterator::callHasChildren - Vérifie la présence d'un fils
    • RecursiveTreeIterator::current - Récupère l'élément courant
    • RecursiveTreeIterator::endChildren - Fin d'un fils
    • RecursiveTreeIterator::endIteration - Fin de l'itération
    • RecursiveTreeIterator::getEntry - Récupère l'entrée courante
    • RecursiveTreeIterator::getPostfix - Récupère le suffixe
    • RecursiveTreeIterator::getPrefix - Récupère le préfixe
    • RecursiveTreeIterator::key - Récupère la clé de l'élément courant
    • RecursiveTreeIterator::next - Se déplace sur l'élément suivant
    • RecursiveTreeIterator::nextElement - Prochain élément
    • RecursiveTreeIterator::rewind - Réinitialise la position de l'itérateur
    • RecursiveTreeIterator::setPostfix - Définit le suffixe
    • RecursiveTreeIterator::setPrefixPart - Définit une partie du préfixe
    • RecursiveTreeIterator::valid - Vérifie la validité
    • RecursiveTreeIterator::__construct - Construit un nouvel objet RecursiveTreeIterator
    • Reflection::export - Exporte
    • Reflection::getModifierNames - Récupère le nom des modificateurs
    • ReflectionAttribute::getArguments - Gets arguments passed to attribute
    • ReflectionAttribute::getName - Gets attribute name
    • ReflectionAttribute::getTarget - Returns the target of the attribute as bitmask
    • ReflectionAttribute::isRepeated - Returns whether the attribute of this name has been repeated on a code element
    • ReflectionAttribute::newInstance - Instantiates the attribute class represented by this ReflectionAttribute class and arguments
    • ReflectionAttribute::__construct - Private constructor to disallow direct instantiation
    • ReflectionClass::export - Exporte une classe
    • ReflectionClass::getAttributes - Gets Attributes
    • ReflectionClass::getConstant - Récupère une constante
    • ReflectionClass::getConstants - Récupère les constantes
    • ReflectionClass::getConstructor - Récupère le constructeur d'une classe
    • ReflectionClass::getDefaultProperties - Récupère les propriétés par défaut
    • ReflectionClass::getDocComment - Récupère les commentaires de documentation
    • ReflectionClass::getEndLine - Récupère la fin d'une ligne
    • ReflectionClass::getExtension - Récupère un objet ReflectionExtension pour l'extension qui définit la classe
    • ReflectionClass::getExtensionName - Récupère le nom de l'extension qui définit la classe
    • ReflectionClass::getFileName - Récupère le nom du fichier où la classe a été déclaré
    • ReflectionClass::getInterfaceNames - Récupère les noms des interfaces
    • ReflectionClass::getInterfaces - Récupère les interfaces
    • ReflectionClass::getMethod - Récupère un ReflectionMethod pour une méthode de classe
    • ReflectionClass::getMethods - Récupère un tableau des méthodes
    • ReflectionClass::getModifiers - Récupère les modificateurs de classe
    • ReflectionClass::getName - Récupère le nom de la classe
    • ReflectionClass::getNamespaceName - Récupère l'espace de noms
    • ReflectionClass::getParentClass - Récupère la classe parente
    • ReflectionClass::getProperties - Récupère les propriétés
    • ReflectionClass::getProperty - Récupère une ReflectionProperty pour une propriété d'une classe
    • ReflectionClass::getReflectionConstant - Récupère un ReflectionClassConstant pour une constante d'une classe
    • ReflectionClass::getReflectionConstants - Récupère les constantes de classe
    • ReflectionClass::getShortName - Récupère le nom court d'une classe
    • ReflectionClass::getStartLine - Récupère le numéro de ligne de départ
    • ReflectionClass::getStaticProperties - Récupère les propriétés statiques
    • ReflectionClass::getStaticPropertyValue - Récupère la valeur d'une propriété statique
    • ReflectionClass::getTraitAliases - Retourne un tableau des alias du trait
    • ReflectionClass::getTraitNames - Retourne un tableau de noms des traits utilisés par cette classe
    • ReflectionClass::getTraits - Retourne un tableau des traits utilisés par cette classe
    • ReflectionClass::hasConstant - Vérifie si une constante est définie
    • ReflectionClass::hasMethod - Vérifie si une méthode est définie
    • ReflectionClass::hasProperty - Vérifie si une propriété est définie
    • ReflectionClass::implementsInterface - Vérifie si une classe implémente une interface
    • ReflectionClass::inNamespace - Vérifie si une classe est définie dans un espace de noms
    • ReflectionClass::isAbstract - Vérifie si une classe est abstraite
    • ReflectionClass::isAnonymous - Vérifie si la classe est anonyme
    • ReflectionClass::isCloneable - Renseigne à propos de la propriété de duplication de la classe
    • ReflectionClass::isEnum - Returns whether this is an enum
    • ReflectionClass::isFinal - Vérifie si une classe est finale
    • ReflectionClass::isInstance - Vérifie si une classe est une instance d'une autre classe
    • ReflectionClass::isInstantiable - Vérifie si une classe est instanciable
    • ReflectionClass::isInterface - Vérifie si une classe est une interface
    • ReflectionClass::isInternal - Vérifie si une classe est définie comme interne par une extension
    • ReflectionClass::isIterable - Vérifie si cette classe est itérable
    • ReflectionClass::isIterateable - Alias de ReflectionClass::isIterable
    • ReflectionClass::isReadOnly - Checks if class is readonly
    • ReflectionClass::isSubclassOf - Vérifie si la classe est une sous-classe
    • ReflectionClass::isTrait - Renseigne s'il s'agit d'un trait
    • ReflectionClass::isUserDefined - Vérifie si une classe a été définie dans l'espace utilisateur
    • ReflectionClass::newInstance - Créer une nouvelle instance de la classe en utilisant les arguments fournis
    • ReflectionClass::newInstanceArgs - Créer une nouvelle instance en utilisant les arguments fournis
    • ReflectionClass::newInstanceWithoutConstructor - Crée une nouvelle instance de la classe sans invoquer le constructeur
    • ReflectionClass::setStaticPropertyValue - Définit la valeur d'une propriété statiques
    • ReflectionClass::__construct - Construit une ReflectionClass
    • ReflectionClass::__toString - Crée une représentation textuelle de l'objet
    • ReflectionClassConstant::export - Exporte
    • ReflectionClassConstant::getAttributes - Gets Attributes
    • ReflectionClassConstant::getDeclaringClass - Récupère la classe déclarante
    • ReflectionClassConstant::getDocComment - Récupère le commentaire de documentation
    • ReflectionClassConstant::getModifiers - Récupère les modificateurs de la constante de classe
    • ReflectionClassConstant::getName - Récupère le nom de la constante
    • ReflectionClassConstant::getValue - Récupère la valeur
    • ReflectionClassConstant::isEnumCase - Checks if class constant is an Enum case
    • ReflectionClassConstant::isFinal - Checks if class constant is final
    • ReflectionClassConstant::isPrivate - Vérifie si la constante de classe est privée
    • ReflectionClassConstant::isProtected - Vérifie si la constante de classe est protégée
    • ReflectionClassConstant::isPublic - Vérifie si la constante de classe est publique
    • ReflectionClassConstant::__construct - Construit une ReflectionClassConstant
    • ReflectionClassConstant::__toString - Retourne la représentation sous forme de chaîne de caractères de l'objet ReflectionClassConstant
    • ReflectionEnum::getBackingType - Gets the backing type of an Enum, if any
    • ReflectionEnum::getCase - Returns a specific case of an Enum
    • ReflectionEnum::getCases - Returns a list of all cases on an Enum
    • ReflectionEnum::hasCase - Checks for a case on an Enum
    • ReflectionEnum::isBacked - Determines if an Enum is a Backed Enum
    • ReflectionEnum::__construct - Instantiates a ReflectionEnum object
    • ReflectionEnumBackedCase::getBackingValue - Gets the scalar value backing this Enum case
    • ReflectionEnumBackedCase::__construct - Instantiates a ReflectionEnumBackedCase object
    • ReflectionEnumUnitCase::getEnum - Gets the reflection of the enum of this case
    • ReflectionEnumUnitCase::getValue - Gets the enum case object described by this reflection object
    • ReflectionEnumUnitCase::__construct - Instantiates a ReflectionEnumUnitCase object
    • ReflectionExtension::export - Exportation
    • ReflectionExtension::getClasses - Récupère les classes
    • ReflectionExtension::getClassNames - Récupère les noms des classes
    • ReflectionExtension::getConstants - Récupère les constantes
    • ReflectionExtension::getDependencies - Récupère les dépendances
    • ReflectionExtension::getFunctions - Récupère les fonctions d'une extension
    • ReflectionExtension::getINIEntries - Récupère les entrées ini de l'extension
    • ReflectionExtension::getName - Récupère le nom de l'extension
    • ReflectionExtension::getVersion - Récupère la version de l'extension
    • ReflectionExtension::info - Affiche des informations sur l'extension
    • ReflectionExtension::isPersistent - Vérifie si l'extension est persistante
    • ReflectionExtension::isTemporary - Vérifie si l'extension est temporaire
    • ReflectionExtension::__clone - Clonage
    • ReflectionExtension::__construct - Construit un nouvel objet ReflectionExtension
    • ReflectionExtension::__toString - Récupère une représentation textuelle
    • ReflectionFiber::getCallable - Gets the callable used to create the Fiber
    • ReflectionFiber::getExecutingFile - Get the file name of the current execution point
    • ReflectionFiber::getExecutingLine - Get the line number of the current execution point
    • ReflectionFiber::getFiber - Get the reflected Fiber instance
    • ReflectionFiber::getTrace - Get the backtrace of the current execution point
    • ReflectionFiber::__construct - Constructs a ReflectionFiber object
    • ReflectionFunction::export - Exporte une fonction
    • ReflectionFunction::getClosure - Retourne une fermeture créée dynamiquement pour la fonction
    • ReflectionFunction::invoke - Invoque une fonction
    • ReflectionFunction::invokeArgs - Invoque les arguments d'une fonction
    • ReflectionFunction::isAnonymous - Checks if a function is anonymous
    • ReflectionFunction::isDisabled - Vérifie si une fonction est désactivée
    • ReflectionFunction::__construct - Construit un nouvel objet ReflectionFunction
    • ReflectionFunction::__toString - Retourne une représentation textuelle de l'objet ReflectionFunction
    • ReflectionFunctionAbstract::getAttributes - Gets Attributes
    • ReflectionFunctionAbstract::getClosureScopeClass - Retourne la portée de la classe associée à la fermeture
    • ReflectionFunctionAbstract::getClosureThis - Retourne le pointeur lié à la fermeture
    • ReflectionFunctionAbstract::getClosureUsedVariables - Returns an array of the used variables in the Closure
    • ReflectionFunctionAbstract::getDocComment - Récupère un commentaire
    • ReflectionFunctionAbstract::getEndLine - Récupère le numéro de la dernière ligne
    • ReflectionFunctionAbstract::getExtension - Récupère les informations d'une extension
    • ReflectionFunctionAbstract::getExtensionName - Récupère le nom de l'extension
    • ReflectionFunctionAbstract::getFileName - Récupère le nom du fichier
    • ReflectionFunctionAbstract::getName - Récupère le nom d'une fonction
    • ReflectionFunctionAbstract::getNamespaceName - Récupère l'espace de noms
    • ReflectionFunctionAbstract::getNumberOfParameters - Récupère le nombre de paramètres
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters - Récupère le nombre de paramètres requis
    • ReflectionFunctionAbstract::getParameters - Récupère les paramètres
    • ReflectionFunctionAbstract::getReturnType - Récupère le type de retour définit pour une fonction
    • ReflectionFunctionAbstract::getShortName - Récupère le nom court d'une fonction
    • ReflectionFunctionAbstract::getStartLine - Récupère le numéro de ligne de départ
    • ReflectionFunctionAbstract::getStaticVariables - Récupère les variables statiques
    • ReflectionFunctionAbstract::getTentativeReturnType - Returns the tentative return type associated with the function
    • ReflectionFunctionAbstract::hasReturnType - Vérifie si la fonction a un type de retour définit
    • ReflectionFunctionAbstract::hasTentativeReturnType - Returns whether the function has a tentative return type
    • ReflectionFunctionAbstract::inNamespace - Vérifie si une fonction est dans un espace de noms
    • ReflectionFunctionAbstract::isClosure - Vérifie si c'est une fermeture
    • ReflectionFunctionAbstract::isDeprecated - Vérifie si la fonction est obsolète
    • ReflectionFunctionAbstract::isGenerator - Vérifie si la fonction est un générateur
    • ReflectionFunctionAbstract::isInternal - Vérifie si la fonction est une fonction interne
    • ReflectionFunctionAbstract::isStatic - Vérifie si la fonction est statique
    • ReflectionFunctionAbstract::isUserDefined - Vérifie si la fonction est définie dans l'espace utilisateur
    • ReflectionFunctionAbstract::isVariadic - Vérifie si la fonction est variadique
    • ReflectionFunctionAbstract::returnsReference - Vérifie si la fonction retourne une référence
    • ReflectionFunctionAbstract::__clone - Clone une fonction
    • ReflectionFunctionAbstract::__toString - Récupère une représentation textuelle d'un objet ReflectionFunctionAbstract
    • ReflectionGenerator::getExecutingFile - Récupère le nom de fichier du générateur actuellement exécuté
    • ReflectionGenerator::getExecutingGenerator - Récupère l'objet Generator exécuté
    • ReflectionGenerator::getExecutingLine - Récupère la ligne actuellement exécutée du générateur
    • ReflectionGenerator::getFunction - Récupère le nom de fonction du générateur
    • ReflectionGenerator::getThis - Récupère la valeur de $this du générateur
    • ReflectionGenerator::getTrace - Récupère la trace du générateur exécutant
    • ReflectionGenerator::__construct - Construit un objet ReflectionGenerator
    • ReflectionIntersectionType::getTypes - Returns the types included in the intersection type
    • ReflectionMethod::createFromMethodName - Creates a new ReflectionMethod
    • ReflectionMethod::export - Exportation d'une méthode de reflection
    • ReflectionMethod::getClosure - Retourne une fermeture créée dynamiquement pour la méthode
    • ReflectionMethod::getDeclaringClass - Récupère la déclaration de la classe de la méthode réfléchie
    • ReflectionMethod::getModifiers - Récupère les modificateurs de la méthode
    • ReflectionMethod::getPrototype - Récupère le prototype de la méthode (s'il existe)
    • ReflectionMethod::hasPrototype - Returns whether a method has a prototype
    • ReflectionMethod::invoke - Invoque
    • ReflectionMethod::invokeArgs - Invoque les arguments
    • ReflectionMethod::isAbstract - Vérifie si la méthode est abstraite
    • ReflectionMethod::isConstructor - Vérifie si la méthode est un constructeur
    • ReflectionMethod::isDestructor - Vérifie si la méthode est un destructeur
    • ReflectionMethod::isFinal - Vérifie si la méthode est finale
    • ReflectionMethod::isPrivate - Vérifie si la méthode est privée
    • ReflectionMethod::isProtected - Vérifie si la méthode est protégée
    • ReflectionMethod::isPublic - Vérifie si la méthode est publique
    • ReflectionMethod::setAccessible - Définit l'accessibilité de la méthode
    • ReflectionMethod::__construct - Construit un nouvel objet ReflectionMethod
    • ReflectionMethod::__toString - Retourne une représentation textuelle de la méthode
    • ReflectionNamedType::getName - Récupère le nom du type en tant que chaîne
    • ReflectionNamedType::isBuiltin - Vérifie si c'est un type intégré
    • ReflectionObject::export - Exportation
    • ReflectionObject::__construct - Construit un nouvel objet ReflectionObject
    • ReflectionParameter::allowsNull - Vérifie si la valeur null est autorisée comme valeur du paramètre
    • ReflectionParameter::canBePassedByValue - Vérifie si le paramètre peut être passé par valeur
    • ReflectionParameter::export - Exportation
    • ReflectionParameter::getAttributes - Gets Attributes
    • ReflectionParameter::getClass - Récupère un objet ReflectionClass pour le paramètre étant reflété ou null
    • ReflectionParameter::getDeclaringClass - Récupère la classe déclarante
    • ReflectionParameter::getDeclaringFunction - Récupère la fonction déclarante
    • ReflectionParameter::getDefaultValue - Récupère la valeur par défaut du paramètre
    • ReflectionParameter::getDefaultValueConstantName - Retourne le nom de la constante de la valeur par défaut si la valeur est une constante ou null
    • ReflectionParameter::getName - Récupère le nom du paramètre
    • ReflectionParameter::getPosition - Récupère la position d'un paramètre
    • ReflectionParameter::getType - Récupère le type du paramètre
    • ReflectionParameter::hasType - Vérifie si un paramètre a un type
    • ReflectionParameter::isArray - Vérifie si le paramètre attend un tableau
    • ReflectionParameter::isCallable - Vérifie si le paramètre est de type callable
    • ReflectionParameter::isDefaultValueAvailable - Vérifie si une valeur par défaut est disponible pour le paramètre
    • ReflectionParameter::isDefaultValueConstant - Vérifie si la valeur par défaut du paramètre est une constante
    • ReflectionParameter::isOptional - Vérifie si le paramètre est optionnel
    • ReflectionParameter::isPassedByReference - Vérifie si le paramètre est passé par référence
    • ReflectionParameter::isVariadic - Vérifie si le paramètre est variadique
    • ReflectionParameter::__clone - Clonage
    • ReflectionParameter::__construct - Constructeur
    • ReflectionParameter::__toString - Récupère une représentation textuelle
    • ReflectionProperty::export - Exporte
    • ReflectionProperty::getAttributes - Gets Attributes
    • ReflectionProperty::getDeclaringClass - Récupère la classe déclarante
    • ReflectionProperty::getDefaultValue - Returns the default value declared for a property
    • ReflectionProperty::getDocComment - Récupère le commentaire de documentation d'une propriété
    • ReflectionProperty::getModifiers - Récupère les modificateurs de propriété
    • ReflectionProperty::getName - Récupère le nom de la propriété
    • ReflectionProperty::getType - Récupère le type d'une propriété
    • ReflectionProperty::getValue - Récupère la valeur de la propriété
    • ReflectionProperty::hasDefaultValue - Checks if property has a default value declared
    • ReflectionProperty::hasType - Vérifie si la propriété à un type
    • ReflectionProperty::isDefault - Vérifie si la propriété est celle par défaut
    • ReflectionProperty::isInitialized - Vérifie si une propriété est initialisée
    • ReflectionProperty::isPrivate - Vérifie si la propriété est privée
    • ReflectionProperty::isPromoted - Checks if property is promoted
    • ReflectionProperty::isProtected - Vérifie si la propriété est protégée
    • ReflectionProperty::isPublic - Vérifie si la propriété est publique
    • ReflectionProperty::isReadOnly - Checks if property is readonly
    • ReflectionProperty::isStatic - Vérifie si la propriété est statique
    • ReflectionProperty::setAccessible - Définit l'accessibilité d'une propriété
    • ReflectionProperty::setValue - Définit la valeur de la propriété
    • ReflectionProperty::__clone - Clonage
    • ReflectionProperty::__construct - Construit un nouvel objet ReflectionProperty
    • ReflectionProperty::__toString - Récupère une représentation textuelle
    • ReflectionReference::fromArrayElement - Create a ReflectionReference from an array element
    • ReflectionReference::getId - Get unique ID of a reference
    • ReflectionReference::__construct - Private constructor to disallow direct instantiation
    • ReflectionType::allowsNull - Vérifie si null est permit
    • ReflectionType::__toString - To string
    • ReflectionUnionType::getTypes - Returns the types included in the union type
    • ReflectionZendExtension::export - Export
    • ReflectionZendExtension::getAuthor - Récupère l'auteur
    • ReflectionZendExtension::getCopyright - Récupère le copyright
    • ReflectionZendExtension::getName - Récupère le nom
    • ReflectionZendExtension::getURL - Récupère l'URL
    • ReflectionZendExtension::getVersion - Récupère la version
    • ReflectionZendExtension::__clone - Gestionnaire de clonage
    • ReflectionZendExtension::__construct - Construit un objet ReflectionZendExtension
    • ReflectionZendExtension::__toString - Gestionnaire de conversion en chaîne de caractères
    • Reflector::export - Exporte
    • RegexIterator::accept - Récupère le statut d'acceptation
    • RegexIterator::getFlags - Récupère les drapeaux
    • RegexIterator::getMode - Retourne le mode de l'opération
    • RegexIterator::getPregFlags - Retourne les drapeaux de l'expression rationnelle
    • RegexIterator::getRegex - Retourne l'expression rationnelle courante
    • RegexIterator::setFlags - Définit les drapeaux
    • RegexIterator::setMode - Définit le mode de l'opération
    • RegexIterator::setPregFlags - Définit les drapeaux de l'expression rationnelle
    • RegexIterator::__construct - Crée un nouvel objet RegexIterator
    • register_shutdown_function - Enregistre une fonction de rappel pour exécution à l'extinction
    • register_tick_function - Enregistre une fonction exécutée à chaque tick
    • rename - Renomme un fichier ou un dossier
    • reset - Remet le pointeur interne de tableau au début
    • ResourceBundle::count - Récupère le nombre d'éléments dans le faisceau
    • ResourceBundle::create - Crée une ressource représentant un faisceau
    • ResourceBundle::get - Récupère les données depuis le faisceau
    • ResourceBundle::getErrorCode - Récupère le dernier code erreur du faisceau
    • ResourceBundle::getErrorMessage - Récupère le dernier message d'erreur depuis le faisceau
    • ResourceBundle::getLocales - Récupère les locales supportées
    • restore_error_handler - Réactive l'ancienne fonction de gestion des erreurs
    • restore_exception_handler - Réactive l'ancienne fonction de gestion d'exceptions
    • restore_include_path - Restaure la valeur de la directive de configuration 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
    • ReturnTypeWillChange::__construct - Construit une nouvelle instance de l'attribut ReturnTypeWillChange
    • rewind - Replace le pointeur de fichier au début
    • rewinddir - Retourne à la première entrée du dossier
    • rmdir - Efface un dossier
    • rnp_backend_string - Return cryptographic backend library name
    • rnp_backend_version - Return cryptographic backend library version
    • rnp_decrypt - Decrypt PGP message
    • rnp_dump_packets - Dump OpenPGP packets stream information in humand-readable format
    • rnp_dump_packets_to_json - Dump OpenPGP packets stream information to the JSON string
    • rnp_ffi_create - Create the top-level object used for interacting with the library
    • rnp_ffi_destroy - Destroy the top-level object used for interacting with the library
    • rnp_ffi_set_pass_provider - Set password provider callback function
    • rnp_import_keys - Import keys from PHP string to the keyring and receive JSON describing new/updated keys
    • rnp_import_signatures - Import standalone signatures to the keyring and receive JSON describing updated keys
    • rnp_key_export - Export a key
    • rnp_key_export_autocrypt - Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)
    • rnp_key_export_revocation - Generate and export primary key revocation signature
    • rnp_key_get_info - Get information about the key
    • rnp_key_remove - Remove a key from keyring(s)
    • rnp_key_revoke - Revoke a key or subkey by generating and adding revocation signature
    • rnp_list_keys - Enumerate all keys present in a keyring by specified identifer type
    • rnp_load_keys - Load keys from PHP string
    • rnp_load_keys_from_path - Load keys from specified path
    • rnp_locate_key - Search for the key
    • rnp_op_encrypt - Encrypt message
    • rnp_op_generate_key - Generate key
    • rnp_op_sign - Perform signing operation on a binary data, return embedded signature(s)
    • rnp_op_sign_cleartext - Perform signing operation on a textual data, return cleartext signed message
    • rnp_op_sign_detached - Perform signing operation, return detached signature(s)
    • rnp_op_verify - Verify embedded or cleartext signatures
    • rnp_op_verify_detached - Verify detached signatures
    • rnp_save_keys - Save keys to PHP string
    • rnp_save_keys_to_path - Save keys to specified path
    • rnp_supported_features - Get supported features in JSON format
    • rnp_version_string - RNP library version
    • rnp_version_string_full - Full version string of RNP library
    • round - Arrondit un nombre à virgule flottante
    • 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
    • rpmgetsymlink - Get target of a symlink
    • rpminfo - Get information from a RPM file
    • rpmvercmp - RPM version comparison
    • RRDCreator::addArchive - Ajoute des valeurs de données RRA - archive pour chaque source de données
    • RRDCreator::addDataSource - Ajoute une définition de source de données pour la base de données RRD
    • RRDCreator::save - Sauvegarde la base de données RRD dans un fichier
    • RRDCreator::__construct - Crée une nouvelle instance RRDCreator
    • rrdc_disconnect - Ferme toutes les connexions vers le daemon de mise en cache rrd
    • RRDGraph::save - Sauvegarde le résultat d'une requête dans une image
    • RRDGraph::saveVerbose - Sauvegarde une requête de base de données RRD dans l'image et retourne les informations verbeuses sur le graphique généré.
    • RRDGraph::setOptions - Définit les options d'exportation d'un graphique RRD
    • RRDGraph::__construct - Crée une nouvelle instance RRDGraph
    • RRDUpdater::update - Met à jour un fichier de base de données RRD
    • RRDUpdater::__construct - Crée une nouvelle instance RRDUpdater
    • rrd_create - Crée un fichier de base de données rrd
    • rrd_error - Récupère le message de la dernière erreur survenue
    • rrd_fetch - Récupère les données pour le graphique
    • rrd_first - Récupère le timestamp du premier échantillon depuis le fichier RRD
    • rrd_graph - Crée une image depuis des données
    • rrd_info - Récupère les informations sur un fichier RRD
    • rrd_last - Récupère le timestamp unix du premier échantillon
    • rrd_lastupdate - Récupère les informations sur les dernières données mises à jour
    • rrd_restore - Restaure le fichier RRD depuis une sauvegarde XML
    • rrd_tune - Affine des options d'en-tête d'un fichier de base de données RRD
    • rrd_update - Met à jour une base de données RRD
    • rrd_version - Récupère les informations de version de la bibliothèque rrdtool
    • rrd_xport - Exporte les informations d'une base de données
    • rsort - Trie un tableau en ordre décroissant
    • rtrim - Supprime les espaces (ou d'autres caractères) de fin de chaîne
    • 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 - Liste les fichiers et dossiers dans un dossier
    • 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 - Record alert log information
    • 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 - Record critical log information
    • SeasLog::debug - Record debug log information
    • SeasLog::emergency - Record emergency log information
    • SeasLog::error - Record error log information
    • SeasLog::flushBuffer - Flush logs buffer, dump to appender file, or send to remote api with tcp/udp
    • SeasLog::getBasePath - Get SeasLog base path.
    • SeasLog::getBuffer - Get the logs buffer in memory as array
    • SeasLog::getBufferEnabled - Determin if buffer enabled
    • SeasLog::getDatetimeFormat - Get SeasLog datetime format style
    • SeasLog::getLastLogger - Get SeasLog last logger path
    • SeasLog::getRequestID - Get SeasLog request_id differentiated requests
    • SeasLog::getRequestVariable - Get SeasLog request variable
    • SeasLog::info - Record info log information
    • SeasLog::log - The Common Record Log Function
    • SeasLog::notice - Record notice log information
    • SeasLog::setBasePath - Set SeasLog base path
    • SeasLog::setDatetimeFormat - Set SeasLog datetime format style
    • SeasLog::setLogger - Set SeasLog logger name
    • SeasLog::setRequestID - Set SeasLog request_id differentiated requests
    • SeasLog::setRequestVariable - Manually set SeasLog request variable
    • SeasLog::warning - Record warning log information
    • SeasLog::__construct - Description
    • SeasLog::__destruct - Description
    • seaslog_get_author - Get SeasLog author.
    • seaslog_get_version - Get SeasLog version.
    • SeekableIterator::seek - Recherche une position
    • sem_acquire - Réserve un sémaphore
    • sem_get - Retourne un identifiant de sémaphore
    • sem_release - Libère un sémaphore
    • sem_remove - Détruit un sémaphore
    • SensitiveParameter::__construct - Construit une nouvelle instance d'attribut SensitiveParameter
    • SensitiveParameterValue::getValue - Retourne la valeur sensible
    • SensitiveParameterValue::__construct - Construit un nouvel objet SensitiveParameterValue
    • SensitiveParameterValue::__debugInfo - Protège la valeur sensible contre une exposition accidentelle
    • Serializable::serialize - Représentation linéaire de l'objet
    • Serializable::unserialize - Construit un objet
    • serialize - Génère une représentation stockable d'une valeur
    • 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 - Ferme la session
    • SessionHandler::create_sid - Retourne un nouvel ID de session
    • SessionHandler::destroy - Détruit une session
    • SessionHandler::gc - Nettoie les anciennes sessions
    • SessionHandler::open - Initialise une session
    • SessionHandler::read - Lit les données de session
    • SessionHandler::write - Ecrit des données dans la session
    • SessionHandlerInterface::close - Ferme la session
    • SessionHandlerInterface::destroy - Détruit une session
    • SessionHandlerInterface::gc - Nettoie les vieilles sessions
    • SessionHandlerInterface::open - Initialise la session
    • SessionHandlerInterface::read - Lit les données de session
    • SessionHandlerInterface::write - Ecrit les données de session
    • SessionIdInterface::create_sid - Créer un ID de session
    • SessionUpdateTimestampHandlerInterface::updateTimestamp - Mettre à jour l'horodatage
    • SessionUpdateTimestampHandlerInterface::validateId - Valider l'ID
    • session_abort - Abandonne les changements sur le tableau de session et termine la session
    • session_cache_expire - Récupère et/ou définie le délai d'expiration du cache
    • session_cache_limiter - Lit et/ou modifie le limiteur de cache de session
    • session_commit - Alias de session_write_close
    • session_create_id - Créer un nouvel ID de session
    • session_decode - Décode les données encodées de session
    • session_destroy - Détruit une session
    • session_encode - Encode les données de session
    • session_gc - Exécute le ramasse miette des données de session
    • session_get_cookie_params - Lit la configuration du cookie de session
    • session_id - Lit et/ou modifie l'identifiant courant de session
    • session_module_name - Lit et/ou modifie le module de session courant
    • session_name - Lit et/ou modifie le nom de la session
    • session_regenerate_id - Remplace l'identifiant de session courant par un nouveau
    • session_register_shutdown - Fonction de fermeture de session
    • session_reset - Réinitialise le tableau de session avec les valeurs originales
    • session_save_path - Lit et/ou modifie le chemin de sauvegarde des sessions
    • session_set_cookie_params - Modifie les paramètres du cookie de session
    • session_set_save_handler - Configure les fonctions de stockage de sessions
    • session_start - Démarre une nouvelle session ou reprend une session existante
    • session_status - Détermine le statut de la session courante
    • session_unset - Détruit toutes les variables d'une session
    • session_write_close - Écrit les données de session et ferme la session
    • setcookie - Envoie un cookie
    • setlocale - Modifie les informations de localisation
    • setrawcookie - Envoie un cookie sans encoder sa valeur en URL
    • settype - Affecte un type à une variable
    • set_error_handler - Spécifie une fonction utilisateur comme gestionnaire d'erreurs
    • set_exception_handler - Définit une fonction utilisateur de gestion d'exceptions
    • set_file_buffer - Alias de stream_set_write_buffer
    • set_include_path - Modifie la valeur de la directive de configuration include_path
    • set_time_limit - Fixe le temps maximum d'exécution d'un script
    • sha1 - Calcule le sha1 d'une chaîne de caractères
    • sha1_file - Calcule le sha1 d'un fichier
    • shell_exec - Exécute une commande via le Shell et retourne le résultat sous forme de chaîne
    • shmop_close - Ferme un bloc de mémoire partagée
    • shmop_delete - Détruit un bloc de mémoire partagée
    • shmop_open - Crée ou ouvre un bloc de mémoire partagée
    • shmop_read - Lit des données à partir d'un bloc
    • shmop_size - Lire la taille du bloc de mémoire partagée
    • shmop_write - Écrire dans un bloc de mémoire partagée
    • shm_attach - Crée ou ouvre un segment de mémoire partagée
    • shm_detach - Libère un segment de mémoire partagée
    • shm_get_var - Lit une variable dans la mémoire partagée
    • shm_has_var - Vérifie si une variable existe en mémoire partagée
    • shm_put_var - Insère ou modifie une variable de la mémoire partagée
    • shm_remove - Supprime un segment de mémoire partagée sous Unix
    • shm_remove_var - Efface une variable de la mémoire partagée
    • show_source - Alias de highlight_file
    • shuffle - Mélange les éléments d'un tableau
    • simdjson_decode - Decodes a JSON string
    • simdjson_is_valid - Check if a JSON string is valid
    • simdjson_key_count - Returns the value at a JSON pointer.
    • simdjson_key_exists - Check if the JSON contains the value referred to by a JSON pointer.
    • simdjson_key_value - Decodes the value of a JSON string located at the requested JSON pointer.
    • similar_text - Calcule la similarité de deux chaînes
    • SimpleXMLElement::addAttribute - Ajoute un attribut à l'élément SimpleXML
    • SimpleXMLElement::addChild - Ajoute un élément enfant au nœud XML
    • SimpleXMLElement::asXML - Retourne une chaîne XML basée sur un élément SimpleXML
    • SimpleXMLElement::attributes - Identifie les attributs d'un élément
    • SimpleXMLElement::children - Cherche les fils d'un nœud donné
    • SimpleXMLElement::count - Compte le nombre de fils pour un élément
    • SimpleXMLElement::current - Retourne l'entrée courante
    • SimpleXMLElement::getChildren - Renvoie les sous-éléments de l'élément courant
    • SimpleXMLElement::getDocNamespaces - Retourne les espaces de noms déclarés dans un document
    • SimpleXMLElement::getName - Récupère le nom d'un élément XML
    • SimpleXMLElement::getNamespaces - Retourne les espaces de noms utilisés dans un document
    • SimpleXMLElement::hasChildren - Vérifie si l'élément actuel a des sous-éléments
    • SimpleXMLElement::key - Retourne la clé courante
    • SimpleXMLElement::next - Se déplace sur l'élément suivant
    • SimpleXMLElement::registerXPathNamespace - Crée un contexte préfixe/ns pour la prochaine requête XPath
    • SimpleXMLElement::rewind - Replace le pointeur au début
    • SimpleXMLElement::saveXML - Alias de SimpleXMLElement::asXML
    • SimpleXMLElement::valid - Vérifie si l'élément actuel est valide
    • SimpleXMLElement::xpath - Exécute une requête Xpath sur des données XML
    • SimpleXMLElement::__construct - Crée un nouvel objet SimpleXMLElement
    • SimpleXMLElement::__toString - Retourne le contenu sous forme de chaine
    • simplexml_import_dom - Construit un objet SimpleXMLElement à partir d'un objet DOM
    • simplexml_load_file - Convertit un fichier XML en objet
    • simplexml_load_string - Convertit une chaîne XML en objet
    • sin - Sinus
    • sinh - Sinus hyperbolique
    • sizeof - Alias de count
    • sleep - Arrête l'exécution durant quelques secondes
    • snmp2_get - Récupère un objet SNMP
    • snmp2_getnext - Récupère l'objet SNMP qui suit immédiatement l'identifiant de l'objet fourni
    • snmp2_real_walk - Retourne tous les objets incluant les identifiants de leurs objets respectifs
    • snmp2_set - Définit la valeur d'un objet SNMP
    • snmp2_walk - Récupère tous les objets SNMP depuis un agent
    • snmp3_get - Récupère un objet SNMP
    • snmp3_getnext - Récupère l'objet SNMP qui suit immédiatement l'objet fourni
    • snmp3_real_walk - Retourne tous les objets incluant les identifiants de leurs objets respectifs
    • snmp3_set - Définit la valeur d'un objet SNMP
    • snmp3_walk - Récupère tous les objets SNMP depuis un agent
    • SNMP::close - Ferme une session SNMP
    • SNMP::get - Récupère un objet SNMP
    • SNMP::getErrno - Récupère le dernier code erreur
    • SNMP::getError - Récupère le dernier message d'erreur
    • SNMP::getnext - Récupère un objet SNMP qui suit l'identifiant d'objet fourni
    • SNMP::set - Définit la valeur d'un objet SNMP
    • SNMP::setSecurity - Configure les paramètres de sécurité des sessions SNMPv3
    • SNMP::walk - Récupère le sous-objet d'un objet SNMP
    • SNMP::__construct - Crée une instance SNMP représentant la session vers l'agent distant SNMP
    • snmpget - Reçoit un objet SNMP
    • snmpgetnext - Récupère un objet SNMP qui suit immédiatement l'objet fourni
    • snmprealwalk - Retourne tous les objets, y compris les identifiants respectifs inclus dans l'objet
    • snmpset - Définit la valeur d'un objet SNMP
    • snmpwalk - Reçoit tous les objets SNMP d'un agent
    • snmpwalkoid - Demande d'informations d'arbre sur une entité du réseau
    • snmp_get_quick_print - Lit la valeur courante de l'option quick_print de la bibliothèque NET-SNMP
    • snmp_get_valueretrieval - Retourne la méthode avec laquelle les valeurs SNMP seront retournées
    • snmp_read_mib - Lit et analyse un fichier MIB dans l'arbre actif MIB
    • snmp_set_enum_print - Retourne toutes les valeurs qui sont des énumérations avec leur valeur d'énumération au lieu de l'entier
    • snmp_set_oid_numeric_print - Alias de snmp_set_oid_output_format
    • snmp_set_oid_output_format - Définit le format de sortie OID
    • snmp_set_quick_print - Écrit la valeur courante de l'option enable de la bibliothèque NET-SNMP
    • snmp_set_valueretrieval - Spécifie la méthode avec laquelle les valeurs SNMP seront retournées
    • SoapClient::__call - Appelle une fonction SOAP (obsolète)
    • SoapClient::__construct - Constructeur SoapClient
    • SoapClient::__doRequest - Exécute une requête SOAP
    • SoapClient::__getCookies - Get list of cookies
    • SoapClient::__getFunctions - Retourne une liste de fonctions SOAP publiées
    • SoapClient::__getLastRequest - Retourne la dernière requête SOAP
    • SoapClient::__getLastRequestHeaders - Retourne les en-têtes de la dernière requête SOAP
    • SoapClient::__getLastResponse - Retourne la dernière réponse SOAP
    • SoapClient::__getLastResponseHeaders - Retourne les en-têtes de la dernière réponse SOAP
    • SoapClient::__getTypes - Retourne une liste des types SOAP
    • SoapClient::__setCookie - Définit un cookie pour les requêtes SOAP
    • SoapClient::__setLocation - Configure l'URL du service Web à utiliser
    • SoapClient::__setSoapHeaders - Ajoute un en-tête SOAP pour les requêtes suivantes
    • SoapClient::__soapCall - Appelle une fonction SOAP
    • SoapFault::__construct - Constructeur SoapFault
    • SoapFault::__toString - Produit une représentation chaîne d'un objet SoapFault
    • SoapHeader::__construct - Constructeur SoapHeader
    • SoapParam::__construct - Constructeur SoapParam
    • SoapServer::addFunction - Ajoute une ou plusieurs fonctions qui vont gérer les requêtes SOAP
    • SoapServer::addSoapHeader - Ajoute un en-tête SOAP à une réponse
    • SoapServer::fault - Emet une erreur SoapServer
    • SoapServer::getFunctions - Retourne la liste des fonctions définies
    • SoapServer::handle - Traite une requête SOAP
    • SoapServer::setClass - Configure la classe qui sera utilisée pour gérer les requêtes SOAP
    • SoapServer::setObject - Configure l'objet qui sera utilisé pour gérer les requêtes SOAP
    • SoapServer::setPersistence - Active le mode persistant de SoapServer
    • SoapServer::__construct - Constructeur SoapServer
    • SoapVar::__construct - Constructeur SoapVar
    • socket_accept - Accepte une connexion sur un 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_atmark - Determines whether socket is at out-of-band mark
    • socket_bind - Lie un nom à un socket
    • socket_clear_error - Efface toutes les erreurs précédemment générées par un socket
    • socket_close - Ferme une instance de Socket
    • socket_cmsg_space - Calcule la taille du buffer
    • socket_connect - Crée une connexion sur un socket
    • socket_create - Crée un socket
    • socket_create_listen - Ouvre un socket sur un port pour accepter les connexions
    • socket_create_pair - Crée une paire de sockets identiques et les stocke dans un tableau
    • socket_export_stream - Export a socket into a stream that encapsulates a socket
    • socket_getopt - Alias de socket_get_option
    • socket_getpeername - Interroge l'autre extrémité de la communication
    • socket_getsockname - Interroge le socket local
    • socket_get_option - Lit les options du socket
    • socket_get_status - Alias de stream_get_meta_data
    • socket_import_stream - Importe un flux
    • socket_last_error - Lit la dernière erreur générée par un socket
    • socket_listen - Attend une connexion sur un socket
    • socket_read - Lit des données d'un socket
    • socket_recv - Reçoit des données d'un socket connecté
    • socket_recvfrom - Reçoit des données d'un socket, connecté ou pas
    • socket_recvmsg - Lit un message
    • socket_select - Exécute l'appel système select() sur un tableau de sockets avec une durée d'expiration
    • socket_send - Envoie des données à un socket connecté
    • socket_sendmsg - Envoi un message
    • socket_sendto - Envoie un message à un socket, qu'il soit connecté ou pas
    • socket_setopt - Alias de socket_set_option
    • socket_set_block - Met le socket en mode bloquant
    • socket_set_blocking - Alias de stream_set_blocking
    • socket_set_nonblock - Sélectionne le mode non bloquant d'un pointeur de fichier
    • socket_set_option - Modifie les options de socket
    • socket_set_timeout - Alias de stream_set_timeout
    • socket_shutdown - Éteint un socket en lecture et/ou écriture
    • socket_strerror - Retourne une chaîne décrivant un message d'erreur
    • socket_write - Écrit dans un 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 - Decodes a base64-encoded string into raw binary.
    • sodium_bin2base64 - Encodes a raw binary string with base64.
    • sodium_bin2hex - Encode to hexadecimal
    • sodium_compare - Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt - Verify then decrypt a message with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_encrypt - Encrypt then authenticate with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_is_available - Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen - Generate a random AES-256-GCM key
    • sodium_crypto_aead_chacha20poly1305_decrypt - Verify then decrypt with ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_encrypt - Encrypt then authenticate with ChaCha20-Poly1305
    • 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 - Generate a random ChaCha20-Poly1305 (IETF) key.
    • sodium_crypto_aead_chacha20poly1305_keygen - Generate a random ChaCha20-Poly1305 key.
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt - (Preferred) Verify then decrypt with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt - (Preferred) Encrypt then authenticate with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen - Generate a random XChaCha20-Poly1305 key.
    • sodium_crypto_auth - Compute a tag for the message
    • sodium_crypto_auth_keygen - Generate a random key for sodium_crypto_auth
    • sodium_crypto_auth_verify - Verifies that the tag is valid for the message
    • sodium_crypto_box - Authenticated public-key encryption
    • sodium_crypto_box_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_keypair_from_secretkey_and_publickey - Create a unified keypair string from a secret key and public key
    • sodium_crypto_box_open - Authenticated public-key decryption
    • sodium_crypto_box_publickey - Extract the public key from a crypto_box keypair
    • sodium_crypto_box_publickey_from_secretkey - Calculate the public key from a secret key
    • sodium_crypto_box_seal - Anonymous public-key encryption
    • sodium_crypto_box_seal_open - Anonymous public-key decryption
    • sodium_crypto_box_secretkey - Extracts the secret key from a crypto_box keypair
    • sodium_crypto_box_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_core_ristretto255_add - Adds an element
    • sodium_crypto_core_ristretto255_from_hash - Maps a vector
    • sodium_crypto_core_ristretto255_is_valid_point - Determines if a point on the ristretto255 curve
    • sodium_crypto_core_ristretto255_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_add - Adds a scalar value
    • sodium_crypto_core_ristretto255_scalar_complement - The sodium_crypto_core_ristretto255_scalar_complement purpose
    • sodium_crypto_core_ristretto255_scalar_invert - Inverts a scalar value
    • sodium_crypto_core_ristretto255_scalar_mul - Multiplies a scalar value
    • sodium_crypto_core_ristretto255_scalar_negate - Negates a scalar value
    • sodium_crypto_core_ristretto255_scalar_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_reduce - Reduces a scalar value
    • sodium_crypto_core_ristretto255_scalar_sub - Subtracts a scalar value
    • sodium_crypto_core_ristretto255_sub - Subtracts an element
    • sodium_crypto_generichash - Get a hash of the message
    • sodium_crypto_generichash_final - Complete the hash
    • sodium_crypto_generichash_init - Initialize a hash for streaming
    • sodium_crypto_generichash_keygen - Generate a random generichash key
    • sodium_crypto_generichash_update - Add message to a hash
    • sodium_crypto_kdf_derive_from_key - Derive a subkey
    • sodium_crypto_kdf_keygen - Generate a random root key for the KDF interface
    • sodium_crypto_kx_client_session_keys - Calculate the client-side session keys.
    • sodium_crypto_kx_keypair - Creates a new sodium keypair
    • sodium_crypto_kx_publickey - Extract the public key from a crypto_kx keypair
    • sodium_crypto_kx_secretkey - Extract the secret key from a crypto_kx keypair.
    • sodium_crypto_kx_seed_keypair - Description
    • sodium_crypto_kx_server_session_keys - Calculate the server-side session keys.
    • sodium_crypto_pwhash - Derive a key from a password, using Argon2
    • sodium_crypto_pwhash_scryptsalsa208sha256 - Derives a key from a password, using scrypt
    • 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 - Determine whether or not to rehash a password
    • 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 - Alias de sodium_crypto_box_publickey_from_secretkey
    • sodium_crypto_scalarmult_ristretto255 - Computes a shared secret
    • sodium_crypto_scalarmult_ristretto255_base - Calculates the public key from a secret key
    • sodium_crypto_secretbox - Authenticated shared-key encryption
    • sodium_crypto_secretbox_keygen - Generate random key for sodium_crypto_secretbox
    • sodium_crypto_secretbox_open - Authenticated shared-key decryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull - Initialize a secretstream context for decryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_push - Initialize a secretstream context for encryption
    • sodium_crypto_secretstream_xchacha20poly1305_keygen - Generate a random secretstream key.
    • sodium_crypto_secretstream_xchacha20poly1305_pull - Decrypt a chunk of data from an encrypted stream
    • sodium_crypto_secretstream_xchacha20poly1305_push - Encrypt a chunk of data so that it can safely be decrypted in a streaming API
    • sodium_crypto_secretstream_xchacha20poly1305_rekey - Explicitly rotate the key in the secretstream state
    • sodium_crypto_shorthash - Compute a short hash of a message and key
    • 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 - Join a secret key and public key together
    • sodium_crypto_sign_open - Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey - Extract the Ed25519 public key from a keypair
    • sodium_crypto_sign_publickey_from_secretkey - Extract the Ed25519 public key from the secret key
    • sodium_crypto_sign_secretkey - Extract the Ed25519 secret key from a keypair
    • 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 - Generate a random sodium_crypto_stream key.
    • sodium_crypto_stream_xchacha20 - Expands the key and nonce into a keystream of pseudorandom bytes
    • sodium_crypto_stream_xchacha20_keygen - Returns a secure random key
    • sodium_crypto_stream_xchacha20_xor - Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xchacha20_xor_ic - Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xor - Encrypt a message without authentication
    • sodium_hex2bin - Decodes a hexadecimally encoded binary string
    • sodium_increment - Increment large number
    • sodium_memcmp - Test for equality in constant-time
    • sodium_memzero - Overwrite a string with NUL characters
    • sodium_pad - Add padding data
    • sodium_unpad - Remove padding data
    • SolrClient::addDocument - Ajoute un document à l'index
    • SolrClient::addDocuments - Ajoute une collection d'instances SolrInputDocument à l'index
    • SolrClient::commit - Commit tous les ajouts/modifications effectués sur l'index
    • SolrClient::deleteById - Effacement par Id
    • SolrClient::deleteByIds - Effacement par Ids
    • SolrClient::deleteByQueries - Efface tous les documents correspondant à des requêtes
    • SolrClient::deleteByQuery - Efface tous les documents correspondant à une requête
    • 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 - Récupère les données de débogage de la dernière tentative de connexion
    • SolrClient::getOptions - Récupère les options clientes définies en interne
    • SolrClient::optimize - Défragmente l'index
    • SolrClient::ping - Vérifie si le serveur Solr est disponible
    • SolrClient::query - Envoi une requête au serveur
    • SolrClient::request - Envoi une requête brute de mise à jour
    • SolrClient::rollback - Annule les ajouts/effacements effectués sur l'index depuis le dernier commit
    • SolrClient::setResponseWriter - Définit le gestionnaire à utiliser pour préparer la réponse depuis Solr
    • SolrClient::setServlet - Modifie le type d'un servlet en une nouvelle valeur
    • SolrClient::system - Retrieve Solr Server information
    • SolrClient::threads - Vérifie le statut des threads
    • SolrClient::__construct - Constructeur de l'objet SolrClient
    • SolrClient::__destruct - Destructeur pour SolrClient
    • SolrClientException::getInternalInfo - Retourne des informations internes sur l'endroit d'où est lancée l'exception
    • 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 - Ajoute un champ au document
    • SolrDocument::clear - Efface tous les champs du document
    • SolrDocument::current - Récupère le champ courant
    • SolrDocument::deleteField - Efface un champ du document
    • SolrDocument::fieldExists - Vérifie si un champ existe dans le document
    • SolrDocument::getChildDocuments - Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrDocument::getField - Récupère un champ par son nom
    • SolrDocument::getFieldCount - Récupère le nombre de champs du document
    • SolrDocument::getFieldNames - Récupère un tableau de noms de champs du document
    • SolrDocument::getInputDocument - Retourne un objet SolrInputDocument équivalent à l'objet
    • SolrDocument::hasChildDocuments - Checks whether the document has any child documents
    • SolrDocument::key - Récupère la clé courante
    • SolrDocument::merge - Fusionne la source à l'objet SolrDocument courant
    • SolrDocument::next - Déplace le pointeur interne sur le champ suivant
    • SolrDocument::offsetExists - Vérifie si un champ particulier existe
    • SolrDocument::offsetGet - Récupère un champ
    • SolrDocument::offsetSet - Ajoute un champ au document
    • SolrDocument::offsetUnset - Efface un champ
    • SolrDocument::reset - Alias de SolrDocument::clear
    • SolrDocument::rewind - Réinitialise le pointeur interne au début
    • SolrDocument::serialize - Utilisé pour une sérialisation personnalisée
    • SolrDocument::sort - Trie les champs du document
    • SolrDocument::toArray - Récupère un tableau représentant le document
    • SolrDocument::unserialize - Sérialisation personnalisée d'objets SolrDocument
    • SolrDocument::valid - Vérifie si la position courant interne est toujours valide
    • SolrDocument::__clone - Crée une copie de l'objet SolrDocument
    • SolrDocument::__construct - Constructeur
    • SolrDocument::__destruct - Destructeur
    • SolrDocument::__get - Accède à un champ comme une propriété
    • SolrDocument::__isset - Vérifie si un champ existe
    • SolrDocument::__set - Ajoute un champ au document
    • SolrDocument::__unset - Efface un champ du document
    • SolrDocumentField::__construct - Constructeur
    • SolrDocumentField::__destruct - Destructeur
    • SolrException::getInternalInfo - Récupère des informations internes lorsqu'une exception a été lancée
    • SolrGenericResponse::__construct - Constructeur
    • SolrGenericResponse::__destruct - Destructeur
    • SolrIllegalArgumentException::getInternalInfo - Retourne des informations sur l'endroit d'où l'exception a été émise
    • SolrIllegalOperationException::getInternalInfo - Récupère des informations internes lorsqu'une exception a été lancée
    • SolrInputDocument::addChildDocument - Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments - Adds an array of child documents
    • SolrInputDocument::addField - Ajoute un champ au document
    • SolrInputDocument::clear - Réinitialise le document d'entrée
    • SolrInputDocument::deleteField - Efface un champ d'un document
    • SolrInputDocument::fieldExists - Vérifie si un champ existe
    • SolrInputDocument::getBoost - Récupère la valeur courante du boost pour le document
    • SolrInputDocument::getChildDocuments - Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrInputDocument::getField - Récupère un champ par son nom
    • SolrInputDocument::getFieldBoost - Récupère la valeur du boost pour un champ donné
    • SolrInputDocument::getFieldCount - Retourne le nombre de champs du document
    • SolrInputDocument::getFieldNames - Retourne un tableau contenant tous les champs du document
    • SolrInputDocument::hasChildDocuments - Returns true if the document has any child documents
    • SolrInputDocument::merge - Fusionne un document d'entrée dans un autre
    • SolrInputDocument::reset - Alias de SolrInputDocument::clear
    • SolrInputDocument::setBoost - Définit la valeur de boost pour le document
    • SolrInputDocument::setFieldBoost - Définit la valeur de boost pour un champ
    • SolrInputDocument::sort - Tri les champs du document
    • SolrInputDocument::toArray - Retourne un représentation sous forme de tableau du document d'entrée
    • SolrInputDocument::__clone - Crée une copie de l'objet SolrDocument
    • SolrInputDocument::__construct - Constructeur
    • SolrInputDocument::__destruct - Destructeur
    • SolrModifiableParams::__construct - Constructeur
    • SolrModifiableParams::__destruct - Destructeur
    • SolrObject::getPropertyNames - Récupère un tableau contenant les noms de toutes les propriétés
    • SolrObject::offsetExists - Vérifie si une propriété existe
    • SolrObject::offsetGet - Récupère une propriété
    • SolrObject::offsetSet - Définit la valeur d'une propriété
    • SolrObject::offsetUnset - Supprime la valeur de la propriété
    • SolrObject::__construct - Crée un objet Solr
    • SolrObject::__destruct - Destructeur
    • SolrParams::add - Alias de SolrParams::addParam
    • SolrParams::addParam - Ajoute un paramètre à l'objet
    • SolrParams::get - Alias de SolrParams::getParam
    • SolrParams::getParam - Retourne la valeur d'un paramètre
    • SolrParams::getParams - Retourne un tableau de paramètres non encodés URL
    • SolrParams::getPreparedParams - Retourne un tableau de paramètres encodés URL
    • SolrParams::serialize - Utilisé pour une sérialisation personnalisée
    • SolrParams::set - Alias de SolrParams::setParam
    • SolrParams::setParam - Définit un paramètre à une valeur spécifique
    • SolrParams::toString - Retourne tous les paramètres de l'objet
    • SolrParams::unserialize - Utilisé pour la sérialisation personnalisée
    • SolrPingResponse::getResponse - Récupère la réponse du serveur
    • SolrPingResponse::__construct - Constructeur
    • SolrPingResponse::__destruct - Destructeur
    • 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 - Lie un facet.date
    • SolrQuery::addFacetDateOther - Ajoute une autre paramètre facet.date.other
    • SolrQuery::addFacetField - Ajoute un autre champ à la facette
    • SolrQuery::addFacetQuery - Ajoute une requête de facette
    • SolrQuery::addField - Spécifie quel champ doit retourner le résultat
    • SolrQuery::addFilterQuery - Spécifie un filtre de requête
    • 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 - Lie un hl.fl
    • SolrQuery::addMltField - Spécifie un champ à utiliser pour les similitudes
    • SolrQuery::addMltQueryField - Lie un mlt.qf
    • SolrQuery::addSortField - Utilisé pour contrôler le tri du résultat
    • SolrQuery::addStatsFacet - Récupère un sous résultat pour y trouver des valeurs d'une facette donnée
    • SolrQuery::addStatsField - Lie un paramètre stats.field
    • 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 - Retourne la valeur du paramètre de facette
    • SolrQuery::getFacetDateEnd - Retourne la valeur du paramètre facet.date.end
    • SolrQuery::getFacetDateFields - Retourne tous les champs facet.date
    • SolrQuery::getFacetDateGap - Récupère la valeur du paramètre facet.date.gap
    • SolrQuery::getFacetDateHardEnd - Récupère la valeur du paramètre facet.date.hardend
    • SolrQuery::getFacetDateOther - Récupère la valeur du paramètre facet.date.other
    • SolrQuery::getFacetDateStart - Récupère la limite inférieure du premier intervalle de la date pour toutes les facettes de date pour ce champ
    • SolrQuery::getFacetFields - Récupère toutes les facettes des champs
    • SolrQuery::getFacetLimit - Récupère le nombre maximal de contraintes qui peut être retourné pour les facettes des champs
    • SolrQuery::getFacetMethod - Récupère la valeur du paramètre facet.method
    • SolrQuery::getFacetMinCount - Récupère le nombre minimal de facettes des champs qui doivent être incluses dans la réponse
    • SolrQuery::getFacetMissing - Récupère l'état courant du paramètre facet.missing
    • SolrQuery::getFacetOffset - Récupère la position dans la liste des contraintes à utiliser pour la pagination
    • SolrQuery::getFacetPrefix - Récupère le préfixe de la facette
    • SolrQuery::getFacetQueries - Récupère toutes les facettes des requêtes
    • SolrQuery::getFacetSort - Retourne le type de tri de la facette
    • SolrQuery::getFields - Récupère la liste des champs qui seront retournés dans la réponse
    • SolrQuery::getFilterQueries - Récupère un tableau de filtres de requêtes
    • 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 - Récupère l'état du paramètre h1
    • SolrQuery::getHighlightAlternateField - Récupère le champ mis en évidence à utiliser comme champ par défaut ou comme champ de sauvegarde
    • SolrQuery::getHighlightFields - Récupère tous les champs pour lesquels Solr doit mettre en évidence un extrait
    • SolrQuery::getHighlightFormatter - Récupère le formatage utilisé pour mettre en évidence la sortie
    • SolrQuery::getHighlightFragmenter - Récupère le générateur d'extrait de texte pour la mise en évidence
    • SolrQuery::getHighlightFragsize - Retourne le nombre de caractères des fragments à considérer pour la mise en évidence
    • SolrQuery::getHighlightHighlightMultiTerm - Retourne si l'on doit activer la mise en évidence pour les intervalles/jokers/flous/préfixes des requêtes
    • SolrQuery::getHighlightMaxAlternateFieldLength - Retourne le nombre maximal de caractères du champ à retourner
    • SolrQuery::getHighlightMaxAnalyzedChars - Retourne le nombre maximal de caractères du document dans lequel les extraits seront cherchés
    • SolrQuery::getHighlightMergeContiguous - Retourne si l'on doit rassembler les fragments contigus en un seul fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Retourne le nombre maximal de caractères depuis un champ lors de l'utilisation d'une regex
    • SolrQuery::getHighlightRegexPattern - Récupère l'expression rationnelle utilisée pour la fragmentation
    • SolrQuery::getHighlightRegexSlop - Récupère le facteur de déviation depuis la taille du fragment idéal
    • SolrQuery::getHighlightRequireFieldMatch - Retourne si le champ ne doit être mis en évidence que si la requête correspond à un champ en particulier
    • SolrQuery::getHighlightSimplePost - Récupère le texte qui doit apparaître après le terme mise en évidence
    • SolrQuery::getHighlightSimplePre - Retourne le texte qui doit apparaître avant le terme mise en évidence
    • SolrQuery::getHighlightSnippets - Récupère le nombre maximal d'extraits mis en évidence à générer par champ
    • SolrQuery::getHighlightUsePhraseHighlighter - Récupère l'état du paramètre hl.usePhraseHighlighter
    • SolrQuery::getMlt - Retourne si les résultats MoreLikeThis doivent être activés
    • SolrQuery::getMltBoost - Retourne si la requête doit être améliorée en utilisant la pertinence des termes
    • SolrQuery::getMltCount - Récupère le nombre de documents similaires à retourner pour chaque résultat
    • SolrQuery::getMltFields - Récupère tous les champs à utiliser pour la similarité
    • SolrQuery::getMltMaxNumQueryTerms - Retourne le nombre maximal de termes de requête qui peuvent être inclus lors de la génération d'une requête
    • SolrQuery::getMltMaxNumTokens - Retourne le nombre maximal de jokers à analyser dans chaque champ du document
    • SolrQuery::getMltMaxWordLength - Retourne la longueur minimale des mots en deçà de laquelle ils seront ignorés
    • SolrQuery::getMltMinDocFrequency - Retourne le seuil de fréquence d'apparition des mots
    • SolrQuery::getMltMinTermFrequency - Retourne la fréquence en deçà duquel les termes doivent être ignorés dans le document source
    • SolrQuery::getMltMinWordLength - Retourne la longueur minimum d'un mot en deça duquel il sera ignoré
    • SolrQuery::getMltQueryFields - Retourne les champs de la requête ainsi que leurs boosts
    • SolrQuery::getQuery - Retourne la requête principale
    • SolrQuery::getRows - Retourne le nombre maximal de documents
    • SolrQuery::getSortFields - Retourne tous les champs de tri
    • SolrQuery::getStart - Retourne la position dans le jeu complet de résultats
    • SolrQuery::getStats - Vérifie si les statistiques sont actives ou non
    • SolrQuery::getStatsFacets - Retourne toutes les statistiques définies
    • SolrQuery::getStatsFields - Retourne les statistiques des champs
    • SolrQuery::getTerms - Vérifie si le TermsComponent est activé ou non
    • SolrQuery::getTermsField - Récupère le champ depuis lequel les termes sont récupérés
    • SolrQuery::getTermsIncludeLowerBound - Vérifie si l'on doit inclure ou non la limite inférieure dans le jeu de résultats
    • SolrQuery::getTermsIncludeUpperBound - Vérifie si l'on doit inclure ou non la limite supérieure dans le jeu de résultats
    • SolrQuery::getTermsLimit - Retourne le nombre maximal de termes que Solr peut retourner
    • SolrQuery::getTermsLowerBound - Retourne le terme sur lequel on doit commencer
    • SolrQuery::getTermsMaxCount - Retourne la fréquence maximale des documents
    • SolrQuery::getTermsMinCount - Retourne la fréquence minimale des documents
    • SolrQuery::getTermsPrefix - Retourne le préfixe du terme
    • SolrQuery::getTermsReturnRaw - Si l'on doit retourner ou non les caractères brutes
    • SolrQuery::getTermsSort - Retourne un entier indiquant le nombre de termes stockés
    • SolrQuery::getTermsUpperBound - Retourne le terme sur lequel on doit s'arrêter
    • SolrQuery::getTimeAllowed - Retourne le délai d'exécution autorisé pour une requête
    • SolrQuery::removeExpandFilterQuery - Removes an expand filter query
    • SolrQuery::removeExpandSortField - Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField - Supprime un champ date
    • SolrQuery::removeFacetDateOther - Supprime un paramètre facet.date.other
    • SolrQuery::removeFacetField - Supprime un paramètre facet.date
    • SolrQuery::removeFacetQuery - Supprime un paramètre facet.query
    • SolrQuery::removeField - Efface un champ depuis la liste des champs
    • SolrQuery::removeFilterQuery - Supprime un filtre de requête
    • SolrQuery::removeHighlightField - Supprime un des champs utilisés pour la mise en évidence
    • SolrQuery::removeMltField - Supprime un des champs moreLikeThis
    • SolrQuery::removeMltQueryField - Supprime un des champs moreLikeThis de la requête
    • SolrQuery::removeSortField - Supprime un champ de tri
    • SolrQuery::removeStatsFacet - Supprime un paramètre stats.facet
    • SolrQuery::removeStatsField - Supprime un paramètre stats.field
    • SolrQuery::setEchoHandler - Bascule le paramètre echoHandler
    • SolrQuery::setEchoParams - Détermine les paramètres à inclure dans la réponse
    • 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 - Définit le paramètre de requête explainOther
    • SolrQuery::setFacet - Lie un paramètre facet. Active ou désactive les facet
    • SolrQuery::setFacetDateEnd - Lie un facet.date.end
    • SolrQuery::setFacetDateGap - Lie un facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Lie un facet.date.hardend
    • SolrQuery::setFacetDateStart - Lie un facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Définit la fréquence minimale du document utilisée pour déterminer le comptage des termes
    • SolrQuery::setFacetLimit - Lie un facet.limit
    • SolrQuery::setFacetMethod - Spécifie le type d'algorithme à utiliser pour un champ facet
    • SolrQuery::setFacetMinCount - Lie un facet.mincount
    • SolrQuery::setFacetMissing - Lie un facet.missing
    • SolrQuery::setFacetOffset - Définit la position dans la liste des contraintes pour la pagination
    • SolrQuery::setFacetPrefix - Spécifie un préfixe utilisé pour limiter les termes
    • SolrQuery::setFacetSort - Détermine le tri des facet
    • 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 - Active ou désactive la coloration
    • SolrQuery::setHighlightAlternateField - Spécifie le champ de sauvegarde à utiliser
    • SolrQuery::setHighlightFormatter - Spécifie un formateur pour la sortie colorisée
    • SolrQuery::setHighlightFragmenter - Définit un générateur d'extraits de texte pour le texte colorisé
    • SolrQuery::setHighlightFragsize - La taille du fragment à considérer pour la coloration
    • SolrQuery::setHighlightHighlightMultiTerm - Utilise SpanScorer pour coloriser les termes d'une phrase
    • SolrQuery::setHighlightMaxAlternateFieldLength - Définit le nombre maximal de caractères du champ à retourner
    • SolrQuery::setHighlightMaxAnalyzedChars - Spécifie le nombre de caractères dans un document pour y chercher des extraits correspondants
    • SolrQuery::setHighlightMergeContiguous - Si l'on doit rassembler les fragments proches dans un seul fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Spécifie le nombre maximal de caractères à analyser
    • SolrQuery::setHighlightRegexPattern - Spécifie l'expression rationnelle pour la fragmentation
    • SolrQuery::setHighlightRegexSlop - Définit le facteur par lequel le fragmenteur regex peut dévier de la taille idéale du fragment
    • SolrQuery::setHighlightRequireFieldMatch - Champ correspondant requis lors de la colorisation
    • SolrQuery::setHighlightSimplePost - Définit le texte qui doit apparaître après un terme colorisé
    • SolrQuery::setHighlightSimplePre - Définit le texte qui doit apparaître avant un terme colorisé
    • SolrQuery::setHighlightSnippets - Définit le nombre maximal d'extraits à coloriser par champ
    • SolrQuery::setHighlightUsePhraseHighlighter - Si l'on doit coloriser les termes d'une phrase uniquement si ils apparaissent dans la requête
    • SolrQuery::setMlt - Active ou désactive moreLikeThis
    • SolrQuery::setMltBoost - Si la requête doit être stimulée par la pertinence des termes
    • SolrQuery::setMltCount - Définit le nombre de documents similaires à retourner à chaque résultat
    • SolrQuery::setMltMaxNumQueryTerms - Définit le nombre maximal de termes de requête à inclure
    • SolrQuery::setMltMaxNumTokens - Spécifie le nombre maximal de motifs à analyser
    • SolrQuery::setMltMaxWordLength - Définit la longueur maximale d'un mot
    • SolrQuery::setMltMinDocFrequency - Définit la fréquence mltMinDoc
    • SolrQuery::setMltMinTermFrequency - Définit la fréquence en dessous de laquelle les termes seront ignorés dans le document source
    • SolrQuery::setMltMinWordLength - Définit la longueur minimale d'un mot
    • SolrQuery::setOmitHeader - Exclut l'en-tête des résultats retournés
    • SolrQuery::setQuery - Définit la requête de recherche
    • SolrQuery::setRows - Spécifie le nombre maximal de lignes à retourner dans le résultat
    • SolrQuery::setShowDebugInfo - Drapeau pour afficher les informations de débogage
    • SolrQuery::setStart - Spécifie le nombre maximal de lignes à ignorer
    • SolrQuery::setStats - Active ou désactive le composant statistique
    • SolrQuery::setTerms - Active ou désactive le TermsComponent
    • SolrQuery::setTermsField - Définit le nom du champ dans lequel les termes seront récupérés
    • SolrQuery::setTermsIncludeLowerBound - Inclut le terme inférieure liée dans le jeu de résultat
    • SolrQuery::setTermsIncludeUpperBound - Inclut le terme supérieure liée dans le jeu de résultat
    • SolrQuery::setTermsLimit - Définit le nombre maximal de termes à retourner
    • SolrQuery::setTermsLowerBound - Spécifie le terme de départ
    • SolrQuery::setTermsMaxCount - Définit la fréquence maximale du document
    • SolrQuery::setTermsMinCount - Définit la fréquence minimale d'un document
    • SolrQuery::setTermsPrefix - Restreint les termes correspondants qui commencent avec un préfixe donné
    • SolrQuery::setTermsReturnRaw - Retourne les caractères brutes d'un terme indexé
    • SolrQuery::setTermsSort - Spécifie la façon dont seront triés les termes retournés
    • SolrQuery::setTermsUpperBound - Définit le terme à partir duquel on doit stopper
    • SolrQuery::setTimeAllowed - Le temps allouée pour faire une recherche
    • SolrQuery::__construct - Constructeur
    • SolrQuery::__destruct - Destructeur
    • SolrQueryResponse::__construct - Constructeur
    • SolrQueryResponse::__destruct - Destructeur
    • SolrResponse::getDigestedResponse - Récupère la réponse XML sous la forme de données PHP sérialisées
    • SolrResponse::getHttpStatus - Récupère le statut HTTP de la réponse
    • SolrResponse::getHttpStatusMessage - Récupère plus de détails sur le statut HTTP
    • SolrResponse::getRawRequest - Récupère la requête brute envpyée au serveur Solr
    • SolrResponse::getRawRequestHeaders - Récupère les en-têtes brutes de la requête envoyée au serveur Solr
    • SolrResponse::getRawResponse - Récupère la réponse brute du serveur
    • SolrResponse::getRawResponseHeaders - Récupère les en-têtes brutes de la réponse du serveur
    • SolrResponse::getRequestUrl - Récupère l'URL complète de la requête émise au serveur
    • SolrResponse::getResponse - Récupère l'objet SolrObject représentant la réponse XML du serveur
    • SolrResponse::setParseMode - Définit le mode d'analyse
    • SolrResponse::success - Vérifie si la requête au serveur a réussi
    • SolrServerException::getInternalInfo - Retourne des informations internes sur le lieu où l'exception a été émise
    • SolrUpdateResponse::__construct - Constructeur
    • SolrUpdateResponse::__destruct - Destructeur
    • SolrUtils::digestXmlResponse - Analyse une réponse XML dans un SolrObject
    • SolrUtils::escapeQueryChars - Protège une requête
    • SolrUtils::getSolrVersion - Récupère la version courant de l'extension Solr
    • SolrUtils::queryPhrase - Prépare une phrase depuis une chaîne non protégée par Lucene
    • solr_get_version - Retourne la version courante de l'extension Solr utilisée par Apache
    • sort - Trie un tableau en ordre croissant
    • soundex - Calcule la clé soundex
    • SplDoublyLinkedList::add - Ajoute/insert une nouvelle valeur à l'index spécifié
    • SplDoublyLinkedList::bottom - Le nœud parent à partir duquel la liste découle
    • SplDoublyLinkedList::count - Compte le nombre d'éléments de la liste
    • SplDoublyLinkedList::current - Retourne l'entrée courante du tableau
    • SplDoublyLinkedList::getIteratorMode - Retourne le mode de l'itérateur
    • SplDoublyLinkedList::isEmpty - Vérifie si la liste est vide
    • SplDoublyLinkedList::key - Retourne l'index du nœud courant
    • SplDoublyLinkedList::next - Se déplace à l'entrée suivante
    • SplDoublyLinkedList::offsetExists - Vérifie si un index existe
    • SplDoublyLinkedList::offsetGet - Retourne la valeur d'un index
    • SplDoublyLinkedList::offsetSet - Spécifie la nouvelle valeur de l'index
    • SplDoublyLinkedList::offsetUnset - Efface la valeur d'un index
    • SplDoublyLinkedList::pop - Dépile et retourne le dernier élément de la liste
    • SplDoublyLinkedList::prev - Recule d'un élément
    • SplDoublyLinkedList::push - Ajoute un élément à la fin de la liste
    • SplDoublyLinkedList::rewind - Replace l'itérateur au début
    • SplDoublyLinkedList::serialize - Sérialise la liste
    • SplDoublyLinkedList::setIteratorMode - Définit le mode d'itération
    • SplDoublyLinkedList::shift - Déplace un nœud de la liste
    • SplDoublyLinkedList::top - Récupère le dernier nœud de la liste
    • SplDoublyLinkedList::unserialize - Désérialise la liste
    • SplDoublyLinkedList::unshift - Ajoute un élément à la liste
    • SplDoublyLinkedList::valid - Vérifie si la liste contient encore des nœuds
    • SplFileInfo::getATime - Lit la date de dernier accès au fichier
    • SplFileInfo::getBasename - Lit le nom de base du fichier
    • SplFileInfo::getCTime - Lit la date de modification du fichier
    • SplFileInfo::getExtension - Récupère l'extension d'un fichier
    • SplFileInfo::getFileInfo - Obtient un objet SplFileInfo pour un fichier
    • SplFileInfo::getFilename - Lit le nom du fichier
    • SplFileInfo::getGroup - Lit le groupe d'appartenance du fichier
    • SplFileInfo::getInode - Lit le inode du fichier
    • SplFileInfo::getLinkTarget - Lit la cible d'un lien symbolique
    • SplFileInfo::getMTime - Lit la date de dernière modification
    • SplFileInfo::getOwner - Lit le propriétaire du fichier
    • SplFileInfo::getPath - Le chemin sans le nom de fichier
    • SplFileInfo::getPathInfo - Crée un objet SplFileInfo pour un chemin
    • SplFileInfo::getPathname - Lit le chemin d'un fichier
    • SplFileInfo::getPerms - Lit les droits d'un fichier
    • SplFileInfo::getRealPath - Lit le chemin absolu d'un fichier
    • SplFileInfo::getSize - Lit la taille d'un fichier
    • SplFileInfo::getType - Lit le type de fichier
    • SplFileInfo::isDir - Indique si le fichier est un dossier
    • SplFileInfo::isExecutable - Indique si un fichier est exécutable
    • SplFileInfo::isFile - Indique si un fichier est un véritable fichier
    • SplFileInfo::isLink - Indique si un fichier est un lien
    • SplFileInfo::isReadable - Indique si le fichier est lisible
    • SplFileInfo::isWritable - Indique si on peut écrire dans un fichier
    • SplFileInfo::openFile - Crée un objet SplFileObject pour le fichier
    • SplFileInfo::setFileClass - Configure la classe utilisée avec SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Configure la classe utilisée par SplFileInfo::getFileInfo et SplFileInfo::getPathInfo
    • SplFileInfo::__construct - Construit un nouvel objet SplFileInfo
    • SplFileInfo::__toString - Retourne le chemin d'un fichier sous forme de chaîne
    • SplFileObject::current - Récupère la ligne courante d'un fichier
    • SplFileObject::eof - Vérifie si la fin du fichier est atteinte
    • SplFileObject::fflush - Écrit l'affichage dans le fichier
    • SplFileObject::fgetc - Récupère un caractère depuis le fichier
    • SplFileObject::fgetcsv - Récupère une ligne depuis le fichier et l'analyse comme étant des données CSV
    • SplFileObject::fgets - Récupère une ligne d'un fichier
    • SplFileObject::fgetss - Récupère une ligne d'un fichier et supprime les balises HTML
    • SplFileObject::flock - Verrouille ou déverrouille un fichier
    • SplFileObject::fpassthru - Affiche toutes les données en attente sur un pointeur de fichier
    • SplFileObject::fputcsv - Écrit un tableau sous la forme d'une ligne CSV
    • SplFileObject::fread - Lit depuis un fichier
    • SplFileObject::fscanf - Analyse une entrée d'un fichier suivant un format donné
    • SplFileObject::fseek - Se déplace à une position donnée
    • SplFileObject::fstat - Récupère les informations d'un fichier
    • SplFileObject::ftell - Retourne la position courant dans le fichier
    • SplFileObject::ftruncate - Coupe le fichier à une longueur donnée
    • SplFileObject::fwrite - Écrit dans le fichier
    • SplFileObject::getChildren - Récupère le fils
    • SplFileObject::getCsvControl - Récupère les options pour CSV
    • SplFileObject::getCurrentLine - Alias de SplFileObject::fgets
    • SplFileObject::getFlags - Récupère les drapeaux pour l'objet SplFileObject
    • SplFileObject::getMaxLineLen - Récupère la longueur maximale d'une ligne
    • SplFileObject::hasChildren - Vérifie si SplFileObject a un fils
    • SplFileObject::key - Récupère le numéro de la ligne courant
    • SplFileObject::next - Se déplace sur la prochaine ligne
    • SplFileObject::rewind - Réinitialise le fichier à la première ligne
    • SplFileObject::seek - Se déplace sur une ligne spécifique
    • SplFileObject::setCsvControl - Définit les options CSV
    • SplFileObject::setFlags - Définit les drapeaux pour l'objet SplFileObject
    • SplFileObject::setMaxLineLen - Définit la longueur maximale d'une ligne
    • SplFileObject::valid - Vérifie si la fin du fichier a été atteinte
    • SplFileObject::__construct - Construit un nouvel objet fichier
    • SplFileObject::__toString - Retourne la ligne courante sous forme de chaîne de caractères
    • SplFixedArray::count - Retourne la taille du tableau à taille fixe
    • SplFixedArray::current - Lit l'élément courant du tableau à taille fixe
    • SplFixedArray::fromArray - Importe un tableau PHP dans un tableau à taille fixe
    • SplFixedArray::getIterator - Retrieve the iterator to go through the array
    • SplFixedArray::getSize - Lit la taille du tableau à taille fixe
    • SplFixedArray::jsonSerialize - Returns a representation that can be converted to JSON
    • SplFixedArray::key - Retourne l'index de la position courante
    • SplFixedArray::next - Déplace l'itérateur à l'élément suivant
    • SplFixedArray::offsetExists - Vérifie si l'index demandé existe
    • SplFixedArray::offsetGet - Retourne la valeur à l'index donné
    • SplFixedArray::offsetSet - Affecte une valeur à un index donné
    • SplFixedArray::offsetUnset - Détruit l'élément à un index donné
    • SplFixedArray::rewind - Remet l'itérateur au début du tableau à taille fixe
    • SplFixedArray::setSize - Change la taille d'un tableau à taille fixe
    • SplFixedArray::toArray - Retourne un tableau PHP à partir d'un tableau à taille fixe
    • SplFixedArray::valid - Vérifie si le tableau contient encore un élément
    • SplFixedArray::__construct - Construit un nouveau SplFixedArray
    • SplFixedArray::__serialize - Serializes the SplFixedArray object
    • SplFixedArray::__unserialize - Deserializes the data parameter into an SplFixedArray object
    • SplFixedArray::__wakeup - Ré-initialise le tableau après sa désérialisation
    • SplHeap::compare - Compare deux éléments
    • SplHeap::count - Compte le nombre d'éléments dans le tas
    • SplHeap::current - Retourne le nœud courant, pointé par l'itérateur
    • SplHeap::extract - Extrait un nœud du haut du tas
    • SplHeap::insert - Insère un élément dans le tas
    • SplHeap::isCorrupted - Informe si le tas est dans un état corrompu
    • SplHeap::isEmpty - Vérifie si le tas est vide
    • SplHeap::key - Retourne l'index du nœud courant
    • SplHeap::next - Se déplace au nœud suivant
    • SplHeap::recoverFromCorruption - Répare un tas
    • SplHeap::rewind - Revient au début de l'itérateur
    • SplHeap::top - Récupère le premier nœud du tas
    • SplHeap::valid - Vérifie si le tas contient des nœuds
    • SplMaxHeap::compare - Compare deux éléments
    • SplMinHeap::compare - Compare deux éléments
    • SplObjectStorage::addAll - Ajoute tous les objets d'un autre stockage
    • SplObjectStorage::attach - Ajoute un objet dans le stockage
    • SplObjectStorage::contains - Vérifie si un stockage contient un objet
    • SplObjectStorage::count - Retourne le nombre d'objets dans le stockage
    • SplObjectStorage::current - Retourne l'objet courant
    • SplObjectStorage::detach - Retire un objet du stockage
    • SplObjectStorage::getHash - Calcule un identifiant unique pour les objets contenus
    • SplObjectStorage::getInfo - Retourne les données associés à l'élément en cours
    • SplObjectStorage::key - Retourne l'index de l'objet courant
    • SplObjectStorage::next - Passe au prochain élément
    • SplObjectStorage::offsetExists - Vérifie si un objet existe dans le stockage
    • SplObjectStorage::offsetGet - Retourne les données associées à un objet
    • SplObjectStorage::offsetSet - Associe des données à un stockage
    • SplObjectStorage::offsetUnset - Retire un objet du stockage
    • SplObjectStorage::removeAll - Retire les objets d'un stockage qui appartienne à un autre stockage
    • SplObjectStorage::removeAllExcept - Supprime tous les objets du stockage courant sauf ceux contenus dans d'autres stockages
    • SplObjectStorage::rewind - Remet l'itérateur au début
    • SplObjectStorage::serialize - Sérialise un stockage
    • SplObjectStorage::setInfo - Modifie les données associée à l'élément courant
    • SplObjectStorage::unserialize - Désérialise un stockage à partir de sa forme en chaîne
    • SplObjectStorage::valid - Vérifie si l'élément courant est valide
    • SplObserver::update - Réception d'une mise à jour depuis un sujet
    • SplPriorityQueue::compare - Compare deux priorités
    • SplPriorityQueue::count - Compte le nombre d'éléments dans la file d'attente
    • SplPriorityQueue::current - Retourne le nœud courant, pointé par l'itérateur
    • SplPriorityQueue::extract - Extrait un nœud depuis le haut du tas
    • SplPriorityQueue::getExtractFlags - Récupère les drapeaux d'extraction
    • SplPriorityQueue::insert - Insère un élément dans la file d'attente
    • SplPriorityQueue::isCorrupted - Informe si la file prioritaire est dans un état corrompue
    • SplPriorityQueue::isEmpty - Vérifie si la file est vide
    • SplPriorityQueue::key - Retourne l'index du nœud courant
    • SplPriorityQueue::next - Se déplace sur le prochain nœud
    • SplPriorityQueue::recoverFromCorruption - Répare une file d'attente
    • SplPriorityQueue::rewind - Revient au début de l'itérateur
    • SplPriorityQueue::setExtractFlags - Définit le mode d'extraction
    • SplPriorityQueue::top - Récupère le nœud du haut de la file d'attente
    • SplPriorityQueue::valid - Vérifie si la file d'attente contient encore des nœuds
    • SplQueue::dequeue - Supprime un nœud de la file d'attente
    • SplQueue::enqueue - Ajoute un élément à la file d'attente
    • SplSubject::attach - Attache un SplObserver
    • SplSubject::detach - Détache un observateur
    • SplSubject::notify - Notifie un observateur
    • SplTempFileObject::__construct - Construit un nouvel objet représentant un fichier temporaire
    • spl_autoload - Implémentation par défaut d'__autoload()
    • spl_autoload_call - Essai toutes les fonctions __autoload() enregistrées pour charger la classe demandée
    • spl_autoload_extensions - Enregistre et retourne l'extension du fichier par défaut pour spl_autoload
    • spl_autoload_functions - Retourne toutes les fonctions __autoload() enregistrées
    • spl_autoload_register - Enregistre une fonction en tant qu'implémentation de __autoload()
    • spl_autoload_unregister - Efface une fonction donnée de l'implémentation __autoload()
    • spl_classes - Retourne les classes SPL disponibles
    • spl_object_hash - Retourne l'identifiant de hachage pour un objet donné
    • spl_object_id - Retourne le gestionnaire d'objet entier pour un objet donné
    • Spoofchecker::areConfusable - Vérifie si les chaînes données peuvent être confondues
    • Spoofchecker::isSuspicious - Vérifie si un texte contient des caractères suspects
    • Spoofchecker::setAllowedLocales - Locales à utiliser lors de la vérification
    • Spoofchecker::setChecks - Spécifie les vérifications à effectuer
    • Spoofchecker::setRestrictionLevel - Set the restriction level
    • Spoofchecker::__construct - Constructeur
    • sprintf - Retourne une chaîne formatée
    • SQLite3::backup - Backup one database to another database
    • SQLite3::busyTimeout - Définit le gestionnaire d'attente de la connexion
    • SQLite3::changes - Retourne le nombre de lignes modifiées (ou insérées, effacées) par la dernière requête SQL
    • SQLite3::close - Ferme la connexion avec la base de données
    • SQLite3::createAggregate - Enregistre une fonction PHP à utiliser comme fonction d'aggrégation SQLite
    • SQLite3::createCollation - Enregistre une fonction PHP pour l'utiliser comme fonction de classement SQL
    • SQLite3::createFunction - Enregistre une fonction PHP à utiliser comme fonction scalaire SQL
    • SQLite3::enableExceptions - Active le lancement d'exceptions
    • SQLite3::escapeString - Retourne une chaîne nettoyée
    • SQLite3::exec - Exécute une requête sur une base de données
    • SQLite3::lastErrorCode - Retourne le code erreur de la dernière requête SQL ayant échouée
    • SQLite3::lastErrorMsg - Retourne le message d'erreur, en anglais, de la dernière requête ayant échouée
    • SQLite3::lastInsertRowID - Retourne l'identifiant de la ligne correspondant à la dernière requête de type INSERT
    • SQLite3::loadExtension - Tente de charger une extension de la bibliothèque SQLite
    • SQLite3::open - Ouvre une base de données SQLite
    • SQLite3::openBlob - Ouvre un flux de ressource pour lire un BLOB
    • SQLite3::prepare - Prépare une requête SQL pour exécution
    • SQLite3::query - Exécute une requête SQL
    • SQLite3::querySingle - Exécute une requête et retourne un seul résultat
    • SQLite3::setAuthorizer - Configures a callback to be used as an authorizer to limit what a statement can do
    • SQLite3::version - Retourne la version de la bibliothèque SQLite3
    • SQLite3::__construct - Instantie un objet SQLite3 et ouvre la base de données SQLite 3
    • SQLite3Result::columnName - Retourne le nom d'une colonne
    • SQLite3Result::columnType - Retourne le type d'une colonne
    • SQLite3Result::fetchArray - Récupère un jeu de résultats sous la forme d'un tableau associatif
    • SQLite3Result::finalize - Ferme un jeu de résultats
    • SQLite3Result::numColumns - Retourne le nombre de colonnes du jeu de résultats
    • SQLite3Result::reset - Repositionne le pointeur sur la première ligne du jeu de résultats
    • SQLite3Result::__construct - Constructs an SQLite3Result
    • SQLite3Stmt::bindParam - Lie un paramètre à une variable de déclaration
    • SQLite3Stmt::bindValue - Lie la valeur d'un paramètre à une variable de déclaration
    • SQLite3Stmt::clear - Supprime tous les paramètres actuellement liés
    • SQLite3Stmt::close - Ferme une requête préparée
    • SQLite3Stmt::execute - Exécute une requête préparée
    • SQLite3Stmt::getSQL - Récupère le SQL d'une déclaration
    • SQLite3Stmt::paramCount - Retourne le nombre de paramètres d'une requête préparée
    • SQLite3Stmt::readOnly - Détermine si une déclaration est uniquement en lecture seule
    • SQLite3Stmt::reset - Réinitialise une requête préparée
    • SQLite3Stmt::__construct - Constructs an SQLite3Stmt object
    • sqlsrv_begin_transaction - Commence une transaction
    • sqlsrv_cancel - Annule une requête
    • sqlsrv_client_info - Retourne les informations sur le client ainsi que sur la connexion spécifiée
    • sqlsrv_close - Clôture une connexion établie et libère les ressources associées
    • sqlsrv_commit - Valide une transaction commencée avec la fonction sqlsrv_begin_transaction
    • sqlsrv_configure - Modifie la configuration du gestionnaire d'erreurs et d'historisations du driver
    • sqlsrv_connect - Ouvre une connexion sur une base de données Microsoft SQL Server
    • sqlsrv_errors - Retourne une erreur ainsi que certaines informations sur la dernière opération SQLSRV effectuée
    • sqlsrv_execute - Exécute une requête préparée avec la fonction sqlsrv_prepare
    • sqlsrv_fetch - Rend la prochaine ligne d'un jeu de résultats disponible pour lecture
    • sqlsrv_fetch_array - Retourne une ligne sous la forme d'un tableau
    • sqlsrv_fetch_object - Récupère la prochaine ligne de données du jeu de résultats sous la forme d'un objet
    • sqlsrv_field_metadata - Récupère les données méta pour les champs d'une requête préparée par la fonction sqlsrv_prepare ou la fonction sqlsrv_query
    • sqlsrv_free_stmt - Libère toutes les ressources de la requête spécifiée
    • sqlsrv_get_config - Retourne la valeur de la configuration spécifiée
    • sqlsrv_get_field - Récupère les données du champ depuis la ligne actuellement sélectionnée
    • sqlsrv_has_rows - Indique si la requête spécifiée contient des lignes
    • sqlsrv_next_result - Rend actif le prochain résultat de la requête spécifiée
    • sqlsrv_num_fields - Récupère le nombre de champs (colonnes) dans une requête
    • sqlsrv_num_rows - Récupère le nombre de lignes d'un jeu de résultats
    • sqlsrv_prepare - Prépare une requête pour exécution
    • sqlsrv_query - Prépare et exécute une requête
    • sqlsrv_rollback - Annule une transaction qui a été commencée grâce à la fonction sqlsrv_begin_transaction
    • sqlsrv_rows_affected - Retourne le nombre de lignes modifiées par la dernière requête de type INSERT, UPDATE, ou DELETE
    • sqlsrv_send_stream_data - Envoie des données depuis le flux vers le serveur
    • sqlsrv_server_info - Retourne des informations sur le serveur
    • 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
    • sqrt - Racine carrée
    • srand - Initialise le générateur de nombres aléatoires
    • sscanf - Analyse une chaîne à l'aide d'un format
    • ssdeep_fuzzy_compare - Calcule le score de correspondance entre 2 signatures de hachages flous
    • ssdeep_fuzzy_hash - Crée un hachage flou depuis une chaîne de caractères
    • ssdeep_fuzzy_hash_filename - Crée un hachage flou d'un fichier
    • ssh2:// - Shell sécurisé 2
    • ssh2_auth_agent - Authentification SSH en utilisant l'agent ssh
    • ssh2_auth_hostbased_file - Identification en utilisant une clé d'hôte publique
    • ssh2_auth_none - Identification en tant que "none"
    • ssh2_auth_password - Identification via SSH en utilisant un mot de passe en clair
    • ssh2_auth_pubkey_file - Identification en utilisant une clé publique
    • ssh2_connect - Connexion à un serveur SSH
    • ssh2_disconnect - Ferme une connexion à un serveur SSH distant
    • ssh2_exec - Exécute une commande sur un serveur distant
    • ssh2_fetch_stream - Parcours un flux étendu de données
    • ssh2_fingerprint - Récupère l'empreinte d'un serveur distant
    • 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 - Retourne une liste de méthodes négociées
    • ssh2_poll - Poll the channels/listeners/streams for events
    • ssh2_publickey_add - Ajoute une clé publique autorisée
    • ssh2_publickey_init - Initialise un Publickey Subsystem (sous-système de clé publique)
    • ssh2_publickey_list - Liste les clés publiques actuellement autorisées
    • ssh2_publickey_remove - Supprime un clé publique autorisée
    • ssh2_scp_recv - Demande un fichier via SCP
    • ssh2_scp_send - Envoie un fichier via SCP
    • ssh2_send_eof - Send EOF to stream
    • ssh2_sftp - Initialise un sous-système SFTP
    • ssh2_sftp_chmod - Modifie le mode d'un fichier
    • ssh2_sftp_lstat - Statue un lien symbolique
    • ssh2_sftp_mkdir - Crée un dossier
    • ssh2_sftp_readlink - Retourne la cible d'un lien symbolique
    • ssh2_sftp_realpath - Résout le chemin réel d'un chemin fourni
    • ssh2_sftp_rename - Renomme un fichier distant
    • ssh2_sftp_rmdir - Efface un dossier
    • ssh2_sftp_stat - Statue un fichier sur un système de fichiers distant
    • ssh2_sftp_symlink - Crée un lien symbolique
    • ssh2_sftp_unlink - Efface un fichier
    • ssh2_shell - Demande un shell interactif
    • ssh2_tunnel - Ouvre un tunnel à travers un serveur distant
    • stat - Renvoie les informations à propos d'un fichier
    • 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 - Annule une transaction en cours
    • Stomp::ack - Valide la réception d'un message
    • Stomp::begin - Débute une transaction
    • Stomp::commit - Valide une transaction en cours
    • Stomp::error - Récupère la dernière erreur stomp
    • Stomp::getReadTimeout - Récupère le délai d'expiration de lecture
    • Stomp::getSessionId - Retourne l'identifiant de la session courante
    • Stomp::hasFrame - Indique si un message est en attente de lecture ou non
    • Stomp::readFrame - Lit le prochain message
    • Stomp::send - Envoi un message
    • Stomp::setReadTimeout - Définit le délai d'expiration de lecture
    • Stomp::subscribe - Souscrit à l'écoute d'une destination donnée
    • Stomp::unsubscribe - Supprime une souscription existante
    • Stomp::__construct - Ouvre une connexion
    • Stomp::__destruct - Ferme une connexion
    • StompException::getDetails - Récupère les détails de l'exception
    • StompFrame::__construct - Constructeur
    • stomp_connect_error - Retourne une chaîne décrivant la dernière erreur de connexion
    • stomp_version - Récupère la version de l'extension Stomp
    • strcasecmp - Comparaison insensible à la casse de chaînes binaires
    • strchr - Alias de strstr
    • strcmp - Comparaison binaire de chaînes
    • strcoll - Comparaison de chaînes localisées
    • strcspn - Trouve un segment de chaîne ne contenant pas certains caractères
    • streamWrapper::dir_closedir - Ferme une ressource de dossier
    • streamWrapper::dir_opendir - Ouvre un dossier en lecture
    • streamWrapper::dir_readdir - Lit un fichier dans un dossier
    • streamWrapper::dir_rewinddir - Remet au début une ressource de dossier
    • streamWrapper::mkdir - Crée un dossier
    • streamWrapper::rename - Renomme un fichier ou un dossier
    • streamWrapper::rmdir - Supprime un dossier
    • streamWrapper::stream_cast - Lit la ressource sous-jacente de flux
    • streamWrapper::stream_close - Ferme une ressource de flux
    • streamWrapper::stream_eof - Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush - Expédie le contenu
    • streamWrapper::stream_lock - Verrouillage logique de fichiers
    • streamWrapper::stream_metadata - Change les metadata du flux
    • streamWrapper::stream_open - Opens file or URL
    • streamWrapper::stream_read - Lit dans le flux
    • streamWrapper::stream_seek - Place le pointeur de flux à une position
    • streamWrapper::stream_set_option - Change les options du flux
    • streamWrapper::stream_stat - Lit les informations sur une ressource de fichier
    • streamWrapper::stream_tell - Lit la position courante dans un flux
    • streamWrapper::stream_truncate - Tronque un flux
    • streamWrapper::stream_write - Écrit dans un flux
    • streamWrapper::unlink - Efface un fichier
    • streamWrapper::url_stat - Lit les informations sur un fichier
    • streamWrapper::__construct - Construit un nouveau gestionnaire de flux
    • streamWrapper::__destruct - Détruit un gestionnaire de flux existant
    • stream_bucket_append - Ajoute un compartiment au corps
    • stream_bucket_make_writeable - Retourne un objet de compartiment depuis le corps pour des opérations sur celui-ci
    • stream_bucket_new - Crée un nouveau compartiment pour l'utiliser sur le flux courant
    • stream_bucket_prepend - Ajout initial d'un bucket dans une brigade
    • stream_context_create - Crée un contexte de flux
    • stream_context_get_default - Lit le contexte par défaut des flux
    • stream_context_get_options - Lit la valeur des options pour un flux/gestionnaire/contexte
    • stream_context_get_params - Lit les paramètres d'un contexte
    • stream_context_set_default - Configure le contexte par défaut des flux
    • stream_context_set_option - Configure une option pour un flux/gestionnaire/contexte
    • stream_context_set_options - Sets options on the specified context
    • stream_context_set_params - Configure les paramètres pour un flux/gestionnaire/contexte
    • stream_copy_to_stream - Copie des données depuis un flux vers un autre
    • stream_filter_append - Attache un filtre à un flux en fin de liste
    • stream_filter_prepend - Attache un filtre à un flux en début de liste
    • stream_filter_register - Enregistre un filtre de flux
    • stream_filter_remove - Retire un filtre d'un flux
    • stream_get_contents - Lit tout un flux dans une chaîne
    • stream_get_filters - Liste les filtres enregistrés
    • stream_get_line - Lit une ligne dans un flux
    • stream_get_meta_data - Lit les en-têtes et données méta des flux
    • stream_get_transports - Liste les gestionnaires de transports de sockets disponibles
    • stream_get_wrappers - Liste les gestionnaires de flux
    • stream_isatty - Vérifie si un flux est un TTY
    • stream_is_local - Vérifie si un flux est local
    • stream_notification_callback - Une fonction de rappel pour le paramètre de contexte notification
    • stream_register_wrapper - Alias de stream_wrapper_register
    • stream_resolve_include_path - Résout un nom de fichier suivant les règles du chemin d'inclusion
    • stream_select - Surveille la modification d'un ou plusieurs flux
    • stream_set_blocking - Configure le mode bloquant d'un flux
    • stream_set_read_buffer - Configure le buffer de lecture d'un flux
    • stream_set_size - Change la taille du segment du flux
    • stream_set_timeout - Configure la durée d'expiration d'un flux
    • stream_set_write_buffer - Configure le buffer d'écriture d'un flux
    • stream_socket_accept - Accepte une connexion sur un socket créé par stream_socket_server
    • stream_socket_client - Ouvre une connexion socket Internet ou Unix
    • stream_socket_enable_crypto - Active ou non le chiffrement, pour un socket déjà connecté
    • stream_socket_get_name - Lit le nom de la socket locale ou distante
    • stream_socket_pair - Crée une paire de sockets connectées et indissociables
    • stream_socket_recvfrom - Lit des données depuis un socket, connecté ou pas
    • stream_socket_sendto - Envoie un message au socket, connecté ou pas
    • stream_socket_server - Crée un socket serveur Unix ou Internet
    • stream_socket_shutdown - Arrête une connexion full-duplex
    • stream_supports_lock - Indique si le flux supporte les verrous
    • stream_wrapper_register - Enregistre un gestionnaire d'URL
    • stream_wrapper_restore - Restaure un gestionnaire d'URL supprimé
    • stream_wrapper_unregister - Supprime un gestionnaire d'URL
    • strftime - Formate une date/heure locale avec la configuration locale
    • Stringable::__toString - Retourne la représentation de l'objet sous forme de chaîne
    • stripcslashes - Décode une chaîne encodée avec addcslashes
    • stripos - Recherche la position de la première occurrence dans une chaîne, sans tenir compte de la casse
    • stripslashes - Supprime les antislashs d'une chaîne
    • strip_tags - Supprime les balises HTML et PHP d'une chaîne
    • stristr - Version insensible à la casse de strstr
    • strlen - Calcule la taille d'une chaîne
    • strnatcasecmp - Comparaison de chaînes avec l'algorithme d'"ordre naturel" (insensible à la casse)
    • strnatcmp - Comparaison de chaînes avec l'algorithme d'"ordre naturel"
    • strncasecmp - Compare en binaire des chaînes de caractères
    • strncmp - Comparaison binaire des n premiers caractères
    • strpbrk - Recherche un ensemble de caractères dans une chaîne de caractères
    • strpos - Cherche la position de la première occurrence dans une chaîne
    • strptime - Analyse une date générée par strftime
    • strrchr - Trouve la dernière occurrence d'un caractère dans une chaîne
    • strrev - Inverse une chaîne
    • strripos - Cherche la position de la dernière occurrence d'une chaîne contenue dans une autre, de façon insensible à la casse
    • strrpos - Cherche la position de la dernière occurrence d'une sous-chaîne dans une chaîne
    • strspn - Trouve la longueur du segment initial d'une chaîne contenant tous les caractères d'un masque donné
    • strstr - Trouve la première occurrence dans une chaîne
    • strtok - Coupe une chaîne en segments
    • strtolower - Renvoie une chaîne en minuscules
    • strtotime - Transforme un texte anglais en timestamp
    • strtoupper - Renvoie une chaîne en majuscules
    • strtr - Remplace des caractères dans une chaîne
    • strval - Récupère la valeur d'une variable, au format chaîne
    • str_contains - Détermine si une chaîne contient une sous-chaîne donnée
    • str_decrement - Décremente une chaîne de caractères alphanumérique
    • str_ends_with - Détermine si une chaîne se termine par une sous-chaîne donnée
    • str_getcsv - Analyse une chaîne de caractères CSV dans un tableau
    • str_increment - Incrémente une chaîne de caractères alphanumérique
    • str_ireplace - Version insensible à la casse de str_replace
    • str_pad - Complète une chaîne jusqu'à une taille donnée
    • str_repeat - Répète une chaîne
    • str_replace - Remplace toutes les occurrences dans une chaîne
    • str_rot13 - Effectue une transformation ROT13
    • str_shuffle - Mélange les caractères d'une chaîne de caractères
    • str_split - Convertit une chaîne de caractères en tableau
    • str_starts_with - Détermine si une chaîne commence par une sous-chaîne donnée
    • str_word_count - Compte le nombre de mots utilisés dans une chaîne
    • substr - Retourne un segment de chaîne
    • substr_compare - Compare deux chaînes depuis un offset jusqu'à une longueur en caractères
    • substr_count - Compte le nombre d'occurrences de segments dans une chaîne
    • substr_replace - Remplace un segment dans une chaîne
    • SVM::crossvalidate - Test les paramètres d'entraînement sur les sous-jeux de données d’entraînement
    • SVM::getOptions - Retourne les paramètres courants d’entraînement
    • SVM::setOptions - Définit des paramètres d'entraînement
    • SVM::train - Crée un modèle SVMModel suivant les données d'entraînement
    • SVM::__construct - Construit un nouvel objet SVM
    • SVMModel::checkProbabilityModel - Retourne true si le modèle a des informations probablistes
    • SVMModel::getLabels - Récupère les labels utilisés pour entraîner le modèle
    • SVMModel::getNrClass - Retourne le nombre de classes utilisées pour entraîner le modèle
    • SVMModel::getSvmType - Récupère le type SVM utilisé pour entraîner le modèle
    • SVMModel::getSvrProbability - Récupère la valeur sigma pour les types de régression
    • SVMModel::load - Charge un modèle SVM sauvegardé
    • SVMModel::predict - Prédit une valeur pour des précédentes données non vues
    • SVMModel::predict_probability - Retourne les probabilités pour les données précédentes non présentées
    • SVMModel::save - Sauvegarde un modèle dans un fichier
    • SVMModel::__construct - Construit un nouvel objet SVMModel
    • svn_add - Prévoit l'ajout d'un élément dans le dossier de travail
    • svn_auth_get_parameter - Récupère un paramètre d'identification
    • svn_auth_set_parameter - Spécifie un paramètre d'identification
    • svn_blame - Récupère les condamnations SVN pour un fichier
    • svn_cat - Récupère le contenu d'un fichier du référentiel
    • svn_checkout - Extrait une copie de travail depuis un référentiel
    • svn_cleanup - Nettoie, récursivement, un dossier de travail, en finissant les opérations incomplètes et en supprimant les verrous
    • svn_client_version - Récupère la version des bibliothèques clientes SVN
    • svn_commit - Envoie les modifications depuis la copie locale vers le référentiel
    • svn_delete - Efface un élément d'un dossier de travail ou d'un dépôt
    • svn_diff - Compare deux chemins, récursivement
    • svn_export - Exporte le contenu d'un dossier SVN
    • svn_fs_abort_txn - Interrompre une transaction
    • svn_fs_apply_text - Crée et retourne un flux à utiliser pour modifier un fichier
    • svn_fs_begin_txn2 - Crée une nouvelle transaction
    • svn_fs_change_node_prop - Retourne true si tout est Ok, false sinon
    • svn_fs_check_path - Détermine quel type d'élément est pointé par un chemin donné
    • svn_fs_contents_changed - Retourne true si le contenu est différent, false sinon
    • svn_fs_copy - Copie un fichier ou un dossier
    • svn_fs_delete - Supprime un fichier ou un dossier
    • svn_fs_dir_entries - Énumère les éléments d'un dossier
    • svn_fs_file_contents - Retourne un flux afin d'accéder au contenu d'un fichier pour une révision donnée
    • svn_fs_file_length - Retourne la taille d'un fichier pour une révision donnée
    • svn_fs_is_dir - Détermine si un chemin donné pointe vers un dossier
    • svn_fs_is_file - Détermine si un chemin donné pointe vers un fichier
    • svn_fs_make_dir - Crée un nouveau dossier vide
    • svn_fs_make_file - Crée un nouveau fichier vide
    • svn_fs_node_created_rev - Retourne la révision dans laquelle le chemin, sous fsroot, a été créé
    • svn_fs_node_prop - Retourne la valeur d'une propriété d'un nœud
    • svn_fs_props_changed - Retourne true si les propriétés sont différentes, false sinon
    • svn_fs_revision_prop - Récupère la valeur d'une propriété nommée
    • svn_fs_revision_root - Récupère un gestionnaire sur une révision spécifique sur la racine du référentiel
    • svn_fs_txn_root - Crée et retourne une transaction
    • svn_fs_youngest_rev - Retourne le numéro de la révision la plus récente du système de fichiers
    • svn_import - Importe un chemin non-versionné dans un référentiel
    • svn_log - Récupère le message d'historisation d'une URL du référentiel
    • svn_ls - Retourne la liste du contenu d'un dossier d'un référentiel, optionnellement à la révision fournie
    • svn_mkdir - Crée un dossier dans la copie de travail ou dans le référentiel
    • svn_repos_create - Crée un nouveau référentiel Subversion
    • svn_repos_fs - Récupère un gestionnaire du système de fichiers
    • svn_repos_fs_begin_txn_for_commit - Crée une nouvelle transaction
    • svn_repos_fs_commit_txn - Livre une transaction et retourne la nouvelle révision
    • svn_repos_hotcopy - Effectue une copie à chaud du référentiel
    • svn_repos_open - Ouvre un verrou partagé sur un référentiel
    • svn_repos_recover - Exécute les procédures de récupération du référentiel
    • svn_revert - Revenir en arrière sur les changements de la copie de travail
    • svn_status - Récupère le statut des fichiers et des dossiers de la copie de travail
    • svn_update - Met à jour la copie de travail
    • 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_clear_error - Clear errors in the socket or on the last error code
    • 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_error_log - Output error messages to the log
    • 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 - Crée un lien symbolique
    • SyncEvent::fire - Lance/défini l'événement
    • SyncEvent::reset - Réinitialise manuellement un événement
    • SyncEvent::wait - Attend que l'objet SyncEvent ne soit lancé
    • SyncEvent::__construct - Construit un nouvel objet SyncEvent
    • SyncMutex::lock - Obtient un verrou exclusif
    • SyncMutex::unlock - Déverouille le mutex
    • SyncMutex::__construct - Construit un nouvel objet SyncMutex
    • SyncReaderWriter::readlock - Obtiens un verrou de lecture
    • SyncReaderWriter::readunlock - Libère un verrou de lecture
    • SyncReaderWriter::writelock - Obtiens un verrou d'écriture exclusif
    • SyncReaderWriter::writeunlock - Libère un verrou d'écriture
    • SyncReaderWriter::__construct - Construit un nouvel objet SyncReaderWriter
    • SyncSemaphore::lock - Décrémente le compteur de l'objet SyncSemaphore ou attend
    • SyncSemaphore::unlock - Incrémente le compteur de l'objet SyncSemaphore
    • SyncSemaphore::__construct - Construit un nouvel objet SyncSemaphore
    • 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 - Génère un message dans l'historique système
    • system - Exécute un programme externe et affiche le résultat
    • sys_getloadavg - Récupère la charge moyenne du système
    • sys_get_temp_dir - Retourne le chemin du répertoire utilisé pour les fichiers temporaires
  • 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 - Nettoie une chaîne
    • tan - Tangente
    • tanh - Tangente hyperbolique
    • tcpwrap_check - Vérification Tcpwrap
    • tempnam - Crée un fichier avec un nom unique
    • textdomain - Définie le domaine par défaut
    • Thread::getCreatorId - Identification
    • Thread::getCurrentThread - Identification
    • Thread::getCurrentThreadId - Identification
    • Thread::getThreadId - Identification
    • Thread::isJoined - Détection de statut
    • Thread::isStarted - Détection de statut
    • Thread::join - Synchronisation
    • Thread::start - Exécution
    • Threaded::chunk - Manipulation
    • Threaded::count - Manipulation
    • Threaded::extend - Manipulation pendant l'exécution
    • Threaded::isRunning - Détection de statut
    • Threaded::isTerminated - Détection de statut
    • Threaded::merge - Manipulation
    • Threaded::notify - Synchronisation
    • Threaded::notifyOne - Synchronization
    • Threaded::pop - Manipulation
    • Threaded::run - Exécution
    • Threaded::shift - Manipulation
    • Threaded::synchronized - Synchronisation
    • Threaded::wait - Synchronisation
    • Throwable::getCode - Récupère le code de l'exception
    • Throwable::getFile - Récupère le fichier où l'objet a été créé
    • Throwable::getLine - Récupère le numéro de ligne où l'objet instancié a été jeté
    • Throwable::getMessage - Récupère le message
    • Throwable::getPrevious - Retourne le Throwable précédent
    • Throwable::getTrace - Récupère la trace d'appels
    • Throwable::getTraceAsString - Récupère la trace d'appels en tant que chaîne de caractères
    • Throwable::__toString - Récupère la représentation sous forme de chaîne de caractère de l'objet jeté
    • tidy::$errorBuffer - Retourne les alertes et erreurs qui sont survenues lors de l'analyse du document
    • tidy::body - Retourne un objet TidyNode, commencé à partir de la balise <body>
    • tidy::cleanRepair - Effectue les opérations de nettoyage et de réparation préparées pour un fichier HTML
    • tidy::diagnose - Établit le diagnostic pour le document analysé et réparé
    • tidy::getConfig - Lit la configuration Tidy courante
    • tidy::getHtmlVer - Détecte le version du code HTML utilisée dans un document
    • Tidy::getopt - Retourne la valeur de l'option de configuration Tidy
    • tidy::getOptDoc - Retourne la documentation pour le nom de l'option donnée
    • tidy::getRelease - Retourne la date de publication (version) de la bibliothèque Tidy
    • tidy::getStatus - Retourne le statut du document spécifié
    • tidy::head - Retourne un objet tidyNode à partir de la balise <head>
    • tidy::html - Retourne un objet tidyNode commençant à la balise <html>
    • tidy::isXhtml - Indique si le document est un document XHTML
    • tidy::isXml - Indique si le document est un document XML générique (non HTML/XHTML)
    • tidy::parseFile - Analyse les balises d'un fichier ou d'une URI
    • tidy::parseString - Analyse un document HTML contenu dans une chaîne
    • tidy::repairFile - Répare un fichier et le renvoie en tant que chaîne
    • tidy::repairString - Répare une chaîne HTML en utilisant un fichier de configuration optionnel
    • tidy::root - Retourne un objet tidyNode représentant la racine du document HTML
    • tidy::__construct - Construit un nouvel objet tidy
    • tidyNode::getParent - Retourne le nœud parent du nœud courant
    • tidyNode::hasChildren - Indique si le nœud a des enfants
    • tidyNode::hasSiblings - Indique si le nœud a des frères
    • tidyNode::isAsp - Vérifie si le nœud est du code ASP
    • tidyNode::isComment - Indique si le nœud représente un commentaire
    • tidyNode::isHtml - Indique si le nœud est une nœud d'élément
    • tidyNode::isJste - Indique si ce nœud est JSTE
    • tidyNode::isPhp - Indique si un nœud contient du code PHP
    • tidyNode::isText - Indique si le nœud représente du texte (sans balise)
    • tidyNode::__construct - Constructeur privée pour interdire l'instanciation directe
    • tidy_access_count - Retourne le nombre d'alertes d'accessibilité Tidy rencontrées dans le document
    • tidy_config_count - Retourne le nombre d'erreurs de configuration Tidy rencontrées dans le document
    • tidy_error_count - Retourne le nombre d'erreurs Tidy rencontrées dans le document
    • tidy_get_output - Retourne une chaîne représentant les balises telles qu'analysées par Tidy
    • tidy_warning_count - Retourne le nombre d'alertes Tidy rencontrées dans le document spécifié
    • time - Retourne l'horodatage UNIX actuel
    • timezone_abbreviations_list - Alias de DateTimeZone::listAbbreviations
    • timezone_identifiers_list - Alias de DateTimeZone::listIdentifiers
    • timezone_location_get - Alias de DateTimeZone::getLocation
    • timezone_name_from_abbr - Retourne le nom d'un fuseau horaire à partir de son abréviation et de son décalage UTC
    • timezone_name_get - Alias de DateTimeZone::getName
    • timezone_offset_get - Alias de DateTimeZone::getOffset
    • timezone_open - Alias de DateTimeZone::__construct
    • timezone_transitions_get - Alias de DateTimeZone::getTransitions
    • timezone_version_get - Lit la version de la timezonedb
    • time_nanosleep - Attendre pendant un nombre de secondes et de nanosecondes
    • time_sleep_until - Arrête le script pendant une durée spécifiée
    • tmpfile - Crée un fichier temporaire
    • token_get_all - Scinde un code source en éléments de base
    • token_name - Retourne le nom d'un élément de code source
    • touch - Modifie la date de modification et de dernier accès d'un fichier
    • trader_acos - Vector Trigonometric ACos
    • trader_ad - Chaikin A/D Line
    • trader_add - Ajoute un vecteur arithmétique
    • 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 - Calcule l'arc tangente
    • 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 - Masque In-Neck
    • trader_cdlinvertedhammer - Marteau inversé
    • trader_cdlkicking - Kicking
    • trader_cdlkickingbylength - Kicking - bull/bear déterminé par le plus marubozu
    • trader_cdlladderbottom - Bas de l'échelle
    • trader_cdllongleggeddoji - Doji : longueur des jambes
    • trader_cdllongline - Long Line Candle
    • trader_cdlmarubozu - Marubozu
    • trader_cdlmatchinglow - Matching Low
    • trader_cdlmathold - Mat Hold
    • trader_cdlmorningdojistar - Etoile Doji du matin
    • trader_cdlmorningstar - Etoile du matin
    • trader_cdlonneck - Masque On-Neck
    • trader_cdlpiercing - Masque Piercing
    • trader_cdlrickshawman - Rickshaw Man
    • trader_cdlrisefall3methods - Hausse / Baisse - 3 méthodes
    • trader_cdlseparatinglines - Lignes séparées
    • trader_cdlshootingstar - Etoile filante
    • trader_cdlshortline - Ligne courte de bougie
    • trader_cdlspinningtop - Toupie
    • trader_cdlstalledpattern - Masque bloqué
    • trader_cdlsticksandwich - Sandwich épinglé
    • trader_cdltakuri - Takuri (Dragonfly Doji avec une ombre inférieure très longue)
    • trader_cdltasukigap - Ecart Tasuki
    • trader_cdlthrusting - Masque de poussée
    • trader_cdltristar - Masque Tristar
    • trader_cdlunique3river - Unique 3 River
    • trader_cdlupsidegap2crows - Ecart inversé Two Crows
    • trader_cdlxsidegap3methods - Ecart supérieur/inférieur trois méthodes
    • trader_ceil - Vecteur plafonné
    • trader_cmo - Oscillateur dynamique Chande
    • trader_correl - Coefficient de corrélation de Pearson (r)
    • trader_cos - Vecteur trigonométrique Cos
    • trader_cosh - Vecteur trigonométrique Cosh
    • trader_dema - Moyenne mobile exponentielle double
    • trader_div - Vecteur arithmétique Div
    • trader_dx - Indice de mouvement directionnel
    • trader_ema - Moyenne mobile exponentielle
    • trader_errno - Récupère le code erreur
    • trader_exp - Vecteur arithmétique Exp
    • trader_floor - Niveau du vecteur
    • trader_get_compat - Récupère le mode de compatibilité
    • trader_get_unstable_period - Récupère la période d'instabilité
    • trader_ht_dcperiod - Transformation de Hilbert - Période de cycle dominant
    • trader_ht_dcphase - Transformation de Hilbert - Phase de cycle dominant
    • trader_ht_phasor - Transformation de Hilbert - Composants de la phase
    • trader_ht_sine - Transformation de Hilbert - Onde sinusoïdale
    • trader_ht_trendline - Transformation de Hilbert - Tendance instantanée
    • trader_ht_trendmode - Transformation de Hilbert - Mode tendance vs mode cycle
    • trader_kama - Moyenne mobile adaptative Kaufman
    • trader_linearreg - Régression linéaire
    • trader_linearreg_angle - Angle de régression linéaire
    • trader_linearreg_intercept - Interception de régression linéaire
    • trader_linearreg_slope - Pente de régression linéaire
    • trader_ln - Vecteur de Log naturel
    • trader_log10 - Vecteur Log10
    • trader_ma - Moyenne mobile
    • trader_macd - Moyenne du déplacement Convergence/Divergence
    • trader_macdext - MACD avec un type MA réglable
    • trader_macdfix - Moyen de déplacement Convergence/Divergence fixé à 12/26
    • trader_mama - MESA moyenne mobile adaptative
    • trader_mavp - Moyenne mobile avec durée variable
    • trader_max - Valeur la plus élevée sur une période déterminée
    • trader_maxindex - Indice de la valeur la plus élevée sur une période déterminée
    • trader_medprice - Prix médian
    • trader_mfi - Indice de fluidité de l'argent
    • trader_midpoint - Milieu sur la période
    • trader_midprice - Prix moyen sur la période
    • trader_min - Valeur la plus basse sur une période spécifique
    • trader_minindex - Indice de la valeur la plus basse sur une période déterminée
    • trader_minmax - Valeurs minimales et maximales sur une période donnée
    • trader_minmaxindex - Indices des valeurs minimales et maximales sur une période donnée
    • trader_minus_di - Indicateur minimum directionnel
    • trader_minus_dm - Mouvement minimum directionnel
    • trader_mom - Elan
    • trader_mult - Vecteur arithmétique mult
    • trader_natr - Intervalle réel normalisé moyen
    • trader_obv - Volume de l'équilibre
    • trader_plus_di - Indicateur positif de direction
    • trader_plus_dm - Mouvement directionnel positif
    • trader_ppo - Oscillateur de prix en pourcentage
    • trader_roc - Taux de variation : ((price/prevPrice)-1)*100
    • trader_rocp - Taux de variation en pourcentage : (price-prevPrice)/prevPrice
    • trader_rocr - Taux de rapport de changement : (price/prevPrice)
    • trader_rocr100 - Taux de taux de variation de l'échelle de 100 : (price/prevPrice)*100
    • trader_rsi - Indice de force relative
    • trader_sar - Parabolique SAR
    • trader_sarext - Parabolique SAR - Etendu
    • trader_set_compat - Définit le mode de compatibilité
    • trader_set_unstable_period - Définit une période instable
    • trader_sin - Vecteur trigonométrique sin
    • trader_sinh - Vecteur trigonométrique sinh
    • trader_sma - Moyenne mobile simple
    • trader_sqrt - Vecteur de racine carrée
    • trader_stddev - Déviation standard
    • trader_stoch - Stochastique
    • trader_stochf - Rapidité stochastique
    • trader_stochrsi - Index stochastique relatif fort
    • trader_sub - Vecteur de soustraction arithmétique
    • trader_sum - Résumé
    • trader_t3 - Triple moyenne mobile exponentielle (T3)
    • trader_tan - Vecteur trigonométrie Tan
    • trader_tanh - Vecteur trigonométrie Tanh
    • trader_tema - Triple moyenne mobile exponentielle
    • trader_trange - Intervalle réel
    • trader_trima - Moyenne mobile triangulaire
    • trader_trix - Taux de variation sur une journée (ROC) d'un triple EMA lissé
    • trader_tsf - Prévisions des séries chronologiques
    • trader_typprice - Prix ??typique
    • trader_ultosc - Oscillateur ultime
    • trader_var - Variance
    • trader_wclprice - Prix clos ??pondéré
    • trader_willr - Williams' %R
    • trader_wma - Moyenne mobile pondérée
    • trait_exists - Vérifie si un trait existe
    • Transliterator::create - Crée un Transliterator
    • Transliterator::createFromRules - Crée un translittérateur depuis des règles
    • Transliterator::createInverse - Crée un translittérateur inverse
    • Transliterator::getErrorCode - Récupère le dernier code erreur
    • Transliterator::getErrorMessage - Récupère le dernier message d'erreur
    • Transliterator::listIDs - Récupère les identifiants de ce translittérateur
    • Transliterator::transliterate - Translittère une chaîne de caractères
    • Transliterator::__construct - Constructeur privé pour interdire l'instantiation
    • trigger_error - Déclenche une erreur utilisateur
    • trim - Supprime les espaces (ou d'autres caractères) en début et fin de chaîne
  • u
    • uasort - Trie un tableau en utilisant une fonction de rappel
    • ucfirst - Met le premier caractère en majuscule
    • UConverter::convert - Convertit une chaîne d'un jeu de caractères vers un autre jeu de caractères
    • UConverter::fromUCallback - Fonction de rappel "from"
    • UConverter::getAliases - Récupère les alias du nom fourni
    • UConverter::getAvailable - Récupère le nom canonique des convertisseurs diponibles
    • UConverter::getDestinationEncoding - Récupère l'encodage de la destination
    • UConverter::getDestinationType - Récupère le type de la destination du convertisseur
    • UConverter::getErrorCode - Récupère le code de la dernière erreur survenue sur l'objet
    • UConverter::getErrorMessage - Récupère le message de la dernière erreur survenue sur l'objet
    • UConverter::getSourceEncoding - Récupère l'encodage de la source
    • UConverter::getSourceType - Récupère le type de source du convertisseur
    • UConverter::getStandards - Récupère les normes associées aux noms de conversion
    • UConverter::getSubstChars - Récupère les caractères de substitution
    • UConverter::reasonText - Récupère la chaîne représentant la raison de la fonction de rappel
    • UConverter::setDestinationEncoding - Définit l'encodage de la destination
    • UConverter::setSourceEncoding - Définit l'encodage de la source
    • UConverter::setSubstChars - Définit les caractères de substitution
    • UConverter::toUCallback - Fonction de rappel "to"
    • UConverter::transcode - Convertit une chaîne d'un jeu de caractères à un autre
    • UConverter::__construct - Crée un objet UConverter
    • ucwords - Met en majuscule la première lettre de tous les mots
    • 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 - Récupére les familles de polices
    • 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 - Quitte la boucle UI
    • UI\run - Entre dans la boucle UI
    • 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 - Affiche un message d'erreur
    • 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 - Trie un tableau par ses clés en utilisant une fonction de rappel
    • umask - Change le "umask" courant
    • uniqid - Génère un identifiant unique
    • UnitEnum::cases - Génère une liste de cas sur une énumération
    • unixtojd - Convertit un timestamp UNIX en un jour Julien
    • unlink - Supprime un fichier
    • unpack - Déconditionne des données depuis une chaîne binaire
    • unregister_tick_function - Annule la fonction exécutée à chaque tick
    • unserialize - Crée une variable PHP à partir d'une valeur sérialisée
    • unset - Détruit une variable
    • untaint - Ne nettoie pas une chaîne
    • uopz_add_function - Adds non-existent function or method
    • uopz_allow_exit - Allows control over disabled exit opcode
    • uopz_backup - Sauvegarde une fonction
    • uopz_compose - Compose une classe
    • uopz_copy - Copie une fonction
    • uopz_delete - Supprime une fonction
    • uopz_del_function - Deletes previously added function or method
    • uopz_extend - Etend une classe à l'exécution
    • uopz_flags - Récupère ou défini les drapeaux d'une fonction ou d'une classe
    • uopz_function - Crée une fonction à l'exécution
    • 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 - Implémente une interface à l'exécution
    • uopz_overload - Surcharge un opcode VM
    • uopz_redefine - Re-défini une constante
    • uopz_rename - Renomme une fonction à l'exécution
    • uopz_restore - Restaure une fonction sauvegardée
    • 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 - Supprime une constante
    • 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 - Décode une chaîne encodée URL
    • urlencode - Encode une chaîne en URL
    • user_error - Alias de trigger_error
    • use_soap_error_handler - Active le gestionnaire d'erreurs SOAP natif
    • usleep - Arrête l'exécution durant quelques microsecondes
    • usort - Trie un tableau en utilisant une fonction de comparaison
    • utf8_decode - Convertit une chaîne UTF-8 en ISO-8859-1, en remplaçant les caractères invalides ou non représentables.
    • utf8_encode - Convertit une chaîne ISO-8859-1 en UTF-8
  • v
    • V8Js::executeString - Exécute une chaîne comme du code Javascript
    • V8Js::getExtensions - Retourne un tableau contenant les extensions enregistrées
    • V8Js::getPendingException - Retourne l'exception Javascript non attrapée restante
    • V8Js::registerExtension - Enregistre des extensions Javascript pour V8Js
    • V8Js::__construct - Construit un nouvel objet V8Js
    • V8JsException::getJsFileName - Le but de getJsFileName
    • V8JsException::getJsLineNumber - Le but de getJsLineNumber
    • V8JsException::getJsSourceLine - Le but de getJsSourceLine
    • V8JsException::getJsTrace - Le but de getJsTrace
    • variant::__construct - Constructeur de la classe variant
    • variant_abs - Retourne la valeur absolue d'un variant
    • variant_add - "Ajoute" deux valeurs de variants et retourne le résultat
    • variant_and - Effectue un ET entre deux variants et retourne le résultat
    • variant_cast - Convertit un variant en un nouvel objet variant de type différent
    • variant_cat - Assemble deux valeurs variantes ensemble et retourne le résultat
    • variant_cmp - Compare deux variants
    • variant_date_from_timestamp - Retourne une représentation date en variant d'un timestamp Unix
    • variant_date_to_timestamp - Convertit une valeur date/temps variante en un timestamp Unix
    • variant_div - Retourne le résultat de la division de deux variants
    • variant_eqv - Effectue une équivalence de bits de deux variants
    • variant_fix - Récupère la portion entière d'un variant
    • variant_get_type - Retourne le type d'un objet variant
    • variant_idiv - Convertit des variants en valeurs entières, et effectue alors une division
    • variant_imp - Exécute une implication sur les bits de deux variants
    • variant_int - Retourne la partie entière d'un variant
    • variant_mod - Divise deux variantes et retourne le reste
    • variant_mul - Multiplie les valeurs de deux variants
    • variant_neg - Effectue une négation logique sur un variant
    • variant_not - Exécute une négation sur les bits sur un variant
    • variant_or - Performe une disjonction logique sur deux variants
    • variant_pow - Retourne le résultat de la fonction puissance avec deux variants
    • variant_round - Arrondit le variant au nombre spécifié de décimales
    • variant_set - Assigne une nouvelle valeur pour un objet variant
    • variant_set_type - Convertit un variant en un autre type "sur-place"
    • variant_sub - Soustrait la valeur du variant de droite de la valeur de celui de gauche
    • variant_xor - Exécute une exclusion logique sur deux variants
    • VarnishAdmin::auth - S'Authentifie sur une instance Varnish
    • VarnishAdmin::ban - Ban des URLs en utilisant une expression VCL
    • VarnishAdmin::banUrl - Ban une URL en utilisant une expression VCL
    • VarnishAdmin::clearPanic - Efface les messages de panique de l'instance Varnish
    • VarnishAdmin::connect - Connexion à l'interface d'administration de l'instance Varnish
    • VarnishAdmin::disconnect - Déconnexion de l'interface d'administration d'une instance varnish
    • VarnishAdmin::getPanic - Récupère le dernier message de panique de l'instance Varnish
    • VarnishAdmin::getParams - Récupère les paramètres de configuration de l'instance Varnish courante
    • VarnishAdmin::isRunning - Vérifie si un processus esclave Varnish est actuellement en cours d'exécution
    • VarnishAdmin::setCompat - Définit le paramètre de configuration compat
    • VarnishAdmin::setHost - Définit le paramètre de configuration host
    • VarnishAdmin::setIdent - Définit le paramètre de configuration ident
    • VarnishAdmin::setParam - Définit un paramètre de configuration sur l'instance courante Varnish
    • VarnishAdmin::setPort - Définit le paramètre de configuration port
    • VarnishAdmin::setSecret - Définit le paramètre de configuration secret
    • VarnishAdmin::setTimeout - Définit le paramètre de configuration timeout
    • VarnishAdmin::start - Démarre un processus Varnish
    • VarnishAdmin::stop - Arrête un processus Varnish
    • VarnishAdmin::__construct - Constructeur VarnishAdmin
    • VarnishLog::getLine - Récupère la prochaine ligne de log
    • VarnishLog::getTagName - Récupère le nom de la balise représenté par son index
    • VarnishLog::__construct - Constructeur Varnishlog
    • VarnishStat::getSnapshot - Récupère les statistiques de l'instance courante Varnish
    • VarnishStat::__construct - Constructeur VarnishStat
    • var_dump - Affiche les informations d'une variable
    • var_export - Retourne le code PHP utilisé pour générer une variable
    • var_representation - Returns a short, readable, parsable string representation of a variable
    • version_compare - Compare deux chaînes de version au format des versions PHP
    • vfprintf - Écrit une chaîne formatée dans un flux
    • virtual - Effectue une sous-requête Apache
    • vprintf - Affiche une chaîne formatée
    • vsprintf - Retourne une chaîne formatée
    • Vtiful\Kernel\Excel::addSheet - Ajoute une feuille de calcul
    • Vtiful\Kernel\Excel::autoFilter - Ajoute un filtre automatique
    • Vtiful\Kernel\Excel::constMemory - Ecrit un gros fichier avec une utilisation constante de la mémoire
    • Vtiful\Kernel\Excel::data - Ecrit des données
    • Vtiful\Kernel\Excel::fileName - Crée un nouveau fichier ainsi qu'une feuille de calcul
    • Vtiful\Kernel\Excel::getHandle - Récupère le gestionnaire de ressource
    • Vtiful\Kernel\Excel::header - Ecrit l'en-tête d'une feuille de calcul
    • Vtiful\Kernel\Excel::insertFormula - Insère une formule
    • Vtiful\Kernel\Excel::insertImage - Insère une image dans une cellule
    • Vtiful\Kernel\Excel::insertText - Ecrit du texte dans une cellule
    • Vtiful\Kernel\Excel::mergeCells - Fusionne des cellules
    • Vtiful\Kernel\Excel::output - Enregistre le fichier xlsx sur le disque
    • Vtiful\Kernel\Excel::setColumn - Définit le format d'une colonne
    • Vtiful\Kernel\Excel::setRow - Définit le format d'une ligne
    • Vtiful\Kernel\Excel::__construct - Constructeur de la classe Vtiful\Kernel\Excel
    • Vtiful\Kernel\Format::align - Définit l'alignement de la cellule
    • Vtiful\Kernel\Format::bold - Mise en gras
    • Vtiful\Kernel\Format::italic - Mise en italique
    • Vtiful\Kernel\Format::underline - Mise en souligné
  • w
    • Warning::__construct - Warning constructor
    • wddx_add_vars - Ajoute des variables à un paquet WDDX
    • wddx_deserialize - Désérialise un paquet WDDX
    • wddx_packet_end - Clôt un paquet WDDX
    • wddx_packet_start - Commence un nouveau paquet WDDX avec une structure
    • wddx_serialize_value - Enregistre une valeur dans un paquet WDDX
    • wddx_serialize_vars - Enregistre plusieurs valeurs dans un paquet WDDX
    • WeakMap::count - Compte le nombre d'entrées actives dans le dictionnaire
    • WeakMap::getIterator - Récupére un itérateur externe
    • WeakMap::offsetExists - Vérifie si un certain objet se trouve dans le dictionnaire
    • WeakMap::offsetGet - Retourne la valeur indiquée par un certain objet
    • WeakMap::offsetSet - Met à jour le dictionnaire avec une nouvelle paire clé-valeur
    • WeakMap::offsetUnset - Supprime une entrée du dictionnaire
    • WeakReference::create - Créer une nouvelle référence faible
    • WeakReference::get - Récupère un objet faiblement référencé
    • WeakReference::__construct - Constructeur qui interdit l'initialisation
    • win32_continue_service - Reprise d'un service en pause
    • win32_create_service - Crée une nouvelle entrée pour service dans la base de données SCM
    • win32_delete_service - Supprime une entrée de service de la base de données SCM
    • win32_get_last_control_message - Retourne le dernier message de contrôle qui a été envoyé à ce service
    • win32_pause_service - Met en pause un service
    • win32_query_service_status - Questionne le statut d'un service
    • win32_send_custom_control - Envoyer un contrôle personnalisé au service
    • win32_set_service_exit_code - Définir ou renvoyer le code de sortie pour le service en cours d'exécution
    • win32_set_service_exit_mode - Définir ou renvoyer le mode de sortie pour le service en cours d'exécution
    • win32_set_service_status - Met à jour le statut d'un service
    • win32_start_service - Démarre un service
    • win32_start_service_ctrl_dispatcher - Enregistre un script avec SCM, alors il peut être interprété en tant que service avec le nom donné
    • win32_stop_service - Arrête un service
    • wincache_fcache_fileinfo - Extrait des informations sur les fichiers mis en cache dans le cache de fichiers
    • wincache_fcache_meminfo - Extrait des informations sur l'utilisation de la mémoire du cache de fichiers.
    • wincache_lock - Acquière un verrou exclusif sur une clé donnée
    • wincache_ocache_fileinfo - Extrait des informations sur les fichiers mis en cache dans le cache opcode
    • wincache_ocache_meminfo - Extrait des informations sur l'utilisation du cache opcode
    • wincache_refresh_if_changed - Actualise les entrées du cache pour les fichiers mis en cache
    • wincache_rplist_fileinfo - Récupère des informations du cache sur un chemin de fichier résolu
    • wincache_rplist_meminfo - Récupère des informations sur l'utilisation de la mémoire par le cache de chemin de fichier résolu
    • wincache_scache_info - Récupère des informations sur des fichiers mis en cache
    • wincache_scache_meminfo - Récupère des informations sur l'utilisation de la mémoire du cache
    • wincache_ucache_add - Ajoute une nouvelle variable au cache utilisateur
    • wincache_ucache_cas - Compare la variable avec son ancienne valeur et lui assigne une nouvelle valeur
    • wincache_ucache_clear - Supprime le contenu d'une entrée du cache utilisateur
    • wincache_ucache_dec - Décrémente la valeur associée à une clé
    • wincache_ucache_delete - Supprime les variables du cache utilisateur
    • wincache_ucache_exists - Vérifie si une variable existe dans le cache utilisateur
    • wincache_ucache_get - Récupère une variable stokée dans le cache utilisateur
    • wincache_ucache_inc - Incrémente la valeur associée à une clé
    • wincache_ucache_info - Récupère des informations sur des données stokées dans le cache utilisateur
    • wincache_ucache_meminfo - Récupère des informations sur l'utilisation mémoire du cache utilisateur
    • wincache_ucache_set - Ajoute une variable au cache utilisateur et écrase la variable si elle existe déjà dans le cache
    • wincache_unlock - Libère un verrou exclusif sur une clé donnée
    • wkhtmltox\Image\Converter::convert - Réalise une conversion d'image
    • wkhtmltox\Image\Converter::getVersion - Détermine la version du convertisseur
    • wkhtmltox\Image\Converter::__construct - Cré un nouveau convertisseur d'image
    • wkhtmltox\PDF\Converter::add - Ajoute un objet pour la conversion
    • wkhtmltox\PDF\Converter::convert - Lance la conversion PDF
    • wkhtmltox\PDF\Converter::getVersion - Détermine la version du convertisseur
    • wkhtmltox\PDF\Converter::__construct - Cré un nouveau convertisseur PDF
    • wkhtmltox\PDF\Object::__construct - Crée un nouvel objet PDF
    • wordwrap - Effectue la césure d'une chaîne
    • Worker::collect - Collect references to completed tasks
    • Worker::getStacked - Obtient la taille de pile restante
    • Worker::isShutdown - Détection de statut
    • Worker::shutdown - Arrêter le worker
    • Worker::stack - Empile la tâche
    • Worker::unstack - Dépile une tâche
  • x
    • xattr_get - Récupère un attribut étendu
    • xattr_list - Récupère une liste d'attributs étendus
    • xattr_remove - Efface un attribut étendu
    • xattr_set - Définit un attribut étendu
    • xattr_supported - Vérifie si un système de fichiers supporte les attributs étendus
    • xdiff_file_bdiff - Crée un diff binaire de 2 fichiers
    • xdiff_file_bdiff_size - Lit la taille d'un fichier créé lors de l'application d'un diff binaire
    • xdiff_file_bpatch - Patche un fichier avec un diff binaire
    • xdiff_file_diff - Créé un diff unifié entre deux fichiers
    • xdiff_file_diff_binary - Alias de xdiff_file_bdiff
    • xdiff_file_merge3 - Fusionne trois fichiers en un seul
    • xdiff_file_patch - Patche un fichier avec un diff unifié
    • xdiff_file_patch_binary - Alias de xdiff_file_bpatch
    • xdiff_file_rabdiff - Crée un diff binaire de 2 fichiers en utilisant l'algorithme polynomial de Rabin des empreintes digitales
    • xdiff_string_bdiff - Crée un diff binaire de 2 chaînes
    • xdiff_string_bdiff_size - Lit la taille d'un fichier créé en appliquant un diff binaire
    • xdiff_string_bpatch - Patche une chaîne avec un diff binaire
    • xdiff_string_diff - Créé un diff unifié entre deux chaînes
    • xdiff_string_diff_binary - Alias de xdiff_string_bdiff
    • xdiff_string_merge3 - Fusionne trois chaînes en une seule
    • xdiff_string_patch - Patche une chaîne avec un diff unifié
    • xdiff_string_patch_binary - Alias de xdiff_string_bpatch
    • xdiff_string_rabdiff - Crée un diff binaire de 2 chaînes en utilisant l'algorithme polynomial de Rabin des empreintes digitales
    • xhprof_disable - Stoppe le profilage xhprof
    • xhprof_enable - Démarre le profilage xhprof
    • xhprof_sample_disable - Stoppe le profilage xhprof sur échantillon
    • xhprof_sample_enable - Démarre le profilage en mode échantillonnage
    • XMLDiff\Base::diff - Produit la différence de deux documents XML
    • XMLDiff\Base::merge - Produit un nouveau document XML basé sur une différence
    • XMLDiff\Base::__construct - Constructeur
    • XMLDiff\DOM::diff - Trouve la différence de deux objets DOMDocument
    • XMLDiff\DOM::merge - Produit un DOMDocument fusionné
    • XMLDiff\File::diff - Effectue la différence entre deux documents XML
    • XMLDiff\File::merge - Fusionne un document XML
    • XMLDiff\Memory::diff - Différence entre deux documents XML
    • XMLDiff\Memory::merge - Fusionne un document XML
    • XMLReader::close - Ferme l'entrée XMLReader
    • XMLReader::expand - Retourne une copie du nœud courant comme un nœud d'objet DOM
    • XMLReader::getAttribute - Récupère la valeur d'un attribut par nom
    • XMLReader::getAttributeNo - Récupère la valeur d'un attribut par index
    • XMLReader::getAttributeNs - Récupère la valeur d'un attribut par nom local et URI
    • XMLReader::getParserProperty - Indique si la propriété spécifiée a été fixée
    • XMLReader::isValid - Indique si le document analysé est valide
    • XMLReader::lookupNamespace - Consulte l'espace de nom pour un préfixe
    • XMLReader::moveToAttribute - Déplace un curseur à un attribut nommé
    • XMLReader::moveToAttributeNo - Déplace le curseur à un attribut par index
    • XMLReader::moveToAttributeNs - Déplace le curseur à un attribut d'espace de nom
    • XMLReader::moveToElement - Positionne le curseur sur l'élément parent de l'attribut courant
    • XMLReader::moveToFirstAttribute - Positionne le curseur sur le premier attribut
    • XMLReader::moveToNextAttribute - Positionne le curseur sur le prochain attribut
    • XMLReader::next - Déplace le curseur au prochain nœud en sautant tous les sous arbres
    • XMLReader::open - Fixe le URI contenant le XML à analyser
    • XMLReader::read - Déplace le curseur sur le prochain nœud du document
    • XMLReader::readInnerXml - Lit le code XML du nœud courant
    • XMLReader::readOuterXml - Lit le code XML du nœud courant, y compris lui-même
    • XMLReader::readString - Lit le contenu du nœud courant sous forme de chaîne
    • XMLReader::setParserProperty - Fixe des options pour l'analyseur
    • XMLReader::setRelaxNGSchema - Fixe le nom du fichier ou l'URI pour le Schéma RelaxNG
    • XMLReader::setRelaxNGSchemaSource - Spécifie le schéma RelaxNG
    • XMLReader::setSchema - Valide le document avec XSD
    • XMLReader::XML - Fixe les données contenant le XML à analyser
    • xmlrpc_decode - Décode le XML en types PHP natifs
    • xmlrpc_decode_request - Décode le code XML en variables PHP natives
    • xmlrpc_encode - Génère le code XML pour une valeur PHP
    • xmlrpc_encode_request - Génère le XML pour une méthode
    • xmlrpc_get_type - Retourne le type XMLRPC d'une valeur PHP
    • xmlrpc_is_fault - Détermine si un tableau de valeurs représente un XMLRPC
    • xmlrpc_parse_method_descriptions - Décode le code XML en une liste de descriptions de méthodes
    • xmlrpc_server_add_introspection_data - Ajoute des données d'introspection
    • xmlrpc_server_call_method - Analyse une requête XML et appelle les méthodes associées
    • xmlrpc_server_create - Crée un serveur XMLRPC
    • xmlrpc_server_destroy - Détruit un serveur XMLRPC
    • xmlrpc_server_register_introspection_callback - Enregistre une fonction PHP pour générer la documentation
    • xmlrpc_server_register_method - Enregistre une fonction PHP avec une méthode
    • xmlrpc_set_type - Définit le type xmlrpc, base64 ou datetime, d'une valeur PHP
    • XMLWriter::endAttribute - Termine un attribut
    • XMLWriter::endCdata - Termine un bloc CDATA
    • XMLWriter::endComment - Termine un commentaire
    • XMLWriter::endDocument - Termine le document courant
    • XMLWriter::endDtd - Termine la DTD courante
    • XMLWriter::endDtdAttlist - Termine la liste des attributs de la DTD courante
    • XMLWriter::endDtdElement - Termine l'élément de la DTD courante
    • XMLWriter::endDtdEntity - Termine l'entité de la DTD courante
    • XMLWriter::endElement - Termine l'élément courant
    • XMLWriter::endPi - Termine le PI courant
    • XMLWriter::flush - Affiche le buffer courant
    • XMLWriter::fullEndElement - Termine l'élément courant
    • XMLWriter::openMemory - Crée un nouveau xmlwriter en utilisant la mémoire pour l'affichage des chaînes
    • XMLWriter::openUri - Crée un nouveau xmlwriter, en utilisant l'URI source pour l'affichage
    • XMLWriter::outputMemory - Retourne le buffer courant
    • XMLWriter::setIndent - Active ou non l'indentation
    • XMLWriter::setIndentString - Définit la chaîne à utiliser pour l'indentation
    • XMLWriter::startAttribute - Crée un attribut
    • XMLWriter::startAttributeNs - Crée un attribut pour l'espace de noms
    • XMLWriter::startCdata - Crée une balise CDATA
    • XMLWriter::startComment - Crée un commentaire
    • XMLWriter::startDocument - Crée un document
    • XMLWriter::startDtd - Crée une DTD
    • XMLWriter::startDtdAttlist - Crée une liste d'attributs pour la DTD
    • XMLWriter::startDtdElement - Crée un élément DTD
    • XMLWriter::startDtdEntity - Crée une entité DTD
    • XMLWriter::startElement - Crée un élément
    • XMLWriter::startElementNs - Crée un élément d'un espace de noms
    • XMLWriter::startPi - Crée une balise PI
    • XMLWriter::text - Écrit du texte
    • XMLWriter::writeAttribute - Écrit un attribut
    • XMLWriter::writeAttributeNs - Écrit un attribut d'un espace de noms
    • XMLWriter::writeCdata - Écrit un bloc CDATA
    • XMLWriter::writeComment - Écrit un commentaire
    • XMLWriter::writeDtd - Écrit une DTD
    • XMLWriter::writeDtdAttlist - Écrit une liste d'attributs DTD
    • XMLWriter::writeDtdElement - Écrit un élément DTD
    • XMLWriter::writeDtdEntity - Écrit une entité DTD
    • XMLWriter::writeElement - Écrit un élément
    • XMLWriter::writeElementNs - Écrit un élément d'un espace de noms
    • XMLWriter::writePi - Écrit la balise PI
    • XMLWriter::writeRaw - Écrit un texte XML brut
    • xml_error_string - Lit le message d'erreur de l'analyseur XML
    • xml_get_current_byte_index - Retourne l'index de l'octet courant d'un analyseur XML
    • xml_get_current_column_number - Retourne le numéro de colonne courant d'un analyseur XML
    • xml_get_current_line_number - Retourne le numéro de ligne courant d'un analyseur XML
    • xml_get_error_code - Récupère le code erreur de l'analyseur XML
    • xml_parse - Commence l'analyse d'un document XML
    • xml_parser_create - Création d'un analyseur XML
    • xml_parser_create_ns - Crée un analyseur XML
    • xml_parser_free - Détruit un analyseur XML
    • xml_parser_get_option - Lit les options d'un analyseur XML
    • xml_parser_set_option - Affecte les options d'un analyseur XML
    • xml_parse_into_struct - Analyse une structure XML
    • xml_set_character_data_handler - Affecte les gestionnaires de texte littéral
    • xml_set_default_handler - Affecte le gestionnaire XML par défaut
    • xml_set_element_handler - Affecte les gestionnaires de début et de fin de balise XML
    • xml_set_end_namespace_decl_handler - Configure le gestionnaire XML de données
    • xml_set_external_entity_ref_handler - Configure le gestionnaire XML de références externes
    • xml_set_notation_decl_handler - Configure le gestionnaire XML de notations
    • xml_set_object - Configure un objet comme analyseur XML
    • xml_set_processing_instruction_handler - Affecte les gestionnaires d'instructions de traitement
    • xml_set_start_namespace_decl_handler - Configure le gestionnaire de caractères
    • xml_set_unparsed_entity_decl_handler - Affecte les gestionnaires d'entités non déclarées
    • XSLTProcessor::getParameter - Récupère la valeur d'un paramètre
    • XSLTProcessor::getSecurityPrefs - Récupère les préférences de sécurité
    • XSLTProcessor::hasExsltSupport - Indique si PHP utilise EXSLT
    • XSLTProcessor::importStylesheet - Importe une feuille de style
    • XSLTProcessor::registerPHPFunctions - Active l'utilisation de PHP dans les feuilles de styles XSLT
    • XSLTProcessor::removeParameter - Efface un paramètre
    • XSLTProcessor::setParameter - Définit la valeur d'un paramètre
    • XSLTProcessor::setProfiling - Spécifie le fichier de profilage
    • XSLTProcessor::setSecurityPrefs - Définit les préférences de sécurité
    • XSLTProcessor::transformToDoc - Transforme en un document
    • XSLTProcessor::transformToUri - Transforme en URI
    • XSLTProcessor::transformToXml - Transformer en XML
    • XSLTProcessor::__construct - Crée un nouvel objet XSLTProcessor
  • y
    • Yac::add - Stock un élément dans le cache
    • Yac::delete - Supprime un ou plusieurs éléments du cache
    • Yac::dump - Extraie les valeurs du cache
    • Yac::flush - Supprime toutes les valeurs mises en cache
    • Yac::get - Récupère un élément du cache
    • Yac::info - Statut du cache
    • Yac::set - Stock une valeur dans le cache
    • Yac::__construct - Constructeur
    • Yac::__get - Récupère un élément du cache
    • Yac::__set - Stock un élément dans le cache
    • Yaconf::get - Récupère une entrée
    • Yaconf::has - Détermine si une entrée existe
    • Yaf_Action_Abstract::execute - Point d'entrée de l'action
    • Yaf_Action_Abstract::getController - Récupère l'objet contrôleur
    • Yaf_Action_Abstract::getControllerName - Récupère le nom du contrôleur
    • Yaf_Application::app - Récupère une instance de l'application
    • Yaf_Application::bootstrap - Appelle bootstrap
    • Yaf_Application::clearLastError - Efface les informations de la dernière erreur
    • Yaf_Application::environ - Récupère la propriété environ
    • Yaf_Application::execute - Exécute une fonction de rappel
    • Yaf_Application::getAppDirectory - Récupère le dossier de l'application
    • Yaf_Application::getConfig - Récupère une instance de configuration
    • Yaf_Application::getDispatcher - Récupère une instance Yaf_Dispatcher
    • Yaf_Application::getLastErrorMsg - Récupère le message de la dernière erreur survenue
    • Yaf_Application::getLastErrorNo - Récupère le code de la dernière erreur survenue
    • Yaf_Application::getModules - Récupère les noms des modules définis
    • Yaf_Application::run - Démarre Yaf_Application
    • Yaf_Application::setAppDirectory - Modifie le dossier de l'application
    • Yaf_Application::__construct - Constructeur de Yaf_Application
    • Yaf_Application::__destruct - Le but de __destruct
    • Yaf_Config_Abstract::get - Permet de récupérer une valeur
    • Yaf_Config_Abstract::readonly - Vérifie si une configuration est en lecture seule
    • Yaf_Config_Abstract::set - Permet de définir une valeur
    • Yaf_Config_Abstract::toArray - Transforme en tableau
    • Yaf_Config_Ini::count - Compte tous les élements dans Yaf_Config.ini
    • Yaf_Config_Ini::current - Récupérer la valeur actuelle
    • Yaf_Config_Ini::key - Récupérer la clé de l'élément actuel
    • Yaf_Config_Ini::next - Avancer le pointeur interne
    • Yaf_Config_Ini::offsetExists - Le but de offsetExists
    • Yaf_Config_Ini::offsetGet - Le but de offsetGet
    • Yaf_Config_Ini::offsetSet - Le but de offsetSet
    • Yaf_Config_Ini::offsetUnset - Le but de offsetUnset
    • Yaf_Config_Ini::readonly - Le but de readonly
    • Yaf_Config_Ini::rewind - Le but de rewind
    • Yaf_Config_Ini::toArray - Retourne la configuration dans un tableau PHP
    • Yaf_Config_Ini::valid - Le but de valid
    • Yaf_Config_Ini::__construct - Constructeur Yaf_Config_Ini
    • Yaf_Config_Ini::__get - Récupérer un élément
    • Yaf_Config_Ini::__isset - Déterminer si une clé existe
    • Yaf_Config_Ini::__set - Le but de __set
    • Yaf_Config_Simple::count - Le but de count
    • Yaf_Config_Simple::current - Le but de current
    • Yaf_Config_Simple::key - Le but de key
    • Yaf_Config_Simple::next - Le but de next
    • Yaf_Config_Simple::offsetExists - Le but de offsetExists
    • Yaf_Config_Simple::offsetGet - Le but de offsetGet
    • Yaf_Config_Simple::offsetSet - Le but de offsetSet
    • Yaf_Config_Simple::offsetUnset - Le but de offsetUnset
    • Yaf_Config_Simple::readonly - Le but de readonly
    • Yaf_Config_Simple::rewind - Le but de rewind
    • Yaf_Config_Simple::toArray - Retourne un tableau PHP
    • Yaf_Config_Simple::valid - Le but de valid
    • Yaf_Config_Simple::__construct - Le but de __construct
    • Yaf_Config_Simple::__get - Le but de __get
    • Yaf_Config_Simple::__isset - Le but de __isset
    • Yaf_Config_Simple::__set - Le but de __set
    • Yaf_Controller_Abstract::display - Le but de display
    • Yaf_Controller_Abstract::forward - Transfère vers une autre action
    • Yaf_Controller_Abstract::getInvokeArg - Le but de getInvokeArg
    • Yaf_Controller_Abstract::getInvokeArgs - Le but de getInvokeArgs
    • Yaf_Controller_Abstract::getModuleName - Récupère le nom du module
    • Yaf_Controller_Abstract::getName - Récupère le nom du contrôleur
    • Yaf_Controller_Abstract::getRequest - Récupère l'objet de la demande courante
    • Yaf_Controller_Abstract::getResponse - Récupère l'objet de la réponse courante
    • Yaf_Controller_Abstract::getView - Récupère le moteur de visualisation
    • Yaf_Controller_Abstract::getViewpath - Le but de getViewpath
    • Yaf_Controller_Abstract::init - Initialisation du contrôleur
    • Yaf_Controller_Abstract::initView - Le but de initView
    • Yaf_Controller_Abstract::redirect - Redirige vers une URL
    • Yaf_Controller_Abstract::render - Affiche le rendu du template
    • Yaf_Controller_Abstract::setViewpath - Le but de setViewpath
    • Yaf_Controller_Abstract::__construct - Constructeur de Yaf_Controller_Abstract
    • Yaf_Dispatcher::autoRender - Active/désactive le rendu automatique
    • Yaf_Dispatcher::catchException - Active/désactive la récupération des exceptions
    • Yaf_Dispatcher::disableView - Désactive le moteur de visualisation
    • Yaf_Dispatcher::dispatch - Envoi une demande
    • Yaf_Dispatcher::enableView - Active le rendu de la vue
    • Yaf_Dispatcher::flushInstantly - Active/désactive l'envoi instantané
    • Yaf_Dispatcher::getApplication - Récupère l'application
    • Yaf_Dispatcher::getDefaultAction - Récupère le nom de l'action par défaut
    • Yaf_Dispatcher::getDefaultController - Récupère le nom du contrôleur par défaut
    • Yaf_Dispatcher::getDefaultModule - Récupère le nom du module par défaut
    • Yaf_Dispatcher::getInstance - Récupère l'instance du module d'envoi
    • Yaf_Dispatcher::getRequest - Récupère l'instance demandée
    • Yaf_Dispatcher::getRouter - Récupère l'instance routeur
    • Yaf_Dispatcher::initView - Initialise la vue et la retourne
    • Yaf_Dispatcher::registerPlugin - Enregistre un plugin
    • Yaf_Dispatcher::returnResponse - Le but de returnResponse
    • Yaf_Dispatcher::setDefaultAction - Modifie le nom par défaut de l'action
    • Yaf_Dispatcher::setDefaultController - Modifie le nom par défaut du controlleur
    • Yaf_Dispatcher::setDefaultModule - Modifie le nom par défaut du module
    • Yaf_Dispatcher::setErrorHandler - Définit un gestionnaire d'erreur personnalisé
    • Yaf_Dispatcher::setRequest - Le but de setRequest
    • Yaf_Dispatcher::setView - Définit un moteur de visualisation personnalisé
    • Yaf_Dispatcher::throwException - Active/désactive le lancement d'exceptions
    • Yaf_Dispatcher::__construct - Constructeur de Yaf_Dispatcher
    • Yaf_Exception::getPrevious - Le but de getPrevious
    • Yaf_Exception::__construct - Le but de __construct
    • Yaf_Loader::autoload - Le but de autoload
    • Yaf_Loader::clearLocalNamespace - Le but de clearLocalNamespace
    • Yaf_Loader::getInstance - Le but de getInstance
    • Yaf_Loader::getLibraryPath - Récupère le chemin de la bibliothèque
    • Yaf_Loader::getLocalNamespace - Récupère toutes les informations de tous les espaces de noms enregistrés
    • Yaf_Loader::getNamespacePath - Récupère le chemin d'un espace de noms enregistré
    • Yaf_Loader::import - Le but de import
    • Yaf_Loader::isLocalName - Le but de isLocalName
    • Yaf_Loader::registerLocalNamespace - Enregistre le préfixe local de la classe
    • Yaf_Loader::registerNamespace - Register namespace with searching path
    • Yaf_Loader::setLibraryPath - Modifie le chemin de la bibliothèque
    • Yaf_Loader::__construct - Le but de __construct
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - Le but de dispatchLoopShutdown
    • Yaf_Plugin_Abstract::dispatchLoopStartup - Crochet avant une boucle de répétitionp
    • Yaf_Plugin_Abstract::postDispatch - Le but de postDispatch
    • Yaf_Plugin_Abstract::preDispatch - Le but de preDispatch
    • Yaf_Plugin_Abstract::preResponse - Le but de preResponse
    • Yaf_Plugin_Abstract::routerShutdown - Le but de routerShutdown
    • Yaf_Plugin_Abstract::routerStartup - Hook RouterStartup
    • Yaf_Registry::del - Supprime un élément du registre
    • Yaf_Registry::get - Récupère un élément depuis le registre
    • Yaf_Registry::has - Vérifie si un élément existe
    • Yaf_Registry::set - Ajoute un élément au registre
    • Yaf_Registry::__construct - Constructeur de la classe Yaf_Registry
    • Yaf_Request_Abstract::clearParams - Supprime tous les paramètres
    • Yaf_Request_Abstract::getActionName - Le but de getActionName
    • Yaf_Request_Abstract::getBaseUri - Le but de getBaseUri
    • Yaf_Request_Abstract::getControllerName - Le but de getControllerName
    • Yaf_Request_Abstract::getEnv - Récupère une variable ENV
    • Yaf_Request_Abstract::getException - Le but de getException
    • Yaf_Request_Abstract::getLanguage - Récupère la langue préférée du client
    • Yaf_Request_Abstract::getMethod - Récupère la méthode utilisée
    • Yaf_Request_Abstract::getModuleName - Le but de getModuleName
    • Yaf_Request_Abstract::getParam - Récupère un paramètre
    • Yaf_Request_Abstract::getParams - Récupère tous les paramètres
    • Yaf_Request_Abstract::getRequestUri - Le but de getRequestUri
    • Yaf_Request_Abstract::getServer - Récupère une variable SERVER
    • Yaf_Request_Abstract::isCli - Vérifie si la requête est une requête en ligne de commande
    • Yaf_Request_Abstract::isDispatched - Vérifie si la requête est une requête isDispatched
    • Yaf_Request_Abstract::isGet - Vérifie si la requête est une requête GET
    • Yaf_Request_Abstract::isHead - Vérifie si la requête est une requête HEAD
    • Yaf_Request_Abstract::isOptions - Vérifie si la requête est une requête OPTIONS
    • Yaf_Request_Abstract::isPost - Vérifie si la requête est une requête isPost
    • Yaf_Request_Abstract::isPut - Vérifie si la requête est une requête PUT
    • Yaf_Request_Abstract::isRouted - Vérifie si la requête a été routée
    • Yaf_Request_Abstract::isXmlHttpRequest - Vérifie si la requête est une requête AJAX
    • Yaf_Request_Abstract::setActionName - Définie le nom de l'action
    • Yaf_Request_Abstract::setBaseUri - Défini l'URI de base
    • Yaf_Request_Abstract::setControllerName - Définie le nom du contrôleur
    • Yaf_Request_Abstract::setDispatched - Le but de setDispatched
    • Yaf_Request_Abstract::setModuleName - Définit le nom du module
    • Yaf_Request_Abstract::setParam - Définie un paramètre dans une requête
    • Yaf_Request_Abstract::setRequestUri - Le but de setRequestUri
    • Yaf_Request_Abstract::setRouted - Le but de setRouted
    • Yaf_Request_Http::get - Récupère la variable depuis le client
    • Yaf_Request_Http::getCookie - Récupère une variable Cookie
    • Yaf_Request_Http::getFiles - Le but de getFiles
    • Yaf_Request_Http::getPost - Récupère une variable POST
    • Yaf_Request_Http::getQuery - Récupère un paramètre de la requête
    • Yaf_Request_Http::getRaw - Récupère le corps brut de la requête
    • Yaf_Request_Http::getRequest - Le but de getRequest
    • Yaf_Request_Http::isXmlHttpRequest - Vérifie s'il s'agit d'une requête Ajax
    • Yaf_Request_Http::__construct - Constructeur de __construct
    • Yaf_Request_Simple::get - Le but de get
    • Yaf_Request_Simple::getCookie - Le but de getCookie
    • Yaf_Request_Simple::getFiles - Le but de getFiles
    • Yaf_Request_Simple::getPost - Le but de getPost
    • Yaf_Request_Simple::getQuery - Le but de getQuery
    • Yaf_Request_Simple::getRequest - Le but de getRequest
    • Yaf_Request_Simple::isXmlHttpRequest - Détermine si la requête est une requête AJAX
    • Yaf_Request_Simple::__construct - Constructeur de __construct
    • Yaf_Response_Abstract::appendBody - Ajoute le corps de la réponse
    • Yaf_Response_Abstract::clearBody - Supprime tous les corps de réponse existants
    • Yaf_Response_Abstract::clearHeaders - Supprime toutes les en-têtes définies
    • Yaf_Response_Abstract::getBody - Récupère un contenu existant
    • Yaf_Response_Abstract::getHeader - Le but de getHeader
    • Yaf_Response_Abstract::prependBody - Le but de prependBody
    • Yaf_Response_Abstract::response - Envoie la réponse
    • Yaf_Response_Abstract::setAllHeaders - Le but de setAllHeaders
    • Yaf_Response_Abstract::setBody - Définit le contenu de la réponse
    • Yaf_Response_Abstract::setHeader - Définit l'en-tête de réponse
    • Yaf_Response_Abstract::setRedirect - Le but de setRedirect
    • Yaf_Response_Abstract::__construct - Le but de __construct
    • Yaf_Response_Abstract::__destruct - Le but de __destruct
    • Yaf_Response_Abstract::__toString - Récupère tout le corps sous la forme d'une chaîne de caractères
    • Yaf_Router::addConfig - Ajoute une route définie dans la configuration d'un routeur
    • Yaf_Router::addRoute - Ajoute une nouvelle route dans un routeur
    • Yaf_Router::getCurrentRoute - Récupère le nom effectif de la route
    • Yaf_Router::getRoute - Récupère une route via son nom
    • Yaf_Router::getRoutes - Récupère les routes enregistrées
    • Yaf_Router::route - Le but de route
    • Yaf_Router::__construct - Constructeur de la classe Yaf_Router
    • Yaf_Route_Interface::assemble - Assemble une requête
    • Yaf_Route_Interface::route - Route une requête
    • Yaf_Route_Map::assemble - Assemble une URL
    • Yaf_Route_Map::route - Le but route
    • Yaf_Route_Map::__construct - Le but de __construct
    • Yaf_Route_Regex::assemble - Assemble une URL
    • Yaf_Route_Regex::route - Le but de route
    • Yaf_Route_Regex::__construct - Contructeur Yaf_Route_Regex
    • Yaf_Route_Rewrite::assemble - Assemble une URL
    • Yaf_Route_Rewrite::route - Le but de route
    • Yaf_Route_Rewrite::__construct - Constructeur Yaf_Route_Rewrite
    • Yaf_Route_Simple::assemble - Assemble une URL
    • Yaf_Route_Simple::route - Route une requête
    • Yaf_Route_Simple::__construct - Constructeur de la classe Yaf_Route_Simple
    • Yaf_Route_Static::assemble - Assemble une URL
    • Yaf_Route_Static::match - Le but de match
    • Yaf_Route_Static::route - Route une requête
    • Yaf_Route_Supervar::assemble - Assemble une URL
    • Yaf_Route_Supervar::route - Le but de route
    • Yaf_Route_Supervar::__construct - Le but de __construct
    • Yaf_Session::count - Le but de count
    • Yaf_Session::current - Le but de current
    • Yaf_Session::del - Le but de del
    • Yaf_Session::getInstance - Le but de getInstance
    • Yaf_Session::has - Le but de has
    • Yaf_Session::key - Le but de key
    • Yaf_Session::next - Le but de next
    • Yaf_Session::offsetExists - Le but de offsetExists
    • Yaf_Session::offsetGet - Le but de offsetGet
    • Yaf_Session::offsetSet - Le but de offsetSet
    • Yaf_Session::offsetUnset - Le but de offsetUnset
    • Yaf_Session::rewind - Le but de rewind
    • Yaf_Session::start - Le but de start
    • Yaf_Session::valid - Le but de valid
    • Yaf_Session::__construct - Le constructeur de __construct
    • Yaf_Session::__get - Le but de __get
    • Yaf_Session::__isset - Le but de __isset
    • Yaf_Session::__set - Le but de __set
    • Yaf_Session::__unset - Le but de __unset
    • Yaf_View_Interface::assign - Assigne une valeur au moteur de rendu
    • Yaf_View_Interface::display - Construit et affiche un template
    • Yaf_View_Interface::getScriptPath - Le but de getScriptPath
    • Yaf_View_Interface::render - Construit un template
    • Yaf_View_Interface::setScriptPath - Le but de setScriptPath
    • Yaf_View_Simple::assign - Assigne une ou plusieurs variables
    • Yaf_View_Simple::assignRef - Le but de assignRef
    • Yaf_View_Simple::clear - Efface les valeurs assignées
    • Yaf_View_Simple::display - Construit et affiche
    • Yaf_View_Simple::eval - Évalue un template
    • Yaf_View_Simple::getScriptPath - Récupère le dossier contenant les templates
    • Yaf_View_Simple::render - Construit un template
    • Yaf_View_Simple::setScriptPath - Définit le dossier contenant les templates
    • Yaf_View_Simple::__construct - Constructeur de la classe Yaf_View_Simple
    • Yaf_View_Simple::__get - Récupère une variable assignée
    • Yaf_View_Simple::__isset - Le but de __isset
    • Yaf_View_Simple::__set - Définit une valeur du moteur
    • yaml_emit - Retourne une chaîne représentant une valeur YAML
    • yaml_emit_file - Envoie une représentation YAML vers un fichier
    • yaml_parse - Analyse un flux YAML
    • yaml_parse_file - Analyse un flux YAML depuis un fichier
    • yaml_parse_url - Analyse un flux YAML depuis une URL
    • Yar_Client::setOpt - Défini le contexte d'appel
    • Yar_Client::__call - Service d'appel
    • Yar_Client::__construct - Crée un client
    • Yar_Client_Exception::getType - Récupérer le type de l'exception
    • Yar_Concurrent_Client::call - Enregistre un appel concurrent
    • Yar_Concurrent_Client::loop - Envoi tous les appels
    • Yar_Concurrent_Client::reset - Nettoie tous les appels enregistré
    • Yar_Server::handle - Démarre un serveur RPC
    • Yar_Server::__construct - Enregistre un serveur
    • Yar_Server_Exception::getType - Récupérer le type de l'exception
    • yaz_addinfo - Retourne plus de détails après une erreur
    • yaz_ccl_conf - Configure l'analyseur CCL
    • yaz_ccl_parse - Appelle l'analyseur CCL
    • yaz_close - Ferme une connexion YAZ
    • yaz_connect - Prépare une connexion à un serveur Z39.50
    • yaz_database - Spécifie la base d'une session YAZ
    • yaz_element - Spécifie le type d'éléments YAZ à lire
    • yaz_errno - Retourne le numéro d'erreur
    • yaz_error - Retourne une description de l'erreur
    • yaz_es - Prépare pour une Requête de Service Étendu
    • yaz_es_result - Inspecte le résultat d'un service étendu
    • yaz_get_option - Retourne la valeur d'une option de connexion YAZ
    • yaz_hits - Retourne le nombre de résultats de la dernière recherche
    • yaz_itemorder - Prépare une requête Z39.50 Item Order avec le paquet ILL-Request
    • yaz_present - Prépare à la lecture (Z39.50 present)
    • yaz_range - Spécifie le nombre maximal de résultats à lire
    • yaz_record - Retourne un résultat
    • yaz_scan - Prépare un scan YAZ
    • yaz_scan_result - Retourne le résultat d'un scan
    • yaz_schema - Spécifie le schéma de lecture
    • yaz_search - Prépare une recherche
    • yaz_set_option - Modifie une ou plusieurs options de connexion YAZ
    • yaz_sort - Configure les critères de tri
    • yaz_syntax - Spécifie la syntaxe de lecture des lignes
    • yaz_wait - Attend l'exécution d'une requête
  • z
    • zend_thread_id - Retourne un identifiant unique du thread courant
    • zend_version - Lit la version courante du moteur Zend
    • ZipArchive::addEmptyDir - Ajoute un nouveau dossier à une archive Zip
    • ZipArchive::addFile - Ajoute un fichier à l'archive ZIP depuis le chemin fourni
    • ZipArchive::addFromString - Ajoute un fichier à une archive ZIP en utilisant son contenu
    • ZipArchive::addGlob - Ajoute des fichiers d'un dossier en utilisant un masque glob
    • ZipArchive::addPattern - Ajoute des fichiers d'un dossier en utilisant une expression régulière PCRE
    • ZipArchive::clearError - Efface le message d'erreur, les messages système et/ou zip
    • ZipArchive::close - Ferme l'archive active
    • ZipArchive::count - Compte le nombre de fichiers dans l'archive
    • ZipArchive::deleteIndex - Efface une entrée de l'archive en utilisant son index
    • ZipArchive::deleteName - Efface une entrée dans l'archive en utilisant son nom
    • ZipArchive::extractTo - Extrait le contenu de l'archive
    • ZipArchive::getArchiveComment - Retourne le commentaire de l'archive ZIP
    • ZipArchive::getArchiveFlag - Returns the value of a Zip archive global flag
    • ZipArchive::getCommentIndex - Retourne le commentaire d'une entrée
    • ZipArchive::getCommentName - Retourne le commentaire d'une entrée en utilisant le nom de l'entrée
    • ZipArchive::getExternalAttributesIndex - Récupère les attributs externes d'une entrée définie par son index
    • ZipArchive::getExternalAttributesName - Récupère les attributs externes d'une entrée définie par son nom
    • ZipArchive::getFromIndex - Retourne le contenu d'une entrée en utilisant son index
    • ZipArchive::getFromName - Retourne le contenu de l'entrée en utilisant son nom
    • ZipArchive::getNameIndex - Retourne le nom d'une entrée en utilisant son index
    • ZipArchive::getStatusString - Retourne le message du statut de l'erreur, du système ou de zip
    • ZipArchive::getStream - Récupère un gestionnaire de fichier pour l'entrée définie par son nom (lecture seule)
    • ZipArchive::getStreamIndex - Récupère un gestionnaire de fichier pour l'entrée définie par son index (lecture seule)
    • ZipArchive::getStreamName - Récupère un gestionnaire de fichier pour l'entrée définie par son nom (lecture seule))
    • ZipArchive::isCompressionMethodSupported - Vérifie si une méthode de compression est supportée par libzip
    • ZipArchive::isEncryptionMethodSupported - Vérifie si une méthode de chiffrement est supportée par libzip
    • ZipArchive::locateName - Retourne l'index d'une entrée de l'archive
    • ZipArchive::open - Ouvre une archive ZIP
    • ZipArchive::registerCancelCallback - Enregistre une fonction de appel permettant d'annuler pendant la clôture d'une archive
    • ZipArchive::registerProgressCallback - Enregistre une fonction de rappel pour permettre des mises à jour pendant la fermeture de l'archive
    • ZipArchive::renameIndex - Renomme une entrée définie par son index
    • ZipArchive::renameName - Renomme une entrée définie par son nom
    • ZipArchive::replaceFile - Remplace un fichier d'une archive ZIP
    • ZipArchive::setArchiveComment - Définit le commentaire d'une archive ZIP
    • ZipArchive::setArchiveFlag - Set a global flag of a ZIP archive
    • ZipArchive::setCommentIndex - Définit le commentaire d'une entrée définie par son index
    • ZipArchive::setCommentName - Définit le commentaire d'une entrée spécifiée par son nom
    • ZipArchive::setCompressionIndex - Définit la méthode de compression d'une entrée définit par son index
    • ZipArchive::setCompressionName - Définit la méthode de compression d'une entrée définit par son nom
    • ZipArchive::setEncryptionIndex - Définit la méthode de chiffrement d'une entrée définit par son index
    • ZipArchive::setEncryptionName - Définit la méthode de chiffrement d'une entrée définit par son nom
    • ZipArchive::setExternalAttributesIndex - Définit les attributs externes d'une entrée définie par son index
    • ZipArchive::setExternalAttributesName - Définit les attributs externes d'une entrée définie par son nom
    • ZipArchive::setMtimeIndex - Définit la date de modification d'une entrée
    • ZipArchive::setMtimeName - Définit le date de modification d'une entée par son nom
    • ZipArchive::setPassword - Définit le mot de passe de l'archive active
    • ZipArchive::statIndex - Récupère les détails d'une entrée définie par son index
    • ZipArchive::statName - Récupère les détails de l'entrée définie par son nom
    • ZipArchive::unchangeAll - Annule toutes les modifications faites sur l'archive
    • ZipArchive::unchangeArchive - Annule toutes les modifications globales faites sur l'archive
    • ZipArchive::unchangeIndex - Annule toutes les modifications faites sur une entrée, définie par nom index
    • ZipArchive::unchangeName - Annule toutes les modifications faites sur une entrée, définie par son nom
    • zip_close - Ferme une archive Zip
    • zip_entry_close - Ferme un dossier d'archive
    • zip_entry_compressedsize - Lit la taille compressée d'un dossier d'archives
    • zip_entry_compressionmethod - Lit la méthode de compression utilisée sur un dossier d'archives
    • zip_entry_filesize - Lit la taille décompressée d'un dossier d'archives
    • zip_entry_name - Lit le nom d'un dossier d'archives
    • zip_entry_open - Ouvre un dossier d'archives en lecture
    • zip_entry_read - Lit le contenu d'un fichier dans un dossier
    • zip_open - Ouvre une archive ZIP
    • zip_read - Lit la prochaine entrée dans une archive ZIP
    • zlib:// - Flux de compression
    • zlib_decode - Décompresse des données encodées raw/gzip/zlib
    • zlib_encode - Compresse des données avec l'encodage spécifié
    • zlib_get_coding_type - Retourne la méthode de compression utilisée avec Gzip
    • ZMQ::__construct - ZMQ constructor
    • ZMQContext::getOpt - Récupère une option de contexte
    • ZMQContext::getSocket - Crée un nouveau socket
    • ZMQContext::isPersistent - Vérifie si le contexte est persistent
    • ZMQContext::setOpt - Défini une option de socket
    • ZMQContext::__construct - Construit un nouvel objet ZMQContext
    • ZMQDevice::getIdleTimeout - Récupère le délai d'attente maximal d'inactivité
    • ZMQDevice::getTimerTimeout - Récupère le délai d'attente maximal du timer
    • ZMQDevice::run - Exécute le nouveau périphérique
    • ZMQDevice::setIdleCallback - Défini la fonction de rappel d'inactivité
    • ZMQDevice::setIdleTimeout - Défini le délai d'attente maximal d'inactivité
    • ZMQDevice::setTimerCallback - Défini la fonction de rappel du timer
    • ZMQDevice::setTimerTimeout - Défini le délai d'attente maximal du timer
    • ZMQDevice::__construct - Construit un nouveau périphérique
    • ZMQPoll::add - Ajoute un élément dans le poll
    • ZMQPoll::clear - Supprime tous les éléments du poll
    • ZMQPoll::count - Compte les éléments du poll
    • ZMQPoll::getLastErrors - Récupère les erreurs du poll
    • ZMQPoll::poll - Sonde les éléments
    • ZMQPoll::remove - Supprime un élément du poll
    • ZMQSocket::bind - Lie un socket
    • ZMQSocket::connect - Connecte le socket
    • ZMQSocket::disconnect - Déconnecte un socket
    • ZMQSocket::getEndpoints - Récupère la liste des points finaux
    • ZMQSocket::getPersistentId - Récupère l'ID persistent
    • ZMQSocket::getSocketType - Récupère le type du socket
    • ZMQSocket::getSockOpt - Récupère une option du socket
    • ZMQSocket::isPersistent - Vérifie si le socket est persistent
    • ZMQSocket::recv - Recoit un message
    • ZMQSocket::recvMulti - Recoit un message multipart
    • ZMQSocket::send - Envoi un message
    • ZMQSocket::sendmulti - Envoi un message multipart
    • ZMQSocket::setSockOpt - Défini une option de socket
    • ZMQSocket::unbind - Dé-lie le socket
    • ZMQSocket::__construct - Construit un nouveau 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 - Tente de charger une classe indéfinie
    • __halt_compiler - Stoppe l'exécution du compilateur

User Contributed Notes

There are no user contributed notes for this page.


Liste d'exemples

Liste de tous les exemples du manuel

  • Example#0 - Exemple d'introduction
  • Example#1 - Notre premier script PHP : bonjour.php
  • Example#2 - Récupération des informations du système depuis PHP
  • Example#3 - Afficher le contenu d'une variable (élément de tableau)
  • Example#4 - Exemple utilisant les structures de contrôle et les fonctions
  • Example#5 - Passer du mode PHP au mode HTML et vice-versa
  • Example#6 - Un simple formulaire HTML
  • Example#7 - Afficher des données issues d'un formulaire
  • Example#8 - Portion du fichier lighttpd.conf
  • Example#9 - Appel des répondeurs FastCGI
  • Example#10 - Connexion à des instances distantes de php-fastcgi
  • Example#11 - Exemple d'installation de PHP sous OpenBSD avec Ports
  • Example#12 - Exemple d'installation sous Debian avec Apache 2
  • Example#13 - Stopper et démarrer Apache une fois PHP installé
  • Example#14 - Méthodes pour lister les paquets PHP supplémentaires
  • Example#15 - Installer PHP avec MySQL et cURL
  • Example#16 - Configuration recommandée pour OpCache
  • Example#17 - Configuration recommandée pour WinCache
  • Example#18 - Ligne de commande pour configurer IIS et PHP
  • Example#19 - Registry changes
  • Example#20 - PHP and Apache 2.x as handler
  • Example#21 - PHP and Apache 2.x as CGI
  • Example#22 - Configure Apache to run PHP as FastCGI
  • Example#23 - Passer des variables d'environnement et des paramètres PHP à un pool
  • Example#24 - Définit les paramètres PHP dans le fichier nginx.conf
  • Example#25 - Appel de la fonction phpinfo
  • Example#26 - Les variables d'environnement dans un fichier php.ini
  • Example#27 - Extrait du php.ini
  • Example#28 - Exemple de configuration Apache
  • Example#29 - Balises d'ouvertures et de fermetures PHP
  • Example#30 - Echappement avancé en utilisant des conditions
  • Example#31 - Exemple montrant que la balise fermente englobe la nouvelle ligne qui suit
  • Example#32 - Exemple de commentaire
  • Example#33 - Les commentaires vont jusqu'à la fin de la ligne
  • Example#34 - Les commentaires de type C
  • Example#35 - Les entiers littéraux
  • Example#36 - Dépassement d'entier sur un système 32-bit
  • Example#37 - Dépassement d'entier sur un système 64-bit
  • Example#38 - Exemple Heredoc basique à partir de PHP 7.3.0
  • Example#39 - Closing identifier must not be indented further than any lines of the body
  • Example#40 - Indentation différente pour le texte (espace) et identifiant de fin
  • Example#41 - Continuer une expression après un identifiant de fin
  • Example#42 - Identifiant de fin dans le corps de la chaîne de caractères tend à causer une ParseError
  • Example#43 - Exemple invalide, antérieur à PHP 7.3.0
  • Example#44 - Exemple valide, même antérieur à PHP 7.3.0
  • Example#45 - Exemple de chaînes Heredoc
  • Example#46 - Exemple d'utilisation de Heredoc pour passer des arguments
  • Example#47 - Utilisation de Heredoc pour initialiser des valeurs statiques
  • Example#48 - Utilisation des guillemets doubles avec Heredoc
  • Example#49 - Exemple de chaîne Nowdoc
  • Example#50 - Exemple de chaîne Nowdoc avec des variables
  • Example#51 - Exemple avec des données statiques
  • Example#52 - Exemple de la syntaxe simple
  • Example#53 - Indices numériques négatifs
  • Example#54 - Quelques exemples de chaînes
  • Example#55 - Exemple de Positions de Chaîne Invalide
  • Example#56 - Un tableau simple
  • Example#57 - Exemple sur la modification de type et l'écrasement
  • Example#58 - Exemple avec des clés de type int et string
  • Example#59 - Tableaux indexés sans clé
  • Example#60 - Exemple avec des clés seulement pour quelques éléments
  • Example#61 - Exemple complexe sur la modification de type et l'écrasement
  • Example#62 - Accès aux éléments d'un tableau
  • Example#63 - Faire référence à un tableau à la sortie d'une fonction ou d'une méthode
  • Example#64 - Déballage simple de tableau
  • Example#65 - Déballage de tableau avec clé dupliqué
  • Example#66 - Utilisation de array()
  • Example#67 - Collection
  • Example#68 - Modification d'un élément dans la boucle
  • Example#69 - Indexation commençant à 1
  • Example#70 - Remplissage d'un tableau
  • Example#71 - Tri d'un tableau
  • Example#72 - Tableaux récursifs et multidimensionnels
  • Example#73 - Exemples de fonctions de rappel
  • Example#74 - Exemple d'une fonction de rappel utilisant une Closure
  • Example#75 - Exemple de valeur par défaut d'un argument itérable
  • Example#76 - Exemple de type de retour itérable.
  • Example#77 - Exemple de type de retour itérable d'un générateur
  • Example#78 -
  • Example#79 - Paramètre typé passé par référence
  • Example#80 - Ancienne façon de rendre les arguments nullables
  • Example#81 - Déclaration de type de classe de base
  • Example#82 - Déclaration de type d’interface de base
  • Example#83 - Déclaration de type de retour de base
  • Example#84 - Renvoi d’un objet
  • Example#85 - Déclaration de type d’argument nullable
  • Example#86 - Déclaration de type de retour nullable
  • Example#87 - Déclaration de type pour les propriétés de classe
  • Example#88 - Typage strict pour les valeurs d'arguments
  • Example#89 - Typage coercitif pour les valeurs d'arguments
  • Example#90 - Typage strict pour les valeurs de retour
  • Example#91 - Exemple de types contraints à une partie type de l'union
  • Example#92 - Validité des noms de variables
  • Example#93 - Assignation de référence
  • Example#94 - Assignation de référence et variables anonymes
  • Example#95 - Valeurs par défaut des variables non initialisées
  • Example#96 - Les variables sont locales à la fonction
  • Example#97 - Exemple avec global
  • Example#98 - Les variables globales et $GLOBALS
  • Example#99 - Exemple montrant les superglobales et la portée
  • Example#100 - Les variables statiques
  • Example#101 - Les variables statiques (2)
  • Example#102 - Les variables statiques et la récursivité
  • Example#103 - Déclaration de variables statiques
  • Example#104 - Utilisation de variables statiques dans les méthodes héritées
  • Example#105 - Exemple de propriété variable
  • Example#106 - Exemple avec un formulaire simple
  • Example#107 - Accéder simplement à des variables de formulaires POST
  • Example#108 - Variables de formulaires complexes
  • Example#109 - Exemple avec setcookie
  • Example#110 - Noms valides et invalides pour les constantes
  • Example#111 - Définir une constante
  • Example#112 - Définir des constantes en utilisant le mot-clé const
  • Example#113 - Associativité
  • Example#114 - Ordre d'évaluation indéfini
  • Example#115 - +, - et . ont la même priorité (antérieur à PHP 8.0.0)
  • Example#116 - Exemple d'incrémentation de chaîne PERL
  • Example#117 - Conversion de chaîne alphanumérique en flottant
  • Example#118 - Affectation par référence
  • Example#119 - Opérations sur les bits et les entiers
  • Example#120 - Opération sur les bits et les chaînes
  • Example#121 - Décalage de bits sur les entiers
  • Example#122 - Comparaison Booléen/null
  • Example#123 - Transcription des comparaisons standards des tableaux
  • Example#124 - Affectation d'une valeur par défaut
  • Example#125 - Comportement de PHP
  • Example#126 - Combinaison de ternaire court
  • Example#127 - Assigner une valeur par défaut
  • Example#128 - Imbrication de l'opération de fusion null
  • Example#129 - Opérateur d'exécution
  • Example#130 - Illustration des opérateurs logiques
  • Example#131 - Opérateur de concaténation
  • Example#132 - Comparer des tableaux
  • Example#133 - Utilisation de instanceof avec des classes
  • Example#134 - Utilisation de instanceof avec des classes héritées
  • Example#135 - Utilisation de instanceof pour vérifier que l'objet n'est pas une instance de la classe
  • Example#136 - Utilisation de instanceof pour une interface
  • Example#137 - Utilisation de instanceof avec d'autres variables
  • Example#138 - Utilisation de instanceof pour tester d'autres variables
  • Example#139 - Utilisation de instanceof pour tester des constantes
  • Example#140 - Utilisation de instanceof avec une expression arbitraire
  • Example#141 - Instruction switch
  • Example#142 - Utilisation de base des expressions match
  • Example#143 - Structure d'une expression match
  • Example#144 - Exemple d'une expression match non gérée
  • Example#145 - Utilisation d'une expression match généralisée pour effectuer des branchements sur des plages d'entiers
  • Example#146 - Utilisation d'une expression match généralisée pour effectuer des branchements sur le contenu d'une chaîne de caractères
  • Example#147 - Exemple d'utilisation des ticks
  • Example#148 - Déclaration d'un encodage pour un script
  • Example#149 - Exemple avec include
  • Example#150 - Inclusion de fichiers dans une fonction
  • Example#151 - Utiliser l'instruction include via HTTP
  • Example#152 - Comparaison de la valeur de retour d'une inclusion
  • Example#153 - include et return
  • Example#154 - Utilisation de la sortie du buffer pour inclure un fichier PHP dans une chaîne
  • Example#155 - Exemple avec goto
  • Example#156 - Exemple de boucle avec goto
  • Example#157 - Ce goto ne fonctionne pas
  • Example#158 - Pseudo code pour illustrer l'usage d'une fonction
  • Example#159 - Fonctions conditionnelles
  • Example#160 - Fonctions dans une autre fonction
  • Example#161 - Fonctions récursives
  • Example#162 - Nombre variable d'arguments sous forme de tableau
  • Example#163 - Function Argument List with trailing Comma
  • Example#164 - Passage d'arguments par référence
  • Example#165 - Valeur par défaut des arguments de fonctions
  • Example#166 - Utilisation de type non-scalaire comme valeur par défaut
  • Example#167 - Utilisation d'objets comme valeurs par défaut (à partir de PHP 8.1.0)
  • Example#168 - Les arguments sans valeur par défaut doivent être en premiers : erreur
  • Example#169 - Les arguments sans valeur par défaut doivent être en premiers : valide
  • Example#170 - Utilisation correcte des arguments de fonction par défaut
  • Example#171 - Déclarer des arguments facultatifs après les arguments obligatoires
  • Example#172 - Utilisation de ... pour accéder aux arguments variables
  • Example#173 - Utilisation de ... pour fournir des arguments
  • Example#174 - Transtypage d'arguments variables
  • Example#175 - Syntaxe des arguments nommés
  • Example#176 - Arguments positionnels comparés aux arguments nommés
  • Example#177 - Même exemple que ci-dessus, mais avec un ordre de paramètre différent
  • Example#178 - Combiner les arguments nommés avec les arguments positionnels
  • Example#179 - Error émise quand un même paramètre est passé plusieurs fois
  • Example#180 - Utiliser les arguments nommés après le déballage
  • Example#181 - Utilisation de return
  • Example#182 - Retourner un tableau d'une fonction
  • Example#183 - Retourner une référence d'une fonction
  • Example#184 - Exemple de fonction variable
  • Example#185 - Exemple de méthode variable
  • Example#186 - Exemple de méthode variable avec des propriétés statiques
  • Example#187 - callables complexe
  • Example#188 -
  • Example#189 - Exemples avec des fonctions anonymes
  • Example#190 - Assignation de fonction anonyme à une variable
  • Example#191 - Héritage de variable depuis le contexte parent
  • Example#192 - Fonctions anonymes et contexte
  • Example#193 - Liage automatique de $this
  • Example#194 - Tentative d'usage de $this dans une fonction anonyme statique
  • Example#195 - Tentative de liage d'un objet à une fonction anonyme statique
  • Example#196 - Les fonctions fléchées capturent les variables par valeur automatiquement
  • Example#197 - Les fonctions fléchées capturent les variables par valeur automatiquement, même imbriquées
  • Example#198 - Exemples de fonctions fléchées
  • Example#199 - Valeurs de la portée extérieure ne peuvent pas être modifiées par les fonctions fléchées
  • Example#200 - Syntaxe callable de première classe basique
  • Example#201 - Comparaison de portée de CallableExpr(...) et des callables traditionnels
  • Example#202 -
  • Example#203 - Définition typique d'une classe
  • Example#204 - Quelques exemples de la pseudo-variable $this
  • Example#205 -
  • Example#206 -
  • Example#207 - Création d'une instance
  • Example#208 - Créer une instance en utilisant une expression arbitraire
  • Example#209 - Assignation d'un objet
  • Example#210 - Créer de nouveaux objets
  • Example#211 - Accéder un membre d'un objet nouvellement créé
  • Example#212 - Accès de propriété contre appel de méthode
  • Example#213 - Appeler une fonction anonyme enregistrée dans une propriété
  • Example#214 - Héritage simple d'une classe
  • Example#215 - Méthodes enfant compatibles
  • Example#216 - Erreur fatale quand une méthode enfant supprime un paramètre
  • Example#217 - Erreur fatale quand une méthode enfant rend un paramètre optionnel obligatoire
  • Example#218 - Erreur lors de l'utilisation des arguments nommés et que les paramètres ont été renommés dans une classe enfant
  • Example#219 - Résolution de nom de classe
  • Example#220 - Résolution de nom de classe manquante
  • Example#221 - Résolution du nom d'un objet
  • Example#222 - Opérateur nullsafe
  • Example#223 - Déclarations de propriétés
  • Example#224 - Exemple de propriétés typées
  • Example#225 - Accès aux propriétés
  • Example#226 - Exemple de propriétés en lecture seule
  • Example#227 - Initialisation illégale de propriétés en lecture seule
  • Example#228 -
  • Example#229 -
  • Example#230 -
  • Example#231 - Définition et utilisation d'une constante de classe
  • Example#232 - Exemple d'utilisation de ::class
  • Example#233 - Exemple d'expressions pour une constante de classe
  • Example#234 - Modificateur de visibilité des constantes de classe, à partir de PHP 7.1
  • Example#235 - Exemple d'autochargement
  • Example#236 - Autre exemple d'autochargement
  • Example#237 - Constructeur lors de l'héritage
  • Example#238 - Utiliser les arguments d'un constructeur
  • Example#239 - Utilisant la promotion de propriété de constructeur
  • Example#240 - Utilisation de new dans des initialiseurs
  • Example#241 - Utilisant la création via une méthode statique
  • Example#242 - Exemple avec un Destructeur
  • Example#243 - Déclaration de propriétés
  • Example#244 - Déclaration de méthodes
  • Example#245 - Déclaration de constantes à partir de PHP 7.1.0
  • Example#246 - Accès aux membres privés d'un objet du même type
  • Example#247 -
  • Example#248 - Exemple d'héritage
  • Example#249 - La méthode surchargée ne déclare pas de type de retour.
  • Example#250 - La méthode surchargée déclare un mauvais type de retour.
  • Example#251 - La méthode surchargée déclare un mauvais type de retour sans notice de dépréciation.
  • Example#252 - :: en dehors de la définition de la classe
  • Example#253 - :: depuis la définition de la classe
  • Example#254 - Appel d'une méthode parente
  • Example#255 - Exemple avec une méthode statique
  • Example#256 - Exemple avec une propriété statique
  • Example#257 - Exemple de classe abstraite
  • Example#258 - Exemple avec une classe abstraite
  • Example#259 - Exemple d'interface
  • Example#260 - Les interfaces extensibles
  • Example#261 - Compatibilité de la variance avec plusieurs interfaces
  • Example#262 - Héritage de plusieurs interfaces
  • Example#263 - Interfaces avec des constantes
  • Example#264 - Les interfaces avec les classes abstraites
  • Example#265 - Étendant et implémentant simultanément
  • Example#266 - Exemple d'utilisation de Trait
  • Example#267 - Exemple avec l'ordre de précédence
  • Example#268 - Autre exemple d'ordre de précédence
  • Example#269 - Utilisation de plusieurs Traits
  • Example#270 - Résolution des conflits
  • Example#271 - Changer la visibilité des méthodes
  • Example#272 - Traits Composés depuis d'autres Traits
  • Example#273 - Obligations requises par les méthodes abstraites
  • Example#274 - Variables statiques
  • Example#275 - Méthodes statiques
  • Example#276 - Propriétés statiques
  • Example#277 - Définir des propriétés
  • Example#278 - Résolution des conflits
  • Example#279 - Trait définissant une constante
  • Example#280 - Résolution de conflit
  • Example#281 - Exemple de surcharge de propriétés avec les méthodes
     __get(),
     __set(),
     __isset() et
     __unset()
  • Example#282 - Surcharge de méthodes avec __call() et __callStatic()
  • Example#283 - Parcours d'objet simple
  • Example#284 - Utilisation de sleep() et wakeup()
  • Example#285 - Serialize et unserialize
  • Example#286 - Exemple simple
  • Example#287 - Exemple avec __invoke()
  • Example#288 - Exemple avec __invoke()
  • Example#289 - Utilisation de __set_state()
  • Example#290 - Utilisation de __debugInfo()
  • Example#291 - Exemple de méthode finale
  • Example#292 - Exemple de classe finale
  • Example#293 - Exemple de constante finale à partir de PHP 8.1.0
  • Example#294 - Exemple de duplication d'objets
  • Example#295 - Accès à un membre d'un objet fraîchement cloné
  • Example#296 - Exemple de comparaison d'objets en PHP
  • Example#297 - Utilisation de self::
  • Example#298 - Utilisation simple de static::
  • Example#299 - Utilisation de static:: dans un contexte non statique
  • Example#300 - Appel avec ou sans transmission
  • Example#301 - Références et Objets
  • Example#302 - Exemple de syntaxe des espaces de noms
  • Example#303 - Déclaration d'un espace de noms
  • Example#304 - Erreur de déclaration d'un espace de noms
  • Example#305 - Déclaration d'un espace de noms avec hiérarchie
  • Example#306 - Déclaration de plusieurs espaces de noms, syntaxe à combinaison simple
  • Example#307 - Déclaration de plusieurs espaces de noms, syntaxe à accolades
  • Example#308 - Déclaration de plusieurs espaces de noms avec un espace sans nom
  • Example#309 - Déclaration de plusieurs espaces de noms avec un espace sans nom (2)
  • Example#310 - Accès aux classes, fonctions et constantes globales depuis un espace de noms
  • Example#311 - Accès dynamique aux éléments
  • Example#312 - Accès dynamique à des espaces de noms
  • Example#313 - Exemple avec __NAMESPACE__, dans un code avec espace de noms
  • Example#314 - Exemple avec __NAMESPACE__, dans un code avec espace de noms global
  • Example#315 - Utilisation de __NAMESPACE__ pour une construction dynamique de noms
  • Example#316 - l'opérateur namespace, dans un espace de noms
  • Example#317 - l'opérateur namespace, dans l'espace de noms global
  • Example#318 - importation et alias avec l'opérateur use
  • Example#319 - importation et alias multiples avec l'opérateur use
  • Example#320 - Importation et noms d'espaces dynamiques
  • Example#321 - Importation et noms d'espaces absolus
  • Example#322 - Règles d'importation incorrectes
  • Example#323 - Spécification d'espace de noms global
  • Example#324 - Accès aux classes globales depuis un espace de noms
  • Example#325 - Accès aux fonctions et constantes globales dans un espace de noms
  • Example#326 - Exemples de résolutions d'espaces de noms
  • Example#327 - Accès à une classe globale de l'extérieur d'un espace de noms
  • Example#328 - Accéder à des classes globales hors d'un espace de noms
  • Example#329 - Accès aux classes internes depuis un espace de noms
  • Example#330 - Accès aux classes, fonctions et constantes internes dans un espace de noms
  • Example#331 - Noms d'espaces absolus
  • Example#332 - Noms qualifiés
  • Example#333 - Classes sans qualification
  • Example#334 - Fonctions et constantes sans espace de noms
  • Example#335 - Dangers de l'utilisation des espaces de noms dans une chaîne
  • Example#336 - Constantes indéfinies
  • Example#337 - Constantes qui ne peuvent être redéfinies
  • Example#338 - Valeurs limitées de base
  • Example#339 - Valeurs exclusives avancées
  • Example#340 - Convertir l'error reporting en exceptions
  • Example#341 - Lancer une exception
  • Example#342 - Gestion de l'exception avec un bloc finally
  • Example#343 - Interaction entre le bloc finally et return
  • Example#344 - Héritage d'une exception
  • Example#345 - Gestion des exceptions de capture multiple
  • Example#346 - Omettre la variable attrapé
  • Example#347 - Throw en tant qu'expression
  • Example#348 - La classe d'exception intégrée
  • Example#349 - Étendre la classe Exception
  • Example#350 - Utilisation de base
  • Example#351 - Implémentation de la fonction range sous la forme d'un générateur
  • Example#352 - Un exemple simple de production de valeurs
  • Example#353 - Production d'une paire clé/valeur
  • Example#354 - Production de valeurs nulles
  • Example#355 - Production de valeurs par référence
  • Example#356 - yield from avec iterator_to_array
  • Example#357 - Utilisation basique de yield from
  • Example#358 - yield from et les valeurs retournées
  • Example#359 - Implémentation de méthodes optionnelles d'une interface avec des attributs
  • Example#360 - Syntaxe des attributs
  • Example#361 - Lecture des attributs à l'aide de l'API de Reflection
  • Example#362 - Lecture d'attributs spécifiques à l'aide de l'API de Reflection
  • Example#363 - Classe d'attribut simple
  • Example#364 - Utilisation de la spécification de la cible pour restreindre l'utilisation des attributs
  • Example#365 - Utilisation de IS_REPEATABLE pour permettre à un attribut d'être utilisé plusieurs fois dans une déclaration
  • Example#366 - Utilisation des références avec des variables indéfinies
  • Example#367 - Référencer des variables globales depuis des fonctions
  • Example#368 - Références et structure foreach
  • Example#369 - Exemple avec $GLOBALS
  • Example#370 - Écrire au tableau entier $GLOBALS résultera en une erreur.
  • Example#371 - Exemple avec $_SERVER
  • Example#372 - Exemple avec $_GET
  • Example#373 - Exemple avec $_POST
  • Example#374 - Exemple avec $_ENV
  • Example#375 - Exemple avec $_COOKIE
  • Example#376 - Exemple avec $php_errormsg
  • Example#377 - Exemple avec $http_response_header
  • Example#378 - Exemple avec $argc
  • Example#379 - Exemple avec $argv
  • Example#380 - Exemple avec Exception::getMessage
  • Example#381 - Exemple avec Exception::getPrevious
  • Example#382 - Exemple avec Exception::getCode
  • Example#383 - Exemple avec Exception::getFile
  • Example#384 - Exemple avec Exception::getLine
  • Example#385 - Exemple avec Exception::getTrace
  • Example#386 - Exemple avec Exception::getTraceAsString
  • Example#387 - Exemple avec Exception::__toString
  • Example#388 - Utilisation de set_error_handler pour changer tous les messages d'erreurs en ErrorException
  • Example#389 - Exemple avec ErrorException::ErrorException
  • Example#390 - Exemple de Error::getMessage
  • Example#391 - Exemple de Error::getPrevious
  • Example#392 - Exemple de Error::getCode
  • Example#393 - Exemple de Error::getFile
  • Example#394 - Exemple de Error::getLine
  • Example#395 - Exemple de Error::getTrace
  • Example#396 - Exemple de Error::getTraceAsString
  • Example#397 - Exemple de Error::__toString
  • Example#398 - Exemple simple
  • Example#399 - Exemple simple
  • Example#400 - Exemple basique
  • Example#401 - Exemple avec ArrayAccess::offsetExists
  • Example#402 - Exemple simple
  • Example#403 - Exemple Closure::bind
  • Example#404 - Exemple Closure::bindTo
  • Example#405 - Exemple deClosure::call
  • Example#406 - Créé à la suite d'une conversion de type en objet
  • Example#407 - Créé en tant que résultat de json_decode
  • Example#408 - Déclaration de propriétés dynamiques
  • Example#409 - Generator::getReturn exemple
  • Example#410 - Exemple avec Generator::key
  • Example#411 - Exemple d'utilisation Generator::send pour injecter des données
  • Example#412 - >Lance une exception dans un générateur
  • Example#413 - Utilisation Simple de WeakReference
  • Example#414 - Exemple d'utilisation d'un Weakmap
  • Example#415 - Exemple simple
  • Example#416 - Utilisation de base
  • Example#417 - Utilisation de base
  • Example#418 - Utilisation de base
  • Example#419 - Passer un objet SensitiveParameterValue à var_dump
  • Example#420 - Exemple de SensitiveParameterValue::getValue
  • Example#421 -
  • Example#422 -
  • Example#423 - Exemple d'utilisation du paramètre bindto
  • Example#424 - Récupération d'une page et envoi de données POST
  • Example#425 - Ignore les redirections mais récupère les en-têtes et le contenu
  • Example#426 - Exemple avec une utilisation simple du paramètre password
  • Example#427 - Détecte la dernière URL après des redirections
  • Example#428 - php://temp/maxmemory
  • Example#429 - php://filter/resource=<flux à filtrer>
  • Example#430 - php://filter/read=<liste de filtres à appliquer lors de la lecture>
  • Example#431 - php://filter/write=<liste des filtres à appliquer lors de l'écriture>
  • Example#432 - php://memory et php://temp ne sont pas réutilisables
  • Example#433 - Affichage d'un contenu data://
  • Example#434 - Récupération du type de média
  • Example#435 - Utilisation simple
  • Example#436 - Ouverture d'un flux depuis une connexion active
  • Example#437 - La variable $session doit rester disponible !
  • Example#438 - Parcours d'une archive RAR
  • Example#439 - Ouverture d'un fichier crypté (en-tête crypté)
  • Example#440 - Ligne d'invocation de PHP
  • Example#441 - Une erreur de vérification de variable conduit à un gros problème
  • Example#442 - Une attaque du système de fichiers!
  • Example#443 - Une vérification renforcée
  • Example#444 - Vérification renforcée de noms de fichiers
  • Example#445 - Script vulnérable aux octets nuls
  • Example#446 - Validation correcte de l'entrée
  • Example#447 - Hacher un champ mot de passe
  • Example#448 - Séparation des résultats en pages, et créer des administrateurs (PostgreSQL et MySQL)
  • Example#449 - Exemple d'injection SQL
  • Example#450 - Liste d'articles ... et ajout de mot de passe
  • Example#451 - Révélation des mots de passe
  • Example#452 - Modifier un mot de passe ... et gain de droits!
  • Example#453 - Une requête et son injection
  • Example#454 - Attaque d'un serveur de bases de données (MSSQL Server)
  • Example#455 - Attaque d'un serveur de base de données (MSSQL Server) - 2
  • Example#456 - Éviter les injections SQL en utilisant des requêtes préparées PDO
  • Example#457 - Attaque de variables avec une page HTML personnalisée
  • Example#458 - Exploiter des variables classiques de débogage
  • Example#459 - Détecter des variables non protégées avec E_ALL
  • Example#460 - Utilisation dangereuse de variables
  • Example#461 - Masquer PHP avec un autre langage
  • Example#462 - Masquer PHP avec des types inconnus
  • Example#463 - Utiliser le type HTML pour les extensions PHP
  • Example#464 - Exemple d'identification HTTP simple
  • Example#465 - Exemple d'identification HTTP Digest
  • Example#466 - Identification HTTP avec nom d'utilisateur/mot de passe forcé
  • Example#467 - Un simple formulaire XForms de recherche
  • Example#468 - Utiliser des XForms pour remplir $_POST
  • Example#469 - Formulaire de chargement de fichier
  • Example#470 - Validation de téléchargement de fichiers
  • Example#471 - Envoi d'un tableau de fichiers
  • Example#472 - Télécharger plusieurs fichiers simultanément
  • Example#473 - Téléverser un dossier entier
  • Example#474 - Méthode PUT pour les chargements de fichiers
  • Example#475 - Directive Apache pour le chargement par méthode PUT
  • Example#476 - Sauvegarde de fichiers HTTP PUT
  • Example#477 - Connaître le titre d'une page distante
  • Example#478 - Stocker des données sur un serveur distant
  • Example#479 - Exemple montrant la différence avec le SAPI CGI :
  • Example#480 -
  • Example#481 - Affichage des modules internes (et chargés) de PHP et Zend
  • Example#482 - Erreur de syntaxe lors de l'utilisation de doubles guillemets
  • Example#483 - Utilisation de guillemets simples pour éviter une substitution par le shell
  • Example#484 - Exemple d'utilisation des options -B, -R et -E pour compter le nombre de lignes d'un projet.
  • Example#485 - Utilisation de l'option -v pour récupérer le nom du SAPI ainsi que la version de PHP et de Zend
  • Example#486 - Exemple avec --ini
  • Example#487 - Exemple avec --rf
  • Example#488 - Exemple avec --rc
  • Example#489 - Exemple avec --re
  • Example#490 - Exemple avec --ri
  • Example#491 - Exécute un script PHP en tant que script shell
  • Example#492 - Script prévu pour être exécuté en ligne de commande (script.php)
  • Example#493 - Fichier batch pour exécuter un script PHP en ligne de commande (script.bat)
  • Example#494 - Exécution de code en utilisant le shell interactif
  • Example#495 - Auto-complétion en utilisant la touche de tabulation
  • Example#496 - Définition de directives du php.ini dans un shell interactif
  • Example#497 - Démarrage du serveur web
  • Example#498 - Démarrage avec un dossier racine spécifique
  • Example#499 - Utilisation d'un script routeur
  • Example#500 - Vérification de l'utilisation CLI du serveur Web
  • Example#501 - Gestion des types de fichiers non supportés
  • Example#502 - Accès au CLI du serveur web depuis une machine distante
  • Example#503 - Création d'un nouveau conteneur zval
  • Example#504 - Affichage des informations zval
  • Example#505 - Incrémentation du refcount d'une zval
  • Example#506 - Décrémentation du refcount d'une zval
  • Example#507 - Création d'une zval array
  • Example#508 - Ajout d'un élément déjà existant au tableau
  • Example#509 - Suppression d'un élément de tableau
  • Example#510 - Ajout du tableau comme référence à lui-même en tant qu'élement
  • Example#511 - Suppression de $a
  • Example#512 - Exemple d'utilisation mémoire
  • Example#513 - Impact de GC sur les performances
  • Example#514 - Lancement du script ci-dessus
  • Example#515 - Recompiler PHP pour activer le support du benchmark du GC
  • Example#516 - Statistiques GC
  • Example#517 - all_probes.d pour tracer toutes les sondes statiques PHP avec DTrace
  • Example#518 - all_probes.stp pour tracer toutes les sondes statiques PHP avec SystemTap
  • Example#519 - Un exemple avec apcu_add
  • Example#520 - Un exemple avec apcu_cache_info
  • Example#521 - Un exemple avec apcu_cas
  • Example#522 - Un exemple avec apcu_dec
  • Example#523 - Un exemple avec apcu_delete
  • Example#524 - Un exemple avec apcu_entry
  • Example#525 - Un exemple avec apcu_exists
  • Example#526 - Un exemple avec apcu_fetch
  • Example#527 - Un exemple avec apcu_inc
  • Example#528 - Un exemple avec apcu_key_info
  • Example#529 - Un exemple avec apcu_sma_info
  • Example#530 - Un exemple avec apcu_store
  • Example#531 - Un exemple avec APCUIterator::__construct
  • Example#532 - Gestion d'erreurs avancées en PHP
  • Example#533 - Exemple avec debug_backtrace
  • Example#534 - Exemple avec debug_print_backtrace
  • Example#535 - Un exemple de error_clear_last
  • Example#536 - Exemple avec error_get_last
  • Example#537 - Exemples avec error_log
  • Example#538 - Exemple avec error_reporting
  • Example#539 - Exemple avec restore_error_handler
  • Example#540 - Exemple avec restore_exception_handler
  • Example#541 - Gestionnaire d'erreurs avec set_error_handler et trigger_error
  • Example#542 - Exemple avec set_exception_handler
  • Example#543 - Exemple avec trigger_error
  • Example#544 - Appel d'une fonction à partir d'une bibliothèque partagée
  • Example#545 - Appel d'une fonction, retournant une structure par l'intermédiaire d'un argument
  • Example#546 - Accès aux variables C existantes
  • Example#547 - Création et modification de variables C
  • Example#548 - Travailler avec des tableaux C
  • Example#549 - Travailler avec des enums en C
  • Example#550 -
  • Example#551 -
  • Example#552 - Exemple de bufferisation de sortie
  • Example#553 - Exemple de réécriture de la sortie
  • Example#554 - Exemple avec ob_end_clean
  • Example#555 - Exemple avec ob_end_flush
  • Example#556 - Exemple avec ob_get_clean
  • Example#557 - Exemple avec ob_get_contents
  • Example#558 - Exemple avec ob_get_flush
  • Example#559 - Exemple avec ob_get_length
  • Example#560 - Exemple avec ob_gzhandler
  • Example#561 - Exemple avec ob_list_handlers
  • Example#562 - Exemple de gestion de sortie avec fonction de rappel
  • Example#563 - Crée un tampon de sortie in-effaçable
  • Example#564 - Exemple avec output_add_rewrite_var
  • Example#565 - Exemple avec output_reset_rewrite_vars
  • Example#566 - Exemple avec assert_options
  • Example#567 - Exemple d'assert
  • Example#568 - Utilisation d'un message personnalisé
  • Example#569 - Utilisation d'une classe d'exception personnalisée
  • Example#570 - Exemple avec cli_get_process_title
  • Example#571 - Exemple avec cli_set_process_title
  • Example#572 - Exemples avec dl
  • Example#573 - Exemple avec extension_loaded
  • Example#574 - Exemple avec gc_enabled
  • Example#575 - Utilisation de gc_status
  • Example#576 - Exemple avec get_current_user
  • Example#577 - Exemple avec get_defined_constants
  • Example#578 - Affiche toutes les fonctions XML
  • Example#579 - Exemple avec get_include_path
  • Example#580 - Exemple avec get_included_files
  • Example#581 - Exemple avec get_loaded_extensions
  • Example#582 - get_resources non-filtré
  • Example#583 - get_resources filtré
  • Example#584 - Exemple avec getenv
  • Example#585 - Exemple avec getlastmod
  • Example#586 - Exemple avec getopt : les bases
  • Example#587 - Second exemple avec getopt : Introduction aux options longues
  • Example#588 - Troisième exemple avec getopt : Passage de plusieurs options
  • Example#589 - Exemple de getopt : Utilisant rest_index
  • Example#590 - Exemple avec getrusage
  • Example#591 - Exemple avec ini_get_all
  • Example#592 - Désactive le paramètre details
  • Example#593 - Exemples avec ini_get
  • Example#594 - A few ini_parse_quantity examples
  • Example#595 - Exemple avec ini_restore
  • Example#596 - Définit une option de configuration
  • Example#597 - Exemple avec memory_get_usage
  • Example#598 - memory_reset_peak_usage example
  • Example#599 - Exemple avec php_ini_loaded_file
  • Example#600 - Un exemple de liste retournée par php_ini_scanned_files
  • Example#601 - Exemple avec php_sapi_name
  • Example#602 - Exemples avec php_uname
  • Example#603 - Exemples avec quelques constantes liées au système
  • Example#604 - Exemple avec phpcredits
  • Example#605 - Affiche les développeurs principaux ansi que le groupe de documentation
  • Example#606 - Affiche tous les crédits
  • Example#607 - Exemple avec phpinfo
  • Example#608 - Exemple avec phpversion
  • Example#609 - Exemple avec PHP_VERSION_ID
  • Example#610 - Modification d'une variable d'environnement
  • Example#611 - Exemple avec restore_include_path
  • Example#612 - Exemple avec set_include_path
  • Example#613 - Ajout dans le chemin d'inclusion
  • Example#614 - Exemple avec sys_get_temp_dir
  • Example#615 - Exemple avec version_compare
  • Example#616 - Exemple avec zend_thread_id
  • Example#617 - Exemple avec zend_version
  • Example#618 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#619 - A runkit7_function_add example
  • Example#620 - A runkit7_function_copy example
  • Example#621 - A runkit7_function_redefine example
  • Example#622 - runkit7_method_add example
  • Example#623 - runkit7_method_copy example
  • Example#624 - runkit7_method_redefine example
  • Example#625 - runkit7_method_remove example
  • Example#626 - runkit7_method_rename example
  • Example#627 - runkit7_zval_inspect example
  • Example#628 - Basic uopz_add_function Usage
  • Example#629 - uopz_allow_exit example
  • Example#630 - Exemple avec uopz_backup
  • Example#631 - Exemple avec uopz_compose
  • Example#632 - Exemple avec uopz_copy
  • Example#633 - Basic uopz_del_function Usage
  • Example#634 - Exemple avec uopz_delete
  • Example#635 - Exemple avec uopz_delete et une classe
  • Example#636 - Exemple avec uopz_extend
  • Example#637 - Exemple avec uopz_flags
  • Example#638 - Transformer une Classe finale en non-finale
  • Example#639 - Exemple avec uopz_function
  • Example#640 - Exemple avec uopz_function et une classe
  • Example#641 - uopz_get_exit_status example
  • Example#642 - Basic uopz_get_hook Usage
  • Example#643 - uopz_get_mock example
  • Example#644 - Basic uopz_get_property Usage
  • Example#645 - uopz_get_return example
  • Example#646 - Basic uopz_get_static Usage
  • Example#647 - Exemple avec uopz_implement
  • Example#648 - Exemple avec uopz_overload
  • Example#649 - Exemple avec uopz_redefine
  • Example#650 - Exemple avec uopz_rename
  • Example#651 - Exemple avec uopz_rename et une classe
  • Example#652 - Exemple avec uopz_restore
  • Example#653 - Basic uopz_set_hook Usage
  • Example#654 - uopz_set_mock example
  • Example#655 - uopz_set_mock example
  • Example#656 - uopz_set_mock and static members
  • Example#657 - Basic uopz_set_property Usage
  • Example#658 - uopz_set_return example
  • Example#659 - uopz_set_return example
  • Example#660 - uopz_set_return class example
  • Example#661 - Basic uopz_set_static Usage
  • Example#662 - Exemple avec uopz_undefine
  • Example#663 - Basic uopz_unset_hook Usage
  • Example#664 - uopz_unset_mock example
  • Example#665 - uopz_unset_return example
  • Example#666 - wincache.ignorelist exemple
  • Example#667 - Configuration de l'authentification pour wincache.php
  • Example#668 - Activer le gestionnaire de session WinCache
  • Example#669 - Activation des fonctionnalités de re routage des fonctions de WinCache
  • Example#670 - Reroute.ini
  • Example#671 - Un exemple de wincache_fcache_fileinfo
  • Example#672 - Un exemple de wincache_fcache_meminfo
  • Example#673 - Exemple avec wincache_lock
  • Example#674 - Un exemple de wincache_ocache_fileinfo
  • Example#675 - Un exemple de wincache_ocache_meminfo
  • Example#676 - Un exemple de wincache_refresh_if_changed
  • Example#677 - Exemple avec wincache_rplist_fileinfo
  • Example#678 - Exemple avec wincache_rplist_meminfo
  • Example#679 - Exemple avec wincache_scache_info
  • Example#680 - Exemple avec wincache_scache_meminfo
  • Example#681 - Exemple avec wincache_ucache_add et le paramètre key sous forme de chaîne de caractères
  • Example#682 - Exemple avec wincache_ucache_add et le paramètre key sous forme d'un tableau
  • Example#683 - Exemple avec wincache_ucache_cas
  • Example#684 - Exemple avec wincache_ucache_clear
  • Example#685 - Exemple avec wincache_ucache_dec
  • Example#686 - Exemple avec wincache_ucache_delete et le paramètre key sous forme de chaîne de caractères
  • Example#687 - Exemple avec wincache_ucache_delete et le paramètre key sous forme d'un tableau
  • Example#688 - Exemple avec wincache_ucache_delete et le paramètre key sous la forme d'un tableau où quelques éléments n'ont pas pu être supprimés
  • Example#689 - Exemple avec wincache_ucache_exists
  • Example#690 - Exemple avec wincache_ucache_get et le paramètre key sous forme de chaîne de caractères
  • Example#691 - Exemple avec wincache_ucache_get et le paramètre key sous forme d'un tableau
  • Example#692 - Exemple avec wincache_ucache_inc
  • Example#693 - Exemple avec wincache_ucache_info
  • Example#694 - Exemple avec wincache_ucache_meminfo
  • Example#695 - Exemple avec wincache_ucache_set et le paramètre key sous forme de chaîne de caractères
  • Example#696 - Exemple avec wincache_ucache_set et le paramètre key sous forme de tableau
  • Example#697 - Exemple avec wincache_unlock
  • Example#698 - Exemple avec Xhprof et la GUI optionnelle
  • Example#699 - Exemple avec xhprof_disable
  • Example#700 - Exemple avec xhprof_enable
  • Example#701 - Exemple avec xhprof_sample_disable
  • Example#702 - Permet de s'assurer que l'élément est stocké
  • Example#703 - Utilisation des mots de passe CHAP
  • Example#704 - Exemple avec radius_acct_open
  • Example#705 - Exemple avec radius_add_server
  • Example#706 - Exemple avec radius_auth_open
  • Example#707 - Exemple avec radius_create_request
  • Example#708 - Exemple avec radius_cvt_addr
  • Example#709 - Exemple avec radius_cvt_int
  • Example#710 - Exemple avec radius_cvt_string
  • Example#711 - Exemple avec radius_get_attr
  • Example#712 - Exemple avec radius_get_tagged_attr_data
  • Example#713 - Exemple avec radius_get_tagged_attr_tag
  • Example#714 - Exemple avec radius_get_vendor_attr
  • Example#715 - Exemple avec radius_put_attr
  • Example#716 - Exemple avec radius_put_int
  • Example#717 - Exemple avec radius_put_string
  • Example#718 - Exemple avec radius_put_vendor_attr
  • Example#719 - Exemple d'interface de rappel de Readline
  • Example#720 - Exemple avec readline
  • Example#721 - Petit exemple avec bzip2
  • Example#722 - Compression de données
  • Example#723 - Décompression d'une chaîne
  • Example#724 - Exemple avec bzerror
  • Example#725 - Exemple avec bzopen
  • Example#726 - Exemple avec bzread
  • Example#727 - Exemple avec bzwrite
  • Example#728 - Utiliser un fichier externe
  • Example#729 - Utilier un fichier contenu dans une archive phar
  • Example#730 - Convertir une archive phar au format tar
  • Example#731 - Exemple d'utilisation de phar.cache_list
  • Example#732 - Un exemple avec Phar::addEmptyDir
  • Example#733 - Un exemple avec Phar::addFile
  • Example#734 - Un exemple avec Phar::addFromString
  • Example#735 - Un exemple avecPhar::apiVersion
  • Example#736 - Un exemple avecPhar::buildFromDirectory
  • Example#737 - Exemple avec Phar::buildFromIterator et SplFileInfo
  • Example#738 - Exemple avec Phar::buildFromIterator et d'autres itérateurs
  • Example#739 - Un exemple avec Phar::canCompress
  • Example#740 - Un exemple avec Phar::canWrite
  • Example#741 - Un exemple avec Phar::compress
  • Example#742 - Un exemple avec Phar::compressFiles
  • Example#743 - Un exemple avec Phar::__construct
  • Example#744 - Un exemple avec Phar::convertToData
  • Example#745 - Un exemple avec Phar::convertToExecutable
  • Example#746 - Exemple avec Phar::copy
  • Example#747 - Un exemple avec Phar::count
  • Example#748 - Exemple avec Phar::createDefaultStub
  • Example#749 - Un exemple avec Phar::decompress
  • Example#750 - Un exemple avec Phar::decompressFiles
  • Example#751 - Un exemple avec Phar::delMetaData
  • Example#752 - Un exemple avec Phar::delete
  • Example#753 - Exemple avec Phar::extractTo
  • Example#754 - Un exemple avec Phar::getMetadata
  • Example#755 - Exemple avec Phar::getStub
  • Example#756 - Un exemple avec Phar::hasMetadata
  • Example#757 - Exemple avec Phar::interceptFileFuncs
  • Example#758 - Un exemple avec Phar::interceptFileFuncs
  • Example#759 - Un exemple avec Phar::isBuffering
  • Example#760 - Exemple avec Phar::isCompressed
  • Example#761 - Un exemple avec Phar::loadPhar
  • Example#762 - Exemple avec Phar::mapPhar
  • Example#763 - Un exemple avec Phar::mount
  • Example#764 - Un exemple avec Phar::mungServer
  • Example#765 - Un exemple avec Phar::offsetExists
  • Example#766 - Exemple avec Phar::offsetGet
  • Example#767 - Un exemple avec Phar::offsetSet
  • Example#768 - Un exemple avec Phar::offsetUnset
  • Example#769 - Un exemple avec Phar::running
  • Example#770 - Un exemple avec Phar::setAlias
  • Example#771 - Un exemple avec Phar::setDefaultStub
  • Example#772 - Un exemple avec Phar::setMetadata
  • Example#773 - Un exemple avec Phar::setStub
  • Example#774 - Un exemple avec Phar::startBuffering
  • Example#775 - Un exemple Phar::stopBuffering
  • Example#776 - Un exemple avec Phar::unlinkArchive
  • Example#777 - Exemple avec Phar::webPhar
  • Example#778 - Un exemple avec PharData::addEmptyDir
  • Example#779 - Un exemple avec PharData::addFile
  • Example#780 - Exemple avec PharData::addFromString
  • Example#781 - Un exemple avec PharData::buildFromDirectory
  • Example#782 - Exemple avec PharData::buildFromIterator et SplFileInfo
  • Example#783 - Exemple avec PharData::buildFromIterator et d'autres itérateurs
  • Example#784 - Un exemple avec PharData::compress
  • Example#785 - Un exemple avec PharData::compressFiles
  • Example#786 - Un exemple avec PharData::__construct
  • Example#787 - Un exemple avec PharData::convertToData
  • Example#788 - Un exemple avec PharData::convertToExecutable
  • Example#789 - Un exemple avec PharData::copy
  • Example#790 - Exemple avec PharData::decompress
  • Example#791 - Un exemple avec PharData::decompressFiles
  • Example#792 - Un exemple avec PharData::delMetaData
  • Example#793 - Un exemple avec PharData::delete
  • Example#794 - Exemple avec PharData::extractTo
  • Example#795 - Un exemple avec PharData::offsetSet
  • Example#796 - Un exemple avec PharData::offsetUnset
  • Example#797 - Un exemple avec Phar::setMetadata
  • Example#798 - Un exemple avec PharFileInfo::chmod
  • Example#799 - Un exemple avec PharFileInfo::compress
  • Example#800 - Exemple avec PharFileInfo::__construct
  • Example#801 - Exemple avec PharFileInfo::decompress
  • Example#802 - Un exemple avec PharFileInfo::delMetaData
  • Example#803 - Exemple avec PharFileInfo::getCRC32
  • Example#804 - Un exemple avec PharFileInfo::getCompressedSize
  • Example#805 - Un exemple avec PharFileInfo::getMetadata
  • Example#806 - Un exemple avecPharFileInfo::getPharFlags
  • Example#807 - Un exemple avec PharFileInfo::isCRCChecked
  • Example#808 - Un exemple avec PharFileInfo::isCompressed
  • Example#809 - Un exemple avec PharFileInfo::setMetadata
  • Example#810 - Installation de Rar
  • Example#811 - Décompression à la volée
  • Example#812 - Exemple d'extractions RAR
  • Example#813 - Style orienté objet
  • Example#814 - Style procédural
  • Example#815 - Style orienté objet
  • Example#816 - Style procédural
  • Example#817 - Style orienté objet
  • Example#818 - Style procédural
  • Example#819 - Style orienté objet
  • Example#820 - Style procédural
  • Example#821 - Style orienté objet
  • Example#822 - Style procédural
  • Example#823 - Style orienté objet
  • Example#824 - Style procédural
  • Example#825 - Style orienté objet
  • Example#826 - Style procédural
  • Example#827 - Fonction de rappel pour le volume
  • Example#828 - Style orienté objet
  • Example#829 - Style procédural
  • Example#830 - Exemple avec RarArchive::__toString
  • Example#831 - Exemple avec RarEntry::extract
  • Example#832 - Comment extraire tous les fichiers d'une archive :
  • Example#833 - Exemple avec RarEntry::getAttr
  • Example#834 - Exemple avec RarEntry::getHostOs (version >= 2.0.0)
  • Example#835 - Exemple avec RarEntry::getHostOs (version <= 1.0.0)
  • Example#836 - Exemple avec RarEntry::getMethod
  • Example#837 - Exemple avec RarEntry::getName
  • Example#838 - Exemple avec RarEntry::getPackedSize
  • Example#839 - Exemple avec RarEntry::getStream
  • Example#840 - Exemple avec RarEntry::getUnpackedSize
  • Example#841 - Exemple avec RarEntry::getVersion
  • Example#842 - Exemple avec RarException::isUsingExceptions
  • Example#843 - Exemple avec RarException::setUsingExceptions
  • Example#844 - Création d'une archive Zip
  • Example#845 - Affiche les détails de l'archive et liste son contenu
  • Example#846 - Flux ZIP : lit les meta-données d'un fichier OpenOffice
  • Example#847 - Exemple d'utilisation de Zip
  • Example#848 - Crée un nouveau dossier dans l'archive
  • Example#849 - Ouverture et ajout
  • Example#850 - Ajout d'une entrée dans une nouvelle archive
  • Example#851 - Ajout d'un fichier dans un dossier d'une archive
  • Example#852 - Exemple avec ZipArchive::addGlob
  • Example#853 - Exemple avec ZipArchive::addPattern
  • Example#854 - Efface le fichier depuis l'archive en utilisant son index
  • Example#855 - Efface un fichier et un dossier de l'archive en utilisant les noms
  • Example#856 - Extrait toutes les entrées
  • Example#857 - Extrait deux entrées
  • Example#858 - Extrait le commentaire de l'archive
  • Example#859 - Test if archive is a torrentzip format
  • Example#860 - Affiche le commentaire d'une entrée
  • Example#861 - Affiche le commentaire d'une entrée
  • Example#862 - Extrait toutes les entrées avec leurs droits Unix
  • Example#863 - Récupère le contenu du fichier
  • Example#864 - Récupère le contenu d'un fichier
  • Example#865 - Convertit une image depuis une entrée ZIP
  • Example#866 - Exemple avec ZipArchive::getNameIndex
  • Example#867 - Récupère le contenu de l'entrée ZIP
  • Example#868 - Récupère une entrée Zip avec la fonction fopen et le gestionnaire de flux ZIP
  • Example#869 - Gestionnaire de flux et image, peut être utilisé également avec les fonctions XML
  • Example#870 - Obtenir le contenu de l'entrée avec fread et le stocker
  • Example#871 - Obtenir le contenu de l'entrée avec fread et le stocker
  • Example#872 - Crée une archive et l'utilise avec ZipArchive::locateName
  • Example#873 - Ouverture et extraction
  • Example#874 - Création d'une archive
  • Example#875 - Créer une archive temporaire
  • Example#876 - Archivage d'un fichier
  • Example#877 - Archive un fichier
  • Example#878 - Renommer une entrée
  • Example#879 - Renommer une entrée
  • Example#880 - Ouvre et remplace
  • Example#881 - Création d'une archive et définition d'un commentaire
  • Example#882 - Create a torrentzip archive
  • Example#883 - Ouvre une archive et définit un commentaire pour une entrée
  • Example#884 - Ouvre une archive et définit le commentaire pour une entrée
  • Example#885 - Ajoute des fichiers avec différentes méthodes de compression dans une archive
  • Example#886 - Ajoute des fichiers avec différentes méthodes de compression dans une archive
  • Example#887 - Ajoute un fichier et définir la méthode de compression
  • Example#888 - Archiver et chiffrer un fichier
  • Example#889 - Archiver un fichier avec ses droits Unix
  • Example#890 - Archive un fichier
  • Example#891 - Archive un fichier
  • Example#892 - Récupère les informations d'une entrée
  • Example#893 - Récupère les informations d'une entrée
  • Example#894 - Exemple avec Zlib
  • Example#895 - Fonctionnement avec l'API de compression et de décompression incrémentale
  • Example#896 - Exemple avec gzclose
  • Example#897 - Exemple avec gzcompress
  • Example#898 - Exemple avec gzdeflate
  • Example#899 - Création d'un fichier gzip
  • Example#900 - Exemple avec gzeof
  • Example#901 - Exemple avec gzfile
  • Example#902 - Exemple avec gzgetc
  • Example#903 - Exemple avec gzgets
  • Example#904 - Exemple avec gzgetss
  • Example#905 - Exemple avec gzinflate
  • Example#906 - Exemple avec gzopen
  • Example#907 - Exemple avec gzpassthru
  • Example#908 - Exemple avec gzread
  • Example#909 - Exemple avec gzseek
  • Example#910 - Exemple avec gzuncompress
  • Example#911 - Exemple avec gzwrite
  • Example#912 - Exemple avec zlib_encode
  • Example#913 - Exemple avec hash_algos
  • Example#914 - Exemple avec hash_copy
  • Example#915 - Exemple dehash_equals example
  • Example#916 - Exemple avec hash_file
  • Example#917 - Exemple avec hash_hkdf
  • Example#918 - Exemple avec hash_hmac_algos
  • Example#919 - Exemple avec hash_hmac_file
  • Example#920 - Exemple avec hash_hmac
  • Example#921 - Exemple de hachage incrémental
  • Example#922 - Exemple avec hash_pbkdf2
  • Example#923 - Exemple avec hash_update_stream
  • Example#924 - Exemple avec hash
  • Example#925 - Exemple avec mcrypt_create_iv
  • Example#926 - Exemple avec mcrypt_enc_get_algorithms_name
  • Example#927 - Exemple avec mcrypt_enc_get_modes_name
  • Example#928 - Exemple avec mcrypt_enc_get_supported_key_sizes
  • Example#929 - Exemple avec mcrypt_encrypt
  • Example#930 - Exemple avec mcrypt_get_block_size
  • Example#931 - Exemple avec mcrypt_get_cipher_name
  • Example#932 - Exemple avec mcrypt_get_iv_size
  • Example#933 - Exemple avec mcrypt_get_key_size
  • Example#934 - Exemple avec mcrypt_list_algorithms
  • Example#935 - Exemple avec mcrypt_list_modes
  • Example#936 - Exemple avec mcrypt_module_open
  • Example#937 - Utilisation de mcrypt_module_open pour chiffrer
  • Example#938 - Exemple avec mcrypt_module_self_test
  • Example#939 - Exemple avec mdecrypt_generic
  • Example#940 - Calcule le MD5 et le hmac, puis l'affiche comme un hexadécimal
  • Example#941 - Parcourir la liste des hash
  • Example#942 - Exemple avec mhash_get_block_size
  • Example#943 - Exemple avec mhash_get_hash_name
  • Example#944 - Exemple avec openssl_cipher_iv_length
  • Example#945 - openssl_cipher_key_length example
  • Example#946 - openssl_cms_sign example
  • Example#947 - openssl_csr_export_to_file() example
  • Example#948 - openssl_csr_export() example
  • Example#949 - openssl_csr_get_public_key() example
  • Example#950 - Exemple avec openssl_csr_get_subject()
  • Example#951 - Création d'un certificat autosigné
  • Example#952 - Créer un certficat ECC autosigné (à partir de PHP 7.1.0)
  • Example#953 - Exemple avec openssl_csr_sign - signer une CSR (comment être votre propre Autorité de Certification)
  • Example#954 - Calcule un secret partagé
  • Example#955 - Générer une paire de clé DH publique/privée en PHP
  • Example#956 - Exemple de chiffrement authentifié AES en mode GCM pour PHP 7.1+
  • Example#957 - Exemple de chiffrement authentifié AES en mode GCM antérieur à PHP 7.1
  • Example#958 - Exemple avec openssl_error_string
  • Example#959 - Exemple avec openssl_get_cert_locations
  • Example#960 - Exemple openssl_get_cipher_methods
  • Example#961 - Exemple avec openssl_get_curve_names
  • Example#962 - Exemple openssl_get_md_methods
  • Example#963 - Exemple avec openssl_open
  • Example#964 - Exemple avec openssl_pbkdf2()
  • Example#965 - openssl_pkcs12_read example
  • Example#966 - Exemple avec openssl_pkcs7_decrypt
  • Example#967 - Exemple avec openssl_pkcs7_encrypt
  • Example#968 - Récupérer un tableau PEM depuis un fichier P7B
  • Example#969 - Exemple avec openssl_pkcs7_sign
  • Example#970 - openssl_pkey_derive example
  • Example#971 - Obtain the public key from a private key
  • Example#972 - Exemple openssl_random_pseudo_bytes
  • Example#973 - Exemple avec openssl_seal
  • Example#974 - Exemple avec openssl_sign
  • Example#975 - Exemple avec openssl_sign
  • Example#976 - Exemple avec openssl_spki_export_challenge
  • Example#977 - Exemple avec openssl_spki_export_challenge depuis <keygen>
  • Example#978 - Exemple avec openssl_spki_export
  • Example#979 - Exemple avec openssl_spki_export depuis <keygen>
  • Example#980 - Exemple avec openssl_spki_new
  • Example#981 - Exemple avec openssl_spki_verify
  • Example#982 - Exemple avec openssl_spki_verify depuis <keygen>
  • Example#983 - Exemple avec openssl_verify
  • Example#984 - Exemple avec openssl_verify
  • Example#985 - Exemple avec openssl_x509_verify
  • Example#986 - Utilisation basique de la fonction password_algos
  • Example#987 - Exemple avec password_hash
  • Example#988 - Exemple avec password_hash en définissant manuellement l'option cost
  • Example#989 - Exemple avec password_hash trouver un bon coût (cost)
  • Example#990 - Exemple avec password_hash et Argon2i
  • Example#991 - Usage de password_needs_rehash
  • Example#992 - Exemple avec password_verify
  • Example#993 - RNP clearsign example
  • Example#994 - simple callback function example
  • Example#995 - sodium_crypto_box_seal_open example
  • Example#996 - sodium_crypto_box_seal example
  • Example#997 - sodium_crypto_core_ristretto255_add example
  • Example#998 - sodium_crypto_core_ristretto255_from_hash example
  • Example#999 - sodium_crypto_core_ristretto255_is_valid_point example
  • Example#1000 - sodium_crypto_core_ristretto255_random example
  • Example#1001 - sodium_crypto_core_ristretto255_scalar_add example
  • Example#1002 - sodium_crypto_core_ristretto255_scalar_invert example
  • Example#1003 - sodium_crypto_core_ristretto255_scalar_negate example
  • Example#1004 - sodium_crypto_core_ristretto255_scalar_random example
  • Example#1005 - sodium_crypto_core_ristretto255_scalar_sub example
  • Example#1006 - sodium_crypto_core_ristretto255_sub example
  • Example#1007 - sodium_crypto_generichash_final example
  • Example#1008 - sodium_crypto_generichash_init example
  • Example#1009 - sodium_crypto_generichash_update example
  • Example#1010 - sodium_crypto_kx_keypair usage
  • Example#1011 - sodium_crypto_pwhash_str example
  • Example#1012 - sodium_crypto_pwhash example
  • Example#1013 - sodium_crypto_secretbox_keygen example
  • Example#1014 - Comparing sodium_crypto_secretbox_keygen with random_bytes
  • Example#1015 - sodium_crypto_secretbox_open example
  • Example#1016 - sodium_crypto_secretbox example
  • Example#1017 - sodium_crypto_secretstream_xchacha20poly1305_init_pull example
  • Example#1018 - sodium_crypto_secretstream_xchacha20poly1305_init_push example
  • Example#1019 - sodium_crypto_stream_xchacha20_xor_ic example
  • Example#1020 - Exemple avec DBA
  • Example#1021 - Lecture d'une base de données
  • Example#1022 - Exemple avec dba_handlers
  • Example#1023 - Lister les Priviléges pour une Colonne
  • Example#1024 - Lister les Colonnes d'une Table
  • Example#1025 - Connexion sans DSN
  • Example#1026 - odbc_connection_string_quote example
  • Example#1027 - Lister les DSNs disponibles
  • Example#1028 - Exemple avec odbc_execute et odbc_prepare
  • Example#1029 - Exemple avec odbc_fetch_into
  • Example#1030 - Exemple avec odbc_next_result
  • Example#1031 - Exemple avec odbc_prepare et odbc_execute
  • Example#1032 - Lister les Clés primaire d'une Colonne
  • Example#1033 - Liste les Colonnes d'une Procédure Stocké
  • Example#1034 - Liste les Procédures stocké d'une Base de Donnée
  • Example#1035 - Exemple avec odbc_result
  • Example#1036 - Exemple avec odbc_setoption
  • Example#1037 - Liste les Statistiques d'une Table
  • Example#1038 - Liste les Priviléges d'une Table
  • Example#1039 - Liste les Tables dans un Catalogue
  • Example#1040 - Utilisation de PDO::ATTR_DRIVER_NAME
  • Example#1041 - Connexion à MySQL
  • Example#1042 - Gestion des erreurs de connexion
  • Example#1043 - Fermeture d'une connexion
  • Example#1044 - Connexions persistantes
  • Example#1045 - Exécution d'un groupe dans une transaction
  • Example#1046 - Insertions répétitives en utilisant les requêtes préparées
  • Example#1047 - Insertions répétées en utilisant des requêtes préparées
  • Example#1048 - Récupération des données en utilisant des requêtes préparées
  • Example#1049 - Appel d'une procédure stockée avec un paramètre de sortie
  • Example#1050 - Appel d'une procédure stockée avec un paramètre d'entrée/sortie
  • Example#1051 - Utilisation invalide de marqueur
  • Example#1052 - Création d'une instance PDO et définition du mode d'erreur
  • Example#1053 - Crée une instance PDO et définit le mode d'erreur depuis le constructeur
  • Example#1054 - Affichage d'une image depuis une base de données
  • Example#1055 - Insertion d'une image dans une base de données
  • Example#1056 - Insertion d'une image dans une base de données Oracle
  • Example#1057 - Annule une transaction
  • Example#1058 - Valide une transaction basique
  • Example#1059 - Committing a DDL transaction
  • Example#1060 - Crée une instance PDO via une invocation de pilote
  • Example#1061 - Crée une instance PDO via une invocation URI
  • Example#1062 - Crée une instance PDO avec un alias
  • Example#1063 - Récupération d'un code SQLSTATE
  • Example#1064 - Affiche les champs d'erreurs pour une connexion PDO_ODBC sur une base de données DB2
  • Example#1065 - Exécution d'une requête DELETE
  • Example#1066 - Récupération des attributs de connexion à une base de données
  • Example#1067 - Exemple avec PDO::getAvailableDrivers
  • Example#1068 - Modèle de déclaration SQL avec des paramètres nommés
  • Example#1069 - Modèle de déclaration SQL avec des marqueurs
  • Example#1070 - Modèle de déclaration SQL avec un point d'interrogation échappé
  • Example#1071 - SQL sans marqueurs de substitution peut être exécuté utilisant PDO::query
  • Example#1072 - Protection d'une chaîne normale
  • Example#1073 - Protection d'une chaîne dangereuse
  • Example#1074 - Protection d'une chaîne complexe
  • Example#1075 - Annulation d'une transaction
  • Example#1076 - Lie l'affichage du jeu de résultats à des variables PHP
  • Example#1077 - Exécution d'une requête préparée avec des emplacements nommés
  • Example#1078 - Exécution d'une requête préparée avec des marqueurs de positionnement
  • Example#1079 - Appel une procédure stockée avec un paramètre INOUT
  • Example#1080 - Exécute une requête préparée avec des marqueurs nommés
  • Example#1081 - Exécute une requête préparée avec des points d'interrogation comme paramètre fictif
  • Example#1082 - Exemple avec PDOStatement::closeCursor
  • Example#1083 - Comptage des colonnes
  • Example#1084 - Exemple avec PDOStatement::debugDumpParams et des paramètres nommés
  • Example#1085 - Exemple avec PDOStatement::debugDumpParams et des paramètres anonymes
  • Example#1086 - Détermine la catégorie de l'erreur qui survient
  • Example#1087 - Affiche les champs de errorInfo pour une connexion PDO_ODBC sur une base de données DB2
  • Example#1088 - Exécute une requête préparée avec des variables et valeurs liées
  • Example#1089 - Exécute une requête préparée avec un tableau de valeurs nommées
  • Example#1090 - Exécute une requête préparée avec un tableau de valeurs positionnels
  • Example#1091 - Exécute une requête préparée avec des variables lié à un marqueur de positionnement
  • Example#1092 - Exécute une requête préparée en utilisant un tableau pour les clauses IN
  • Example#1093 - Récupération de lignes en utilisant différentes méthodes
  • Example#1094 - Récupération des lignes avec un curseur scrollable
  • Example#1095 - Ordre de construction
  • Example#1096 - Récupération de toutes les lignes d'un jeu de résultats
  • Example#1097 - Récupération de toutes les valeurs d'une seule colonne depuis un jeu de résultats
  • Example#1098 - Grouper toutes les valeurs d'une seule colonne
  • Example#1099 - Instancier une classe pour chaque résultat
  • Example#1100 - Appel d'une fonction pour chaque résultat
  • Example#1101 - Retourne la première colonne de la ligne suivante
  • Example#1102 - Récupération des métadonnées pour une colonne
  • Example#1103 - Récupération de multiples lignes de résultats retournées par une procédure stockée
  • Example#1104 - Retourne le nombre de lignes effacées
  • Example#1105 - Comptage des lignes retournées par une requête SELECT
  • Example#1106 - Définition du mode de récupération
  • Example#1107 - Insertion de LOBs dans CUBRID PDO
  • Example#1108 - Récupère des LOBs depuis CUBRID PDO
  • Example#1109 - Insertion d'un jeu dans CUBRID PDO avec le type de données par défaut.
  • Example#1110 - Spécifie le type de données lors de l'insertion du jeu dans CUBRID PDO
  • Example#1111 - Exemples de DSN PDO_CUBRID
  • Example#1112 - Exemple avec PDO::cubrid_schema
  • Example#1113 - Exemples avec PDO_DBLIB DSN
  • Example#1114 - Exemples avec PDO_FIREBIRD DSN
  • Example#1115 - Exemple avec un DSN PDO_FIREBIRD avec un port et un chemin
  • Example#1116 - Exemple avec un DSN PDO_FIREBIRD en local et un chemin vers le fichier employee.fdb sur un système Debian
  • Example#1117 - Un DSN PDO_FIREBIRD pour se connecter à une base de donnée en dialecte 1
  • Example#1118 - Exemple avec PDO_IBM DSN en utilisant db2cli.ini
  • Example#1119 - Exemple avec PDO_IBM DSN en utilisant une chaîne complète de connexion
  • Example#1120 - Exemple DSN de PDO_INFORMIX avec odbc.ini
  • Example#1121 - Exemple DSN de PDO_INFORMIX avec une chaîne de caractères de connexion
  • Example#1122 - Activation du mode non mis en cache de MySQL
  • Example#1123 - Exemples avec le DSN de PDO_MYSQL
  • Example#1124 - Exemples de DSN PDO_SQLSRV
  • Example#1125 - Exemples avec PDO_OCI DSN
  • Example#1126 - Exemple avec PDO_ODBC DSN (pilote ODBC Manager)
  • Example#1127 - Exemple avec PDO_ODBC DSN (connexion non cataloguée IBM DB2)
  • Example#1128 - Exemple avec PDO_ODBC DSN (connexion non cataloguée Microsoft Access)
  • Example#1129 - Exemples avec PDO_PGSQL DSN
  • Example#1130 - Exemple avec PDO::pgsqlLOBCreate
  • Example#1131 - Exemple avec PDO::pgsqlLOBOpen
  • Example#1132 - Exemple avec PDO::pgsqlLOBUnlink
  • Example#1133 - Exemples avec PDO_SQLITE DSN
  • Example#1134 - Exemple d'agrégation avec une fonction max_length
  • Example#1135 - Exemple avec PDO::sqliteCreateCollation
  • Example#1136 - Exemple avec PDO::sqliteCreateFunction
  • Example#1137 - Exemple de récupération de données
  • Example#1138 - Exemple d'insertion de données
  • Example#1139 - Exemple avec cubrid_bind
  • Example#1140 - Exemple avec cubrid_bind et les types BLOB/CLOB
  • Example#1141 - Exemple avec cubrid_bind et BLOB/CLOB
  • Example#1142 - Exemple avec cubrid_close_prepare
  • Example#1143 - Exemple avec cubrid_close_request
  • Example#1144 - Exemple avec cubrid_col_get
  • Example#1145 - Exemple avec cubrid_col_size
  • Example#1146 - Exemple avec cubrid_column_names
  • Example#1147 - Exemple avec cubrid_column_types
  • Example#1148 - Exemple avec cubrid_commit
  • Example#1149 - Exemple avec cubrid_connect_with_url
  • Example#1150 - Exemple avec cubrid_connect_with_url
  • Example#1151 - Exemple avec cubrid_connect
  • Example#1152 - Exemple avec cubrid_current_oid
  • Example#1153 - Exemple avec cubrid_disconnect
  • Example#1154 - Exemple avec cubrid_drop
  • Example#1155 - Exemple avec cubrid_error_code_facility
  • Example#1156 - Exemple avec cubrid_error_code
  • Example#1157 - Exemple avec cubrid_error_msg
  • Example#1158 - Exemple avec cubrid_execute
  • Example#1159 - Exemple avec cubrid_fetch
  • Example#1160 - Exemple avec cubrid_free_result
  • Example#1161 - Exemple avec cubrid_get_charset
  • Example#1162 - Exemple avec cubrid_get_class_name
  • Example#1163 - Exemple avec cubrid_get_client_info
  • Example#1164 - Exemple avec cubrid_get_db_parameter
  • Example#1165 - Exemple avec cubrid_get_query_timeout
  • Example#1166 - Exemple avec cubrid_get_server_info
  • Example#1167 - Exemple avec cubrid_get
  • Example#1168 - Exemple avec cubrid_insert_id
  • Example#1169 - Exemple avec cubrid_is_instance
  • Example#1170 - Exemple avec cubrid_lob_close
  • Example#1171 - Exemple avec cubrid_lob_export
  • Example#1172 - Exemple avec cubrid_lob_get
  • Example#1173 - Exemple avec cubrid_lob_send
  • Example#1174 - Exemple avec cubrid_lob_size
  • Example#1175 - Exemple avec cubrid_lob2_bind
  • Example#1176 - cubrid_lob2_export example
  • Example#1177 - Exemple avec cubrid_lob2_export
  • Example#1178 - Exemple 1 avec cubrid_lob2_read
  • Example#1179 - Exemple 2 avec cubrid_lob2_read
  • Example#1180 - Exemple avec cubrid_lob2_seek64
  • Example#1181 - Exemple avec cubrid_lob2_seek
  • Example#1182 - Exemple 1 avec cubrid_lob2_write
  • Example#1183 - Exemple 2 avec cubrid_lob2_write
  • Example#1184 - Exemple avec cubrid_lock_read
  • Example#1185 - Exemple avec cubrid_lock_write
  • Example#1186 - Exemple avec cubrid_move_cursor
  • Example#1187 - Exemple avec cubrid_next_result
  • Example#1188 - Exemple avec cubrid_num_cols
  • Example#1189 - Exemple avec cubrid_num_rows
  • Example#1190 - Exemple avec cubrid_pconnect_with_url sans propriétés
  • Example#1191 - cubrid_pconnect_with_url url with properties example
  • Example#1192 - Exemple avec cubrid_connect
  • Example#1193 - Exemple avec cubrid_prepare
  • Example#1194 - Exemple avec cubrid_put
  • Example#1195 - Exempe avec cubrid_rollback
  • Example#1196 - Exemple avec cubrid_schema
  • Example#1197 - Exemple avec cubrid_seq_drop
  • Example#1198 - Exemple avec cubrid_seq_insert
  • Example#1199 - Exemple avec cubrid_seq_put
  • Example#1200 - Exemple avec cubrid_set_add
  • Example#1201 - Exemple avec cubrid_get_db_parameter
  • Example#1202 - Exemple avec cubrid_set_drop
  • Example#1203 - Exemple avec cubrid_version
  • Example#1204 - Exemple avec cubrid_affected_rows
  • Example#1205 - Exemple avec cubrid_client_encoding
  • Example#1206 - Exemple avec cubrid_close
  • Example#1207 - Exemple avec cubrid_data_seek
  • Example#1208 - Exemple avec cubrid_db_name
  • Example#1209 - Exemple avec cubrid_errno
  • Example#1210 - Exemple avec cubrid_error
  • Example#1211 - Exemple avec cubrid_fetch_array
  • Example#1212 - Exemple avec cubrid_fetch_assoc
  • Example#1213 - Exemple avec cubrid_fetch_field
  • Example#1214 - Exemple avec cubrid_fetch_lengths
  • Example#1215 - Exemple avec cubrid_fetch_object
  • Example#1216 - Exemple avec cubrid_fetch_row
  • Example#1217 - Exemple avec cubrid_field_flags
  • Example#1218 - Exemple avec cubrid_field_len
  • Example#1219 - Exemple avec cubrid_field_name
  • Example#1220 - Exemple avec cubrid_field_seek
  • Example#1221 - Exemple avec cubrid_field_table
  • Example#1222 - Exemple avec cubrid_field_type
  • Example#1223 - Exemple avec cubrid_list_dbs
  • Example#1224 - Exemple avec cubrid_num_fields
  • Example#1225 - Exemple avec cubrid_ping
  • Example#1226 - Requête invalide
  • Example#1227 - Requête valide
  • Example#1228 - Exemple avec cubrid_real_escape_string
  • Example#1229 - Exemple avec cubrid_result
  • Example#1230 - Exemple avec cubrid_unbuffered_query
  • Example#1231 - Exemple avec cubrid_load_from_glo
  • Example#1232 - Exemple avec cubrid_new_glo
  • Example#1233 - Exemple avec cubrid_save_to_glo
  • Example#1234 - Exemple avec cubrid_send_glo
  • Example#1235 - Insertion d'un enregistrement dans une base de données dBase
  • Example#1236 - Ferme un fichier de base de données dBase
  • Example#1237 - Création d'un fichier de base de données dBase
  • Example#1238 - Affiche les informations d'en-têtes pour un fichier de base de données dBase
  • Example#1239 - Liste tous les membres enregistrés dans la base de données
  • Example#1240 - Exemple avec dbase_numfields
  • Example#1241 - Lecture de tous les enregistrements de la base de données
  • Example#1242 - Ouverture d'un fichier de base de données dBase
  • Example#1243 - Vide une base de données dBase
  • Example#1244 - Mise à jour d'un enregistrement dans une base de données
  • Example#1245 - Exemple avec ibase_backup
  • Example#1246 - Exemple de ibase_backup avec des arguments
  • Example#1247 - Exemple avec ibase_blob_get
  • Example#1248 - Exemple avec ibase_blob_import
  • Example#1249 - Exemple avec ibase_connect
  • Example#1250 - Exemple avec ibase_execute
  • Example#1251 - Exemple avec ibase_fetch_object
  • Example#1252 - Exemple avec ibase_field_info
  • Example#1253 - Exemple avec ibase_name_result
  • Example#1254 - Exemple avec ibase_num_fields
  • Example#1255 - Exemple avec ibase_query
  • Example#1256 - Exemple avec ibase_restore
  • Example#1257 - Exemple de ibase_restore avec des arguments
  • Example#1258 - Exemple avec ibase_service_attach
  • Example#1259 - Exemple avec ibase_service_attach
  • Example#1260 - Exemple deibase_service_attach en utilisant la syntaxe hostname/port
  • Example#1261 - Exemple avec ibase_service_detach
  • Example#1262 - Exemple avec ibase_set_event_handler
  • Example#1263 - Récupération de la valeur de AUTOCOMMIT pour une connexion
  • Example#1264 - Modification de la valeur de AUTOCOMMIT pour une connexion
  • Example#1265 - Association de variables PHP à une requête préparée
  • Example#1266 - Appel de procédures d'enregistrement avec les paramètres IN et OUT
  • Example#1267 - Insertion d'un objet large binaire (BLOB) provenant directement d'un fichier
  • Example#1268 - Exemple avec db2_client_info
  • Example#1269 - Fermeture d'une connexion
  • Example#1270 - Récupération de la valeur de SQLSTATE pour une tentative de connexion échouée
  • Example#1271 - Récupération du message d'erreur retourné par une tentative de connexion échouée
  • Example#1272 - Création d'une connexion cataloguée
  • Example#1273 - Création d'une connexion non cataloguée
  • Example#1274 - Création d'une connexion avec autocommit désactivé par défaut
  • Example#1275 - Meilleure performance i5/OS
  • Example#1276 - Utilisation du contexte
  • Example#1277 - Exemple avec db2_escape_string
  • Example#1278 - Création d'une table avec db2_exec
  • Example#1279 - Exécution d'une requête SELECT avec un curseur flottant
  • Example#1280 - Retourne des données XML en tant que ResultSet SQL
  • Example#1281 - Exécuter un "JOIN" avec des données XML
  • Example#1282 - Retourne des données SQL faisant partie d'un document XML large
  • Example#1283 - Préparation et exécution d'une requête SQL avec des marqueurs
  • Example#1284 - Appel d'une procédure d'enregistrement avec un paramètre de SORTIE
  • Example#1285 - Retourne des données XML en tant que ResultSet SQL
  • Example#1286 - Exécuter un "JOIN" avec des données XML
  • Example#1287 - Retourne des données SQL faisant partie d'un document XML large
  • Example#1288 - Itère avec un curseur d'avancement seul
  • Example#1289 - Récupération de lignes spécifiques avec db2_fetch_array provenant d'un curseur flottant
  • Example#1290 - Itère avec un curseur d'avancement seul
  • Example#1291 - Récupération de lignes spécifiques avec db2_fetch_assoc provenant d'un curseur flottant
  • Example#1292 - Itère avec un curseur d'avancement seul
  • Example#1293 - Récupération de lignes spécifiques avec db2_fetch_both provenant d'un curseur flottant
  • Example#1294 - Exemple avec db2_fetch_object
  • Example#1295 - Itère à travers un jeu de résultats
  • Example#1296 - Alternatives recommandées i5/OS pour db2_fetch_row/db2_result
  • Example#1297 - Fixe et récupère les paramètres d'une ressource de connexion
  • Example#1298 - Exemple avec db2_last_insert_id
  • Example#1299 - Itére à travers différents types de données
  • Example#1300 - Exemple avec db2_next_result
  • Example#1301 - Exemple avec db2_num_fields
  • Example#1302 - Fermer une connexion DB2 persistante
  • Example#1303 - Exemple d'utilisation de db2_pconnect
  • Example#1304 - Utilisation de contextes de confiance DB2
  • Example#1305 - Préparation et exécution d'une requête SQL avec des marqueurs
  • Example#1306 - Exemple d'utilisation de db2_result
  • Example#1307 - Annulation d'une requête DELETE
  • Example#1308 - Exemple avec db2_server_info
  • Example#1309 - Fixer un paramètre à une ressource de connexion
  • Example#1310 - Fixe des paramètres multiples avec une ressource de connexion
  • Example#1311 - Fixe des paramètres multiples avec une clé invalide
  • Example#1312 - Fixe des paramètres multiples avec une valeur invalide
  • Example#1313 - Fixe des paramètres multiples avec une ressource de connexion et un mauvais type
  • Example#1314 - Fixe des paramètres multiples avec une mauvaise ressource
  • Example#1315 - Tout mettre ensemble
  • Example#1316 - Les curseurs i5/OS sont en lecture seule
  • Example#1317 - MongoDB\Driver\Manager::__construct basic example
  • Example#1318 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1319 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1320 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1321 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1322 - Limiting execution time for a command
  • Example#1323 - MongoDB\Driver\Manager::executeQuery example
  • Example#1324 - Limiting execution time for a query
  • Example#1325 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1326 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1327 - Exemple avec MongoDB\Driver\Manager::getServers
  • Example#1328 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1329 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1330 - Exemple avec MongoDB\Driver\Command::__construct
  • Example#1331 - Exemple avec MongoDB\Driver\Command::__construct
  • Example#1332 - MongoDB\Driver\Query::__construct example
  • Example#1333 - Mixed write operations are grouped by type
  • Example#1334 - Ordered write operations causing an error
  • Example#1335 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1336 - MongoDB\Driver\BulkWrite::count example
  • Example#1337 - MongoDB\Driver\BulkWrite::delete example
  • Example#1338 - MongoDB\Driver\BulkWrite::insert example
  • Example#1339 - MongoDB\Driver\BulkWrite::update example
  • Example#1340 - Declare an API version on a manager
  • Example#1341 - Declare a strict API version on a manager
  • Example#1342 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1343 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1344 - Exemple avec MongoDB\Driver\WriteConcern::__construct
  • Example#1345 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1346 - MongoDB\Driver\WriteConcern::getW example
  • Example#1347 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1348 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1349 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1350 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1351 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1352 - Exemple avec MongoDB\Driver\ReadPreference::__construct
  • Example#1353 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1354 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1355 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1356 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1357 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1358 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1359 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1360 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1361 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1362 - Lecture d'un jeu de résultats
  • Example#1363 - Lecture d'un jeu de résultats pour un curseur à queue
  • Example#1364 - Exemple avec MongoDB\Driver\Cursor::getId
  • Example#1365 - Exemple avec MongoDB\Driver\Cursor::getServer
  • Example#1366 - Exemple avec MongoDB\Driver\Cursor::isDead
  • Example#1367 - Exemple avec MongoDB\Driver\Cursor::setTypeMap
  • Example#1368 - Exemple avec MongoDB\Driver\Cursor::toArray
  • Example#1369 - Exemple avec MongoDB\Driver\CursorId::__toString
  • Example#1370 - Exemple avec MongoDB\Driver\Server::getHost
  • Example#1371 - Exemple avec MongoDB\Driver\Server::getInfo
  • Example#1372 - Exemple avec MongoDB\Driver\Server::getLatency
  • Example#1373 - Exemple avec MongoDB\Driver\Server::getPort
  • Example#1374 - Exemple avec MongoDB\Driver\WriteConcernError::getCode
  • Example#1375 - Exemple avec MongoDB\Driver\WriteConcernError::getInfo
  • Example#1376 - Exemple avec MongoDB\Driver\WriteConcernError::getMessage
  • Example#1377 - Exemple avec MongoDB\Driver\WriteError::getCode
  • Example#1378 - Exemple avec MongoDB\Driver\WriteError::getIndex
  • Example#1379 - Exemple avec MongoDB\Driver\WriteError::getMessage
  • Example#1380 - Exemple avec MongoDB\Driver\WriteResult::getDeletedCount
  • Example#1381 - Exemple avec MongoDB\Driver\WriteResult::getInsertedCount
  • Example#1382 - Exemple avec MongoDB\Driver\WriteResult::getMatchedCount
  • Example#1383 - Exemple avec MongoDB\Driver\WriteResult::getModifiedCount
  • Example#1384 - Exemple avec MongoDB\Driver\WriteResult::getServer
  • Example#1385 - Exemple avec MongoDB\Driver\WriteResult::getUpsertedCount
  • Example#1386 - Exemple avec MongoDB\Driver\WriteResult::getUpsertedIds
  • Example#1387 - Exemple avec MongoDB\Driver\WriteResult::getWriteConcernError
  • Example#1388 - MongoDB\Driver\WriteResult::getWriteErrors avec une seule erreur
  • Example#1389 - MongoDB\Driver\WriteResult::getWriteErrors avec plusieurs erreurs
  • Example#1390 - MongoDB\Driver\WriteResult::isAcknowledged avec la préocupation d'écriture reconnue
  • Example#1391 - MongoDB\Driver\WriteResult::isAcknowledged avec la préocupation d'écriture non reconnue
  • Example#1392 - Exemple avec MongoDB\BSON\fromJSON
  • Example#1393 - Exemple avec MongoDB\BSON\fromPHP
  • Example#1394 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1395 - Exemple avec MongoDB\BSON\toJSON
  • Example#1396 - MongoDB\BSON\toPHP example
  • Example#1397 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1398 - MongoDB\BSON\Document::toCanonicalExtendedJSON example
  • Example#1399 - MongoDB\BSON\Document::toRelaxedExtendedJSON example
  • Example#1400 - Exemple avec MongoDB\BSON\Binary::__construct
  • Example#1401 - Exemple avec MongoDB\BSON\Binary::getData
  • Example#1402 - Exemple avec MongoDB\BSON\Binary::getType
  • Example#1403 - Exemple avec MongoDB\BSON\Binary::__toString
  • Example#1404 - Exemple avec MongoDB\BSON\Decimal128::__construct
  • Example#1405 - Exemple avec MongoDB\BSON\Decimal128::__toString
  • Example#1406 - MongoDB\BSON\Javascript::__construct example
  • Example#1407 - Exemple avec MongoDB\BSON\Javascript::getCode
  • Example#1408 - Exemple avec MongoDB\BSON\Javascript::getScope
  • Example#1409 - Exemple avec MongoDB\BSON\Javascript::__toString
  • Example#1410 - Exemple avec MongoDB\BSON\MaxKey::__construct
  • Example#1411 - Exemple avec MongoDB\BSON\MinKey::__construct
  • Example#1412 - Exemple avec MongoDB\BSON\ObjectId::__construct
  • Example#1413 - Exemple avec MongoDB\BSON\ObjectId::getTimestamp
  • Example#1414 - Exemple avec MongoDB\BSON\ObjectId::__toString
  • Example#1415 - MongoDB\BSON\Regex::__construct example
  • Example#1416 - Exemple avec BSON\Regex::getFlags
  • Example#1417 - Exemple avec BSON\Regex::getPattern
  • Example#1418 - Exemple avec BSON\Regex::__toString
  • Example#1419 - Exemple avec MongoDB\BSON\Timestamp::__construct
  • Example#1420 - Exemple avec MongoDB\BSON\Timestamp::__toString
  • Example#1421 - Exemple avec MongoDB\BSON\UTCDatetime::__construct
  • Example#1422 - Exemple avec MongoDB\BSON\UTCDatetime::toDateTime
  • Example#1423 - Exemple avec MongoDB\BSON\UTCDatetime::__toString
  • Example#1424 - MongoDB\BSON\Serializable::bsonSerialize renvoyant un tableau associatif pour le document racine
  • Example#1425 - MongoDB\BSON\Serializable::bsonSerialize renvoyant un tableau séquentiel pour le document racine
  • Example#1426 - MongoDB\BSON\Serializable::bsonSerialize renvoyant un tableau associatif pour le champ de document
  • Example#1427 - MongoDB\BSON\Serializable::bsonSerialize renvoyant un tableau séquentiel pour le champ de document
  • Example#1428 - Exemple avec MongoDB\BSON\Unserializable::bsonUnserialize
  • Example#1429 - Exemple avec MongoDB\BSON\Int64::__toString
  • Example#1430 - Exemple avec MongoDB\Driver\Exception\WriteException::getWriteResult
  • Example#1431 - Comparaison des APIs MySQL
  • Example#1432 - Commande de configuration pour l'utilisation de mysqlnd ou de libmysqlclient
  • Example#1433 - Comparaison des instructions préparées
  • Example#1434 - Exemple de requêtes n'utilisant pas la mémoire tampon : mysqli
  • Example#1435 - Exemple de requêtes n'utilisant pas la mémoire tampon : pdo_mysql
  • Example#1436 - Problèmes lors de la définition du jeu de caractères avec SQL
  • Example#1437 - Exemple de définition du jeu de caractères : mysqli
  • Example#1438 - Exemple de définition du jeu de caractères : pdo_mysql
  • Example#1439 - Migration facile depuis l'ancienne extension mysql
  • Example#1440 - Interface procédurale et orientée objet
  • Example#1441 - Mauvais style de codage
  • Example#1442 - Signification spéciale de localhost
  • Example#1443 - Paramètres par défaut
  • Example#1444 - Exécution des requêtes
  • Example#1445 - Navigation dans des résultats mis en mémoire tampon
  • Example#1446 - Navigation dans des résultats non mis en mémoire tampon
  • Example#1447 - Le protocole texte retourne des chaînes de caractères par défaut
  • Example#1448 - Types natifs des données avec mysqlnd et l'option de connexion
  • Example#1449 - Première étape : la préparation
  • Example#1450 - Requête de type INSERT préparée une seule fois, et exécutée plusieurs fois
  • Example#1451 - Moins d'aller-retour en utilisant les multi-INSERTs SQL
  • Example#1452 - Types de données natifs
  • Example#1453 - Liage des variables de sortie
  • Example#1454 - Utilisation de mysqli_result pour récupérer les résultats
  • Example#1455 - Jeu de résultats mis en mémoire tampon pour plus de flexibilité dans la lecture
  • Example#1456 - Appel d'une procédure stockée
  • Example#1457 - Utilisation des variables de session
  • Example#1458 - Récupération des résultats issus d'une procédure stockée
  • Example#1459 - Procédures stockées et requête préparée
  • Example#1460 - Procédures stockées et requête préparée en utilisant l'API de liage
  • Example#1461 - Requêtes multiples
  • Example#1462 - Injection SQL
  • Example#1463 - Définir le mode autocommit via SQL ou via l'API
  • Example#1464 - Validation et annulation d'une transaction
  • Example#1465 - Accès aux méta-données du jeu de résultats
  • Example#1466 - Méta-données via des requêtes préparées
  • Example#1467 - Exemple avec $mysqli->affected_rows
  • Example#1468 - Exemple avec mysqli::autocommit
  • Example#1469 - Exemple avec mysqli::begin_transaction
  • Example#1470 - Exemple avec mysqli::change_user
  • Example#1471 - mysqli::character_set_name example
  • Example#1472 - mysqli::close example
  • Example#1473 - Exemple avec $mysqli->connect_errno
  • Example#1474 - Exemple avec $mysqli->connect_error
  • Example#1475 - Exemple mysqli::__construct
  • Example#1476 - Étendre la classe mysqli
  • Example#1477 - Gestion d'erreur manuelle
  • Example#1478 - Génération d'un fichier de "traces"
  • Example#1479 - Exemple avec $mysqli->errno
  • Example#1480 - Exemple avec $mysqli->error_list
  • Example#1481 - Exemple avec $mysqli->error
  • Example#1482 - mysqli::execute_query example
  • Example#1483 - Exemple avec $mysqli->field_count
  • Example#1484 - Exemple avec mysqli::get_charset
  • Example#1485 - Exemple avec mysqli_get_client_info
  • Example#1486 - Exemple avec mysqli_get_client_version
  • Example#1487 - Exemple avec mysqli_get_connection_stats
  • Example#1488 - Exemple avec $mysqli->host_info
  • Example#1489 - Exemple avec $mysqli->protocol_version
  • Example#1490 - Exemple avec $mysqli->server_info
  • Example#1491 - Exemple avec $mysqli->server_version
  • Example#1492 - Exemple avec $mysqli->info
  • Example#1493 - Exemple avec $mysqli->insert_id
  • Example#1494 - Exemple avec mysqli::kill
  • Example#1495 - Exemple avec mysqli::multi_query
  • Example#1496 - Exemple avec mysqli::ping
  • Example#1497 - Exemple avec mysqli_poll
  • Example#1498 - Exemple avec mysqli::prepare
  • Example#1499 - Exemple avec mysqli::query
  • Example#1500 - Exemple avec mysqli::real_connect
  • Example#1501 - Exemple avec mysqli::real_escape_string
  • Example#1502 - Exemple avec mysqli::select_db
  • Example#1503 - Exemple avec mysqli::set_charset
  • Example#1504 - Exemple avec $mysqli->sqlstate
  • Example#1505 - Exemple avec mysqli::stat
  • Example#1506 - Exemple avec $mysqli->thread_id
  • Example#1507 - Exemple avec mysqli::use_result
  • Example#1508 - Exemple avec $mysqli->warning_count
  • Example#1509 - Exemple de mysqli_stmt_affected_rows
  • Example#1510 - Exemple avec mysqli_stmt::bind_param
  • Example#1511 - Using ... to provide arguments
  • Example#1512 - Style orienté objet
  • Example#1513 - Style procédural
  • Example#1514 - Style orienté objet
  • Example#1515 - Style procédural
  • Example#1516 - Style orienté objet
  • Example#1517 - Style procédural
  • Example#1518 - Style orienté objet
  • Example#1519 - Style procédural
  • Example#1520 - Style orienté objet
  • Example#1521 - Style procédural
  • Example#1522 - Exécuter une instruction préparée avec des variables liées
  • Example#1523 - Exécuter une instruction préparée avec un tableau de valeurs
  • Example#1524 - Style orienté objet
  • Example#1525 - Style procédural
  • Example#1526 - Style orienté objet
  • Example#1527 - Style procédural
  • Example#1528 - Style orienté objet
  • Example#1529 - Style procédural
  • Example#1530 - Style orienté objet
  • Example#1531 - Style procédural
  • Example#1532 - Style orienté objet
  • Example#1533 - Style procédural
  • Example#1534 - Exemple pour mysqli_stmt::prepare
  • Example#1535 - Style orienté objet
  • Example#1536 - Style procédural
  • Example#1537 - Style orienté objet
  • Example#1538 - Style orienté objet
  • Example#1539 - Style procédural
  • Example#1540 - Style orienté objet
  • Example#1541 - Style procédural
  • Example#1542 - Creation of a mysqli_result object
  • Example#1543 - Style orienté objet
  • Example#1544 - Style procédural
  • Example#1545 - Exemple avec mysqli::data_seek
  • Example#1546 - Ajustement du pointeur de résultat lors de l'itération
  • Example#1547 - mysqli_result::fetch_all example
  • Example#1548 - mysqli_result::fetch_array example
  • Example#1549 - Exemple mysqli_result::fetch_assoc
  • Example#1550 - Comparaison de l'usage de mysqli_result iterator et mysqli_result::fetch_assoc
  • Example#1551 - mysqli_result::fetch_column example
  • Example#1552 - Style orienté objet
  • Example#1553 - Style procédural
  • Example#1554 - Style orienté objet
  • Example#1555 - Style procédural
  • Example#1556 - Style orienté objet
  • Example#1557 - Style procédural
  • Example#1558 - Exemple mysqli_result::fetch_object
  • Example#1559 - Exemple mysqli_result::fetch_row
  • Example#1560 - Style orienté objet
  • Example#1561 - Style procédural
  • Example#1562 - Style orienté objet
  • Example#1563 - Style procédural
  • Example#1564 - Style orienté objet
  • Example#1565 - Style procédural
  • Example#1566 - Style orienté objet
  • Example#1567 - Style procédural
  • Example#1568 - Style orienté objet
  • Example#1569 - Style procédural
  • Example#1570 - Rapport d'erreur à l'exception des erreurs de mauvais index
  • Example#1571 - Un exemple avec mysqli_get_client_stats
  • Example#1572 - Connecting to a MySQL Server
  • Example#1573 - Creating a Schema and Collection on the MySQL Server
  • Example#1574 - Storing and Retrieving Data
  • Example#1575 - Fetching and Iterating Multiple Documents
  • Example#1576 - mysql_xdevapi\Expression example
  • Example#1577 - URI examples
  • Example#1578 - mysql_xdevapi\getSession example
  • Example#1579 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1580 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1581 - mysql_xdevapi\Client::__construct example
  • Example#1582 - mysql_xdevapi\Collection::add example
  • Example#1583 - mysql_xdevapi\Collection::addOrReplaceOne example
  • Example#1584 - mysql_xdevapi\Collection::getOne example
  • Example#1585 - mysql_xdevapi\Collection::count example
  • Example#1586 - mysql_xdevapi\Collection::createIndex example
  • Example#1587 - mysql_xdevapi\Collection::dropIndex example
  • Example#1588 - mysql_xdevapi\Collection::existsInDatabase example
  • Example#1589 - mysql_xdevapi\Collection::find example
  • Example#1590 - mysql_xdevapi\Collection::getName example
  • Example#1591 - mysql_xdevapi\Collection::getOne example
  • Example#1592 - mysql_xdevapi\Collection::getSchema example
  • Example#1593 - mysql_xdevapi\Collection::getSession example
  • Example#1594 - mysql_xdevapi\Collection::modify example
  • Example#1595 - mysql_xdevapi\Collection::remove example
  • Example#1596 - mysql_xdevapi\Collection::removeOne example
  • Example#1597 - mysql_xdevapi\Collection::replaceOne example
  • Example#1598 - mysql_xdevapi\CollectionAdd::__construct example
  • Example#1599 - mysql_xdevapi\CollectionAdd::execute example
  • Example#1600 - mysql_xdevapi\CollectionFind::bind example
  • Example#1601 - CollectionFind example
  • Example#1602 - CollectionFind example
  • Example#1603 - mysql_xdevapi\CollectionFind::fields example
  • Example#1604 - mysql_xdevapi\CollectionFind::groupBy example
  • Example#1605 - mysql_xdevapi\CollectionFind::having example
  • Example#1606 - mysql_xdevapi\CollectionFind::limit example
  • Example#1607 - mysql_xdevapi\CollectionFind::lockExclusive example
  • Example#1608 - mysql_xdevapi\CollectionFind::lockShared example
  • Example#1609 - mysql_xdevapi\CollectionFind::offset example
  • Example#1610 - mysql_xdevapi\CollectionFind::sort example
  • Example#1611 - mysql_xdevapi\CollectionModify::arrayAppend example
  • Example#1612 - mysql_xdevapi\CollectionModify::arrayInsert example
  • Example#1613 - mysql_xdevapi\CollectionModify::bind example
  • Example#1614 - mysql_xdevapi\CollectionModify::__construct example
  • Example#1615 - mysql_xdevapi\CollectionModify::execute example
  • Example#1616 - mysql_xdevapi\CollectionModify::limit example
  • Example#1617 - mysql_xdevapi\CollectionModify::patch example
  • Example#1618 - mysql_xdevapi\CollectionModify::replace example
  • Example#1619 - mysql_xdevapi\CollectionModify::set example
  • Example#1620 - mysql_xdevapi\CollectionModify::skip example
  • Example#1621 - mysql_xdevapi\CollectionModify::sort example
  • Example#1622 - mysql_xdevapi\CollectionModify::unset example
  • Example#1623 - mysql_xdevapi\CollectionRemove::bind example
  • Example#1624 - mysql_xdevapi\Collection::remove example
  • Example#1625 - mysql_xdevapi\CollectionRemove::execute example
  • Example#1626 - mysql_xdevapi\CollectionRemove::limit example
  • Example#1627 - mysql_xdevapi\CollectionRemove::sort example
  • Example#1628 - mysql_xdevapi\ColumnResult::__construct example
  • Example#1629 - mysql_xdevapi\ColumnResult::getCharacterSetName example
  • Example#1630 - mysql_xdevapi\ColumnResult::getCollationName example
  • Example#1631 - mysql_xdevapi\ColumnResult::getColumnLabel example
  • Example#1632 - mysql_xdevapi\ColumnResult::getColumnName example
  • Example#1633 - mysql_xdevapi\ColumnResult::getFractionalDigits example
  • Example#1634 - mysql_xdevapi\ColumnResult::getLength example
  • Example#1635 - mysql_xdevapi\ColumnResult::getSchemaName example
  • Example#1636 - mysql_xdevapi\ColumnResult::getTableLabel example
  • Example#1637 - mysql_xdevapi\ColumnResult::getTableName example
  • Example#1638 - mysql_xdevapi\ColumnResult::getType example
  • Example#1639 - mysql_xdevapi\ColumnResult::isNumberSigned example
  • Example#1640 - mysql_xdevapi\ColumnResult::isPadded example
  • Example#1641 - mysql_xdevapi\CrudOperationBindable::bind example
  • Example#1642 - mysql_xdevapi\CrudOperationLimitable::limit example
  • Example#1643 - mysql_xdevapi\CrudOperationSkippable::skip example
  • Example#1644 - mysql_xdevapi\CrudOperationSortable::sort example
  • Example#1645 - mysql_xdevapi\DatabaseObject::existsInDatabase example
  • Example#1646 - mysql_xdevapi\DatabaseObject::getName example
  • Example#1647 - mysql_xdevapi\DatabaseObject::getSession example
  • Example#1648 - A DocResult example
  • Example#1649 - mysql_xdevapi\DocResult::fetchAll example
  • Example#1650 - mysql_xdevapi\DocResult::fetchOne example
  • Example#1651 - mysql_xdevapi\DocResult::getWarnings example
  • Example#1652 - mysql_xdevapi\DocResult::getWarningsCount example
  • Example#1653 - execute() examples
  • Example#1654 - mysql_xdevapi\ExecutionStatus::__construct example
  • Example#1655 - mysql_xdevapi\Expression::__construct example
  • Example#1656 - mysql_xdevapi\Result::__construct example
  • Example#1657 - mysql_xdevapi\Result::getAffectedItemsCount example
  • Example#1658 - mysql_xdevapi\Result::getAutoIncrementValue example
  • Example#1659 - mysql_xdevapi\Result::getGeneratedIds example
  • Example#1660 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1661 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1662 - mysql_xdevapi\RowResult::__construct example
  • Example#1663 - mysql_xdevapi\RowResult::fetchAll example
  • Example#1664 - mysql_xdevapi\RowResult::fetchOne example
  • Example#1665 - mysql_xdevapi\RowResult::getColumnsCount example
  • Example#1666 - mysql_xdevapi\RowResult::getColumnNames example
  • Example#1667 - mysql_xdevapi\RowResult::getColumns example
  • Example#1668 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1669 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1670 - Schema::__construct example
  • Example#1671 - Schema::createCollection example
  • Example#1672 - Schema::createCollection validate parameter example
  • Example#1673 - Schema::dropCollection example
  • Example#1674 - Schema::existsInDatabase example
  • Example#1675 - Schema::getCollection example
  • Example#1676 - Schema::getCollectionAsTable example
  • Example#1677 - mysql_xdevapi\Schema::getCollections example
  • Example#1678 - mysql_xdevapi\Schema::getName example
  • Example#1679 - mysql_xdevapi\Schema::getSession example
  • Example#1680 - mysql_xdevapi\Schema::getTable example
  • Example#1681 - mysql_xdevapi\Schema::getTables example
  • Example#1682 - mysql_xdevapi\Session::getSchema example
  • Example#1683 - mysql_xdevapi\Session::close example
  • Example#1684 - mysql_xdevapi\Session::commit example
  • Example#1685 - mysql_xdevapi\Session::__construct example
  • Example#1686 - mysql_xdevapi\Session::createSchema example
  • Example#1687 - mysql_xdevapi\Session::dropSchema example
  • Example#1688 - mysql_xdevapi\Session::generateUuid example
  • Example#1689 - mysql_xdevapi\Session::getSchema example
  • Example#1690 - mysql_xdevapi\Session::getSchema example
  • Example#1691 - mysql_xdevapi\Session::getSchemas example
  • Example#1692 - mysql_xdevapi\Session::getServerVersion example
  • Example#1693 - mysql_xdevapi\Session::listClients example
  • Example#1694 - mysql_xdevapi\Session::quoteName example
  • Example#1695 - mysql_xdevapi\Session::releaseSavepoint example
  • Example#1696 - mysql_xdevapi\Session::rollback example
  • Example#1697 - mysql_xdevapi\Session::rollbackTo example
  • Example#1698 - mysql_xdevapi\Session::setSavepoint example
  • Example#1699 - mysql_xdevapi\Session::sql example
  • Example#1700 - mysql_xdevapi\Session::startTransaction example
  • Example#1701 - mysql_xdevapi\SqlStatement::bind example
  • Example#1702 - mysql_xdevapi\SqlStatement::__construct example
  • Example#1703 - mysql_xdevapi\SqlStatement::execute example
  • Example#1704 - mysql_xdevapi\SqlStatement::getNextResult example
  • Example#1705 - mysql_xdevapi\SqlStatement::getResult example
  • Example#1706 - mysql_xdevapi\SqlStatement::hasMoreResults example
  • Example#1707 - mysql_xdevapi\SqlStatementResult::__construct example
  • Example#1708 - mysql_xdevapi\SqlStatementResult::fetchAll example
  • Example#1709 - mysql_xdevapi\SqlStatementResult::fetchOne example
  • Example#1710 - mysql_xdevapi\SqlStatementResult::getAffectedItemsCount example
  • Example#1711 - mysql_xdevapi\SqlStatementResult::getColumnsCount example
  • Example#1712 - mysql_xdevapi\SqlStatementResult::getColumnNames example
  • Example#1713 - mysql_xdevapi\SqlStatementResult::getColumns example
  • Example#1714 - mysql_xdevapi\SqlStatementResult::getGeneratedIds example
  • Example#1715 - mysql_xdevapi\SqlStatementResult::getLastInsertId example
  • Example#1716 - mysql_xdevapi\SqlStatementResult::getWarnings example
  • Example#1717 - mysql_xdevapi\SqlStatementResult::getWarningsCount example
  • Example#1718 - mysql_xdevapi\SqlStatementResult::hasData example
  • Example#1719 - mysql_xdevapi\SqlStatementResult::nextResult example
  • Example#1720 - mysql_xdevapi\Statement::__construct example
  • Example#1721 - mysql_xdevapi\Statement::getNextResult example
  • Example#1722 - mysql_xdevapi\Statement::getResult example
  • Example#1723 - mysql_xdevapi\Statement::hasMoreResults example
  • Example#1724 - mysql_xdevapi\Table::__construct example
  • Example#1725 - mysql_xdevapi\Table::count example
  • Example#1726 - mysql_xdevapi\Table::delete example
  • Example#1727 - mysql_xdevapi\Table::existsInDatabase example
  • Example#1728 - mysql_xdevapi\Table::getName example
  • Example#1729 - mysql_xdevapi\Table::getSchema example
  • Example#1730 - mysql_xdevapi\Table::getSession example
  • Example#1731 - mysql_xdevapi\Table::insert example
  • Example#1732 - mysql_xdevapi\Table::isView example
  • Example#1733 - mysql_xdevapi\Table::count example
  • Example#1734 - mysql_xdevapi\Table::update example
  • Example#1735 - mysql_xdevapi\TableDelete::bind example
  • Example#1736 - mysql_xdevapi\TableDelete::__construct example
  • Example#1737 - mysql_xdevapi\TableDelete::execute example
  • Example#1738 - mysql_xdevapi\TableDelete::limit example
  • Example#1739 - mysql_xdevapi\TableDelete::orderBy example
  • Example#1740 - mysql_xdevapi\TableDelete::where example
  • Example#1741 - mysql_xdevapi\TableInsert::__construct example
  • Example#1742 - mysql_xdevapi\TableInsert::execute example
  • Example#1743 - mysql_xdevapi\TableInsert::values example
  • Example#1744 - mysql_xdevapi\TableSelect::bind example
  • Example#1745 - mysql_xdevapi\TableSelect::__construct example
  • Example#1746 - mysql_xdevapi\TableSelect::execute example
  • Example#1747 - mysql_xdevapi\TableSelect::groupBy example
  • Example#1748 - mysql_xdevapi\TableSelect::having example
  • Example#1749 - mysql_xdevapi\TableSelect::limit example
  • Example#1750 - mysql_xdevapi\TableSelect::lockExclusive example
  • Example#1751 - mysql_xdevapi\TableSelect::lockShared example
  • Example#1752 - mysql_xdevapi\TableSelect::offset example
  • Example#1753 - mysql_xdevapi\TableSelect::orderBy example
  • Example#1754 - mysql_xdevapi\TableSelect::where example
  • Example#1755 - mysql_xdevapi\TableUpdate::bind example
  • Example#1756 - mysql_xdevapi\TableUpdate::__construct example
  • Example#1757 - mysql_xdevapi\TableUpdate::execute example
  • Example#1758 - mysql_xdevapi\TableUpdate::limit example
  • Example#1759 - mysql_xdevapi\TableUpdate::orderby example
  • Example#1760 - mysql_xdevapi\TableUpdate::set example
  • Example#1761 - mysql_xdevapi\TableUpdate::where example
  • Example#1762 - mysql_xdevapi\Warning::__construct example
  • Example#1763 - Exemple de présentation de l'extension MySQL
  • Example#1764 - Exemple avec mysql_affected_rows
  • Example#1765 - Exemple avec mysql_affected_rows en utilisant les transactions
  • Example#1766 - Exemple avec mysql_client_encoding
  • Example#1767 - Exemple avec mysql_close
  • Example#1768 - Exemple avec mysql_connect
  • Example#1769 - Exemple avec mysql_connect en utilisant la syntaxe hostname:port
  • Example#1770 - Exemple avec mysql_connect en utilisant la syntaxe ":/path/to/socket"
  • Example#1771 - Exemple alternative avec mysql_create_db
  • Example#1772 - Exemple avec mysql_data_seek
  • Example#1773 - Exemple mysql_db_name
  • Example#1774 - Exemple alternatif avec mysql_db_query
  • Example#1775 - Exemple avec mysql_drop_db
  • Example#1776 - Exemple avec mysql_errno
  • Example#1777 - Exemple avec mysql_error
  • Example#1778 - Exemple avec mysql_escape_string
  • Example#1779 - Requête avec duplication de nom de colonnes
  • Example#1780 - mysql_fetch_array avec MYSQL_NUM
  • Example#1781 - mysql_fetch_array avec MYSQL_ASSOC
  • Example#1782 - mysql_fetch_array avec MYSQL_BOTH
  • Example#1783 - Exemple avec mysql_fetch_assoc
  • Example#1784 - Exemple avec mysql_fetch_field
  • Example#1785 - Exemple avec mysql_fetch_lengths
  • Example#1786 - Exemple avec mysql_fetch_object
  • Example#1787 - Exemple avec mysql_fetch_object
  • Example#1788 - Exemple avec mysql_fetch_row
  • Example#1789 - Exemple avec mysql_field_flags
  • Example#1790 - Exemple avec mysql_field_len
  • Example#1791 - Exemple avec mysql_field_name
  • Example#1792 - Exemple avec mysql_field_table
  • Example#1793 - Exemple avec mysql_field_type
  • Example#1794 - Exemple avec mysql_free_result
  • Example#1795 - Exemple avec mysql_get_client_info
  • Example#1796 - Exemple avec mysql_get_host_info
  • Example#1797 - Exemple avec mysql_get_proto_info
  • Example#1798 - Exemple avec mysql_get_server_info
  • Example#1799 - Requêtes MySQL
  • Example#1800 - Exemple avec mysql_insert_id
  • Example#1801 - Exemple avec mysql_list_dbs
  • Example#1802 - Exemple d'alternative à mysql_list_fields
  • Example#1803 - Exemple avec mysql_list_processes
  • Example#1804 - Exemple d'alternative à mysql_list_tables
  • Example#1805 - Exemple avec mysql_num_fields
  • Example#1806 - Exemple avec mysql_num_rows
  • Example#1807 - Exemple avec mysql_ping
  • Example#1808 - Requête invalide
  • Example#1809 - Requête valide
  • Example#1810 - Exemple simple avec mysql_real_escape_string
  • Example#1811 - Exemple avec mysql_real_escape_string et la nécessité de la présence d'une connexion
  • Example#1812 - Un exemple d'attaque par injection SQL
  • Example#1813 - Exemple avec mysql_result
  • Example#1814 - Exemple avec mysql_select_db
  • Example#1815 - Exemple avec mysql_stat
  • Example#1816 - Exemple alternatif pour mysql_stat
  • Example#1817 - Exemple avec mysql_tablename
  • Example#1818 - Exemple avec mysql_thread_id
  • Example#1819 - Requête simple
  • Example#1820 - Insertion de données en utilisant des variables liées
  • Example#1821 - Liage d'une clause WHERE d'une requête
  • Example#1822 - Insertion de données dans une colonne CLOB
  • Example#1823 - Utilisation d'une procédure stockée PL/SQL
  • Example#1824 - Utilisation d'une procédure stockée PL/SQL
  • Example#1825 - Appel d'une fonction PL/SQL qui retourne un REF CURSOR
  • Example#1826 -
  • Example#1827 - user_oci8_probes.d pour suivre toutes les découvertes statiques au niveau utilisation PHP OCI8 avec DTrace
  • Example#1828 - Exemple avec oci_bind_array_by_name
  • Example#1829 - Insertion de données avec la fonction oci_bind_by_name
  • Example#1830 - Une association avec de multiples appels
  • Example#1831 - Association avec une boucle foreach
  • Example#1832 - Association dans une clause WHERE
  • Example#1833 - Association avec une clause LIKE
  • Example#1834 - Association avec REGEXP_LIKE
  • Example#1835 - Association de plusieurs valeurs dans une clause IN
  • Example#1836 - Association d'un ROWID retourné par une requête
  • Example#1837 - Association d'un ROWID dans un INSERT
  • Example#1838 - Association pour une fonction stockée PL/SQL
  • Example#1839 - Association de paramètres à une procédure stockée PL/SQL
  • Example#1840 - Association sur une colonne CLOB
  • Example#1841 - Association sur un booléen dans un script PL/SQL
  • Example#1842 - Exemple avec oci_client_version
  • Example#1843 - Fermeture d'une connexion
  • Example#1844 - Les connexions à la base de données sont fermées à partir du moment où les références le sont
  • Example#1845 - Fermeture d'un connexion ouverte plus d'une fois
  • Example#1846 - Les connexions sont fermées lorsque les variables sortent du contexte
  • Example#1847 - Exemple avec oci_commit
  • Example#1848 - Exemple avec oci_connect en utilisant la syntaxe simplifiée
  • Example#1849 - Exemple avec oci_connect en utilisant un nom de connexion réseau
  • Example#1850 - Exemple avec oci_connect en utilisant un jeu de caractère spécifique
  • Example#1851 - Exemple avec plusieurs appels à la fonction oci_connect
  • Example#1852 - Exemple avec oci_define_by_name
  • Example#1853 - Exemple avec oci_define_by_name et des noms de colonne sensibles à la casse
  • Example#1854 - Exemple avec oci_define_by_name et des colonnes de type LOB
  • Example#1855 - Exemple avec oci_define_by_name et un type explicite
  • Example#1856 - Exemple d'affichage d'un message d'erreur Oracle après une erreur de connexion
  • Example#1857 - Exemple d'affichage d'un message d'erreur Oracle après une erreur d'analyse
  • Example#1858 - Exemple d'affichage d'un message d'erreur Oracle après une erreur d'exécution rencontré dans une requête SQL
  • Example#1859 - Exemple avec oci_execute pour des requêtes
  • Example#1860 - Exemple avec oci_execute sans spécifier de mode
  • Example#1861 - Exemple avec oci_execute et OCI_NO_AUTO_COMMIT
  • Example#1862 - Exemple avec oci_execute et différents modes dans le même script
  • Example#1863 - Exemple avec oci_execute et OCI_DESCRIBE_ONLY
  • Example#1864 - Exemple avec oci_fetch_all
  • Example#1865 - Exemple avec oci_fetch_all et OCI_FETCHSTATEMENT_BY_ROW
  • Example#1866 - Exemple avec oci_fetch_all et OCI_NUM
  • Example#1867 - Exemple avec oci_fetch_array avec OCI_BOTH
  • Example#1868 - Exemple avec oci_fetch_array avec OCI_NUM
  • Example#1869 - Exemple avec oci_fetch_array avec OCI_ASSOC
  • Example#1870 - Exemple avec oci_fetch_array avec OCI_RETURN_NULLS
  • Example#1871 - oci_fetch_array with OCI_RETURN_LOBS
  • Example#1872 - Exemple avec oci_fetch_array avec des noms de colonnes sensibles à la casse
  • Example#1873 - Exemple avec oci_fetch_array avec des colonnes possédant des noms dupliqués
  • Example#1874 - Exemple avec oci_fetch_array et des colonnes DATE
  • Example#1875 - Exemple avec oci_fetch_array et REF CURSOR
  • Example#1876 - Pagination avec oci_fetch_array en utilisant une requête utilisant le paramètre LIMIT
  • Example#1877 - Exemple avec oci_fetch_array avec Oracle Database
  • Example#1878 - Exemple avec oci_fetch_assoc
  • Example#1879 - Exemple avec oci_fetch_object
  • Example#1880 - Exemple avec oci_fetch_object avec des noms de colonne sensibles à la casse
  • Example#1881 - Exemple avec oci_fetch_object avec des LOBs
  • Example#1882 - Exemple avec oci_fetch_row
  • Example#1883 - Exemple avec oci_fetch avec des variables définies
  • Example#1884 - Exemple avec oci_fetch et oci_result
  • Example#1885 - Exemple avec oci_field_name
  • Example#1886 - Exemple avec oci_field_name
  • Example#1887 - Exemple avec oci_field_precision
  • Example#1888 - Exemple avec oci_field_scale
  • Example#1889 - Exemple avec oci_field_size
  • Example#1890 - Exemple avec oci_field_type_raw
  • Example#1891 - Exemple avec oci_field_type
  • Example#1892 - Récupèration des jeux de résultats implicites via une boucle
  • Example#1893 - Récupère individuellement les gestionnaires de requêtes fils
  • Example#1894 - Définission explicite du compteur de pré-récupération
  • Example#1895 - Exemple de jeu de résultats implicite sans utiliser la fonction oci_get_implicit_resultset
  • Example#1896 - Exemple avec oci_new_connect
  • Example#1897 - Utiliser un REF CURSOR issu d'une procédure enregistrée
  • Example#1898 - Exemple avec oci_new_descriptor
  • Example#1899 - Exemple avec oci_new_descriptor
  • Example#1900 - Exemple avec oci_num_fields
  • Example#1901 - Exemple avec oci_num_rows
  • Example#1902 - Exemple avec oci_parse
  • Example#1903 - Exemple avec oci_parse et une requête PL/SQL
  • Example#1904 - Exemple avec oci_password_change pour changer le mot de passe d'un utilisateur déjà connecté
  • Example#1905 - Exemple avec oci_password_change pour se connecter et changer le mot de passe en une seule étape
  • Example#1906 - Exemple avec oci_pconnect
  • Example#1907 - Exemple avec oci_fetch et oci_result
  • Example#1908 - Exemple avec oci_rollback
  • Example#1909 - Exemple de retour à un point de sauvegarde (SAVEPOINT)
  • Example#1910 - Exemple avec oci_server_version
  • Example#1911 - Définition d'une action
  • Example#1912 - Setting the timeout
  • Example#1913 - Définit l'identifiant du client comme l'utilisateur de l'application
  • Example#1914 - Définit l'information sur le client
  • Example#1915 - Setting the DBOP
  • Example#1916 - 2 scripts peuvent utiliser différentes versions de myfunc() au même moment
  • Example#1917 - Définition du nom du module
  • Example#1918 - Changing the LOB prefetch value for a query
  • Example#1919 - Modification de la valeur de préchargement pour une requête
  • Example#1920 - Modification de la valeur de préchargement pour une récupération REF CURSOR
  • Example#1921 - Définition de la valeur de préchargement lorsque l'on retourne un curseur REF CURSOR à Oracle
  • Example#1922 - Exemple avec oci_statement_type
  • Example#1923 - Exemple général de l'extension PostgreSQL
  • Example#1924 - Exemple de fonctions PostgreSQL définies par l'utilisateur
  • Example#1925 - Exemple avec pg_affected_rows
  • Example#1926 - Exemple avec pg_cancel_query
  • Example#1927 - Exemple avec pg_client_encoding
  • Example#1928 - Exemple avec pg_close
  • Example#1929 - Exemple avec pg_connect
  • Example#1930 - Exemple avec pg_connection_busy
  • Example#1931 - Exemple avec pg_connection_reset
  • Example#1932 - Exemple avec pg_connection_status
  • Example#1933 - Exemple avec pg_convert
  • Example#1934 - Exemple avec pg_copy_from
  • Example#1935 - Exemple avec pg_copy_to
  • Example#1936 - Exemple avec pg_dbname
  • Example#1937 - Exemple avec pg_delete
  • Example#1938 - Exemple avec pg_end_copy
  • Example#1939 - Exemple avec pg_escape_bytea
  • Example#1940 - Exemple avec pg_escape_identifier
  • Example#1941 - Exemple avec pg_escape_literal
  • Example#1942 - Exemple avec pg_escape_string
  • Example#1943 - Exemple avec pg_execute
  • Example#1944 - Exemple avec pg_fetch_all_columns
  • Example#1945 - Exemple avec pg_fetch_all
  • Example#1946 - Exemple avec pg_fetch_array
  • Example#1947 - Exemple avec pg_fetch_assoc
  • Example#1948 - Exemple avec pg_fetch_object
  • Example#1949 - Exemple avec pg_fetch_result
  • Example#1950 - Exemple avec pg_fetch_row
  • Example#1951 - Exemple avec pg_field_is_null
  • Example#1952 - Récupération d'informations des champs
  • Example#1953 - Récupération d'informations des champs
  • Example#1954 - Récupération d'informations à propos des champs
  • Example#1955 - Récupération d'informations des champs
  • Example#1956 - Récupération des informations d'une table à partir d'un champ
  • Example#1957 - Récupération d'informations des champs
  • Example#1958 - Récupération d'informations des champs
  • Example#1959 - Exemple avec pg_free_result
  • Example#1960 - Exemple avec pg_get_notify
  • Example#1961 - Exemple avec pg_get_pid
  • Example#1962 - Exemple avec pg_get_result
  • Example#1963 - Exemple avec pg_host
  • Example#1964 - Exemple avec pg_insert
  • Example#1965 - Exemple avec pg_last_error
  • Example#1966 - Exemple avec pg_last_notice
  • Example#1967 - Exemple avec pg_last_oid
  • Example#1968 - Exemple avec pg_lo_close
  • Example#1969 - Exemple avec pg_lo_create
  • Example#1970 - Exemple avec pg_lo_export
  • Example#1971 - Exemple avec pg_lo_import
  • Example#1972 - Exemple avec pg_lo_open
  • Example#1973 - Exemple avec pg_lo_read_all
  • Example#1974 - Exemple avec pg_lo_read
  • Example#1975 - Exemple avec pg_lo_seek
  • Example#1976 - Exemple avec pg_lo_tell
  • Example#1977 - Exemple avec pg_lo_truncate
  • Example#1978 - Exemple avec pg_lo_unlink
  • Example#1979 - Exemple avec pg_lo_write
  • Example#1980 - Récupération des métadonnées d'une table
  • Example#1981 - Exemple avec pg_num_fields
  • Example#1982 - Exemple avec pg_num_rows
  • Example#1983 - Exemple avec pg_options
  • Example#1984 - Exemple avec pg_parameter_status
  • Example#1985 - Exemple avec pg_pconnect
  • Example#1986 - Exemple avec pg_ping
  • Example#1987 - Exemple avec pg_port
  • Example#1988 - Exemple avec pg_prepare
  • Example#1989 - Exemple avec pg_put_line
  • Example#1990 - Exemple avec pg_query_params
  • Example#1991 - Exemple avec pg_query
  • Example#1992 - Utilisation de pg_query avec plusieurs requêtes
  • Example#1993 - Exemple avec pg_result_error_field
  • Example#1994 - Exemple avec pg_result_error
  • Example#1995 - Exemple avec pg_result_seek
  • Example#1996 - Exemple avec pg_result_status
  • Example#1997 - Exemple avec pg_select
  • Example#1998 - Exemple avec pg_send_execute
  • Example#1999 - Exemple pg_send_prepare
  • Example#2000 - Exemple avec pg_send_query_params
  • Example#2001 - Exemple avec pg_send_query
  • Example#2002 - Exemple avec pg_set_client_encoding
  • Example#2003 - pg_set_error_context_visibility exemple
  • Example#2004 - Exemple avec pg_set_error_verbosity
  • Example#2005 - Exemple avec pg_trace
  • Example#2006 - Exemple avec pg_transaction_status
  • Example#2007 - Exemple avec pg_tty
  • Example#2008 - Exemple avec pg_unescape_bytea
  • Example#2009 - Exemple avec pg_untrace
  • Example#2010 - Exemple avec pg_update
  • Example#2011 - Exemple avec pg_version
  • Example#2012 - Backup an existing database
  • Example#2013 - Exemple avec SQLite3::changes
  • Example#2014 - Exemple avec SQLite3::close
  • Example#2015 - Exemple avec SQLite3::__construct
  • Example#2016 - Exemple d'une fonction d'agrégation avec max_length
  • Example#2017 - Exemple avec SQLite3::createCollation
  • Example#2018 - Exemple avec SQLite3::createFunction
  • Example#2019 - Exemple avec SQLite3::enableExceptions
  • Example#2020 - Exemple avec SQLite3::exec
  • Example#2021 - Exemple avec SQLite3::loadExtension
  • Example#2022 - Exemple avec SQLite3::open
  • Example#2023 - Exemple avec SQLite3::openBlob
  • Example#2024 - Écrire progressivement un BLOB
  • Example#2025 - Exemple avec SQLite3::prepare
  • Example#2026 - Exemple avec SQLite3::query
  • Example#2027 - Exemple avec SQLite3::querySingle
  • Example#2028 - SQLite3::setAuthorizer example
  • Example#2029 - Exemple avec SQLite3::version
  • Example#2030 - Utilisation de SQLite3Stmt::bindParam
  • Example#2031 - Exemple avec SQLite3Stmt::bindValue
  • Example#2032 - Inspecter le SQL étendue
  • Example#2033 - Exemple avec sqlsrv_begin_transaction
  • Example#2034 - Exemple avec sqlsrv_cancel
  • Example#2035 - Exemple avec sqlsrv_client_info
  • Example#2036 - Exemple avec sqlsrv_close
  • Example#2037 - Exemple avec sqlsrv_commit
  • Example#2038 - Connexion en utilisant l'authentification Windows.
  • Example#2039 - Connexion en spécifiant un nom d'utilisateur et un mot de passe.
  • Example#2040 - Connexion sur un port spécifique.
  • Example#2041 - Exemple avec functionname
  • Example#2042 - Exemple avec sqlsrv_execute
  • Example#2043 - Récupération d'un tableau associatif
  • Example#2044 - Récupération d'un tableau numérique
  • Example#2045 - Exemple avec sqlsrv_fetch_object
  • Example#2046 - Exemple avec sqlsrv_fetch
  • Example#2047 - Exemple avec sqlsrv_field_metadata
  • Example#2048 - Exemple avec sqlsrv_free_stmt
  • Example#2049 - sqlsrv_get_field example
  • Example#2050 - Exemple avec sqlsrv_has_rows
  • Example#2051 - Exemple avec sqlsrv_next_result
  • Example#2052 - Exemple avec sqlsrv_num_fields
  • Example#2053 - Exemple avec sqlsrv_num_rows
  • Example#2054 - Exemple avec sqlsrv_prepare
  • Example#2055 - sqlsrv_query example
  • Example#2056 - Exemple avec sqlsrv_rollback
  • Example#2057 - Exemple avec sqlsrv_rows_affected
  • Example#2058 - Exemple avec sqlsrv_send_stream_data
  • Example#2059 - Exemple avec sqlsrv_server_info
  • Example#2060 - Exemple avec cal_days_in_month
  • Example#2061 - Exemple avec cal_from_jd
  • Example#2062 - Exemple avec cal_info
  • Example#2063 - Exemple avec easter_date
  • Example#2064 - Utilisation de easter_date avec DateTime
  • Example#2065 - Exemple avec easter_days
  • Example#2066 - Fonctions calendrier
  • Example#2067 - Comportement de débordement
  • Example#2068 - Exemple avec jdtojewish
  • Example#2069 - DateTimeImmutable::add/sub ajout d'un interval de temps écoulé.
  • Example#2070 - DateTimeImmutable::modify et strtotime incrémentation ou décrémentation de valeurs individuelles
  • Example#2071 - L'ajout ou la soustraction de dates/heures peut dépasser (en plus ou en moins) des dates
  • Example#2072 - Créer un objet de date et temps mutable
  • Example#2073 - Création d'un objet de date et temps mutable
  • Example#2074 - Exemple avec DateTime::modify
  • Example#2075 - Méfiez-vous lors de l'ajout ou la soustraction de mois
  • Example#2076 - Tous les formats de date et d'heure sont pris en charge
  • Example#2077 - Exemple avec DateTime::setTimeZone
  • Example#2078 - Exemple de DateTimeImmutable::add
  • Example#2079 - Exemples supplémentaires de DateTimeImmutable::add
  • Example#2080 - Faire attention lors de l'ajout de mois
  • Example#2081 - Exemple de DateTimeImmutable::__construct
  • Example#2082 - Intricacies of DateTimeImmutable::__construct
  • Example#2083 - Changement du fuseau horaire associé
  • Example#2084 - Utilisation d'une chaîne de date/heure relative
  • Example#2085 - Exemple avec DateTimeImmutable::createFromFormat
  • Example#2086 - Utilisation des constantes de format prédéfinies avec DateTimeImmutable::createFromFormat
  • Example#2087 - Les subtilités de DateTimeImmutable::createFromFormat
  • Example#2088 - Texte de Format avec des caractères litéraux
  • Example#2089 - Comportement de débordement
  • Example#2090 - Comportement pour le nom de jour débordant
  • Example#2091 - Détecter les dates dépassées
  • Example#2092 - Comportement d'analyse gourmand
  • Example#2093 - Création d'un objet de date et temps immutable
  • Example#2094 - Création d'un objet date temps immutable
  • Example#2095 - Exemple de DateTimeImmutable::getLastErrors
  • Example#2096 - Exemple de DateTimeImmutable::modify
  • Example#2097 - Faire attention lors de l'ajout ou soustraction de mois
  • Example#2098 - Exemple de DateTimeImmutable::setDate
  • Example#2099 - Les valeurs excédant la plage sont ajouté à leur valeur parente
  • Example#2100 - Exemple de DateTimeImmutable::setISODate
  • Example#2101 - Les valeurs excédant la plage sont ajouté à leur valeur parente
  • Example#2102 - Trouver le mois dont une semaine se trouve
  • Example#2103 - Exemple de DateTimeImmutable::setTime
  • Example#2104 - Values exceeding ranges are added to their parent values
  • Example#2105 - Exemple de DateTimeImmutable::setTimestamp
  • Example#2106 - Exemple de DateTimeImmutable::setTimeZone
  • Example#2107 - Exemple de DateTimeImmutable::sub
  • Example#2108 - Exemples supplémentaires de DateTimeImmutable::sub
  • Example#2109 - Faire attention lors de la soustraction de mois
  • Example#2110 - Exemple avec DateTimeImmutable::diff
  • Example#2111 - DateTimeInterface::diff lors du passage à l'heure d'été
  • Example#2112 - Calcul d'intervalle avec DateTimeInterface::diff
  • Example#2113 - Comparaison de deux objets DateTime
  • Example#2114 - Exemple avec DateTime::format
  • Example#2115 - Plus d'exemples
  • Example#2116 - Échappement de caractères lors du formatage
  • Example#2117 - Exemple avec DateTime::getOffset
  • Example#2118 - Exemple avec DateTime::getTimestamp
  • Example#2119 - Récupération de l'horodatage avec une précision en millisecondes et microsecondes
  • Example#2120 - Exemple avec DateTime::getTimezone
  • Example#2121 - Creating and attaching DateTimeZone to a DateTimeImmutable
  • Example#2122 - Interception des erreurs avec DateTimeZone
  • Example#2123 - Exemple avec DateTimeZone::getLocation
  • Example#2124 - Exemple avec DateTimeZone::getOffset
  • Example#2125 - Exemple avec timezone_transitions_get
  • Example#2126 - Un exemple de timezone_transitions_get avec timestampBegin défini
  • Example#2127 - Exemple avec timezone_abbreviations_list
  • Example#2128 - Exemple avec DateTimeZone::listIdentifiers
  • Example#2129 - Listing identifiers for a specific region
  • Example#2130 - Lister les identifiants de plusieurs régions
  • Example#2131 - Lister les identifiants d'un seul pays
  • Example#2132 - Construction et utilisation des objets DateInterval
  • Example#2133 - Exemple avec DateInterval
  • Example#2134 - Analyse d'intervalles de dates valides
  • Example#2135 - Parsing combinations and negative intervals
  • Example#2136 - Analyse des combinaisons et des intervalles négatifs
  • Example#2137 - Exemple avec DateInterval
  • Example#2138 - DateInterval et retenue
  • Example#2139 - DateInterval et DateTime::diff avec les modificateurs %a et %d
  • Example#2140 -
  • Example#2141 - Exemple avec DatePeriod
  • Example#2142 - Exemple avec DatePeriod et DatePeriod::EXCLUDE_START_DATE
  • Example#2143 - DatePeriod montrant tous les derniers jeudis du mois sur une année
  • Example#2144 - DatePeriod::createFromISO8601String example
  • Example#2145 - Exemple avec DatePeriod::getDateInterval
  • Example#2146 - Exemples avec DatePeriod::getEndDate
  • Example#2147 - DatePeriod::getEndDate sans date de fin
  • Example#2148 - Valeurs différentes pour DatePeriod::getRecurrences
  • Example#2149 - Exemple DatePeriod::getStartDate
  • Example#2150 - Exemple avec checkdate
  • Example#2151 - Récupération du décalage horaire par défaut
  • Example#2152 - Récupération de l'abréviation d'un décalage horaire
  • Example#2153 - Récupération du décalage horaire par défaut
  • Example#2154 - Exemple avec date_parse_from_format
  • Example#2155 - Exemple de date_parse_from_format avec des warnings (avertissements)
  • Example#2156 - Exemple de date_parse_from_format avec des errors (erreurs)
  • Example#2157 - date_parse avec une chaîne datetime complète
  • Example#2158 - date_parse avec des informations abrégé sur le fuseau horaire
  • Example#2159 - date_parse avec des informations abrégé sur le fuseau horaire
  • Example#2160 - date_parse avec une chaîne minimale
  • Example#2161 - Exemple avec date_parse et des formats relatifs
  • Example#2162 - date_parse avec des effets secondaires
  • Example#2163 - Exemple avec date_sun_info
  • Example#2164 - Nuit polaire avec un peu de traitement
  • Example#2165 - Soleil de minuit (Tromso, Norvège)
  • Example#2166 - Calcul de la durée du jour (Kyiv)
  • Example#2167 - Exemple avec date_sunrise
  • Example#2168 - Pas de levé de soleil
  • Example#2169 - Exemple avec date_sunset
  • Example#2170 - Pas de coucher du soleil
  • Example#2171 - Exemple avec date
  • Example#2172 - Protection des caractères dans la fonction date
  • Example#2173 - Exemple avec date et mktime
  • Example#2174 - Exemple avec date
  • Example#2175 - Exemple avec getdate
  • Example#2176 - Exemple avec gettimeofday
  • Example#2177 - Exemple avec gmdate
  • Example#2178 - Exemple avec gmmktime
  • Example#2179 - Exemple avec gmstrftime
  • Example#2180 - Exemple avec idate
  • Example#2181 - Exemple avec localtime
  • Example#2182 - Durée d'exécution d'un script en PHP
  • Example#2183 - Exemple avec microtime et REQUEST_TIME_FLOAT
  • Example#2184 - Exemple simple avec mktime
  • Example#2185 - Exemple avec mktime
  • Example#2186 - Dernier jour d'un mois
  • Example#2187 - Exemple avec strftime
  • Example#2188 - Exemple au format de date ISO 8601:1988
  • Example#2189 - %e fonctionnant sous toute plateforme
  • Example#2190 - Affiche tous les formats connus ou non.
  • Example#2191 - Exemple avec strptime
  • Example#2192 - Exemple avec strtotime
  • Example#2193 - Vérification d'erreur
  • Example#2194 - Exemple avec time
  • Example#2195 - Exemple avec timezone_name_from_abbr
  • Example#2196 - Lecture de la version de la timezonedb
  • Example#2197 -
  • Example#2198 -
  • Example#2199 - Mesure l'exécution de différents blocs et retourne le total
  • Example#2200 - Fermeture d'une ressource de fichier
  • Example#2201 - Positionnement et suppression d'un verrou
  • Example#2202 - Ouverture d'un fichier
  • Example#2203 - Positionnement dans un fichier
  • Example#2204 - Définition du débit des bauds sur un port série
  • Example#2205 - Exemple avec chdir
  • Example#2206 - Exemple avec chroot
  • Example#2207 - Exemple avec closedir
  • Example#2208 - Exemple avec dir
  • Example#2209 - Exemple avec getcwd
  • Example#2210 - Exemple avec opendir
  • Example#2211 - Liste de toutes les entrées d'un dossier
  • Example#2212 - Liste toutes les entrées du dossier courant et enlève les . et ..
  • Example#2213 - Un simple exemple avec scandir
  • Example#2214 - Exemple avec finfo_buffer
  • Example#2215 - Exemple avec finfo_file
  • Example#2216 - Style orienté objet
  • Example#2217 - Style procédural
  • Example#2218 - Exemple avec mime_content_type
  • Example#2219 - Exemple avec basename
  • Example#2220 - Modification de groupe d'un fichier
  • Example#2221 - Exemple avec chown
  • Example#2222 - Exemple avec clearstatcache
  • Example#2223 - Exemple avec copy
  • Example#2224 - Exemple avec dirname
  • Example#2225 - Exemple avec disk_free_space
  • Example#2226 - Exemple avec disk_total_space
  • Example#2227 - Exemple avec fclose
  • Example#2228 - fdatasync example
  • Example#2229 - Gestion des délais d'attente dépassés feof
  • Example#2230 - Exemple avec feof et un pointeur de fichier invalide
  • Example#2231 - Écriture d'un fichier en utilisant fflush
  • Example#2232 - Exemple avec fgetc
  • Example#2233 - Lit et affiche le contenu d'un fichier CSV
  • Example#2234 - Lecture d'un fichier ligne par ligne
  • Example#2235 - Lecture d'un fichier PHP ligne par ligne
  • Example#2236 - Teste l'existence d'un fichier
  • Example#2237 - Lit et affiche le code HTML d'un site Web
  • Example#2238 - Recherche un fichier dans le include_path
  • Example#2239 - Lit une section d'un fichier
  • Example#2240 - Utilisation des contextes de flux
  • Example#2241 - Utilisation simple de file_put_contents
  • Example#2242 - Utilisation d'options pour file_put_contents
  • Example#2243 - Exemple avec file
  • Example#2244 - Exemple avec fileatime
  • Example#2245 - Exemple avec filectime
  • Example#2246 - Recherche le groupe d'un fichier
  • Example#2247 - Comparaison de l'inode d'un fichier avec le fichier courant
  • Example#2248 - Exemple avec filemtime
  • Example#2249 - Recherche du propriétaire d'un fichier
  • Example#2250 - Affichage des droits en valeur octale
  • Example#2251 - Affichage de tous les droits
  • Example#2252 - Exemple avec filesize
  • Example#2253 - Exemple avec filetype
  • Example#2254 - Exemple avec flock
  • Example#2255 - Exemple avec flock en utilisant l'option LOCK_NB
  • Example#2256 - Vérifier le nom d'une couleur avec un masque Shell
  • Example#2257 - Exemple avec fopen
  • Example#2258 - Utilisation de fpassthru avec un fichier binaire
  • Example#2259 - Exemple avec fputcsv
  • Example#2260 - Exemple avec fread
  • Example#2261 - Exemple avec fread et un fichier binaire
  • Example#2262 - Exemple avec fread et un fichier distant
  • Example#2263 - Exemple avec fscanf
  • Example#2264 - Contenu du fichier users.txt
  • Example#2265 - Exemple avec fseek
  • Example#2266 - Exemple avec fstat
  • Example#2267 - fsync example
  • Example#2268 - Exemple avec ftell
  • Example#2269 - Exemple avec ftruncate
  • Example#2270 - Exemple avec fwrite
  • Example#2271 - Un moyen pratique pour remplacer opendir par glob
  • Example#2272 - Exemple avec is_dir
  • Example#2273 - Exemple avec is_executable
  • Example#2274 - Exemple avec is_file
  • Example#2275 - Création et vérification d'un lien symbolique
  • Example#2276 - Exemple avec is_readable
  • Example#2277 - Exemple avec is_uploaded_file
  • Example#2278 - Exemple avec is_writable
  • Example#2279 - Modification du groupe d'un lien symbolique
  • Example#2280 - Modification du propriétaire d'un lien symbolique
  • Example#2281 - Création d'un lien
  • Example#2282 - Exemple avec linkinfo
  • Example#2283 - Comparaison entre stat et lstat
  • Example#2284 - Exemple avec mkdir
  • Example#2285 - mkdir utilisant le paramètre recursive
  • Example#2286 - Téléchargement de plusieurs fichiers
  • Example#2287 - Contenu du fichier sample.ini
  • Example#2288 - Exemple avec parse_ini_file
  • Example#2289 - parse_ini_file pour analyser un fichier php.ini
  • Example#2290 - Interpolation de Valeur
  • Example#2291 - Échapper des Caractères
  • Example#2292 - Exemple avec pathinfo
  • Example#2293 - Exemple pathinfo sans extension
  • Example#2294 - Exemple avec pathinfo
  • Example#2295 - Exemple de pathinfo avec déréférencement de tableau
  • Example#2296 - Exemple avec pclose
  • Example#2297 - Exemple avec popen
  • Example#2298 - Exemple avec popen
  • Example#2299 - Forcer le téléchargement en utilisant readfile
  • Example#2300 - Exemple avec readlink
  • Example#2301 - Exemple avec realpath_cache_get
  • Example#2302 - Exemple avec realpath_cache_size
  • Example#2303 - Exemple avec realpath
  • Example#2304 - Exemple avec realpath sous Windows
  • Example#2305 - Exemple avec rename
  • Example#2306 - Exemple avec rewind
  • Example#2307 - Exemple avec rmdir
  • Example#2308 - Exemple avec stat
  • Example#2309 - Utilisation des informations issues de stat conjointement avec la fonction touch
  • Example#2310 - Création d'un lien symbolique
  • Example#2311 - Exemple avec tempnam
  • Example#2312 - Exemple avec tmpfile
  • Example#2313 - Exemple avec touch
  • Example#2314 - Exemple avec touch en utilisant le paramètre mtime
  • Example#2315 - Exemple avec umask
  • Example#2316 - Exemple avec unlink
  • Example#2317 - Exemple d'utilisatio d'inotify
  • Example#2318 - Vérifie si l'administrateur système a signé le fichier
  • Example#2319 - Affiche les noms de tous les attributs étendus d'un fichier
  • Example#2320 - Efface tous les attributs étendus d'un fichier
  • Example#2321 - Définition des attributs étendus dans un fichier .wav
  • Example#2322 - Exemple avec xattr_supported
  • Example#2323 - Exemple avec xdiff_file_bdiff_size
  • Example#2324 - Exemple avec xdiff_file_bdiff
  • Example#2325 - Exemple avec xdiff_file_bpatch
  • Example#2326 - Exemple avec xdiff_file_diff_binary
  • Example#2327 - Exemple avec xdiff_file_diff
  • Example#2328 - Exemple avec xdiff_file_merge3
  • Example#2329 - Exemple avec xdiff_file_patch_binary
  • Example#2330 - Exemple avec xdiff_file_patch
  • Example#2331 - Exemple de retour à l'état initial après l'application d'un patch
  • Example#2332 - Exemple avec xdiff_file_rabdiff
  • Example#2333 - Exemple avec xdiff_string_bdiff_size
  • Example#2334 - Exemple avec xdiff_string_diff
  • Example#2335 - Exemple avec xdiff_string_patch
  • Example#2336 - Exemple d'utilisation d'Enchant
  • Example#2337 - Liste les interfaces fournies par un sponsor donné
  • Example#2338 - Exemple avec enchant_broker_dict_exists
  • Example#2339 - Liste tous les dictionnaires disponibles pour un sponsor
  • Example#2340 - Exemple avec enchant_broker_request_dict
  • Example#2341 - Ajout d'un mot à un PWL
  • Example#2342 - Exemple avec enchant_dict_describe
  • Example#2343 - Exemple avec enchant_dict_quick_check
  • Example#2344 - Exemple avec enchant_dict_suggest
  • Example#2345 - Exemple d'utilisation
  • Example#2346 - Exemple avec Gender\Gender::country
  • Example#2347 - Exemple avec bindtextdomain
  • Example#2348 - Exemple avec gettext
  • Example#2349 - Exemple avec ngettext
  • Example#2350 - Exemple avec iconv_get_encoding
  • Example#2351 - Exemple avec iconv_mime_decode_headers
  • Example#2352 - Exemple avec iconv_mime_decode
  • Example#2353 - Exemple avec iconv_mime_encode
  • Example#2354 - Exemple avec iconv_set_encoding
  • Example#2355 - Exemple avec iconv
  • Example#2356 - Exemple avec ob_iconv_handler
  • Example#2357 - Exemple d'API procédurale pour intl
  • Example#2358 - Exemple d'API orientée objet pour intl
  • Example#2359 - Règles de FRENCH_COLLATION
  • Example#2360 - Règles ALTERNATE_HANDLING
  • Example#2361 - Règles CASE_FIRST
  • Example#2362 - Règles CASE_LEVEL
  • Example#2363 - Exemple avec collator_asort
  • Example#2364 - Exemple avec collator_compare
  • Example#2365 - Comparer des chaînes sans diacritique ou sensibilité à la casse
  • Example#2366 - Exemple avec Collator::__construct
  • Example#2367 - Exmple avec collator_create
  • Example#2368 - Exemple avec collator_get_attribute
  • Example#2369 - Exemple avec collator_get_error_code
  • Example#2370 - Exemple avec collator_get_error_message
  • Example#2371 - Exemple avec collator_get_locale
  • Example#2372 - Exemple collator_get_sort_key
  • Example#2373 - Exemple avec collator_get_strength
  • Example#2374 - Exemple avec collator_set_attribute
  • Example#2375 - Exemple avec collator_set_strength
  • Example#2376 - Exemple avec collator_sort_with_sort_keys
  • Example#2377 - Exemple avec collator_sort
  • Example#2378 - Exemple avec numfmt_create::create, Style procédural
  • Example#2379 - Exemple avec numfmt_create::create, style POO
  • Example#2380 - Exemple avec numfmt_format_currency, Style procédural
  • Example#2381 - Exemple avec numfmt_format_currency, style POO
  • Example#2382 - Exemple avec numfmt_format, Style procédural
  • Example#2383 - Exemple avec numfmt_format, style POO
  • Example#2384 - Exemple avec numfmt_get_attribute, Style procédural
  • Example#2385 - Exemple avec numfmt_get_attribute, style POO
  • Example#2386 - Exemple avec numfmt_get_error_code, Style procédural
  • Example#2387 - Exemple avec numfmt_get_error_code, style POO
  • Example#2388 - Exemple avec numfmt_get_error_message, Style procédural
  • Example#2389 - Exemple avec numfmt_get_error_code, style POO
  • Example#2390 - Exemple avec numfmt_get_error_code, Style procédural
  • Example#2391 - Exemple avec numfmt_get_pattern, Style procédural
  • Example#2392 - Exemple avec numfmt_get_pattern, style POO
  • Example#2393 - Exemple avec numfmt_get_symbol, Style procédural
  • Example#2394 - Exemple avec numfmt_get_symbol, style POO
  • Example#2395 - Exemple avec numfmt_get_text_attribute, Style procédural
  • Example#2396 - Exemple avec numfmt_get_text_attribute, style POO
  • Example#2397 - Exemple avec numfmt_parse_currency, Style procédural
  • Example#2398 - Exemple avec numfmt_parse_currency, Style procédural
  • Example#2399 - Exemple avec numfmt_parse, Style procédural
  • Example#2400 - Exemple avec numfmt_parse, style POO
  • Example#2401 - Exemple avec numfmt_set_attribute, Style procédural
  • Example#2402 - Exemple avec numfmt_set_attribute, style POO
  • Example#2403 - Exemple avec numfmt_set_pattern, Style procédural
  • Example#2404 - Exemple avec numfmt_set_pattern, style POO
  • Example#2405 - Exemple avec numfmt_set_symbol, Style procédural
  • Example#2406 - Exemple avec numfmt_set_symbol, style POO
  • Example#2407 - Exemple avec numfmt_set_text_attribute, Style procédural
  • Example#2408 - Exemple avec numfmt_set_text_attribute, Style procédural
  • Example#2409 - Exemple avec locale_accept_from_http, procédural
  • Example#2410 - Exemple avec locale_accept_from_http, POO
  • Example#2411 - Exemple avec locale_compose, procédural
  • Example#2412 - Exemple avec locale_compose, POO
  • Example#2413 - Limites des Sous-tags
  • Example#2414 - Exemple avec locale_filter_matches, procédural
  • Example#2415 - Exemple avec locale_filter_matches, POO
  • Example#2416 - Exemple avec locale_get_all_variants, procédural
  • Example#2417 - Exemple avec locale_get_all_variants, POO
  • Example#2418 - Exemple avec locale_get_default, procédural
  • Example#2419 - Exemple avec locale_get_default, POO
  • Example#2420 - Exemple avec locale_get_display_language, procédural
  • Example#2421 - Exemple avec locale_get_display_language, POO
  • Example#2422 - Exemple avec locale_get_display_name, procédural
  • Example#2423 - Exemple avec locale_get_display_name, POO
  • Example#2424 - Exemple avec locale_get_display_region, procédural
  • Example#2425 - Exemple avec locale_get_display_region, POO
  • Example#2426 - Exemple avec locale_get_display_script, procédural
  • Example#2427 - Exemple avec locale_get_display_script, POO
  • Example#2428 - Exemple avec locale_get_display_variant, procédural
  • Example#2429 - Exemple avec locale_get_display_variant, POO
  • Example#2430 - Exemple avec locale_get_keywords, procédural
  • Example#2431 - Exemple avec locale_get_keywords, POO
  • Example#2432 - Exemple avec locale_get_primary_language, procédural
  • Example#2433 - Exemple avec locale_get_primary_language, POO
  • Example#2434 - Exemple avec locale_get_region, procédural
  • Example#2435 - Exemple avec locale_get_region, POO
  • Example#2436 - Exemple avec locale_get_script, procédural
  • Example#2437 - Exemple avec locale_get_script, POO
  • Example#2438 - Exemple avec locale_lookup, procédural
  • Example#2439 - Exemple avec Locale::lookup, POO
  • Example#2440 - Exemple avec locale_parse, procédural
  • Example#2441 - Exemple avec locale_parse, POO
  • Example#2442 - Exemple avec locale_set_default, procédural
  • Example#2443 - Exemple avec locale_set_default, POO
  • Example#2444 - Normalizer::getRawDecomposition example
  • Example#2445 - Exemple avec normalizer_is_normalized, en style procédural
  • Example#2446 - Exemple avec normalizer_is_normalized, en style orienté objet
  • Example#2447 - Exemple avec normalizer_normalize, procédural
  • Example#2448 - Exemple avec normalizer_normalize, POO
  • Example#2449 - Exemple avec msgfmt_create, style procédural
  • Example#2450 - Exemple avec msgfmt_create, style procédural
  • Example#2451 - Exemple avec msgfmt_format_message, style procédural
  • Example#2452 - Exemple avec msgfmt_format_message, style procédural
  • Example#2453 - Demander à ICU de formater la devise avec le symbole monétaire commun et avec le symbole monétaire court.
  • Example#2454 - Exemple avec msgfmt_format, style procédural
  • Example#2455 - Exemple avec msgfmt_format, style POO
  • Example#2456 - Exemple avec msgfmt_get_error_message, style procédural
  • Example#2457 - Exemple avec msgfmt_get_error_message, style POO
  • Example#2458 - Exemple avec msgfmt_get_locale, style procédural
  • Example#2459 - Exemple avec msgfmt_get_locale, style POO
  • Example#2460 - Exemple avec msgfmt_get_pattern, style procédural
  • Example#2461 - Exemple avec msgfmt_get_pattern, style POO
  • Example#2462 - Exemple avec msgfmt_parse_message, style procédural
  • Example#2463 - Exemple avec msgfmt_parse_message, style POO
  • Example#2464 - Exemple avec msgfmt_parse, style procédural
  • Example#2465 - Exemple avec msgfmt_parse, style POO
  • Example#2466 - Exemple avec msgfmt_set_pattern, style procédural
  • Example#2467 - Exemple avec msgfmt_set_pattern, style POO
  • Example#2468 - Exemple avec IntlCalendar::add
  • Example#2469 - Exemple avec IntlCalendar::after
  • Example#2470 - Exempe avec IntlCalendar::clear
  • Example#2471 - Exemple avec IntlCalendar::createInstance
  • Example#2472 - Exemple avec IntlCalendar::equals
  • Example#2473 - Exemple avec IntlCalendar::fieldDifference
  • Example#2474 - IntlCalendar::fromDateTime
  • Example#2475 - IntlCalendar::get
  • Example#2476 - IntlCalendar::getActualMaximum
  • Example#2477 - IntlCalendar::getAvailableLocales
  • Example#2478 - IntlCalendar::getDayOfWeekType
  • Example#2479 - IntlCalendar::getErrorCode and IntlCalendar::getErrorMessage
  • Example#2480 - IntlCalendar::getErrorMessage
  • Example#2481 - IntlCalendar::getFirstDayOfWeek
  • Example#2482 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2483 - Maxima examples
  • Example#2484 - IntlCalendar::getLocale
  • Example#2485 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2486 - Exemple avec IntlCalendar::getNow
  • Example#2487 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2488 - IntlCalendar::getSkippedWallTimeOption
  • Example#2489 - IntlCalendar::getTime
  • Example#2490 - Exemple avec IntlCalendar::getTimeZone
  • Example#2491 - Exemple avec IntlCalendar::getType
  • Example#2492 - IntlCalendar::inDaylightTime
  • Example#2493 - IntlCalendar::isEquivalentTo
  • Example#2494 - IntlCalendar::isLenient
  • Example#2495 - IntlCalendar::isWeekend
  • Example#2496 - IntlCalendar::roll
  • Example#2497 - IntlCalendar::set
  • Example#2498 - IntlCalendar::setDate example
  • Example#2499 - IntlCalendar::setDateTime example
  • Example#2500 - Exemple avec IntlCalendar::setFirstDayOfWeek
  • Example#2501 - Exemple avec IntlCalendar::setTime
  • Example#2502 - Exemple avec IntlCalendar::setTimeZone
  • Example#2503 - Exemple avec IntlCalendar::toDateTime
  • Example#2504 - IntlGregorianCalendar::createFromDate example
  • Example#2505 - IntlCalendar::setDateTime example
  • Example#2506 - Exemple avec datefmt_create, procédural
  • Example#2507 - Exemple avec datefmt_create, POO
  • Example#2508 - Exemple de gestion de locale invalide
  • Example#2509 - Exemple avec datefmt_format
  • Example#2510 - Exemple orienté objet
  • Example#2511 - Exemple avec un objet IntlCalendar
  • Example#2512 - Exemple avec IntlDateFormatter::formatObject
  • Example#2513 - Exemple avec datefmt_get_calendar
  • Example#2514 - Exemple orienté objet
  • Example#2515 - Exemple de gestion de locale invalide
  • Example#2516 - Exemple avec datefmt_get_datetype
  • Example#2517 - Exemple orienté objet
  • Example#2518 - Exemple avec datefmt_get_error_code
  • Example#2519 - Exemple orienté objet
  • Example#2520 - Exemple avec datefmt_get_error_message
  • Example#2521 - Exemple orienté objet
  • Example#2522 - Exemple avec datefmt_get_locale
  • Example#2523 - Exemple orienté objet
  • Example#2524 - Exemple avec datefmt_get_pattern
  • Example#2525 - Exemple orienté objet
  • Example#2526 - Exemple avec datefmt_get_timetype
  • Example#2527 - Exemple orienté objet
  • Example#2528 - Exemple avec datefmt_get_timezone_id
  • Example#2529 - Exemple orienté objet
  • Example#2530 - Exemple avec IntlDateFormatter::getCalendarObject
  • Example#2531 - Exemple avec IntlDateFormatter::getTimeZone
  • Example#2532 - Exemple avec datefmt_is_lenient
  • Example#2533 - Exemple orienté objet
  • Example#2534 - Exemple avec datefmt_localtime
  • Example#2535 - Exemple orienté objet
  • Example#2536 - Exemple orienté objet
  • Example#2537 - Exemple avec datefmt_parse
  • Example#2538 - Exemple avec datefmt_set_calendar
  • Example#2539 - Exemple orienté objet
  • Example#2540 - Exemple avec des arguments à IntlCalendar
  • Example#2541 - Exemple avec datefmt_set_lenient
  • Example#2542 - Exemple orienté objet
  • Example#2543 - Exemple avec datefmt_get_pattern
  • Example#2544 - Exemple orienté objet
  • Example#2545 - Exemple avec IntlDateFormatter::setTimeZone
  • Example#2546 - Exemple avec resourcebundle_count
  • Example#2547 - Exemple orienté objet
  • Example#2548 - Exemple avec resourcebundle_create
  • Example#2549 - Exemple avec ResourceBundle::create
  • Example#2550 - Exemple avec resourcebundle_get_error_code
  • Example#2551 - Exemple orienté objet
  • Example#2552 - Exemple avec resourcebundle_get_error_message
  • Example#2553 - Exemple orienté objet
  • Example#2554 - Exemple avec resourcebundle_get
  • Example#2555 - Exemple orienté objet
  • Example#2556 - Exemple avec resourcebundle_locales
  • Example#2557 - Exemple orienté objet
  • Example#2558 - Exemple Spoofchecker::areConfusable
  • Example#2559 - Exemple Spoofchecker::isSuspicious
  • Example#2560 - Récupération des identifiants transliterator enregistrés
  • Example#2561 - Conversion des échappements en unité UTF-16
  • Example#2562 - IntlDatePatternGenerator::getBestPattern example
  • Example#2563 - Conversion de UTF-8 à UTF-16 et inversement
  • Example#2564 - Caractères non valides en entrée
  • Example#2565 - Caractères ne pouvant être encodés
  • Example#2566 - Exemple avec grapheme_extract
  • Example#2567 - Exemple avec grapheme_stripos
  • Example#2568 - Exemple avec grapheme_stristr
  • Example#2569 - Exemple avec grapheme_strlen
  • Example#2570 - Exemple avec grapheme_strpos
  • Example#2571 - Exemple avec grapheme_strripos
  • Example#2572 - Exemple avec grapheme_strrpos
  • Example#2573 - Exemple avec grapheme_strstr
  • Example#2574 - Exemple avec grapheme_substr
  • Example#2575 - Exemple avec idn_to_ascii
  • Example#2576 - Exemple avec idn_to_utf8
  • Example#2577 - Test de différents codepoint
  • Example#2578 - Test de différents codepoint
  • Example#2579 - Test de différents codepoint
  • Example#2580 - Test de différents codepoint
  • Example#2581 - Test de différents codepoint
  • Example#2582 - Test de différents codepoint
  • Example#2583 - Test de différents codepoint
  • Example#2584 - Test de différents codepoint
  • Example#2585 - Test de différents codepoint
  • Example#2586 - Enumerating over a sample range of code points
  • Example#2587 - Enumerating over a sample range of code points
  • Example#2588 - Test de différents codepoint
  • Example#2589 - Test de différents codepoint
  • Example#2590 - Test de différents codepoint
  • Example#2591 - Test de différents codepoint
  • Example#2592 - Test de différents codepoint
  • Example#2593 - Test de différentes propriétés
  • Example#2594 - Test de différentes propriétés
  • Example#2595 - Test de différentes propriétés
  • Example#2596 - Test de différents codepoint
  • Example#2597 - Test de différentes propriétés
  • Example#2598 - Test de différentes propriétés
  • Example#2599 - Test de différentes propriétés
  • Example#2600 - Test de différentes propriétés
  • Example#2601 - Test de différentes propriétés
  • Example#2602 - Test de différentes propriétés
  • Example#2603 - Test de différents codepoint
  • Example#2604 - Test de différents codepoint
  • Example#2605 - Test de différents codepoint
  • Example#2606 - Test de différents codepoint
  • Example#2607 - Test de différents codepoint
  • Example#2608 - Test de différents codepoint
  • Example#2609 - Test de différents codepoint
  • Example#2610 - Test de différents codepoint
  • Example#2611 - Test de différents codepoint
  • Example#2612 - Test de différents codepoint
  • Example#2613 - Test de différents codepoint
  • Example#2614 - Test de différents codepoint
  • Example#2615 - Test de différents codepoint
  • Example#2616 - Test de différents codepoint
  • Example#2617 - Test de différents codepoint
  • Example#2618 - Test de différents codepoint
  • Example#2619 - Test de différents codepoint
  • Example#2620 - Test de différents codepoint
  • Example#2621 - Test de différents codepoint
  • Example#2622 - Test de différents codepoint
  • Example#2623 - Test de différents codepoint
  • Example#2624 - Test de différents codepoint
  • Example#2625 - Test de différents codepoint
  • Example#2626 - Test de différents codepoint
  • Example#2627 - Test de différents codepoint
  • Example#2628 - Test de différents codepoint
  • Example#2629 - Test de différents codepoint
  • Example#2630 - Test de différents codepoint
  • Example#2631 - Test de différents codepoint
  • Example#2632 - Test de différents codepoint
  • Example#2633 - Test de différents codepoint
  • Example#2634 - Test de différents codepoint
  • Example#2635 - Exemple avec intl_error_name
  • Example#2636 - Exemple avec intl_get_error_code
  • Example#2637 - Exemple avec intl_get_error_message
  • Example#2638 - Exemple avec intl_is_failure
  • Example#2639 - Configuration de php.ini pour mbstring
  • Example#2640 - Configuration de php.ini pour les utilisateurs de EUC-JP
  • Example#2641 - Configuration de php.ini pour les utilisateurs de SJIS
  • Example#2642 - Désactive la conversion HTTP dans le php.ini
  • Example#2643 - Exemple de configuration de mbstring dans php.ini
  • Example#2644 - Exemple de script avec mbstring
  • Example#2645 - Test de différents codepoint
  • Example#2646 - Exemple avec mb_convert_case
  • Example#2647 - Exemple avec mb_convert_case avec du texte UTF-8 non latin
  • Example#2648 - Exemple avec mb_convert_encoding
  • Example#2649 - Exemple avec mb_convert_kana
  • Example#2650 - Exemple avec mb_convert_variables
  • Example#2651 - Exemple avec map
  • Example#2652 - L'exemple map échappe la chaîne JavaScript
  • Example#2653 - Exemple avec mb_detect_encoding
  • Example#2654 - Effet du paramètre strict
  • Example#2655 - Effet de l'ordre quand plusieurs encodages correspondent
  • Example#2656 - Exemple avec mb_detect_order
  • Example#2657 - Exemple d'ordre de détection inutile
  • Example#2658 - Exemple avec mb_encode_mimeheader
  • Example#2659 - Exemple avec map
  • Example#2660 - Exemple avec mb_encode_numericentity
  • Example#2661 - Exemple avec mb_encoding_aliases
  • Example#2662 - Exemple avec mb_ereg_replace_callback
  • Example#2663 - mb_ereg_replace_callback utilisant les fonctions anonymes
  • Example#2664 - Exemple avec mb_internal_encoding
  • Example#2665 - Exemple avec mb_list_encodings
  • Example#2666 -
  • Example#2667 - Exemple avec mb_output_handler
  • Example#2668 - Exemple avec mb_preferred_mime_name
  • Example#2669 - mb_str_pad example
  • Example#2670 - Exemple avec mb_strimwidth
  • Example#2671 - Exemple avec mb_strtolower
  • Example#2672 - Exemple avec mb_strtolower avec du texte UTF-8 non latin
  • Example#2673 - Exemple avec mb_strtoupper
  • Example#2674 - Exemple avec mb_strtoupper et du texte UTF-8 non latin
  • Example#2675 - Exemple mb_strwidth
  • Example#2676 - Exemple avec mb_substitute_character
  • Example#2677 - Exemple avec mb_substr_count
  • Example#2678 - pspell_add_to_personal
  • Example#2679 - Exemple avec pspell_check
  • Example#2680 - Exemple avec pspell_add_to_personal
  • Example#2681 - pspell_config_create
  • Example#2682 - pspell_config_ignore
  • Example#2683 - Exemple avec pspell_config_mode
  • Example#2684 - pspell_config_personal
  • Example#2685 - pspell_config_repl
  • Example#2686 - pspell_config_runtogether
  • Example#2687 - pspell_new_config
  • Example#2688 - pspell_new_personal
  • Example#2689 - pspell_new
  • Example#2690 - pspell_add_to_personal
  • Example#2691 - pspell_store_replacement
  • Example#2692 - Exemple avec pspell_suggest
  • Example#2693 - Exemple avec recode_file
  • Example#2694 - Exemple avec recode_string
  • Example#2695 - Exemple avec exif_imagetype
  • Example#2696 - Exemple avec exif_read_data
  • Example#2697 - exif_read_data avec les flux disponible depuis PHP 7.2.0
  • Example#2698 - Exemple pour exif_tagname
  • Example#2699 - Exemple avec exif_thumbnail
  • Example#2700 - Création d'une image PNG avec PHP
  • Example#2701 - Ajout d'un tatouage numérique sur des images en utilisant un canal Alpha
  • Example#2702 - Exemple avec imagecopymerge pour créer un tatouage numérique translucide
  • Example#2703 - Exemple avec gd_info
  • Example#2704 - getimagesize et types MIME
  • Example#2705 - Exemple avec getimagesize
  • Example#2706 - getimagesize avec une URL
  • Example#2707 - getimagesize qui retourne IPTC
  • Example#2708 - Exemple avec getimagesizefromstring
  • Example#2709 - Exemple avec image_type_to_extension
  • Example#2710 - Exemple avec image_type_to_mime_type
  • Example#2711 - Exemple avec image2wbmp
  • Example#2712 - Exemple pour imageaffinematrixconcat
  • Example#2713 - Exemple pour imageaffinematrixget
  • Example#2714 - Exemple avec imagealphablending
  • Example#2715 - Comparaison de 2 lignes, dont l'une est anti-aliasée
  • Example#2716 - Dessine d'un cercle avec imagearc
  • Example#2717 - Enregistrer un fichier BMP
  • Example#2718 - Exemple avec imagechar
  • Example#2719 - Exemple avec imagecharup
  • Example#2720 - Exemple avec imagecolorallocate
  • Example#2721 - Exemple d'utilisation de imagecolorallocatealpha
  • Example#2722 - Conversion de valeur alpha typique pour l'utiliser avec imagecolorallocatealpha
  • Example#2723 - Accès aux valeurs RGB
  • Example#2724 - Valeurs RVB lisibles en utilisant la fonction imagecolorsforindex
  • Example#2725 - Recherche d'un jeu de couleur dans une image
  • Example#2726 - Cherche un jeu de couleurs dans une image
  • Example#2727 - Exemple avec imagecolorclosesthwb
  • Example#2728 - Exemple avec imagecolordeallocate
  • Example#2729 - Récupération des couleurs composant le logo GD
  • Example#2730 - Récupération des couleurs composant le logo GD
  • Example#2731 - Exemple avec imagecolormatch
  • Example#2732 - Exemple avec imagecoloresolve pour récupérer les couleurs d'une image
  • Example#2733 - Exemple avec imagecoloresolve pour récupérer les couleurs d'une image
  • Example#2734 - Exemple avec imagecolorset
  • Example#2735 - Exemple avec imagecolorsforindex
  • Example#2736 - Récupération du nombre total de couleurs dans une image en utilisant la fonction imagecolorstotal
  • Example#2737 - Exemple avec imagecolortransparent
  • Example#2738 - Impression du logo PHP.net avec imageconvolution
  • Example#2739 - Flou gaussien avec imageconvolution
  • Example#2740 - On coupe le logo PHP.net
  • Example#2741 - Fusionne 2 copies du logo PHP.net avec 75% de transparence
  • Example#2742 - Exemple avec imagecopymergegray
  • Example#2743 - Exemple simple
  • Example#2744 - Redimensionnement proportionnel d'une image
  • Example#2745 - Redimensionnement d'une image
  • Example#2746 - Création d'une image GD et affichage de cette image
  • Example#2747 - Convertit une image BMP en image PNG en utilisant imagecreatefrombmp
  • Example#2748 - Exemple avec imagecreatefromgd2
  • Example#2749 - Exemple avec imagecreatefromgd2part
  • Example#2750 - Exemple avec imagecreatefromgd
  • Example#2751 - Exemple de prise en charge d'une erreur lors du chargement d'une image GIF
  • Example#2752 - Exemple de gestion d'une erreur lors du chargement d'une image JPEG
  • Example#2753 - Exemple de gestion d'une erreur lors du chargement d'une image PNG
  • Example#2754 - Exemple avec imagecreatefromstring
  • Example#2755 - Exemple de gestion d'une erreur lors du chargement d'une image WBMP
  • Example#2756 - Convertit une image WebP en une image jpeg en utilisant la fonction imagecreatefromwebp
  • Example#2757 - Convertie une image XBM en une image PNG en utilisant la fonction imagecreatefromxbm
  • Example#2758 - Création d'une instance d'image en utilisant la fonction imagecreatefromxpm
  • Example#2759 - Création d'un flux d'image GD, et affichage
  • Example#2760 - Exemple avec imagecrop
  • Example#2761 - Rognage automatique correcte
  • Example#2762 - Exemple avec imagedashedline
  • Example#2763 - Alternative à la fonction imagedashedline
  • Example#2764 - Utilisation de imagedestroy antérieur à PHP 8.0.0
  • Example#2765 - Exemple avec imageellipse
  • Example#2766 - Exemple avec imagefill
  • Example#2767 - Création d'un camembert en 3D
  • Example#2768 - Exemple avec imagefilledellipse
  • Example#2769 - Exemple avec imagefilledpolygon
  • Example#2770 - Exemple avec imagefilledrectangle
  • Example#2771 - Remplissage d'un ellipse avec une couleur
  • Example#2772 - Exemple de niveaux de gris avec imagefilter
  • Example#2773 - Exemple de luminosité avec imagefilter
  • Example#2774 - Exemple de colorisation avec imagefilter
  • Example#2775 - Exemple de négatif avec imagefilter
  • Example#2776 - Exemple de pixellisation avec imagefilter
  • Example#2777 - Exemple de dispersion avec imagefilter
  • Example#2778 - Retourne une image verticalement
  • Example#2779 - Retourne une image horizontalement
  • Example#2780 - Exemple avec imagefontheight et des polices internes
  • Example#2781 - Exemple avec imagefontheight et imageloadfont
  • Example#2782 - Exemple avec imagefontwidth et les polices internes
  • Example#2783 - Exemple avec imagefontwidth et imageloadfont
  • Example#2784 - Exemple avec imageftbbox
  • Example#2785 - Exemple avec imagefttext
  • Example#2786 - Exemple avec imagegammacorrect
  • Example#2787 - Affichage d'une image GD2
  • Example#2788 - Sauvegarde d'une image GD2
  • Example#2789 - Affichage d'une image GD
  • Example#2790 - Sauvegarde d'une image GD
  • Example#2791 - Exemple avec imagegetclip
  • Example#2792 - Affichage d'une image en utilisant imagegif
  • Example#2793 - Conversion d'une image PNG en GIF, en utilisant imagegif
  • Example#2794 - Exemple avec imagegrabscreen
  • Example#2795 - Exemple avec imagegrabwindow
  • Example#2796 - Activation de l'entrelacement en utilisant la fonction imageinterlace
  • Example#2797 - Détection simple d'une image en truecolor avec imageistruecolor
  • Example#2798 - Affichage d'une image JPEG vers le navigateur
  • Example#2799 - Sauvegarde d'une image JPEG dans un fichier
  • Example#2800 - Affichage de l'image avec une qualité de 75% vers le navigateur
  • Example#2801 - Exemple avec imagelayereffect
  • Example#2802 - Trace une ligne fine
  • Example#2803 - Exemple avec imageloadfont
  • Example#2804 - Exemple avec imageopenpolygon
  • Example#2805 - Exemple avec imagepalettecopy
  • Example#2806 - Convertit n'importe quelle objet image en couleur vraie
  • Example#2807 - Exemple avec imagepolygon
  • Example#2808 - Exemple avec imagerectangle
  • Example#2809 - Définir et récupérer la résolution d'une image
  • Example#2810 - Rotation d'une image de 180 degrés
  • Example#2811 - Utilisation simple de imagesavealpha
  • Example#2812 - Exemple avec imagesetbrush
  • Example#2813 - Exemple avec imagesetinterpolation
  • Example#2814 - Exemple avec imagesetpixel
  • Example#2815 - Exemple pour imagesetstyle
  • Example#2816 - Exemple avec imagesetthickness
  • Example#2817 - Exemple avec imagesettile
  • Example#2818 - Exemple avec imagestring
  • Example#2819 - Exemple avec imagestringup
  • Example#2820 - Exemple avec imagesx
  • Example#2821 - Exemple avec imagesy
  • Example#2822 - Convertion d'une image truecolor en une palette
  • Example#2823 - Exemple avec imagettfbbox
  • Example#2824 - Exemple avec imagettftext
  • Example#2825 - Exemple avec imagetypes
  • Example#2826 - Affichage d'une image WBMP
  • Example#2827 - Sauvegarde de l'image WBMP
  • Example#2828 - Affichage de l'image avec un premier-plan différent
  • Example#2829 - Sauvegarde d'un fichier WebP
  • Example#2830 - Sauvegarde d'un fichier XBM
  • Example#2831 - Sauvegarde d'un fichier XBM avec une couleur de premier-plan différente
  • Example#2832 - Exemple avec iptcembed
  • Example#2833 - Exemple avec iptcparse() et getimagesize
  • Example#2834 - Exemple avec jpeg2wbmp
  • Example#2835 - Exemple avec png2wbmp
  • Example#2836 - Gmagick Example
  • Example#2837 - Exemple avec Gmagick::despeckleimage
  • Example#2838 - Exemple avec Gmagick::setCompressionQuality
  • Example#2839 - Création d'une miniature avec Imagick
  • Example#2840 - Création de miniature de toutes les images JPG d'un dossier
  • Example#2841 - Création d'un reflet sur une image
  • Example#2842 - Remplissage d'un texte avec un dégradé
  • Example#2843 - Lit une image GIF et redimensionne toutes les frames
  • Example#2844 - Create a PHP logo
  • Example#2845 - Exemple avec Imagick::adaptiveBlurImage
  • Example#2846 - Exemple avec Imagick::adaptiveResizeImage
  • Example#2847 - Exemple avec Imagick::adaptiveSharpenImage
  • Example#2848 - Exemple avec Imagick::adaptiveThresholdImage
  • Example#2849 - Exemple avec Imagick::addNoiseImage
  • Example#2850 - Exemple avec Imagick::affineTransformImage
  • Example#2851 - Exemple avec Imagick::annotateImage
  • Example#2852 - Exemple avec Imagick::appendImages
  • Example#2853 - Imagick::autoLevelImage
  • Example#2854 - Exemple avec Imagick::blackThresholdImage
  • Example#2855 - Imagick::blueShiftImage
  • Example#2856 - Exemple avec Imagick::blurImage
  • Example#2857 - Exemple avec Imagick::borderImage
  • Example#2858 - Imagick::brightnessContrastImage
  • Example#2859 - Exemple avec Imagick::charcoalImage
  • Example#2860 - Exemple avec Imagick::chopImage
  • Example#2861 - Clonage d'objet Imagick avec différentes versions d'Imagick
  • Example#2862 - Exemple avec Imagick::clutImage
  • Example#2863 - Exemple avec Imagick::colorizeImage
  • Example#2864 - Imagick::colorMatrixImage
  • Example#2865 - Exemple avec Imagick::commentImage
  • Example#2866 - Exemple avec Imagick::compareImageLayers
  • Example#2867 - Exemple avec Imagick::compareImages
  • Example#2868 - Using Imagick::compositeImage:
  • Example#2869 - Exemple avec Imagick::contrastImage
  • Example#2870 - Exemple avec Imagick::convolveImage
  • Example#2871 - Exemple avec Imagick::cropImage
  • Example#2872 - Exemple avec Imagick::deskewImage
  • Example#2873 - Exemple avec Imagick::despeckleImage
  • Example#2874 - Exemple avec Imagick::distortImage
  • Example#2875 - Exemple avec Imagick::edgeImage
  • Example#2876 - Exemple avec Imagick::embossImage
  • Example#2877 - Exemple avec Imagick::enhanceImage
  • Example#2878 - Exemple avec Imagick::equalizeImage
  • Example#2879 - Exemple avec Imagick::evaluateImage
  • Example#2880 - Exemple avec Imagick::exportImagePixels
  • Example#2881 - Imagick::filter
  • Example#2882 - Exemple avec Imagick::flipImage
  • Example#2883 - Exemple avec Imagick::floodfillPaintImage
  • Example#2884 - Exemple avec Imagick::flopImage
  • Example#2885 - Imagick::forwardFourierTransformImage
  • Example#2886 - Exemple avec Imagick::frameImage
  • Example#2887 - Crée un gradient sinusoidal
  • Example#2888 - Crée un gradient depuis le polynome (4x^2 - 4x + 1)
  • Example#2889 - Crée un gradient complexe depuis le polynome (4x^2 - 4x^2 + 1) modulé par un gradient sinusoidal
  • Example#2890 - Exemple avec Imagick::fxImage
  • Example#2891 - Exemple avec Imagick::gammaImage
  • Example#2892 - Exemple avec Imagick::gaussianBlurImage
  • Example#2893 - Utilisation de Imagick::getImageGeometry
  • Example#2894 - Exemple avec Imagick::getImageHistogram
  • Example#2895 - Exemple avec Imagick::getImageLength:
  • Example#2896 - Exemple avec Imagick::getImageProperties
  • Example#2897 - Exemple avec Imagick::getImageProperty
  • Example#2898 - Exemple avec Imagick::getIteratorIndex
  • Example#2899 - Exemple avec Imagick::getPixelIterator
  • Example#2900 - Imagick::getPixelRegionIterator example
  • Example#2901 - Obtention de la taille d'une image RVB brute définie à 200x400, après mise à l'échelle à 400x800 (par rapport à la largeur/hauteur)
  • Example#2902 - Exemple avec Imagick::haldClutImage
  • Example#2903 - Imagick::identifyFormat
  • Example#2904 - Exemple de format du résultat
  • Example#2905 - Exemple avec Imagick::implodeImage
  • Example#2906 - Exemple avec Imagick::importImagePixels
  • Example#2907 - Exemple avec Imagick::levelImage
  • Example#2908 - Exemple avec Imagick::linearStretchImage
  • Example#2909 - Exemple avec Imagick::magnifyImage
  • Example#2910 - Exemple avec Imagick::medianFilterImage
  • Example#2911 - Exemple avec Imagick::mergeImageLayers
  • Example#2912 - Exemple avec Imagick::modulateImage
  • Example#2913 - Convolve Imagick::morphology
  • Example#2914 - Correlate Imagick::morphology
  • Example#2915 - Erode Imagick::morphology
  • Example#2916 - Erode Intensity Imagick::morphology
  • Example#2917 - Dilate Imagick::morphology
  • Example#2918 - Dilate intensity Imagick::morphology
  • Example#2919 - Distance with Chebyshev kernel Imagick::morphology
  • Example#2920 - Distance with Manhattan kernel Imagick::morphology
  • Example#2921 - Distance with ocatagonal kernel Imagick::morphology
  • Example#2922 - Distance with Euclidean kernel Imagick::morphology
  • Example#2923 - Edge Imagick::morphology
  • Example#2924 - Open Imagick::morphology
  • Example#2925 - Open intensity Imagick::morphology
  • Example#2926 - Close Imagick::morphology
  • Example#2927 - Close Intensity Imagick::morphology
  • Example#2928 - Smooth Imagick::morphology
  • Example#2929 - Edge in Imagick::morphology
  • Example#2930 - Edge out Imagick::morphology
  • Example#2931 - 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#2932 - 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#2933 - Hit and Miss Imagick::morphology
  • Example#2934 - Thinning Imagick::morphology
  • Example#2935 - Thicken Imagick::morphology
  • Example#2936 - Thick to generate a convex hull Imagick::morphology
  • Example#2937 - Iterative morphology Imagick::morphology
  • Example#2938 - Helper function to get an image silhouette Imagick::morphology
  • Example#2939 - Exemple avec Imagick::motionBlurImage
  • Example#2940 - Exemple avec Imagick::negateImage
  • Example#2941 - Exemple avec Imagick::newImage
  • Example#2942 - Exemple avec Imagick::newPseudoImage
  • Example#2943 - Exemple avec Imagick::normalizeImage
  • Example#2944 - Exemple avec Imagick::oilPaintImage
  • Example#2945 - Exemple avec Imagick::optimizeImageLayers
  • Example#2946 - Exemple avec Imagick::orderedPosterizeImage
  • Example#2947 - Exemple avec Imagick::pingImageBlob
  • Example#2948 - Exemple avec Imagick::pingImageFile
  • Example#2949 - Exemple avec Imagick::polaroidImage
  • Example#2950 - Exemple avec Imagick::posterizeImage
  • Example#2951 - Exemple avec Imagick::quantizeImage
  • Example#2952 - Exemple avec Imagick::queryFontMetrics
  • Example#2953 - Exemple avec Imagick::queryFonts
  • Example#2954 - Exemple avec Imagick::queryFormats
  • Example#2955 - Exemple avec Imagick::radialBlurImage
  • Example#2956 - Exemple avec Imagick::raiseImage
  • Example#2957 - Exemple avec Imagick::randomThresholdImage
  • Example#2958 - Exemple avec Imagick::readImageBlob
  • Example#2959 - Exemple avec Imagick::recolorImage
  • Example#2960 - Exemple avec Imagick::reduceNoiseImage
  • Example#2961 - Exemple avec Imagick::resampleImage
  • Example#2962 - Exemple avec Imagick::resizeImage
  • Example#2963 - Exemple avec Imagick::rollImage
  • Example#2964 - Exemple avec Imagick::rotateImage
  • Example#2965 - Imagick::rotationalBlurImage
  • Example#2966 - Exemple avec Imagick::roundCorners:
  • Example#2967 - Exemple avec Imagick::scaleImage
  • Example#2968 - Exemple avec Imagick::segmentImage
  • Example#2969 - Imagick::selectiveBlurImage
  • Example#2970 - Exemple avec Imagick::separateImageChannel
  • Example#2971 - Exemple avec Imagick::sepiaToneImage
  • Example#2972 - Exemple avec Imagick::setCompressionQuality
  • Example#2973 - Exemple avec Imagick::setFont
  • Example#2974 - Exemple avec Imagick::setImage
  • Example#2975 - Exemple avec Imagick::setImageArtifact
  • Example#2976 - Exemple avec Imagick::setImageBias
  • Example#2977 - Exemple avec Imagick::setImageClipMask
  • Example#2978 - Exemple avec Imagick::setImageCompressionQuality
  • Example#2979 - Modification d'un GIF animé avec Imagick::setImageDelay
  • Example#2980 - Utilisation basique de la méthode Imagick::setImageIterations
  • Example#2981 - Exemple avec Imagick::setImageOpacity
  • Example#2982 - Exempe avec Imagick::setImageOrientation
  • Example#2983 - Exemple avec Imagick::setImageProperty
  • Example#2984 - Exempe avec Imagick::setImageResolution
  • Example#2985 - Modification d'un GIF animé avec la méthode Imagick::setImageTicksPerSecond
  • Example#2986 - Exemple avec Imagick::setIteratorIndex
  • Example#2987 - Tentative d'atteindre la taille '$extent' avec Imagick::setOption
  • Example#2988 - Exemple avec Imagick::setOption
  • Example#2989 - Exemple avec Imagick::setOption
  • Example#2990 - Exemple avec Imagick::setPointSize
  • Example#2991 - Imagick::setProgressMonitor
  • Example#2992 - Exemple avec Imagick::setSamplingFactors
  • Example#2993 - Exemple avec Imagick::shadeImage
  • Example#2994 - Exemple avec Imagick::shadowImage
  • Example#2995 - Exemple avec Imagick::sharpenImage
  • Example#2996 - Exemple avec Imagick::shaveImage
  • Example#2997 - Exemple avec Imagick::shearImage
  • Example#2998 - Crée une gradient d'image en utilisant la méthode Imagick::sigmoidalContrastImage pour mélanger deux images en douceur, où le mélange est défini par les variables $contrast et $midpoint.
  • Example#2999 - Exemple avec Imagick::sketchImage
  • Example#3000 - Imagick::smushImages
  • Example#3001 - Exemple avec Imagick::solarizeImage
  • Example#3002 - Exemple avec Imagick::sparseColorImage et SPARSECOLORMETHOD_BARYCENTRIC
  • Example#3003 - Exemple avec Imagick::sparseColorImage et SPARSECOLORMETHOD_BILINEAR
  • Example#3004 - Exemple avec Imagick::sparseColorImage et SPARSECOLORMETHOD_SPEPARDS
  • Example#3005 - Exemple avec Imagick::sparseColorImage et SPARSECOLORMETHOD_VORONOI
  • Example#3006 - Exemple avec Imagick::sparseColorImage et SPARSECOLORMETHOD_BARYCENTRIC
  • Example#3007 - createGradientImage est utilisé par les autres exemples. Imagick::sparseColorImage
  • Example#3008 - Exemple avec Imagick::spliceImage
  • Example#3009 - Exemple avec Imagick::spreadImage
  • Example#3010 - Imagick::statisticImage
  • Example#3011 - Imagick::subImageMatch
  • Example#3012 - Exemple avec Imagick::swirlImage
  • Example#3013 - Exemple avec Imagick::textureImage
  • Example#3014 - Exemple avec Imagick::thresholdImage
  • Example#3015 - Exemple avec Imagick::thumbnailImage
  • Example#3016 - Exemple avec Imagick::tintImage
  • Example#3017 - Exemple avec Imagick::transformImage:
  • Example#3018 - Imagick::transformImageColorspace example
  • Example#3019 - Exemple avec Imagick::transparentPaintImage
  • Example#3020 - Exemple avec Imagick::transposeImage
  • Example#3021 - Exemple avec Imagick::transverseImage
  • Example#3022 - Exemple avec Imagick::trimImage:
  • Example#3023 - Exemple avec Imagick::uniqueImageColors
  • Example#3024 - Exemple avec Imagick::unsharpMaskImage
  • Example#3025 - Exemple avec Imagick::vignetteImage
  • Example#3026 - WaveImage peut être très lent ; Imagick::waveImage
  • Example#3027 - Exemple avec Imagick::whiteThresholdImage
  • Example#3028 - Exemple avec ImagickDraw::affine
  • Example#3029 - Exemple avec ImagickDraw::arc
  • Example#3030 - Exemple avec ImagickDraw::bezier
  • Example#3031 - Exemple avec ImagickDraw::circle
  • Example#3032 - Exemple avec ImagickDraw::composite
  • Example#3033 - Exemple avec ImagickDraw::ellipse
  • Example#3034 - Exemple avec ImagickDraw::line
  • Example#3035 - Exemple avec ImagickDraw::matte
  • Example#3036 - Exemple avec ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • Example#3037 - Exemple avec ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • Example#3038 - Exemple avec ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • Example#3039 - Exemple avec ImagickDraw::pathStart
  • Example#3040 - Exemple avec ImagickDraw::point
  • Example#3041 - Exemple avec ImagickDraw::polygon
  • Example#3042 - Exempe avec ImagickDraw::polyline
  • Example#3043 - Exemple avec ImagickDraw::popDefs
  • Example#3044 - Exemple avec ImagickDraw::push
  • Example#3045 - Exemple avec ImagickDraw::pushPattern
  • Example#3046 - Exemple avec ImagickDraw::rectangle
  • Example#3047 - Exemple avec ImagickDraw::rotate
  • Example#3048 - Exemple avec ImagickDraw::roundRectangle
  • Example#3049 - Exemple avec ImagickDraw::scale
  • Example#3050 - Exemple avec ImagickDraw::setClipPath
  • Example#3051 - Exemple avec ImagickDraw::setClipRule
  • Example#3052 - Exemple avec ImagickDraw::setClipUnits
  • Example#3053 - Exemple avec ImagickDraw::setFillAlpha
  • Example#3054 - Exemple avec ImagickDraw::setFillColor
  • Example#3055 - Exemple avec ImagickDraw::setFillOpacity
  • Example#3056 - Exemple avec ImagickDraw::setFillRule
  • Example#3057 - Exemple avec ImagickDraw::setFont
  • Example#3058 - Exemple avec ImagickDraw::setFontFamily
  • Example#3059 - Exemple avec ImagickDraw::setFontSize
  • Example#3060 - Exemple avec ImagickDraw::setFontStretch
  • Example#3061 - Exemple avec ImagickDraw::setFontStyle
  • Example#3062 - Exemple avec ImagickDraw::setFontWeight
  • Example#3063 - Exemple avec ImagickDraw::setGravity
  • Example#3064 - Exemple avec ImagickDraw::setStrokeAlpha
  • Example#3065 - Exemple avec ImagickDraw::setStrokeAntialias
  • Example#3066 - Exemple avec ImagickDraw::setStrokeColor
  • Example#3067 - Exemple avec ImagickDraw::setStrokeDashArray
  • Example#3068 - Exemple avec ImagickDraw::setStrokeDashOffset
  • Example#3069 - Exemple avec ImagickDraw::setStrokeLineCap
  • Example#3070 - Exemple avec ImagickDraw::setStrokeLineJoin
  • Example#3071 - Exemple avec ImagickDraw::setStrokeMiterLimit
  • Example#3072 - Exemple avec ImagickDraw::setStrokeOpacity
  • Example#3073 - Exemple avec ImagickDraw::setStrokeWidth
  • Example#3074 - Exemple avec ImagickDraw::setTextAlignment
  • Example#3075 - Exemple avec ImagickDraw::setTextAntialias
  • Example#3076 - Exemple avec ImagickDraw::setTextDecoration
  • Example#3077 - Exemple avec ImagickDraw::setTextUnderColor
  • Example#3078 - Exemple avec ImagickDraw::setVectorGraphics
  • Example#3079 - Exemple avec ImagickDraw::setViewBox
  • Example#3080 - Exemple avec ImagickDraw::skewX
  • Example#3081 - Exemple avec ImagickDraw::skewY
  • Example#3082 - Exemple avec ImagickDraw::translate
  • Example#3083 - Exemple avec ImagickPixel::construct
  • Example#3084 - Utilisation simple de la méthode Imagick::getColor
  • Example#3085 - Utilisation basique de la méthode Imagick::getColorAsString
  • Example#3086 - ImagickPixel getColorCount
  • Example#3087 - Utilisation basique de la méthode Imagick::getColorValue
  • Example#3088 - ImagickPixel::getColorValueQuantum
  • Example#3089 - Exemple avec Imagick::getHSL
  • Example#3090 - Exemple avec ImagickPixel::isSimilar
  • Example#3091 - Exemple avec ImagickPixel::setColor
  • Example#3092 - Exemple avec Imagick::setColorValue
  • Example#3093 - ImagickPixel::setColorValueQuantum
  • Example#3094 - Exemple avec ImagickPixel::setHSL pour modifier une couleur
  • Example#3095 - Exemple avec ImagickPixelIterator::clear
  • Example#3096 - Exemple avec ImagickPixelIterator::construct
  • Example#3097 - Exemple avec ImagickPixelIterator::getNextIteratorRow
  • Example#3098 - Exemple avec ImagickPixelIterator::resetIterator
  • Example#3099 - Exemple avec ImagickPixelIterator::setIteratorRow
  • Example#3100 - ImagickKernel::addKernel
  • Example#3101 - ImagickKernel::addUnityKernel
  • Example#3102 - ImagickKernel::addUnityKernel
  • Example#3103 - ImagickKernel::fromBuiltin
  • Example#3104 - ImagickKernel::fromMatrix
  • Example#3105 - ImagickKernel::getMatrix
  • Example#3106 - ImagickKernel::scale
  • Example#3107 - ImagickKernel::separate
  • Example#3108 - Exemple avec imap_append
  • Example#3109 - Exemple avec imap_check
  • Example#3110 - Exemple avec imap_createmailbox
  • Example#3111 - Exemple avec imap_delete
  • Example#3112 - Exemple avec imap_fetch_overview
  • Example#3113 - Exemple avecimap_gc
  • Example#3114 - Exemple avec imap_get_quota
  • Example#3115 - Exemple avec imap_get_quota 4.3 ou supérieur
  • Example#3116 - Exemple avec imap_get_quotaroot
  • Example#3117 - Exemple avec imap_getacl
  • Example#3118 - Exemple avec imap_getmailboxes
  • Example#3119 - Exemple de imap_is_open
  • Example#3120 - Exemple avec imap_list
  • Example#3121 - Exemple avec imap_mail_compose
  • Example#3122 - Exemple avec imap_mailboxmsginfo
  • Example#3123 - Exemple avec imap_mime_header_decode
  • Example#3124 - Différentes utilisations de imap_open
  • Example#3125 - Exemple avec imap_open
  • Example#3126 - Exemple avec imap_ping
  • Example#3127 - Exemple avec imap_reopen
  • Example#3128 - Exemple avec imap_rfc822_parse_adrlist
  • Example#3129 - Exemple avec imap_rfc822_write_address
  • Example#3130 - Exemple avec imap_search
  • Example#3131 - Exemple avec imap_set_quota
  • Example#3132 - Exemple avec imap_setflag_full
  • Example#3133 - Exemple avec imap_status
  • Example#3134 - Exemple avec imap_thread
  • Example#3135 - Exemple avec imap_timeout
  • Example#3136 - Utilisation de base de la fonction imap_utf8
  • Example#3137 - Calcul du hachage et enregistrement d'un utilisateur de liste de diffusion
  • Example#3138 - Envoi d'un mail
  • Example#3139 - Envoi d'un mail avec des en-têtes supplémentaires
  • Example#3140 - Envoi d'un mail avec un array d'en-têtes supplémentaires
  • Example#3141 - Envoi d'un mail avec un paramètre de ligne de commande additionnel
  • Example#3142 - Envoi de mail HTML
  • Example#3143 - Exemple avec mailparse_determine_best_xfer_encoding
  • Example#3144 - Exemple avec mailparse_rfc822_parse_addresses
  • Example#3145 - Exemple avec mailparse_stream_encode
  • Example#3146 - Exemple avec mailparse_uudecode_all
  • Example#3147 - Exemple avec bcadd
  • Example#3148 - Exemple avec bccomp
  • Example#3149 - Exemple avec bcdiv
  • Example#3150 - Exemple avec bcmod
  • Example#3151 - bcmod aved des décimales
  • Example#3152 - Exemple avec bcmul
  • Example#3153 - bcpow exemple pour scale
  • Example#3154 - Exemple avec bcpow
  • Example#3155 - bcpow exemple pour scale
  • Example#3156 - Exemple avec bcscale
  • Example#3157 - Exemple avec bcsqrt
  • Example#3158 - Exemple avec bcsub
  • Example#3159 - Factorielle avec GMP
  • Example#3160 - Exemple avec gmp_abs
  • Example#3161 - Exemple avec gmp_add
  • Example#3162 - Exemple avec gmp_and
  • Example#3163 - Exemple avec gmp_clrbit
  • Example#3164 - Exemple avec gmp_cmp
  • Example#3165 - Exemple avec gmp_com
  • Example#3166 - Exemple avec gmp_div_q
  • Example#3167 - Division de nombres GMP
  • Example#3168 - Exemple avec gmp_div_r
  • Example#3169 - Exemple avec gmp_divexact
  • Example#3170 - Exemple avec gmp_export
  • Example#3171 - Exemple avec gmp_fact
  • Example#3172 - Exemple avec gmp_gcd
  • Example#3173 - Résolution d'une équation Diophantine linéaire
  • Example#3174 - Exemple avec gmp_hamdist
  • Example#3175 - Exemple avec gmp_import
  • Example#3176 - Création d'un nombre GMP
  • Example#3177 - Exemple avec gmp_intval
  • Example#3178 - Exemple avec gmp_invert
  • Example#3179 - Exemple avec gmp_jacobi
  • Example#3180 - Exemple avec gmp_legendre
  • Example#3181 - Exemple avec gmp_mod
  • Example#3182 - Exemple avec gmp_mul
  • Example#3183 - Exemple avec gmp_neg
  • Example#3184 - Exemple avec gmp_nextprime
  • Example#3185 - Exemple avec gmp_or
  • Example#3186 - Exemple avec gmp_perfect_square
  • Example#3187 - Exemple avec gmp_popcount
  • Example#3188 - Exemple avec gmp_pow
  • Example#3189 - Exemple avec gmp_powm
  • Example#3190 - Exemple avec gmp_prob_prime
  • Example#3191 - Exemple avec gmp_random_bits
  • Example#3192 - Exemple avec gmp_random_range
  • Example#3193 - Exemple avec gmp_random_seed
  • Example#3194 - Exemple avec gmp_random
  • Example#3195 - Exemple avec gmp_scan0
  • Example#3196 - Exemple avec gmp_scan1
  • Example#3197 - Exemple avec gmp_setbit - index 0
  • Example#3198 - Exemple avec gmp_setbit - index 1
  • Example#3199 - Exemple avec gmp_setbit - annule un octet
  • Example#3200 - Exemple avec gmp_sign
  • Example#3201 - Exemple avec gmp_sqrt
  • Example#3202 - Exemple avec gmp_sqrtrem
  • Example#3203 - Convertir un nombre GMP en chaîne de caractères
  • Example#3204 - Exemple avec gmp_sub
  • Example#3205 - Exemple avec gmp_testbit
  • Example#3206 - Exemple avec gmp_xor
  • Example#3207 - Exemple avec abs
  • Example#3208 - Exemple avec base_convert
  • Example#3209 - Exemple avec bindec
  • Example#3210 - bindec interprète l'entrée comme un entier non-signé
  • Example#3211 - Exemple avec ceil
  • Example#3212 - Exemple avec cos
  • Example#3213 - Exemple avec decbin
  • Example#3214 - Exemple avec dechex
  • Example#3215 - Exemple avec la fonction dechex avec de gros entiers
  • Example#3216 - Exemple avec decoct
  • Example#3217 - Exemple avec deg2rad
  • Example#3218 - Exemple avec exp
  • Example#3219 - Using fdiv
  • Example#3220 - Exemple avec floor
  • Example#3221 - Exemple avec fmod
  • Example#3222 - Exemple avec hexdec
  • Example#3223 - Exemple de intdiv
  • Example#3224 - Exemple de is_finite
  • Example#3225 - Exemple de is_infinite
  • Example#3226 - Exemple avec is_nan
  • Example#3227 - Exemple avec max
  • Example#3228 - Exemple avec min
  • Example#3229 - Exemple avec octdec
  • Example#3230 - Exemple avec pi
  • Example#3231 - Exemple avec pow
  • Example#3232 - Exemple avec rad2deg
  • Example#3233 - Exemple avec round
  • Example#3234 - Comment precision affecte un flottant
  • Example#3235 - Exemple avec mode
  • Example#3236 - Exemple avec mode et precision
  • Example#3237 - Exemple avec sin
  • Example#3238 - Exemple avec sqrt
  • Example#3239 - Exemple avec tan
  • Example#3240 - Évaluer un document FDF
  • Example#3241 - Ajout de code JavaScript à un document FDF
  • Example#3242 - Préremplir un formulaire PDF
  • Example#3243 - Enregistrement d'un fichier téléchargé
  • Example#3244 - Détecter tous les noms d'un formulaire FDF
  • Example#3245 - Accès aux données de formulaire FDF
  • Example#3246 - Accéder aux données du formulaire
  • Example#3247 - Lire un document FDF sous forme de chaîne de caractères
  • Example#3248 - Passer des données FDF à un second formulaire
  • Example#3249 - Exemple avec gnupg clearsign (Style procédural)
  • Example#3250 - Exemple avec gnupg clearsign (Style orienté objet)
  • Example#3251 - keylistiterator
  • Example#3252 - Exemple avec gnupg_adddecryptkey (Style procédural)
  • Example#3253 - Exemple avec gnupg_adddecryptkey (Style orienté objet)
  • Example#3254 - Exemple avec gnupg_addencryptkey (Style procédural)
  • Example#3255 - Exemple avec gnupg_addencryptkey (Style orienté objet)
  • Example#3256 - Exemple avec gnupg_addsignkey (Style procédural)
  • Example#3257 - Exemple avec gnupg_addsignkey (Style orienté objet)
  • Example#3258 - Exemple avec gnupg_cleardecryptkeys (Style procédural)
  • Example#3259 - Exemple avec gnupg_cleardecryptkeys (Style orienté objet)
  • Example#3260 - Exemple avec gnupg_clearencryptkeys (Style procédural)
  • Example#3261 - Exemple avec gnupg_clearencryptkeys (Style orienté objet)
  • Example#3262 - Exemple avec gnupg_clearsignkeys (Style procédural)
  • Example#3263 - Exemple avec gnupg_clearsignkeys (Style orienté objet)
  • Example#3264 - Exemple avec gnupg_decrypt (Style procédural)
  • Example#3265 - Exemple avec gnupg_decrypt (Style orienté objet)
  • Example#3266 - Exemple avec gnupg_decryptverify (Style procédural)
  • Example#3267 - Exemple avec gnupg_decryptverify (Style orienté objet)
  • Example#3268 - Procedural gnupg_deletekey example
  • Example#3269 - OO gnupg_deletekey example
  • Example#3270 - Exemple avec gnupg_encrypt (Style procédural)
  • Example#3271 - Exemple avec gnupg_encrypt (Style orienté objet)
  • Example#3272 - Exemple avec gnupg_encryptsign (Style procédural)
  • Example#3273 - Exemple avec gnupg_encryptsign (Style orienté objet)
  • Example#3274 - Exemple avec gnupg_export (Style procédural)
  • Example#3275 - Exemple avec gnupg_export (Style orienté objet)
  • Example#3276 - Procedural gnupg_getengineinfo example
  • Example#3277 - OO gnupg_getengineinfo example
  • Example#3278 - Exemple avec gnupg_geterror (Style procédural)
  • Example#3279 - Exemple avec gnupg_geterror (Style orienté objet)
  • Example#3280 - Procedural gnupg_geterrorinfo example
  • Example#3281 - OO gnupg_geterrorinfo example
  • Example#3282 - Exemple avec gnupg_getprotocol (Style procédural)
  • Example#3283 - Exemple avec gnupg_getprotocol (Style orienté objet)
  • Example#3284 - Procedural gnupg_gettrustlist example
  • Example#3285 - OO gnupg_gettrustlist example
  • Example#3286 - Exemple avec gnupg_import (Style procédural)
  • Example#3287 - Exemple avec gnupg_import (Style orienté objet)
  • Example#3288 - Exemple avec gnupg_init avec réglage par défaut (Style procédural)
  • Example#3289 - Exemple avec gnupg_init avec un nom de fichier et un répertoire d'origine surchargés (Style procédural)
  • Example#3290 - Exemple avec gnupg_init avec réglage par défaut (Style orienté objet)
  • Example#3291 - Exemple avec gnupg_init avec un nom de fichier et un répertoire d'origine surchargés (Style orienté objet)
  • Example#3292 - Exemple avec gnupg_keyinfo (Style procédural)
  • Example#3293 - Exemple avec gnupg_keyinfo (Style orienté objet)
  • Example#3294 - Procedural gnupg_listsignatures example
  • Example#3295 - OO gnupg_listsignatures example
  • Example#3296 - Exemple avec gnupg_setarmor (Style procédural)
  • Example#3297 - Exemple avec gnupg_setarmor (Style orienté objet)
  • Example#3298 - Exemple avec gnupg_seterrormode (Style procédural)
  • Example#3299 - Exemple avec gnupg_seterrormode (Style orienté objet)
  • Example#3300 - Exemple avec gnupg_setsignmode (Style procédural)
  • Example#3301 - Exemple avec gnupg_setsignmode (Style orienté objet)
  • Example#3302 - Exemple avec gnupg_sign (Style procédural)
  • Example#3303 - Exemple avec gnupg_sign (Style orienté objet)
  • Example#3304 - Exemple avec gnupg_verify (Style procédural)
  • Example#3305 - Exemple avec gnupg_verify (Style orienté objet)
  • Example#3306 - Création et utilisation d'un motif
  • Example#3307 - Création et utilisation d'un modèle PostScript
  • Example#3308 - Coupe un texte
  • Example#3309 - Dessin d'un rectangle
  • Example#3310 - Création et utilisation d'une tache de couleur
  • Example#3311 - Rotation d'un système de coordonnées
  • Example#3312 - Placement de texte à une position donnée
  • Example#3313 - Dessin d'une ligne pointillée
  • Example#3314 - Translation du système de coordonnées
  • Example#3315 - A rpmdbinfo example
  • Example#3316 - Searching for the package owning a file
  • Example#3317 - A rpminfo example
  • Example#3318 - Exemple
  • Example#3319 - Exemple
  • Example#3320 - Exemple
  • Example#3321 - Exemple
  • Example#3322 - Exemple
  • Example#3323 - Exemple
  • Example#3324 - Exemple
  • Example#3325 - Exemple
  • Example#3326 - Exemple
  • Example#3327 - example
  • Example#3328 - Exemple
  • Example#3329 - Exemple
  • Example#3330 - Exemple
  • Example#3331 - Exemple
  • Example#3332 - Exemple
  • Example#3333 - Exemple
  • Example#3334 - Exemple
  • Example#3335 - Exemple
  • Example#3336 - Exemple
  • Example#3337 - Demandes incorrectes
  • Example#3338 - Exécution d'une demande dans la fonction de rappel d'une autre
  • Example#3339 - Exécution d'une demande depuis la fonction de rappel d'une autre
  • Example#3340 - Utilisation de eio et libevent
  • Example#3341 - Annulation d'une demande
  • Example#3342 - Appel de la fonction eio_chmod
  • Example#3343 - Fabrication d'une demande personnalisée
  • Example#3344 - Création d'un groupe de demandes
  • Example#3345 - Utilisation de eio avec libevent
  • Example#3346 - Utilisation de eio avec l'extension event
  • Example#3347 - Exemple avec eio_cancel
  • Example#3348 - Exemple avec eio_custom
  • Example#3349 - Exemple avec eio_event_loop
  • Example#3350 - eio_lstat example
  • Example#3351 - Utilisation de eio avec libevent
  • Example#3352 - Le regroupement des requêtes
  • Example#3353 - Exemple avec eio_grp
  • Example#3354 - Exemple avec eio_link
  • Example#3355 - Exemple avec eio_lstat
  • Example#3356 - Exemple avec eio_mkdir
  • Example#3357 - Exemple avec eio_mknod
  • Example#3358 - Exemple avec eio_nreqs
  • Example#3359 - Exempe avec eio_open
  • Example#3360 - Exemple avec eio_poll
  • Example#3361 - Exemple avec eio_read
  • Example#3362 - Exemple avec eio_readdir
  • Example#3363 - Exemple avec eio_readlink
  • Example#3364 - Exemple avec eio_realpath
  • Example#3365 - Exemple avec eio_rename
  • Example#3366 - Exemple avec eio_rmdir
  • Example#3367 - Exemple avec eio_stat
  • Example#3368 - Exemple avec eio_statvfs
  • Example#3369 - Exemple avec eio_symlink
  • Example#3370 - Exemple de minuteurs
  • Example#3371 - Minuteur périodique. Alerte toutes les 10.5 secondes
  • Example#3372 - Minuteur périodique. Utilisation de la fonction de rappel de reprogrammation
  • Example#3373 - Minuteur périodique. Alerte toutes les 10.5 secondes, en commençant maintenant
  • Example#3374 - Attend que STDIN devienne accessible en lecture
  • Example#3375 - Utilisation de quelques I/O asynchrones pour accéder à un socket
  • Example#3376 - Encapsule une boucle dans une autre
  • Example#3377 - Encapsule une boucle créée avec le backend kqueue dans la boucle par défaut
  • Example#3378 - Gestion du signal SIGTERM
  • Example#3379 - Surveillance des modifications dans /var/log/messages
  • Example#3380 - Surveillance des modifications dans /var/log/messages. On regarde les modifications avec une seconde de délai
  • Example#3381 - Modification du statut d'un processus
  • Example#3382 - Using reschedule callback
  • Example#3383 - Encapsule une boucle créée avec le backend kqueue dans la boucle par défaut
  • Example#3384 - Encapsule une boucle dans une autre
  • Example#3385 - Boucle embarqué créé avec le backend kqueue dans la boucle par défaut
  • Example#3386 - Encapsulage d'une boucle créée avec le gestionnaire kqueue dans la boucle par défaut
  • Example#3387 - Periodic timer. Use reschedule callback
  • Example#3388 - Timer périodique. Appelé toutes les 10.5 secondes
  • Example#3389 - Watcher chaque heure
  • Example#3390 - Gestion d'un signal SIGTERM
  • Example#3391 - Surveillance des modifications dans /var/log/messages
  • Example#3392 - Sruveillance des modifications dans le dossier /var/log/messages
  • Example#3393 - timers simples
  • Example#3394 - Surveillance des modifications dans of /var/log/messages. Détecte les mises à jour oubliées en ajoutant une seconde de délai
  • Example#3395 - Enregistre un Watcher I/O pour des sockets UDP
  • Example#3396 - Exemple d'Utilisation avec Expect
  • Example#3397 - Autre exemple d'utilisation d'Expect
  • Example#3398 - Exemple avec expect_expectl
  • Example#3399 - Exemple avec expect_popen
  • Example#3400 - Exemple de contrôle de processus
  • Example#3401 - Exemple avec pcntl_fork
  • Example#3402 - pcntl_rfork example
  • Example#3403 - Exemple avec pcntl_signal_dispatch
  • Example#3404 - Exemple avec pcntl_signal_get_handler
  • Example#3405 - Exemple avec pcntl_signal
  • Example#3406 - Exemple avec pcntl_sigprocmask
  • Example#3407 - Exemple avec pcntl_sigwaitinfo
  • Example#3408 - Exemple avec posix_access
  • Example#3409 - Exemple avec posix_ctermid
  • Example#3410 - posix_eaccess example
  • Example#3411 - posix_fpathconf example
  • Example#3412 - Exemple avec posix_get_last_error
  • Example#3413 - Exemple avec posix_getcwd
  • Example#3414 - Exemple avec posix_getegid
  • Example#3415 - Exemple avec posix_geteuid
  • Example#3416 - Exemple avec posix_getgid
  • Example#3417 - Exemple avec posix_getgrgid
  • Example#3418 - Exemple avec posix_getgrnam
  • Example#3419 - Exemple avec posix_getgroups
  • Example#3420 - Exemple avec posix_getlogin
  • Example#3421 - Exemple avec posix_getpgid
  • Example#3422 - Exemple avec posix_getpid
  • Example#3423 - Exemple avec posix_getppid
  • Example#3424 - Exemple avec posix_getpwnam
  • Example#3425 - Exemple avec posix_getpwuid
  • Example#3426 - Exemple avec posix_getrlimit
  • Example#3427 - Exemple avec posix_getsid
  • Example#3428 - Exemple avec posix_getuid
  • Example#3429 - Exemple avec posix_mknod
  • Example#3430 - posix_pathconf example
  • Example#3431 - Exemple avec posix_setegid
  • Example#3432 - Exemple avec posix_setgid
  • Example#3433 - Exemple avec posix_setuid
  • Example#3434 - Exemple avec posix_strerror
  • Example#3435 - posix_sysconf example
  • Example#3436 - Exemple avec posix_times
  • Example#3437 - Exemple avec posix_uname
  • Example#3438 - Exemple avec escapeshellarg
  • Example#3439 - Exemple avec escapeshellcmd
  • Example#3440 - Exemple avec exec
  • Example#3441 - Utilisation de proc_nice pour définir la priorité de processus à haute
  • Example#3442 - Exemple avec proc_open
  • Example#3443 - Bizarrerie de proc_open sur Windows
  • Example#3444 - Exemple avec shell_exec
  • Example#3445 - Exemple avec system
  • Example#3446 - Example showing Future as return value
  • Example#3447 - Example showing Future as synchronization point
  • Example#3448 - Parcours une partie de la table des propriétés
  • Example#3449 - Compte les propriétés d'un objet
  • Example#3450 - Héritage à l'exécution
  • Example#3451 - Détecte le statut de l'objet référencé
  • Example#3452 - Détecte le statut de l'objet référencé
  • Example#3453 - Fusionne l'objet threadé dans la table des propriétés
  • Example#3454 - Notifications et attente
  • Example#3455 - Notifications and Waiting
  • Example#3456 - Enlève le dernier élément depuis la table des propriétés d'un objet threadé
  • Example#3457 - Enlève le premier élément depuis la table de propriétés de l'objet threadé
  • Example#3458 - Synchronisation
  • Example#3459 - Notifications et attente
  • Example#3460 - Retourne l'identité du Thread ou du processus qui a créé le Thread référencé
  • Example#3461 - Retourne le thread actuellement en cours d'exécution
  • Example#3462 - Retourne l'identité du thread actuellement en cours d'exécution
  • Example#3463 - Retourne l'identité du Thread référencé
  • Example#3464 - Détecte le statut du Thread référencé
  • Example#3465 - Indique si le Thread référencé a été démarré
  • Example#3466 - Rejoint le Thread référencé
  • Example#3467 - Démarre les Threads
  • Example#3468 - A basic example of Worker::collect
  • Example#3469 - Un exemple de base de Worker::getStacked
  • Example#3470 - Détecte le statut d'un worker
  • Example#3471 - Eteint le worker référencé
  • Example#3472 - Empilage d'une tâche pour l'exécution sur un worker
  • Example#3473 - Supprime l'objet depuis la pile d'attente des Workers
  • Example#3474 - Un exemple de base de Pool::collect
  • Example#3475 - Création d'un Pool
  • Example#3476 - Shutting down a pool
  • Example#3477 - Soumission de tâches
  • Example#3478 - Soumission d'une tâche à un worker spécifique
  • Example#3479 - New immutability semantics of Threaded
  • Example#3480 - Volatile use-case
  • Example#3481 - Introduction à la mémoire partagée
  • Example#3482 - Fermeture d'un bloc de mémoire partagée
  • Example#3483 - Effacement d'un bloc de mémoire partagée
  • Example#3484 - Créer un nouveau bloc de mémoire partagée Shmop
  • Example#3485 - Lit un bloc de mémoire partagée
  • Example#3486 - Lit la taille d'un bloc de mémoire partagée
  • Example#3487 - Écrit un bloc de mémoire partagée
  • Example#3488 - Exemple avec SyncMutex::__construct et un mutex nommé avec un délai d'attente maximal pour le verrou
  • Example#3489 - Exemple avec SyncMutex::__construct et un mutex non nommé
  • Example#3490 - Exemple avec SyncMutex::lock
  • Example#3491 - Exemple avec SyncMutex::unlock
  • Example#3492 - Exemple avec SyncSemaphore::__construct
  • Example#3493 - Exemple avec SyncSemaphore::lock
  • Example#3494 - Exemple avec SyncSemaphore::unlock
  • Example#3495 - Exemple avec SyncEvent::__construct
  • Example#3496 - Exemple avec SyncEvent::fire
  • Example#3497 - Exemple avec SyncEvent::reset
  • Example#3498 - Exemple avec SyncEvent::wait
  • Example#3499 - Exemple avec SyncReaderWriter::__construct
  • Example#3500 - Exemple avec SyncReaderWriter::readlock
  • Example#3501 - Exemple avec SyncReaderWriter::readunlock
  • Example#3502 - Exemple avec SyncReaderWriter::writelock
  • Example#3503 - Exemple avec SyncReaderWriter::writeunlock
  • Example#3504 - SyncSharedMemory::__construct example
  • Example#3505 - SyncSharedMemory::first example
  • Example#3506 - SyncSharedMemory::__construct example
  • Example#3507 - SyncSharedMemory::size example
  • Example#3508 - SyncSharedMemory::write example
  • Example#3509 - Exemple avec geoip_asnum_by_name
  • Example#3510 - Exemple avec geoip_continent_code_by_name
  • Example#3511 - Exemple avec geoip_country_code_by_name
  • Example#3512 - Exemple avec geoip_country_code3_by_name
  • Example#3513 - Exemple avec geoip_country_name_by_name
  • Example#3514 - Exemple avec geoip_database_info
  • Example#3515 - Exemple avec geoip_db_avail
  • Example#3516 - Exemple avec geoip_db_filename
  • Example#3517 - Exemple avec geoip_db_get_all_info
  • Example#3518 - Exemple avec geoip_db_get_all_info
  • Example#3519 - Exemple avec geoip_domain_by_name
  • Example#3520 - Exemple avec geoip_id_by_name
  • Example#3521 - Exemple avec geoip_isp_by_name
  • Example#3522 - Exemple avec geoip_netspeedcell_by_name
  • Example#3523 - Exemple avec geoip_org_by_name
  • Example#3524 - Exemple avec geoip_record_by_name
  • Example#3525 - Exemple avec geoip_region_by_name
  • Example#3526 - Exemple avec geoip_region_name_by_code pour les USA et le Canada
  • Example#3527 - Exemple avec geoip_region_name_by_code en utilisant les codes FIPS
  • Example#3528 - Exemple avec geoip_setup_custom_directory
  • Example#3529 - Exemple avec geoip_time_zone_by_country_and_region pour les USA et Canada
  • Example#3530 - Exemple avec geoip_time_zone_by_country_and_region et les codes FIPS
  • Example#3531 - xor.data file
  • Example#3532 - Simple train
  • Example#3533 - Simple test
  • Example#3534 - Exemple avec fann_create_train_from_callback
  • Example#3535 - Exemple avec fann_read_train_from_file
  • Example#3536 - igbinary_serialize example
  • Example#3537 - Exemple avec JsonSerializable::jsonSerialize retournant un tableau
  • Example#3538 - Exemple avec JsonSerializable::jsonSerialize retournant un tableau associatif
  • Example#3539 - Exemple avec JsonSerializable::jsonSerialize retournant un entier
  • Example#3540 - Exemple avec JsonSerializable::jsonSerialize retournant une chaîne de caractères
  • Example#3541 - Exemple avec json_decode
  • Example#3542 - Accès à des propriétés d'objet invalides
  • Example#3543 - Erreurs habituelles lors de l'utilisation de la fonction json_decode
  • Example#3544 - Erreurs avec le paramètre depth
  • Example#3545 - Exemple avec json_decode et de gros entiers
  • Example#3546 - Exemple avec json_encode
  • Example#3547 - Exemple avec json_encode montrant quelques drapeaux en action
  • Example#3548 - Exemple avec l'option JSON_NUMERIC_CHECK
  • Example#3549 - Exemple avec un tableau séquentiel et un tableau non-séquentiel
  • Example#3550 - Exemple avec l'option JSON_PRESERVE_ZERO_FRACTION
  • Example#3551 - Exemple avec json_last_error
  • Example#3552 - json_last_error avec json_encode
  • Example#3553 - json_last_error et JSON_THROW_ON_ERROR
  • Example#3554 - json_validate examples
  • Example#3555 - simdjson_decode examples
  • Example#3556 - Accessing invalid object properties
  • Example#3557 - common mistakes using simdjson_decode
  • Example#3558 - depth errors
  • Example#3559 - simdjson_decode of large integers
  • Example#3560 - simdjson_decode examples
  • Example#3561 - depth errors
  • Example#3562 - Exemple avec Lua::assign
  • Example#3563 - Exemple avec Lua::call
  • Example#3564 - Exemple avec Lua::eval
  • Example#3565 - Exemple avec Lua::registerCallback
  • Example#3566 - Exemple avec LuaClosure::__invoke
  • Example#3567 - Execute some Lua code
  • Example#3568 - Calling a Lua function
  • Example#3569 - Profiling Lua code
  • Example#3570 - Loading code into Lua
  • Example#3571 - Manipulating the usage timer
  • Example#3572 - Registering PHP functions to call from Lua
  • Example#3573 - Calling a Lua function
  • Example#3574 - Calling a Lua function
  • Example#3575 - Utilisation de la fonction constant avec des constantes
  • Example#3576 - Utilisation de la fonction constant avec des types enum (à partir de PHP 8.1.0)
  • Example#3577 - Définition d'une constante
  • Example#3578 - Constantes avec des Noms Réservés
  • Example#3579 - Vérifier la présence de constantes avec defined
  • Example#3580 - Vérification des types enum (à partir de PHP 8.1.0)
  • Example#3581 - Exemple avec eval - concaténation de texte
  • Example#3582 - Exemple avec exit
  • Example#3583 - Exemple avec exit et un code d'erreur
  • Example#3584 - Exemple d'exécution des fonctions d'extinction et des destructeurs d'objets
  • Example#3585 - Exemple avec get_browser : liste des capacités du navigateur du client web
  • Example#3586 - Exemple avec __halt_compiler
  • Example#3587 - Exemple avec highlight_string
  • Example#3588 - hrtime usage
  • Example#3589 - Exemple avec ignore_user_abort
  • Example#3590 - Exemple avec pack
  • Example#3591 - Exemple avec php_strip_whitespace
  • Example#3592 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#3593 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#3594 - sapi_windows_vt100_support default state
  • Example#3595 - sapi_windows_vt100_support changing state
  • Example#3596 - Example usage of VT100 support enabled
  • Example#3597 - Exemple avec sleep
  • Example#3598 - Exemple avec sys_getloadavg
  • Example#3599 - Exemple avec time_nanosleep
  • Example#3600 - Exemple avec time_sleep_until
  • Example#3601 - Exemple avec uniqid
  • Example#3602 - Exemple avec unpack
  • Example#3603 - Exemple avec unpack et un argument de répétition
  • Example#3604 - Exemple avec unpack avec des clés non nommées
  • Example#3605 - Exemple avec usleep
  • Example#3606 - Exemple Random
  • Example#3607 - Exemple avec mt_rand
  • Example#3608 - Exemple avec rand
  • Example#3609 - Exemple avec random_bytes
  • Example#3610 - Exemple avec random_int
  • Example#3611 - Random\Randomizer::__construct example
  • Example#3612 - Random\Randomizer::getBytes example
  • Example#3613 - Random\Randomizer::getBytesFromString example
  • Example#3614 - Generate a random code for multi-factor authentication
  • Example#3615 - Select from a string with a non-uniform distribution
  • Example#3616 - Random\Randomizer::getFloat example
  • Example#3617 - Random\Randomizer::getInt example
  • Example#3618 - Random\Randomizer::nextFloat example
  • Example#3619 - Incorrect scaling using an affine transformation
  • Example#3620 - Random\Randomizer::nextInt example
  • Example#3621 - Random\Randomizer::pickArrayKeys example
  • Example#3622 - Picking random values
  • Example#3623 - Random\Randomizer::__serialize example
  • Example#3624 - Random\Randomizer::shuffleArray example
  • Example#3625 - Random\Randomizer::shuffleBytes example
  • Example#3626 - Byte-wise shuffling breaks Unicode characters
  • Example#3627 - Random\Randomizer::__unserialize example
  • Example#3628 - Exemple de Random\Engine::generate
  • Example#3629 - Random\Engine\Mt19937::__construct example
  • Example#3630 - Random\Engine\Mt19937::__debugInfo example
  • Example#3631 - Random\Engine\Mt19937::__serialize example
  • Example#3632 - Random\Engine\Mt19937::__unserialize example
  • Example#3633 - Random\Engine\PcgOneseq128XslRr64::__construct example
  • Example#3634 - Deriving a seed from a chaîne de caractères
  • Example#3635 - Random\Engine\PcgOneseq128XslRr64::__debugInfo example
  • Example#3636 - Random\Engine\PcgOneseq128XslRr64::jump example
  • Example#3637 - Randomizer methods may call the engine more than once
  • Example#3638 - Random\Engine\PcgOneseq128XslRr64::__serialize example
  • Example#3639 - Random\Engine\PcgOneseq128XslRr64::__unserialize example
  • Example#3640 - Random\Engine\Xoshiro256StarStar::__construct example
  • Example#3641 - Deriving a seed from a chaîne de caractères
  • Example#3642 - Random\Engine\Xoshiro256StarStar::__debugInfo example
  • Example#3643 - Random\Engine\Xoshiro256StarStar::jump example
  • Example#3644 - Random\Engine\Xoshiro256StarStar::jumpLong example
  • Example#3645 - Random\Engine\Xoshiro256StarStar::__serialize example
  • Example#3646 - Random\Engine\Xoshiro256StarStar::__unserialize example
  • Example#3647 - Get and set base path
  • Example#3648 - Get and set logger
  • Example#3649 - Fast write log
  • Example#3650 - Fast count some type of log count value
  • Example#3651 - Acquisit some type of log list
  • Example#3652 - seaslog_get_author example
  • Example#3653 - seaslog_get_version example
  • Example#3654 - SeasLog::alert example
  • Example#3655 - SeasLog::analyzerCount example
  • Example#3656 - SeasLog::analyzerDetail example
  • Example#3657 - SeasLog::closeLoggerStream example
  • Example#3658 - SeasLog::__construct example
  • Example#3659 - SeasLog::critical example
  • Example#3660 - SeasLog::debug example
  • Example#3661 - SeasLog::__destruct example
  • Example#3662 - SeasLog::emergency example
  • Example#3663 - SeasLog::error example
  • Example#3664 - SeasLog::flushBuffer example
  • Example#3665 - SeasLog::getBasePath example
  • Example#3666 - SeasLog::getBuffer example
  • Example#3667 - SeasLog::getBufferEnabled example
  • Example#3668 - SeasLog::getDatetimeFormat example
  • Example#3669 - SeasLog::getLastLogger example
  • Example#3670 - SeasLog::getRequestID example
  • Example#3671 - SeasLog::getRequestVariable example
  • Example#3672 - SeasLog::info example
  • Example#3673 - SeasLog::log example
  • Example#3674 - SeasLog::notice example
  • Example#3675 - SeasLog::setBasePath example
  • Example#3676 - SeasLog::setDatetimeFormat example
  • Example#3677 - SeasLog::setLogger example
  • Example#3678 - SeasLog::setRequestID example
  • Example#3679 - SeasLog::setRequestVariable example
  • Example#3680 - SeasLog::warning example
  • Example#3681 - Exemple de SplStack
  • Example#3682 - Exemple de SplQueue
  • Example#3683 - Traiter efficacement les tâches avec SplQueue
  • Example#3684 - Exemple avec SplFixedArray
  • Example#3685 - Exemple avec SplFixedArray::__construct
  • Example#3686 - Exemple avec SplFixedArray::count
  • Example#3687 - Exemple avec SplFixedArray::fromArray
  • Example#3688 - Exemple avec SplFixedArray::getSize
  • Example#3689 - Exemple avec SplFixedArray::setSize
  • Example#3690 - Exemple avec SplFixedArray::toArray
  • Example#3691 - Exemple avec SplObjectStorage, sous forme d'ensemble d'objets
  • Example#3692 - Exemple avec SplObjectStorage, sous forme de carte
  • Example#3693 - Exemple avec SplObjectStorage::addAll
  • Example#3694 - Exemple avec SplObjectStorage::attach
  • Example#3695 - Exemple avec SplObjectStorage::contains
  • Example#3696 - Exemple avec SplObjectStorage::count
  • Example#3697 - Exemple avec SplObjectStorage::current
  • Example#3698 - Exemple avec SplObjectStorage::detach
  • Example#3699 - Exemple avec SplObjectStorage::getHash
  • Example#3700 - Exemple avec SplObjectStorage::getInfo
  • Example#3701 - Exemple avec SplObjectStorage::key
  • Example#3702 - Exemple avec SplObjectStorage::next
  • Example#3703 - Exemple avec SplObjectStorage::offsetExists
  • Example#3704 - Exemple avec SplObjectStorage::offsetGet
  • Example#3705 - Exemple avec SplObjectStorage::offsetSet
  • Example#3706 - Exemple avec SplObjectStorage::offsetUnset
  • Example#3707 - Exemple avec SplObjectStorage::removeAll
  • Example#3708 - Exemple avec SplObjectStorage::removeAllExcept
  • Example#3709 - Exemple avec SplObjectStorage::rewind
  • Example#3710 - Exemple avec SplObjectStorage::serialize
  • Example#3711 - Exemple avec SplObjectStorage::setInfo
  • Example#3712 - Exemple avec SplObjectStorage::unserialize
  • Example#3713 - Exemple avec SplObjectStorage::valid
  • Example#3714 - Exemple avec AppendIterator::append
  • Example#3715 - Itère un AppendIterator avec la structure foreach
  • Example#3716 - Itère un AppendIterator avec l'API AppendIterator
  • Example#3717 - Exemple avec AppendIterator.getIteratorIndex
  • Example#3718 - Exemple avec AppendIterator::key
  • Example#3719 - Exemple avec ArrayIterator::current
  • Example#3720 - Exemple avec ArrayIterator::key
  • Example#3721 - Exemple avec ArrayIterator::next
  • Example#3722 - Exemple avec ArrayIterator::rewind
  • Example#3723 - Exemple avec ArrayIterator::valid
  • Example#3724 - Exemple avec CachingIterator::getCache
  • Example#3725 - Arguments disponibles pour la fonction de rappel
  • Example#3726 - Exemples simples de fonction de rappel
  • Example#3727 - Exemple avec DirectoryIterator::__construct
  • Example#3728 - Exemple avec DirectoryIterator::current
  • Example#3729 - Exemple avec DirectoryIterator::getBasename
  • Example#3730 - Exemple avec DirectoryIterator::getExtension
  • Example#3731 -
  • Example#3732 - Exemple avec DirectoryIterator::getFilename
  • Example#3733 - Exemple avec DirectoryIterator::isDot
  • Example#3734 - Exemple avec DirectoryIterator::key
  • Example#3735 - Exemple avec DirectoryIterator::next
  • Example#3736 - Exemple avec DirectoryIterator::rewind
  • Example#3737 - Exemple avec DirectoryIterator::seek
  • Example#3738 - Exemple avec DirectoryIterator::__toString
  • Example#3739 - Exemple avec DirectoryIterator::valid
  • Example#3740 - Exemple avec FilesystemIterator::__construct
  • Example#3741 - Exemple avec FilesystemIterator::current
  • Example#3742 - Exemple avec FilesystemIterator::key
  • Example#3743 - Exemple avec FilesystemIterator::next
  • Example#3744 - Exemple avec FilesystemIterator::rewind
  • Example#3745 - Exemple avec FilesystemIterator::key
  • Example#3746 - Exemple avec FilterIterator::accept
  • Example#3747 - Exemple avec GlobIterator
  • Example#3748 - Exemple avec GlobIterator::count
  • Example#3749 - Exemple avec InfiniteIterator::__construct
  • Example#3750 - Exemple d'utilisation de LimitIterator
  • Example#3751 - Exemple LimitIterator::__construct
  • Example#3752 - Exemple LimitIterator::getPosition
  • Example#3753 - Itère un MultipleIterator
  • Example#3754 - Exemple avec NoRewindIterator::__construct
  • Example#3755 - Exemple avec NoRewindIterator::rewind
  • Example#3756 - Exemple avec RecursiveArrayIterator::getChildren
  • Example#3757 - Exemple avec RecursiveArrayIterator::hasChildren
  • Example#3758 - Arguments disponibles pour la fonction de rappel
  • Example#3759 - Exemple simple d'une fonction de rappel récursive
  • Example#3760 - Exemple avec RecursiveCallbackFilterIterator::hasChildren
  • Example#3761 - Exemple avec RecursiveDirectoryIterator
  • Example#3762 - Exemple getSubPath
  • Example#3763 - Exemple getSubPathname
  • Example#3764 - Exemple avec RecursiveFilterIterator
  • Example#3765 - Exemple avec RecursiveFilterIterator
  • Example#3766 - Parcours d'un RecursiveIteratorIterator
  • Example#3767 - Exemple avec RecursiveRegexIterator::__construct
  • Example#3768 - Exemple avec RecursiveRegexIterator::getChildren
  • Example#3769 - Exemple avec RecursiveRegexIterator::hasChildren
  • Example#3770 - Exemple avec RegexIterator::accept
  • Example#3771 - Exemple avec RegexIterator::__construct
  • Example#3772 - Exemple avec RegexIterator::getFlags
  • Example#3773 - Exemple avec RegexIterator::getMode
  • Example#3774 - Exemple avec RegexIterator::getPregFlags
  • Example#3775 - Exemple avec RegexIterator::setFlags
  • Example#3776 - Exemple avec RegexIterator::setMode
  • Example#3777 - Exemple avec RegexIterator::setPregFlags
  • Example#3778 - Exemple avec Countable::count
  • Example#3779 - Utilisation simple
  • Example#3780 - Exemple avec SeekableIterator::seek
  • Example#3781 - Exemple avec class_implements
  • Example#3782 - Exemple avec class_parents
  • Example#3783 - Exemples pour class_uses
  • Example#3784 - Exemple avec iterator_apply
  • Example#3785 - Exemple avec iterator_count
  • Example#3786 - Exemple avec iterator_count qui modifie la position
  • Example#3787 - Exemple avec iterator_count dans une boucle foreach
  • Example#3788 - Exemple avec iterator_to_array
  • Example#3789 - Exemple avec spl_autoload_extensions
  • Example#3790 - Exemple avec spl_autoload_register comme remplacement d'une fonction __autoload
  • Example#3791 - Exemple avec spl_autoload_register où la classe n'est pas chargée
  • Example#3792 - L'identifiant sera fourni sans le backslash initial.
  • Example#3793 - Exemple avec spl_classes
  • Example#3794 - Exemple avec spl_object_hash
  • Example#3795 - Un exemple de spl_object_id
  • Example#3796 - Exemple avec SplFileInfo::__construct
  • Example#3797 - Exemple avec SplFileInfo::getATime
  • Example#3798 - Exemple avec SplFileInfo::getBasename
  • Example#3799 - Exemple avec SplFileInfo::getCTime
  • Example#3800 - Exemple avec SplFileInfo::getExtension
  • Example#3801 -
  • Example#3802 - Exemple avec SplFileInfo::getFilename
  • Example#3803 - Exemple avec SplFileInfo::getGroup
  • Example#3804 - Exemple avec SplFileInfo::getLinkTarget
  • Example#3805 - Exemple avec SplFileInfo::getMTime
  • Example#3806 - Exemple avec SplFileInfo::getOwner
  • Example#3807 - Exemple avec SplFileInfo::getPath
  • Example#3808 - Exemple avec SplFileInfo::getPathInfo
  • Example#3809 - Exemple avec SplFileInfo::getPathname
  • Example#3810 - Exemple avec SplFileInfo::getPerms
  • Example#3811 - Exemple avec SplFileInfo::getRealPath
  • Example#3812 - Exemple avec SplFileInfo::getSize
  • Example#3813 - Exemple avec SplFileInfo::getType
  • Example#3814 - Exemple avec SplFileInfo::isDir
  • Example#3815 - Exemple avec SplFileInfo::isExecutable
  • Example#3816 - Exemple avec SplFileInfo::isFile
  • Example#3817 - Exemple avec SplFileInfo::isLink
  • Example#3818 - Exemple avec SplFileInfo::isReadable
  • Example#3819 - Exemple avec SplFileInfo::isWriteable
  • Example#3820 - Exemple avec SplFileInfo::openFile
  • Example#3821 - Exemple avec SplFileInfo::setFileClass
  • Example#3822 - Exemple avec SplFileInfo::setFileClass
  • Example#3823 - Exemple avec SplFileInfo::__toString
  • Example#3824 - Exemple avec SplFileObject::__construct
  • Example#3825 - Exemple avec SplFileObject::current
  • Example#3826 - Exemple avec SplFileObject::eof
  • Example#3827 - Exemple avec SplFileObject::fflush
  • Example#3828 - Exemple avec SplFileObject::fgetc
  • Example#3829 - Exemple avec SplFileObject::fgetcsv
  • Example#3830 - Exemple avec SplFileObject::READ_CSV
  • Example#3831 - Exemple avec SplFileObject::fgets
  • Example#3832 - Exemple avec SplFileObject::fgetss
  • Example#3833 - Exemple avec SplFileObject::flock
  • Example#3834 - Exemple avec SplFileObject::fpassthru
  • Example#3835 - Exemple avec SplFileObject::fputcsv
  • Example#3836 - Exemple avec SplFileObject::fread
  • Example#3837 - Exemple avec SplFileObject::fscanf
  • Example#3838 - Exemple avec SplFileObject::fseek
  • Example#3839 - Exemple avec SplFileObject::fstat
  • Example#3840 - Exemple avec SplFileObject::ftell
  • Example#3841 - Exemple avec SplFileObject::ftruncate
  • Example#3842 - Exemple avec SplFileObject::fwrite
  • Example#3843 - Exemple avec SplFileObject::getCsvControl
  • Example#3844 - Exemple avec SplFileObject::getFlags
  • Example#3845 - Exemple avec SplFileObject::getMaxLineLen
  • Example#3846 - Exemple avec SplFileObject::key
  • Example#3847 - Exemple avec SplFileObject::key et SplFileObject::setMaxLineLen
  • Example#3848 - Exemple avec SplFileObject::next
  • Example#3849 - Exemple avec SplFileObject::rewind
  • Example#3850 - Exemple avec SplFileObject::seek
  • Example#3851 - Exemple avec SplFileObject::setCsvControl
  • Example#3852 - Exemple avec SplFileObject::setFlags
  • Example#3853 - Exemple avec SplFileObject::setMaxLineLen
  • Example#3854 - Exemple avec SplFileObject::valid
  • Example#3855 - Exemple avec SplTempFileObject
  • Example#3856 - Exemple avec ArrayObject::append
  • Example#3857 - Exemple avec ArrayObject::asort
  • Example#3858 - Exemple avec ArrayObject::__construct
  • Example#3859 - Exemple avec ArrayObject::count
  • Example#3860 - Exemple avec ArrayObject::exchangeArray
  • Example#3861 - Exemple avec ArrayObject::getArrayCopy
  • Example#3862 - Exemple avec ArrayObject::getFlags
  • Example#3863 - Exemple avec ArrayObject::getIterator
  • Example#3864 - Exemple avec ArrayObject::getIteratorClass
  • Example#3865 - Exemple avec ArrayObject::ksort
  • Example#3866 - Exemple avec ArrayObject::natcasesort
  • Example#3867 - Exemple avec ArrayObject::natsort
  • Example#3868 - Exemple avec ArrayObject::offsetExists
  • Example#3869 - Exemple avec ArrayObject::offsetGet
  • Example#3870 - Exemple avec ArrayObject::offsetSet
  • Example#3871 - Exemple avec ArrayObject::offsetUnset
  • Example#3872 - Exemple avec ArrayObject::serialize
  • Example#3873 - Exemple avec ArrayObject::setFlags
  • Example#3874 - Exemple avec ArrayObject::setIteratorClass
  • Example#3875 - Exemple avec ArrayObject::uasort
  • Example#3876 - Exemple avec ArrayObject::uksort
  • Example#3877 - Exemples avec file_get_contents
  • Example#3878 - Envoi d'une requête de type POST sur un serveur sécurisé
  • Example#3879 - Écrire des données dans un fichier compressé
  • Example#3880 - Un flux pour lire et écrire des variables globales
  • Example#3881 - Liste des fichiers d'une archive tar
  • Example#3882 - Exemple avec stream_bucket_prepend
  • Example#3883 - Exemple avec stream_context_create
  • Example#3884 - Exemple avec stream_context_get_default
  • Example#3885 - Exemple avec stream_context_get_options
  • Example#3886 - Exemple avec stream_context_get_params
  • Example#3887 - Exemple avec stream_context_set_default
  • Example#3888 - stream_context_set_options example
  • Example#3889 - Exemple avec stream_copy_to_stream
  • Example#3890 - Contrôler l'application des filtres
  • Example#3891 - Filtre sur les lettres majuscules sur le flux foo-bar.txt
  • Example#3892 - Enregistrement d'une classe de filtre générique pour correspondre avec de multiples noms de filtres
  • Example#3893 - Refiltrage dynamique d'un flux
  • Example#3894 - Exemple avec stream_get_contents
  • Example#3895 - Exemple avec stream_get_filters
  • Example#3896 - Exemple de stream_get_meta_data utilisant fopen avec http
  • Example#3897 - Exemple de stream_get_meta_data utilisant stream_socket_client avec https
  • Example#3898 - Exemple avec stream_get_transports
  • Example#3899 - Exemple avec stream_get_wrappers
  • Example#3900 - Vérification de l'existence d'un gestionnaire de flux
  • Example#3901 - Exemple avec stream_is_local
  • Example#3902 - Exemple avec stream_isatty
  • Example#3903 - Exemple avec stream_notification_callback
  • Example#3904 - Barre de progression simple pour un client de téléchargement en ligne de commande
  • Example#3905 - Exemple avec stream_resolve_include_path
  • Example#3906 - Exemple avec stream_select
  • Example#3907 - Exemple avec stream_set_timeout
  • Example#3908 - Exemple avec stream_set_write_buffer
  • Example#3909 - Exemple avec stream_socket_client
  • Example#3910 - Utilisation de connexions UDP
  • Example#3911 - Exemple avec stream_socket_enable_crypto
  • Example#3912 - Exemple avec stream_socket_pair
  • Example#3913 - Exemple avec stream_socket_recvfrom
  • Example#3914 - Exemple avec stream_socket_sendto
  • Example#3915 - Exemple avec stream_socket_server
  • Example#3916 - Utiliser un serveur de socket UDP
  • Example#3917 - Exemple avec stream_socket_shutdown
  • Example#3918 - Comment enregistrer un gestionnaire de flux
  • Example#3919 - Utilisation de base de Tidy
  • Example#3920 - Exemple avec tidy::getBody
  • Example#3921 - Exemple avec tidy::cleanrepair
  • Example#3922 - Exemple avec tidy::__construct
  • Example#3923 - Exemple avec tidy::diagnose
  • Example#3924 - Exemple avec tidy_get_error_buffer
  • Example#3925 - Exemple avec tidy::getConfig
  • Example#3926 - Exemple avec Tidy::getopt
  • Example#3927 - Affichage de toutes les options avec leur documentation et leur valeur par défaut
  • Example#3928 - Exemple avec tidy::getStatus
  • Example#3929 - Exemple avec tidy::head
  • Example#3930 - Exemple avec tidy::html
  • Example#3931 - Exemple avec tidy::parseFile
  • Example#3932 - Exemple avec tidy::parseString
  • Example#3933 - Exemple avec tidy::repairFile
  • Example#3934 - Exemple avec tidy::repairString
  • Example#3935 - Exemple avec tidy::root
  • Example#3936 - Exemple avec tidyNode::hasChildren
  • Example#3937 - Exemple avec tidyNode::hasChildren
  • Example#3938 - Exemple avec tidyNode::hasSiblings
  • Example#3939 - Extrait di code ASP depuis un document HTML mixte
  • Example#3940 - Extrait les commentais depuis un document HTML
  • Example#3941 - Extrait du code HTML depuis un document mixte
  • Example#3942 - Extrait du code JSTE depuis un document HTML
  • Example#3943 - Récupération de code PHP dans un document HTML
  • Example#3944 - Extrait du texte depuis un document HTML mixte
  • Example#3945 - Exemple avec ob_tidyhandler
  • Example#3946 - Exemple avec tidy_access_count
  • Example#3947 - Exemple avec tidy_config_count
  • Example#3948 - Exemple avec tidy_error_count
  • Example#3949 - Exemple avec tidy_get_output
  • Example#3950 - Exemple avec tidy_warning_count
  • Example#3951 - Supprime les commentaires avec le tokenizer
  • Example#3952 - PhpToken::getTokenName example
  • Example#3953 - PhpToken::is example
  • Example#3954 - Usage with array
  • Example#3955 - PhpToken::isIgnorable example
  • Example#3956 - PhpToken::__toString example
  • Example#3957 - PhpToken::tokenize example
  • Example#3958 - Extending PhpToken
  • Example#3959 - Exemple avec token_get_all
  • Example#3960 - Exemple d'utilisation incorrecte de la fonction token_get_all
  • Example#3961 - token_get_all dans une classe en utilisant un mot réservé
  • Example#3962 - Exemple avec token_name
  • Example#3963 - Exemple avec base64_decode
  • Example#3964 - Exemple avec base64_encode
  • Example#3965 - Exemple avec get_headers
  • Example#3966 - Exemple avec get_headers en utilisant HEAD
  • Example#3967 - Ce que la fonction get_meta_tags analyse
  • Example#3968 - Ce que la fonction get_meta_tags retourne
  • Example#3969 - Utilisation simple de http_build_query
  • Example#3970 - http_build_query avec tableau indexé
  • Example#3971 - http_build_query avec tableau complexe
  • Example#3972 - Utilisation de http_build_query avec un objet
  • Example#3973 - Exemple avec parse_url
  • Example#3974 - Exemple avec la fonction parse_url sans schéma
  • Example#3975 - Exemple avec rawurldecode
  • Example#3976 - Exemple avec rawurlencode
  • Example#3977 - Exemple avec rawurlencode
  • Example#3978 - Exemple avec urldecode
  • Example#3979 - Exemple avec urlencode
  • Example#3980 - Exemple avec urlencode et htmlentities
  • Example#3981 - Exécution d'un Javascript simple
  • Example#3982 - Exemples Yaml
  • Example#3983 - Exemple d'analyse de fonction de rappel
  • Example#3984 - Exemple d'émission des fonctions de rappel
  • Example#3985 - Exemple yaml_emit
  • Example#3986 - Exemple yaml_parse
  • Example#3987 - Une architecture classique d'une application
  • Example#3988 - Entry
  • Example#3989 - Règle de ré-écriture des requêtes
  • Example#3990 - Configuration de l'application
  • Example#3991 - Controlleur par défaut
  • Example#3992 - Template de rendu par défaut
  • Example#3993 - Exécution de l'application
  • Example#3994 - Exemple avec un tableau PHP
  • Example#3995 - Exemple avec un fichier ini
  • Example#3996 - Exemple avec A Bootstrap
  • Example#3997 - Exemple avec Yaf_Application::bootstrap
  • Example#3998 - Exemple avec Yaf_Application::clearLastError
  • Example#3999 - Un exemple de fichier de configuration au format ini
  • Example#4000 - Exemple avec Yaf_Application::__construct
  • Example#4001 - Exemple avec Yaf_Application::__construct
  • Example#4002 - Exemple avec Yaf_Application::environ
  • Example#4003 - Exemple avec Yaf_Application::execute
  • Example#4004 - Exemple avec Yaf_Application::getConfig
  • Example#4005 - Exemple avec Yaf_Application::getDispatcher
  • Example#4006 - Exemple avec Yaf_Application::getLastErrorMsg
  • Example#4007 - Exemple avec Yaf_Application::getLastErrorNo
  • Example#4008 - Exemple avec Yaf_Application::getModules
  • Example#4009 - Bootstrap example
  • Example#4010 - Exemple avec Yaf_Dispatcher::autoRender
  • Example#4011 - Exemple avec Yaf_Dispatcher::catchException
  • Example#4012 - Exemple avec Yaf_Dispatcher::registerPlugin
  • Example#4013 - Exemple avec Yaf_Dispatcher::setView
  • Example#4014 - Exemple avec Yaf_Dispatcher::setView
  • Example#4015 - Exemple avec Yaf_Dispatcher::throwexception
  • Example#4016 - Exemple avec Yaf_Dispatcher::throwexception
  • Example#4017 - Exemple avec Yaf_Config_Ini
  • Example#4018 - Définission d'une action dans un fichier séparé
  • Example#4019 - Dummy_action.php
  • Example#4020 - Exemple avec Yaf_Controller_Abstract::forward
  • Example#4021 - Exemple avec Yaf_Action_Abstract::execute
  • Example#4022 - Exemple avec Yaf_Action_Abstract::execute
  • Example#4023 - Exemple avec Yaf_View_Simple::assign
  • Example#4024 - Exemple avec template
  • Example#4025 - Exemple avec Yaf_View_Simple::assignRef
  • Example#4026 - Exemple avec template
  • Example#4027 - Exemple avec Yaf_View_Simple::clear
  • Example#4028 - Exemple avec Yaf_View_Simple::__constructor
  • Example#4029 - Exemple avec Yaf_View_Simple::__set
  • Example#4030 - Exemple de configuration
  • Example#4031 - Enregistrement de localnamespace
  • Example#4032 - Load class example
  • Example#4033 - Exemple de chargement de classe via des espaces de noms
  • Example#4034 - Exemple de chargement de classe MVC
  • Example#4035 - Distinctions d'une classe MVC
  • Example#4036 - Exemple de chargement MVC
  • Example#4037 - Exemple avec Yaf_Loader::registerNamespace
  • Example#4038 - Exemple avec Yaf_Loader::registerLocalNamespace
  • Example#4039 - Yaf_Loader::registerNamespaceexample
  • Example#4040 - Exemple d'un plugin
  • Example#4041 - Exemple avec Yaf_Plugin_Abstract::routerShutdown
  • Example#4042 - Exemple avec Yaf_Response_Abstract::appendBody
  • Example#4043 - Exemple avec Yaf_Response_Abstract::getBody
  • Example#4044 - Exemple avec Yaf_Response_Abstract::prependBody
  • Example#4045 - Exemple avec Yaf_Response_Abstract::response
  • Example#4046 - Exemple avec Yaf_Response_Abstract::setBody
  • Example#4047 - Exemple avec Yaf_Route_Map::assemble
  • Example#4048 - Exemple avec Yaf_Route_Map
  • Example#4049 - Exemple avec Yaf_Route_Map
  • Example#4050 - Exemple avec Yaf_Route_Map
  • Example#4051 - Exemple avec Yaf_Route_Regex::assemble
  • Example#4052 - Exemple avec Yaf_Route_Regex
  • Example#4053 - Exemple avec Yaf_Route_Regex (depuis la version 2.3.0)
  • Example#4054 - Exemple avec Yaf_Route_Regex et la capture du nom (depuis 2.3.0)
  • Example#4055 - Exemple avec Yaf_Route_Regex
  • Example#4056 - Exemple avec Yaf_Route_Rewrite::assemble
  • Example#4057 - Exemple avec Yaf_Route_Rewrite
  • Example#4058 - Exemple avec Yaf_Route_Rewrite
  • Example#4059 - Exemple avec Yaf_Route_Rewrite (depuis 2.3.0)
  • Example#4060 - Règle de ré-écriture pour Apache
  • Example#4061 - Règle de ré-écriture pour Apache
  • Example#4062 - Règle de ré-écriture pour Lighttpd
  • Example#4063 - Règle de ré-écriture pour Nginx
  • Example#4064 - Exemple avec Yaf_Route_Static (route par défaut)
  • Example#4065 - Exemple avec application.ini
  • Example#4066 - Exemple avec Yaf_Dispatcher::autoConfig
  • Example#4067 - Exemple avec Yaf_Dispatcher::autoRender
  • Example#4068 - Enregistre quelques routes dans le Bootstrap
  • Example#4069 - plugin Dummy.php (sous le dossier application.directory/plugins)
  • Example#4070 - Exemple avec Yaf_Route_Simple::assemble
  • Example#4071 - Exemple avec Yaf_Route_Simple::route
  • Example#4072 - Exemple avec Yaf_Route_Simple::route
  • Example#4073 - Exemple avec Yaf_Route_Static::assemble
  • Example#4074 - Exemple avec Yaf_Route_Static::route
  • Example#4075 - Exemple avec Yaf_Route_Supervar::assemble
  • Example#4076 - Exemple avec Yaf_Route_Supervar
  • Example#4077 - Exemple INI
  • Example#4078 - Exemple avec les sections INI
  • Example#4079 - Exemple INI
  • Example#4080 - Exemple avec Taint
  • Example#4081 - Vector
  • Example#4082 - Map
  • Example#4083 - Ds\Collection::clear example
  • Example#4084 - Ds\Collection::copy exemple
  • Example#4085 - Ds\Collection::isEmpty exemple
  • Example#4086 - Ds\Collection::toArray exemple
  • Example#4087 - Ds\Hashable::hash example
  • Example#4088 - Ds\Sequence::allocate example
  • Example#4089 - Ds\Sequence::apply example
  • Example#4090 - Ds\Sequence::capacity example
  • Example#4091 - Ds\Sequence::contains example
  • Example#4092 - Ds\Sequence::filter example using callback function
  • Example#4093 - Ds\Sequence::filter example without a callback function
  • Example#4094 - Ds\Sequence::find example
  • Example#4095 - Ds\Sequence::first example
  • Example#4096 - Ds\Sequence::get example
  • Example#4097 - Ds\Sequence::get example using array syntax
  • Example#4098 - Ds\Sequence::insert example
  • Example#4099 - Ds\Sequence::join example using a separator string
  • Example#4100 - Ds\Sequence::join example without a separator string
  • Example#4101 - Ds\Sequence::last example
  • Example#4102 - Ds\Sequence::map example
  • Example#4103 - Ds\Sequence::merge example
  • Example#4104 - Ds\Sequence::pop example
  • Example#4105 - Ds\Sequence::push example
  • Example#4106 - Ds\Sequence::reduce with initial value example
  • Example#4107 - Ds\Sequence::reduce without an initial value example
  • Example#4108 - Ds\Sequence::remove example
  • Example#4109 - Ds\Sequence::reverse example
  • Example#4110 - Ds\Sequence::reversed example
  • Example#4111 - Ds\Sequence::rotate example
  • Example#4112 - Ds\Sequence::set example
  • Example#4113 - Ds\Sequence::set example using array syntax
  • Example#4114 - Ds\Sequence::shift example
  • Example#4115 - Ds\Sequence::slice example
  • Example#4116 - Ds\Sequence::sort example
  • Example#4117 - Ds\Sequence::sort example using a comparator
  • Example#4118 - Ds\Sequence::sorted example
  • Example#4119 - Ds\Sequence::sorted example using a comparator
  • Example#4120 - Ds\Sequence::sum integer example
  • Example#4121 - Ds\Sequence::sum float example
  • Example#4122 - Ds\Sequence::unshift example
  • Example#4123 - Ds\Vector::allocate example
  • Example#4124 - Ds\Vector::apply example
  • Example#4125 - Ds\Vector::capacity example
  • Example#4126 - Ds\Vector::clear example
  • Example#4127 - Ds\Vector::__construct example
  • Example#4128 - Ds\Vector::contains example
  • Example#4129 - Ds\Vector::copy example
  • Example#4130 - Ds\Vector::filter example using callback function
  • Example#4131 - Ds\Vector::filter example without a callback function
  • Example#4132 - Ds\Vector::find example
  • Example#4133 - Ds\Vector::first example
  • Example#4134 - Ds\Vector::get example
  • Example#4135 - Ds\Vector::get example using array syntax
  • Example#4136 - Ds\Vector::insert example
  • Example#4137 - Ds\Vector::isEmpty example
  • Example#4138 - Ds\Vector::join example using a separator string
  • Example#4139 - Ds\Vector::join example without a separator string
  • Example#4140 - Ds\Vector::last example
  • Example#4141 - Ds\Vector::map example
  • Example#4142 - Ds\Vector::merge example
  • Example#4143 - Ds\Vector::pop example
  • Example#4144 - Ds\Vector::push example
  • Example#4145 - Ds\Vector::reduce with initial value example
  • Example#4146 - Ds\Vector::reduce without an initial value example
  • Example#4147 - Ds\Vector::remove example
  • Example#4148 - Ds\Vector::reverse example
  • Example#4149 - Ds\Vector::reversed example
  • Example#4150 - Ds\Vector::rotate example
  • Example#4151 - Ds\Vector::set example
  • Example#4152 - Ds\Vector::set example using array syntax
  • Example#4153 - Ds\Vector::shift example
  • Example#4154 - Ds\Vector::slice example
  • Example#4155 - Ds\Vector::sort example
  • Example#4156 - Ds\Vector::sort example using a comparator
  • Example#4157 - Ds\Vector::sorted example
  • Example#4158 - Ds\Vector::sorted example using a comparator
  • Example#4159 - Ds\Vector::sum integer example
  • Example#4160 - Ds\Vector::sum float example
  • Example#4161 - Ds\Vector::toArray example
  • Example#4162 - Ds\Vector::unshift example
  • Example#4163 - Ds\Deque::allocate example
  • Example#4164 - Ds\Deque::apply example
  • Example#4165 - Ds\Deque::capacity example
  • Example#4166 - Ds\Deque::clear example
  • Example#4167 - Ds\Deque::__construct example
  • Example#4168 - Ds\Deque::contains example
  • Example#4169 - Ds\Deque::copy example
  • Example#4170 - Ds\Deque::filter example using callback function
  • Example#4171 - Ds\Deque::filter example without a callback function
  • Example#4172 - Ds\Deque::find example
  • Example#4173 - Ds\Deque::first example
  • Example#4174 - Ds\Deque::get example
  • Example#4175 - Ds\Deque::get example using array syntax
  • Example#4176 - Ds\Deque::insert example
  • Example#4177 - Ds\Deque::isEmpty example
  • Example#4178 - Ds\Deque::join example using a separator string
  • Example#4179 - Ds\Deque::join example without a separator string
  • Example#4180 - Ds\Deque::last example
  • Example#4181 - Ds\Deque::map example
  • Example#4182 - Ds\Deque::merge example
  • Example#4183 - Ds\Deque::pop example
  • Example#4184 - Ds\Deque::push example
  • Example#4185 - Ds\Deque::reduce with initial value example
  • Example#4186 - Ds\Deque::reduce without an initial value example
  • Example#4187 - Ds\Deque::remove example
  • Example#4188 - Ds\Deque::reverse example
  • Example#4189 - Ds\Deque::reversed example
  • Example#4190 - Ds\Deque::rotate example
  • Example#4191 - Ds\Deque::set example
  • Example#4192 - Ds\Deque::set example using array syntax
  • Example#4193 - Ds\Deque::shift example
  • Example#4194 - Ds\Deque::slice example
  • Example#4195 - Ds\Deque::sort example
  • Example#4196 - Ds\Deque::sort example using a comparator
  • Example#4197 - Ds\Deque::sorted example
  • Example#4198 - Ds\Deque::sorted example using a comparator
  • Example#4199 - Ds\Deque::sum integer example
  • Example#4200 - Ds\Deque::sum float example
  • Example#4201 - Ds\Deque::toArray example
  • Example#4202 - Ds\Deque::unshift example
  • Example#4203 - Ds\Map::allocate example
  • Example#4204 - Ds\Map::apply example
  • Example#4205 - Ds\Map::capacity example
  • Example#4206 - Ds\Map::clear example
  • Example#4207 - Ds\Map::__construct example
  • Example#4208 - Ds\Map::copy example
  • Example#4209 - Ds\Map::diff example
  • Example#4210 - Ds\Map::filter example using callback function
  • Example#4211 - Ds\Map::filter example without a callback function
  • Example#4212 - Ds\Map::first example
  • Example#4213 - Ds\Map::get example
  • Example#4214 - Ds\Map::get example using array syntax
  • Example#4215 - Ds\Map::hasKey example
  • Example#4216 - Ds\Map::hasValue example
  • Example#4217 - Ds\Map::intersect example
  • Example#4218 - Ds\Map::isEmpty example
  • Example#4219 - Ds\Map::keys example
  • Example#4220 - Ds\Map::ksort example
  • Example#4221 - Ds\Map::ksort example using a comparator
  • Example#4222 - Ds\Map::ksorted example
  • Example#4223 - Ds\Map::ksorted example using a comparator
  • Example#4224 - Ds\Map::last example
  • Example#4225 - Ds\Map::map example
  • Example#4226 - Ds\Map::merge example
  • Example#4227 - Ds\Map::pairs example
  • Example#4228 - Ds\Map::put example
  • Example#4229 - Ds\Map::put example using objects as keys
  • Example#4230 - Ds\Map::putAll example
  • Example#4231 - Ds\Map::reduce with initial value example
  • Example#4232 - Ds\Map::reduce without an initial value example
  • Example#4233 - Ds\Map::remove example
  • Example#4234 - Ds\Map::reverse example
  • Example#4235 - Ds\Map::reversed example
  • Example#4236 - Ds\Map::skip example
  • Example#4237 - Ds\Map::slice example
  • Example#4238 - Ds\Map::sort example
  • Example#4239 - Ds\Map::sort example using a comparator
  • Example#4240 - Ds\Map::sort example
  • Example#4241 - Ds\Map::sort example using a comparator
  • Example#4242 - Ds\Map::sum integer example
  • Example#4243 - Ds\Map::sum float example
  • Example#4244 - Ds\Map::toArray example
  • Example#4245 - Ds\Map::union example
  • Example#4246 - Ds\Map::values example
  • Example#4247 - Ds\Map::xor example
  • Example#4248 - Ds\Pair::clear example
  • Example#4249 - Ds\Pair::copy example
  • Example#4250 - Ds\Pair::isEmpty example
  • Example#4251 - Ds\Pair::toArray example
  • Example#4252 - Ds\Set::add example using integers
  • Example#4253 - Ds\Set::add example using objects
  • Example#4254 - Ds\Set::allocate example
  • Example#4255 - Ds\Set::capacity example
  • Example#4256 - Ds\Set::clear example
  • Example#4257 - Ds\Set::__construct example
  • Example#4258 - Ds\Set::contains example
  • Example#4259 - Ds\Set::copy example
  • Example#4260 - Ds\Set::diff example
  • Example#4261 - Ds\Set::filter example using callback function
  • Example#4262 - Ds\Set::filter example without a callback function
  • Example#4263 - Ds\Set::first example
  • Example#4264 - Ds\Set::get example
  • Example#4265 - Ds\Set::get example using array syntax
  • Example#4266 - Ds\Set::intersect example
  • Example#4267 - Ds\Set::isEmpty example
  • Example#4268 - Ds\Set::join example using a separator string
  • Example#4269 - Ds\Set::join example without a separator string
  • Example#4270 - Ds\Set::last example
  • Example#4271 - Ds\Set::merge example
  • Example#4272 - Ds\Set::reduce with initial value example
  • Example#4273 - Ds\Set::reduce without an initial value example
  • Example#4274 - Ds\Set::remove example
  • Example#4275 - Ds\Set::reverse example
  • Example#4276 - Ds\Set::reversed example
  • Example#4277 - Ds\Set::slice example
  • Example#4278 - Ds\Set::sort example
  • Example#4279 - Ds\Set::sort example using a comparator
  • Example#4280 - Ds\Set::sorted example
  • Example#4281 - Ds\Set::sorted example using a comparator
  • Example#4282 - Ds\Set::sum integer example
  • Example#4283 - Ds\Set::sum float example
  • Example#4284 - Ds\Set::toArray example
  • Example#4285 - Ds\Set::union example
  • Example#4286 - Ds\Set::xor example
  • Example#4287 - Ds\Stack::clear example
  • Example#4288 - Ds\Stack::__construct example
  • Example#4289 - Ds\Stack::copy example
  • Example#4290 - Ds\Stack::isEmpty example
  • Example#4291 - Ds\Stack::peek example
  • Example#4292 - Ds\Stack::pop example
  • Example#4293 - Ds\Stack::push example
  • Example#4294 - Ds\Stack::toArray example
  • Example#4295 - Ds\Queue::allocate example
  • Example#4296 - Ds\Queue::capacity example
  • Example#4297 - Ds\Queue::clear example
  • Example#4298 - Ds\Queue::__construct example
  • Example#4299 - Ds\Queue::copy example
  • Example#4300 - Ds\Queue::isEmpty example
  • Example#4301 - Ds\Queue::peek example
  • Example#4302 - Ds\Queue::pop example
  • Example#4303 - Ds\Queue::push example
  • Example#4304 - Ds\Queue::toArray example
  • Example#4305 - Ds\PriorityQueue::allocate example
  • Example#4306 - Ds\PriorityQueue::capacity example
  • Example#4307 - Ds\PriorityQueue::clear example
  • Example#4308 - Ds\PriorityQueue::__construct example
  • Example#4309 - Ds\PriorityQueue::copy example
  • Example#4310 - Ds\PriorityQueue::isEmpty example
  • Example#4311 - Ds\PriorityQueue::peek example
  • Example#4312 - Ds\PriorityQueue::pop example
  • Example#4313 - Ds\PriorityQueue::push example
  • Example#4314 - Ds\PriorityQueue::toArray example
  • Example#4315 - var_representation Examples
  • Example#4316 - Escaping control characters
  • Example#4317 - Exporting stdClass
  • Example#4318 - Exporting classes
  • Example#4319 - Using __set_state()
  • Example#4320 - Utilisation du module cURL pour récupérer la page d'accueil de example.com
  • Example#4321 - Initialise une session cURL et récupère une page web
  • Example#4322 - Copie d'une ressource cURL
  • Example#4323 - Exemple avec curl_errno
  • Example#4324 - Exemple avec curl_error
  • Example#4325 - Exemple avec curl_escape
  • Example#4326 - Récupère le contenu d'une page web
  • Example#4327 - Exemple avec curl_getinfo
  • Example#4328 - Exemple de curl_getinfo avec le paramètre option
  • Example#4329 - Initialiser une session cURL et récupérer une page web
  • Example#4330 - Exemple avec curl_multi_add_handle
  • Example#4331 - Exemple avec curl_multi_close
  • Example#4332 - Exemple avec curl_multi_exec
  • Example#4333 - Exemple avec curl_multi_info_read
  • Example#4334 - Exemple avec curl_multi_init
  • Example#4335 - Exemple avec curl_multi_strerror
  • Example#4336 - Exemple avec curl_reset
  • Example#4337 - Initialisation d'une nouvelle session cURL et récupération d'une page web
  • Example#4338 - Initialisation d'une nouvelle session CURL et recherche d'une page Web
  • Example#4339 - Exempe avec curl_share_setopt
  • Example#4340 - Exemple avec curl_share_init
  • Example#4341 - Exemple avec curl_share_setopt
  • Example#4342 - Exemple avec curl_errno
  • Example#4343 - Exemple avec curl_escape
  • Example#4344 - Exemple de curl_upkeep
  • Example#4345 - Exemple avec curl_version
  • Example#4346 - Exemple avec CURLFile::__construct
  • Example#4347 - Exemple de téléversement de plusieurs fichiers avec CURLFile::__construct
  • Example#4348 - Exemple de CURLStringFile::__construct
  • Example#4349 - Client HTTP simple
  • Example#4350 - Client HTTP en utilisant une résolution DNS asynchrone
  • Example#4351 - Serveur d'affichage
  • Example#4352 - Serveur d'affichage SSL
  • Example#4353 - Gestionnaire de signal
  • Example#4354 - Utilisation d'une boucle libevent pour réaliser les requêtes de l'extension `eio'
  • Example#4355 - Divers
  • Example#4356 - Serveur HTTP simple
  • Example#4357 - Serveur HTTPS simple
  • Example#4358 - Connexion OpenSSL
  • Example#4359 - Exemple avec EventHttpConnection::makeRequest
  • Example#4360 - Ecoute d'une connexion en se basant sur un socket de domaine Unix
  • Example#4361 - Exemple de serveur SMTP
  • Example#4362 - Gestion d'un signal SIGTERM
  • Example#4363 - Ajout d'un signal personnalisé
  • Example#4364 - Ajout d'une minuterie
  • Example#4365 - Exemple avec EventBase::getFeatures
  • Example#4366 - Exemple avec EventBase::getMethod
  • Example#4367 - Exemple avec EventBuffer::search
  • Example#4368 - Exemple avec EventBufferEvent::connect
  • Example#4369 - Connexion à un socket UNIX, lecture de la réponse depuis le serveur, et affichage dans une console
  • Example#4370 - Exemple avec EventBufferEvent::connectHost
  • Example#4371 - Fonction de rappel pour un événement de lecture sur le tampon
  • Example#4372 - Exemple avec EventBufferEvent::getOutput
  • Example#4373 - Exemple avec EventBufferEvent::sslError
  • Example#4374 - Exemple de serveur SMTP
  • Example#4375 - Exemple avec EventConfig::avoidMethod
  • Example#4376 - Exemple avec EventConfig::__construct
  • Example#4377 - Exemple avec EventConfig::requireFeatures
  • Example#4378 - Exemple avec EventHttp::accept
  • Example#4379 - Exemple avec EventHttp::addServerAlias
  • Example#4380 - Exemple avec EventHttp::bind
  • Example#4381 - Serveur HTTP simple
  • Example#4382 - Exemple avec EventHttp::setCallback
  • Example#4383 - Exemple avec EventHttp::setDefaultCallback
  • Example#4384 - Exemple avec EventHttpConnection::makeRequest
  • Example#4385 - Exemple avec EventHttpConnection::setCloseCallback
  • Example#4386 - Exemple avec EventHttpRequest::__construct
  • Example#4387 - Exemple avec EventHttpRequest::sendError
  • Example#4388 - Exemple avec EventListener::__construct
  • Example#4389 - Exemple avec EventSslContext::__construct
  • Example#4390 - Exemple avec FTP
  • Example#4391 - Exemple avec ftp_alloc
  • Example#4392 - Exemple avec ftp_cdup
  • Example#4393 - Exemple avec ftp_chdir
  • Example#4394 - Exemple avec ftp_chmod
  • Example#4395 - Exemple avec ftp_close
  • Example#4396 - Exemple avec ftp_connect
  • Example#4397 - Exemple avec ftp_delete
  • Example#4398 - Exemple avec ftp_exec
  • Example#4399 - Exemple avec ftp_fget
  • Example#4400 - Exemple avec ftp_fput
  • Example#4401 - Exemple avec ftp_get_option
  • Example#4402 - Exemple avec ftp_get
  • Example#4403 - Exemple avec ftp_login
  • Example#4404 - Exemple avec ftp_mdtm
  • Example#4405 - Exemple avec ftp_mkdir
  • Example#4406 - Exemple avec ftp_mlsd
  • Example#4407 - Exemple avec ftp_nb_continue
  • Example#4408 - Exemple avec ftp_nb_fget
  • Example#4409 - Exemple avec ftp_nb_fput
  • Example#4410 - Exemple avec ftp_nb_get
  • Example#4411 - Reprise d'un téléchargement avec ftp_nb_get
  • Example#4412 - Reprise d'un téléchargement à la position 100 dans un nouveau fichier avec ftp_nb_get
  • Example#4413 - Exemple avec ftp_nb_put
  • Example#4414 - Reprise d'un chargement avec ftp_nb_put
  • Example#4415 - Exemple avec ftp_nlist
  • Example#4416 - Exemple avec ftp_pasv
  • Example#4417 - Exemple avec ftp_put
  • Example#4418 - Exemple avec ftp_pwd
  • Example#4419 - Utilisation de ftp_raw pour s'identifier manuellement sur un serveur FTP
  • Example#4420 - Exemple avec ftp_rawlist
  • Example#4421 - Exemple avec ftp_rename
  • Example#4422 - Exemple avec ftp_rmdir
  • Example#4423 - Exemple avec ftp_set_option
  • Example#4424 - Envoi d'une commande SITE à un serveur FTP
  • Example#4425 - Exemple avec ftp_size
  • Example#4426 - Exemple avec ftp_ssl_connect
  • Example#4427 - Exemple avec ftp_systype
  • Example#4428 - Client et agent Gearman simple
  • Example#4429 - Client et agent Gearman simple, en arrière-plan
  • Example#4430 - Client et agent Gearman simple, avec la soumission de tâches
  • Example#4431 - Ajout de deux serveurs
  • Example#4432 - Ajout de deux serveurs
  • Example#4433 - Ajout de 2 tâches
  • Example#4434 - Ajout de 2 tâches en passant le contexte de l'application
  • Example#4435 - 2 tâches dont une en arrière-plan
  • Example#4436 - Une tâche de forte priorité en même temps que deux tâches normales
  • Example#4437 - Une tâche de faible priorité en même temps que deux tâches normales
  • Example#4438 - Surveiller l'accomplissement de plusieurs tâches de fond
  • Example#4439 - Soumission d'une seule tâche avec un retour immédiat
  • Example#4440 - Soumission d'un travail et récupération incrémentale du statut
  • Example#4441 - Soumet et surveille un travail en arrière-plan
  • Example#4442 - Soumission d'une tâche avec un retour immédiat
  • Example#4443 - Soumission d'une tâche et récupération incrémentale du statut
  • Example#4444 - Récupère le statut d'un travail dont l'exécution prend du temps
  • Example#4445 - Surveille le statut d'un travail en arrière-plan mettant du temps à s'exécuter
  • Example#4446 - Agent simple qui utilise des données de contexte de l'application
  • Example#4447 - Ajout de serveurs Gearman
  • Example#4448 - Ajout de 2 serveurs de travaux
  • Example#4449 - Exemple avec GearmanWorker::setId
  • Example#4450 - Un agent simple qui attend 5 secondes
  • Example#4451 - Exécution d'un agent en mode non bloquant
  • Example#4452 - Exemple avec GearmanWorker::work
  • Example#4453 - Testing support for paged result control
  • Example#4454 - Recherche avec LDAP
  • Example#4455 - Lier avec des informations policy
  • Example#4456 - Modifier la description uniquement si elle n'est pas vide
  • Example#4457 - Lire des valeurs avant leurs suppresion
  • Example#4458 - Supprimer une référence
  • Example#4459 - Utiliser la pagination pour une recherche
  • Example#4460 - Exemple complet avec identification LDAP
  • Example#4461 - Authentification avec LDAP
  • Example#4462 - Connexion anonyme à un serveur LDAP
  • Example#4463 - Exemple complet de vérification de mot de passe avec lDAP
  • Example#4464 - Exemple de connexion à un serveur LDAP
  • Example#4465 - Exemple de connexion à un serveur LDAP SSL
  • Example#4466 - Pagination LDAP
  • Example#4467 - Pagination LDAP
  • Example#4468 - Exemple avec ldap_count_entries
  • Example#4469 - Énumérer tous les messages d'erreur LDAP
  • Example#4470 - Générer et intercepter une erreur
  • Example#4471 - Chercher une addresse email
  • Example#4472 - PASSWD extended operation
  • Example#4473 - Whoami extended operation
  • Example#4474 - Affiche la liste des attributs d'une entrée
  • Example#4475 - Vérification de la version du protocole
  • Example#4476 - Liste toutes les valeurs de l'attribut "mail" d'une entrée
  • Example#4477 - Produit une liste de tous les services d'une société
  • Example#4478 - Ajout d'un numéro de téléphone à un contact
  • Example#4479 - Renomme un utilisateur
  • Example#4480 - Ajoute deux adresses emails à un utilisateur
  • Example#4481 - Modifie le mot de passe d'un utilisateur
  • Example#4482 - Modifie le mot de passe d'un utilisateur (Active Directory)
  • Example#4483 - Exemple avec ldap_parse_result
  • Example#4484 - Recherche LDAP
  • Example#4485 - Modification de la version du protocole
  • Example#4486 - Modification des contrôles du serveur
  • Example#4487 - Tri LDAP
  • Example#4488 - Exemple avec l'extension Memcache
  • Example#4489 - Utilisation de memcache comme gestionnaire de session
  • Example#4490 - Exemple avec Memcache::add
  • Example#4491 - Exemple avec Memcache::addServer
  • Example#4492 - Exemple avec Memcache::close
  • Example#4493 - Exemple avec Memcache::connect
  • Example#4494 - Exemple avec Memcache::decrement
  • Example#4495 - Exemple avec Memcache::delete
  • Example#4496 - Exemple avec Memcache::flush
  • Example#4497 - Exemple avec Memcache::get
  • Example#4498 - Exemple avec Memcache::getExtendedStats
  • Example#4499 - Exemple avec Memcache::getServerStatus
  • Example#4500 - Exemple avec Memcache::getVersion
  • Example#4501 - Exemple avec Memcache::increment
  • Example#4502 - Exemple avec Memcache::pconnect
  • Example#4503 - Exemple avec Memcache::replace
  • Example#4504 - Exemple avec Memcache::set
  • Example#4505 - Exemple avec Memcache::set
  • Example#4506 - Exemple avec Memcache::setCompressThreshold
  • Example#4507 - Exemple avec Memcache::setServerParams
  • Example#4508 - Exemple de fonction de rappel de résultats
  • Example#4509 - Fonctions de rappel sur clé absente
  • Example#4510 - Exemple avec Memcached::addServer
  • Example#4511 - Exemple avec Memcached::addServers
  • Example#4512 - Exemple avec Memcached::append
  • Example#4513 - Exemple avec Memcached::cas
  • Example#4514 - Création d'un objet Memcached
  • Example#4515 - Exemple avec Memcached::decrement
  • Example#4516 - Exemple avec Memcached::delete
  • Example#4517 - Exemple avec Memcached::fetch
  • Example#4518 - Exemple avec Memcached::fetchAll
  • Example#4519 - Exemple avec Memcached::flush
  • Example#4520 - Exemple avec Memcached::get 1
  • Example#4521 - Exemple avec Memcached::get 2
  • Example#4522 - Exemple avec Memcached::getDelayed
  • Example#4523 - Exemple de Memcached::getMulti pour Memcached v3
  • Example#4524 - Exemple de Memcached::getMulti pour Memcached v1 et v2
  • Example#4525 - Exemple de Memcached::GET_PRESERVE_ORDER pour Memcached v3
  • Example#4526 - Exemple de Memcached::GET_PRESERVE_ORDER pour Memcached v1 et v2
  • Example#4527 - Lecture des options Memcached
  • Example#4528 - Exemple avec Memcached::getResultCode
  • Example#4529 - Exemple avec Memcached::getResultMessage
  • Example#4530 - Exemple avec Memcached::getServerByKey
  • Example#4531 - Exemple avec Memcached::getResultCode
  • Example#4532 - Exemple avec Memcached::getStats
  • Example#4533 - Exemple avec Memcached::getVersion
  • Example#4534 - Exemple avec Memcached::getResultCode
  • Example#4535 - Exemple avec Memcached::prepend
  • Example#4536 - Exemple avec Memcached::set
  • Example#4537 - Exemple avec Memcached::setByKey
  • Example#4538 - Exemple avec Memcached::setMulti
  • Example#4539 - Configuration d'une option Memcached
  • Example#4540 - Définit des options Memcache
  • Example#4541 - Exemple avec mqseries_back
  • Example#4542 - Exemple avec mqseries_begin
  • Example#4543 - Exemple avec mqseries_close
  • Example#4544 - Exemple avec mqseries_cmit
  • Example#4545 - Exemple avec mqseries_conn
  • Example#4546 - Exemple avec mqseries_connx
  • Example#4547 - Exemple avec mqseries_connx en utilisant une connexion SSL et une URL OCSP Responder
  • Example#4548 - Exemple avec mqseries_disc
  • Example#4549 - Exemple avec mqseries_get
  • Example#4550 - Exemple avec mqseries_inq
  • Example#4551 - Exemple avec mqseries_open
  • Example#4552 - Exemple avec mqseries_put
  • Example#4553 - Exemple avec mqseries_strerror
  • Example#4554 - Exemple avec dns_get_record
  • Example#4555 - Exemple avec dns_get_record et DNS_ANY
  • Example#4556 - Exemple avec fsockopen
  • Example#4557 - Utilisation d'une connexion UDP
  • Example#4558 - Exemple avec gethostbyaddr
  • Example#4559 - Exemple avec gethostbyname
  • Example#4560 - Exemple avec gethostbynamel
  • Example#4561 - Exemple avec gethostname
  • Example#4562 - Exemple avec getprotobyname
  • Example#4563 - Exemple avec getservbyname
  • Example#4564 - Exemple avec header_register_callback
  • Example#4565 - Supprimer un en-tête HTTP avec header_remove
  • Example#4566 - Supprimer tous les en-têtes HTTP avec header_remove
  • Example#4567 - Boîte de téléchargement
  • Example#4568 - Directives concernant la mise en cache
  • Example#4569 - Exemple avec headers_list
  • Example#4570 - Exemple avec headers_sent
  • Example#4571 - Utiliser http_response_code dans un environnement de serveur Web
  • Example#4572 - Utiliser http_response_code dans un environnement CLI
  • Example#4573 - Exemple avec inet_ntop
  • Example#4574 - Exemple avec inet_pton
  • Example#4575 - Exemple avec ip2long
  • Example#4576 - Affichage d'une adresse IP
  • Example#4577 - Exemple d'envoi d'un cookie avec setcookie
  • Example#4578 - Exemple d'effacement d'un cookie avec setcookie
  • Example#4579 - setcookie et les tableaux
  • Example#4580 - Exemple avec syslog
  • Example#4581 - Utilisation procédurale de rrd
  • Example#4582 - Utilisation orientée objet de rrd
  • Example#4583 - Exemple avec RRDGraph::setOptions
  • Example#4584 - Défini plusieurs options de couleur
  • Example#4585 - Exemple avec RRDUpdater::update
  • Example#4586 - Fetch instrumented calls
  • Example#4587 - Fetch the list of functions scoutapm will instrument
  • Example#4588 - Exemple avec snmp_get_quick_print
  • Example#4589 - Exemple avec snmp_get_valueretrieval
  • Example#4590 - Exemple avec snmp_read_mib
  • Example#4591 - Exemple avec snmp_set_enum_print
  • Example#4592 - Exemple avec snmprealwalk
  • Example#4593 - Exemple avec snmp_set_quick_print
  • Example#4594 - Exemple avec snmp_set_valueretrieval
  • Example#4595 - Exemple avec snmp2_get
  • Example#4596 - Exemple avec snmp2_get_next
  • Example#4597 - Exemple avec snmp2_real_walk
  • Example#4598 - Exemple avec snmp2_set
  • Example#4599 - Exemple avec snmp2_set pour configurer l'identifiant de l'objet SNMP BITS
  • Example#4600 - Exemple avec snmp2_walk
  • Example#4601 - Exemple avec snmp3_get
  • Example#4602 - Exemple avec snmp3_getnext
  • Example#4603 - Exemple avec snmp3_real_walk
  • Example#4604 - Exemple avec snmp3_set
  • Example#4605 - Exemple avec snmp3_set pour configurer l'identifiant de l'objet SNMP BITS
  • Example#4606 - Exemple avec snmp3_walk
  • Example#4607 - Exemple avec snmpget
  • Example#4608 - Exemple avec snmpgetnext
  • Example#4609 - Exemple avec snmprealwalk
  • Example#4610 - Exemple avec snmpset
  • Example#4611 - Exemple avec snmpset pour configurer l'identifiant de l'objet SNMP BITS
  • Example#4612 - Exemple avec snmpwalk
  • Example#4613 - Exemple avec snmpwalkoid
  • Example#4614 - Exemple avec SNMP::close
  • Example#4615 - Récupération de sysLocation
  • Example#4616 - Un seul objet SNMP
  • Example#4617 - Plusieurs objets SNMP
  • Example#4618 - SNMP::getErrno example
  • Example#4619 - Exemple avec SNMP::getError
  • Example#4620 - Un seul objet SNMP
  • Example#4621 - Plusieurs objets SNMP
  • Example#4622 - Définit un seul identifiant d'objet SNMP
  • Example#4623 - Définit plusieurs valeurs en utilisant un seul appel à la méthode SNMP::set call
  • Example#4624 - Exemple avec SNMP::set pour configurer l'identifiant d'objet SNMP BITS
  • Example#4625 - Exemple avec SNMP::setSecurity
  • Example#4626 - Exemple avec SNMP::walk
  • Example#4627 - Exemple avec la paramètre suffixAsKey
  • Example#4628 - Exemple de socket : serveur TCP/IP simple
  • Example#4629 - Exemple avec les sockets : client TCP/IP simple
  • Example#4630 - Using socket_atmark to set the source address
  • Example#4631 - Utilisation de socket_bind pour définir l'adresse de la source
  • Example#4632 - Exemple avec socket_create_pair
  • Example#4633 - Exemple IPC avec socket_create_pair
  • Example#4634 - Exemple avec socket_get_option
  • Example#4635 - Exemple avec socket_import_stream
  • Example#4636 - Exemple avec socket_last_error
  • Example#4637 - Exemples avec socket_recv
  • Example#4638 - Exemple avec socket_recvfrom
  • Example#4639 - Passer null à socket_select
  • Example#4640 - Analyser le résultat de socket_select
  • Example#4641 - Exemple avec socket_select
  • Example#4642 - Exemple avec socket_sendto
  • Example#4643 - Exemple avec socket_set_block
  • Example#4644 - Exemple avec socket_set_nonblock
  • Example#4645 - Exemple avec socket_set_option
  • Example#4646 - Exemple avec socket_strerror
  • Example#4647 - Authentification en utilisant un agent ssh
  • Example#4648 - Identification en utilisant une clé d'hôte publique
  • Example#4649 - Récupération de la liste des méthodes d'identification
  • Example#4650 - Identification avec un mot de passe
  • Example#4651 - Identification en utilisant une clé publique
  • Example#4652 - Exemple avec ssh2_connect
  • Example#4653 - Exécution d'une commande
  • Example#4654 - Ouverture d'un shell et récupération du flux stderr qui lui est associé
  • Example#4655 - Comparaison d'une empreinte à une valeur connue
  • Example#4656 - Détermine quelles méthodes ont été négociées
  • Example#4657 - Ajout d'une clé publique avec ssh2_publickey_add
  • Example#4658 - Liste des clés autorisées avec ssh2_publickey_list
  • Example#4659 - Téléchargement d'un fichier via SCP
  • Example#4660 - Chargement d'un fichier via SCP
  • Example#4661 - Changement du mode du fichier sur le serveur distant
  • Example#4662 - Statue un lien symbolique via SFTP
  • Example#4663 - Création d'un dossier sur un serveur distant
  • Example#4664 - Lecture d'un lien symbolique
  • Example#4665 - Résoudre un nom de chemin
  • Example#4666 - Renommer un fichier via sftp
  • Example#4667 - Effacement d'un dossier sur un serveur distant
  • Example#4668 - Statut d'un fichier via SFTP
  • Example#4669 - Création d'un lien symbolique
  • Example#4670 - Effacement d'un fichier
  • Example#4671 - Ouverture d'un fichier via SFTP
  • Example#4672 - Exécution d'une commande
  • Example#4673 - Ouverture d'un tunnel sur un hôte arbitraire
  • Example#4674 - Style orienté objet
  • Example#4675 - Style procédural
  • Example#4676 - Exemple avec stomp_connect_error
  • Example#4677 - Exemple avec stomp_version
  • Example#4678 - Style orienté objet
  • Example#4679 - Style procédural
  • Example#4680 - Style orienté objet
  • Example#4681 - Style procédural
  • Example#4682 - Style orienté objet
  • Example#4683 - Style procédural
  • Example#4684 - Style orienté objet
  • Example#4685 - Style procédural
  • Example#4686 - Style orienté objet
  • Example#4687 - Style procédural
  • Example#4688 - Style orienté objet
  • Example#4689 - Style procédural
  • Example#4690 - Style orienté objet
  • Example#4691 - Style procédural
  • Example#4692 - Style orienté objet
  • Example#4693 - Style procédural
  • Example#4694 - Style orienté objet
  • Example#4695 - Style procédural
  • Example#4696 - Entraînement depuis un tableau
  • Example#4697 - Entraînement depuis un fichier
  • Example#4698 - Exemple avec svn_add
  • Example#4699 - Exemple d'identification
  • Example#4700 - Exemple d'utilisation de svn_blame
  • Example#4701 - Exemple d'utilisation
  • Example#4702 - Exemple d'utilisation
  • Example#4703 - Exemple d'utilisation
  • Example#4704 - Exemple d'utilisation
  • Example#4705 - Exemple d'utilisation
  • Example#4706 - Exemple d'utilisation
  • Example#4707 - Comparaison de deux révisions d'un chemin du référentiel
  • Example#4708 - Comparaison, plus portable, de deux fichiers locaux
  • Example#4709 - Exemple d'utilisation de svn_export
  • Example#4710 - Exemple d'utilisation
  • Example#4711 - Exemple avec svn_log
  • Example#4712 - Exemple avec svn_ls
  • Example#4713 - Exemple d'utilisation
  • Example#4714 - Exemple d'utilisation
  • Example#4715 - Refuser toutes les connexions depuis localhost
  • Example#4716 - Bannir une URL
  • Example#4717 - Récupération de statistiques
  • Example#4718 - Lecture des logs Varnish depuis la mémoire partagée
  • Example#4719 - Exemple avec VarnishAdmin::__construct
  • Example#4720 - Recherche parallèle en utilisant Yaz
  • Example#4721 - Configuration CCL
  • Example#4722 - Analyse CCL
  • Example#4723 - Mise à Jour d'Enregistrements
  • Example#4724 - Tableau pour des enregistrements GRS-1
  • Example#4725 - Travail avec MARCXML
  • Example#4726 - Fonction PHP qui analyse les titres sur un serveur YAZ
  • Example#4727 - Exemples de Requête
  • Example#4728 - Critères de Tri
  • Example#4729 - Exemple avec ZMQContext
  • Example#4730 - Exemple avec ZMQContext
  • Example#4731 - Exemple avec ZMQContext
  • Example#4732 - Exemple avec ZMQSocket
  • Example#4733 - Un exemple d'envoi/réception
  • Example#4734 - Exemple avec ZMQPoll
  • Example#4735 - zookeeper_dispatch example #1
  • Example#4736 - zookeeper_dispatch example #2
  • Example#4737 - Zookeeper::addAuth example
  • Example#4738 - Zookeeper::create example
  • Example#4739 - Zookeeper::delete example
  • Example#4740 - Zookeeper::exists example
  • Example#4741 - Zookeeper::get example
  • Example#4742 - Zookeeper::get stat example
  • Example#4743 - Zookeeper::getAcl example
  • Example#4744 - Zookeeper::getChildren example
  • Example#4745 - Zookeeper::set example
  • Example#4746 - Zookeeper::setAcl example
  • Example#4747 - Zookeeper::setDebugLevel example
  • Example#4748 - ZookeeperConfig::add example
  • Example#4749 - ZookeeperConfig::get example
  • Example#4750 - ZookeeperConfig::remove example
  • Example#4751 - ZookeeperConfig::set example
  • Example#4752 - Exemple avec solr_get_version
  • Example#4753 - Contenu du fichier BootStrap
  • Example#4754 - Ajout d'un document à l'index
  • Example#4755 - Fusion d'un document dans un autre
  • Example#4756 - Recherche de documents - réponses sous la forme d'un objet SolrObject
  • Example#4757 - Recherche de documents - réponses sous la forme d'un objet SolrDocument
  • Example#4758 - Exemple simple avec TermsComponent
  • Example#4759 - Exemple simple avec TermsComponent en utilisant un préfixe
  • Example#4760 - Exemple simple avec TermsComponent en spécifiant une fréquence minimale
  • Example#4761 - Exemple simple avec Facet
  • Example#4762 - Exemple simple avec Facet et un champ optionnel d'écrasement pour mincount
  • Example#4763 - Exemple avec les Facet
  • Example#4764 - Connexion à un serveur SSL
  • Example#4765 - Exemple avec SolrQuery
  • Example#4766 - Exemple "Solr Real Time Get (RTG)" avec SolrClient::getById
  • Example#4767 - SolrInputDocument::addChildDocument example
  • Example#4768 - SolrInputDocument::addChildDocuments example
  • Example#4769 - Exemple avec SolrDocument::toArray
  • Example#4770 - Exemple avec SolrObject::__construct
  • Example#4771 - Exemple avec SolrObject::offsetUnset
  • Example#4772 - Exemple avec SolrClient::addDocument example
  • Example#4773 - Exemple 2 avec SolrClient::addDocument
  • Example#4774 - Exemple avec SolrClient::addDocuments
  • Example#4775 - Exemple avec SolrClient::__construct
  • Example#4776 - Exemple avec SolrQuery::deleteByQuery
  • Example#4777 - SolrClient::getById example
  • Example#4778 - SolrClient::getByIds example
  • Example#4779 - Exemple avec SolrClient::ping
  • Example#4780 - Exemple avec SolrClient::query
  • Example#4781 - Exemple avec SolrClient::request
  • Example#4782 - Exemple avec SolrClient::setResponseWriter
  • Example#4783 - Exemple avec SolrParams::setParam
  • Example#4784 - Exemple avec SolrQuery::addFacetField
  • Example#4785 - Exemple avec SolrQuery::addFacetField
  • Example#4786 - Exemple avec SolrQuery::addFilterQuery
  • Example#4787 - SolrQuery::addGroupSortField example
  • Example#4788 - SolrQuery::collapse example
  • Example#4789 - SolrQuery::setExpand example
  • Example#4790 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#4791 - SolrDisMaxQuery::addBoostQuery example
  • Example#4792 - SolrDisMaxQuery::addPhraseField example
  • Example#4793 - SolrDisMaxQuery::addQueryField example
  • Example#4794 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#4795 - SolrDisMaxQuery::addUserField example
  • Example#4796 - SolrDisMaxQuery::__construct example
  • Example#4797 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#4798 - SolrDisMaxQuery::removeBoostQuery example
  • Example#4799 - SolrDisMaxQuery::removePhraseField example
  • Example#4800 - SolrDisMaxQuery::removeQueryField example
  • Example#4801 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#4802 - SolrDisMaxQuery::removeUserField example
  • Example#4803 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#4804 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#4805 - SolrDisMaxQuery::setBoostFunction example
  • Example#4806 - SolrDisMaxQuery::setBoostQuery example
  • Example#4807 - SolrDisMaxQuery::setMinimumMatch example
  • Example#4808 - SolrDisMaxQuery::setPhraseFields example
  • Example#4809 - SolrDisMaxQuery::setPhraseSlop example
  • Example#4810 - SolrDisMaxQuery::setQueryAlt example
  • Example#4811 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#4812 - SolrDisMaxQuery::setTieBreaker example
  • Example#4813 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#4814 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#4815 - SolrDisMaxQuery::setUserFields example
  • Example#4816 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#4817 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#4818 - SolrCollapseFunction::__construct example
  • Example#4819 - SolrCollapseFunction::setHint example
  • Example#4820 - SolrCollapseFunction::setMax example
  • Example#4821 - Désactiver l'analyse des fichiers PHP dans un dossier avec .htaccess
  • Example#4822 - Exemple avec apache_get_modules
  • Example#4823 - Exemple avec apache_get_version
  • Example#4824 - Exemple avec apache_getenv
  • Example#4825 - Exemple avec apache_lookup_uri
  • Example#4826 - Passage d'informations entre PHP et Perl
  • Example#4827 - Valeurs d'identification dans le fichier access.log
  • Example#4828 - Exemple avec apache_request_headers
  • Example#4829 - Exemple avec apache_response_headers
  • Example#4830 - Exemple avec apache_setenv
  • Example#4831 - Exemple avec getallheaders
  • Example#4832 - Enregistrer une variable avec $_SESSION.
  • Example#4833 - Retirer une variable de session avec la superglobale $_SESSION.
  • Example#4834 - Compter le nombre de passages d'un utilisateur sur une page
  • Example#4835 - Exemple
  • Example#4836 - Exemple avec session_cache_expire
  • Example#4837 - Exemple avec session_cache_limiter
  • Example#4838 - Exemple de session_create_id avec session_regenerate_id
  • Example#4839 - Destruction d'une session avec $_SESSION
  • Example#4840 - Exemple de session_gc pour les planificateurs de tâches comme cron
  • Example#4841 - Exemple de session_gc pour des scripts accessible par l'utilisateur
  • Example#4842 - Exemple avec session_name
  • Example#4843 - Exemple avec session_regenerate_id
  • Example#4844 - Eviter la perte de session par session_regenerate_id
  • Example#4845 - Gestionnaire de session personnalisé : voir le code complet dans la documentation sur l'interface SessionHandlerInterface.
  • Example#4846 - page1.php
  • Example#4847 - Récupération de la session : page2.php
  • Example#4848 - Remplacement de la durée de vie du cookie
  • Example#4849 - Lecture de la session et fermeture
  • Example#4850 - Utilisation de la classe SessionHandler pour ajouter un cryptage aux gestionnaires de sauvegarde interne de PHP.
  • Example#4851 - Exemple avec SessionHandlerInterface
  • Example#4852 - Tokenize comma separated integer list
  • Example#4853 - Tokenize assign statement
  • Example#4854 - Simple calculator
  • Example#4855 - Parse words out from a sentence
  • Example#4856 - Exemples de masques valides
  • Example#4857 - Exemples de masques invalides
  • Example#4858 - Usage de commentaire dans un masque PCRE
  • Example#4859 - Exemple de comparaison de preg_filter avec preg_replace
  • Example#4860 - Exemple avec preg_grep
  • Example#4861 - preg_last_error_msg example
  • Example#4862 - Exemple avec preg_last_error
  • Example#4863 - Extraction de tous les numéros de téléphone d'un texte
  • Example#4864 - Recherche les couples de balises HTML (gourmand)
  • Example#4865 - Utilisation d'un sous-masque nommé
  • Example#4866 - Trouve la chaîne "php"
  • Example#4867 - Trouve le mot "web"
  • Example#4868 - Lire un nom de domaine dans une URL
  • Example#4869 - Utilisation des sous-masques nommés
  • Example#4870 - Exemple avec preg_quote
  • Example#4871 - Mise en italique d'un mot dans un texte
  • Example#4872 - Exemple de preg_replace_callback_array
  • Example#4873 - preg_replace_callback et fonction anonyme
  • Example#4874 - Exemple avec preg_replace_callback
  • Example#4875 - Exemple avec preg_replace_callback en utilisant une structure récursive pour gérer du BB code
  • Example#4876 - Utilisation des références arrières avec des littéraux numériques
  • Example#4877 - Utilisation de tableaux indexé avec preg_replace
  • Example#4878 - Remplacement de plusieurs valeurs simultanément
  • Example#4879 - Suppression des espaces
  • Example#4880 - Utilisation du paramètre count
  • Example#4881 -
  • Example#4882 - Exemple avec preg_split : Éclatement d'une chaîne de recherche
  • Example#4883 - Scinder une chaîne en caractères
  • Example#4884 - Scinde une chaîne et capture les positions
  • Example#4885 - Exemple avec addcslashes
  • Example#4886 - Exemple avec addslashes
  • Example#4887 - Exemple avec bin2hex
  • Example#4888 - Exemple avec chr
  • Example#4889 - Comportement de débordement
  • Example#4890 - Construite une chaîne UTF-8 à partir d'octet individuel
  • Example#4891 - Exemple avec chunk_split
  • Example#4892 - Exemple avec convert_uudecode
  • Example#4893 - Exemple avec convert_uuencode
  • Example#4894 - Exemple avec count_chars
  • Example#4895 - Afficher une somme de contrôle CRC32
  • Example#4896 - Exemple avec crypt
  • Example#4897 - Exemple avec echo
  • Example#4898 -
  • Example#4899 - Exemple avec explode
  • Example#4900 - Exemple de valeurs retournées par la fonction explode
  • Example#4901 - Exemple avec explode et le paramètre limit
  • Example#4902 - fprintf : Entiers avec zéros initiaux
  • Example#4903 - fprintf : Format monétaire
  • Example#4904 - Exemple avec la table de traduction des caractères en entités HTML
  • Example#4905 - Exemple avec hex2bin
  • Example#4906 - Décoder des entités HTML
  • Example#4907 - Exemple avec htmlentities
  • Example#4908 - Utilisation de ENT_IGNORE
  • Example#4909 - Exemple avec htmlspecialchars_decode
  • Example#4910 - Exemple avec htmlspecialchars
  • Example#4911 - Exemple avec implode
  • Example#4912 - Exemple avec lcfirst
  • Example#4913 - Exemple avec levenshtein
  • Example#4914 - Exemple avec localeconv
  • Example#4915 - Exemple avec ltrim
  • Example#4916 - Exemple d'utilisation de md5_file
  • Example#4917 - Exemple avec md5
  • Example#4918 - Exemple avec metaphone
  • Example#4919 - Utilisation du paramètre max_phonemes
  • Example#4920 - Utilisant le paramètre de max_phonemes
  • Example#4921 - Exemple avec money_format
  • Example#4922 - Exemple avec nl_langinfo
  • Example#4923 - Exemple avec nl2br
  • Example#4924 - Génération de code HTML valide avec le paramètre use_xhtml
  • Example#4925 - Divers séparateurs de nouvelles lignes
  • Example#4926 - Exemple avec number_format
  • Example#4927 - Exemple avec ord
  • Example#4928 - Examiner les octets individuels d'une chaîne UTF-8
  • Example#4929 - Exemple avec parse_str
  • Example#4930 - Déformation des nom par parse_str
  • Example#4931 - Exemple avec print
  • Example#4932 -
  • Example#4933 -
  • Example#4934 - printf : divers exemples
  • Example#4935 - printf : spécificateurs chaînes de caractères
  • Example#4936 - Exemple avec quoted_printable_decode
  • Example#4937 - Exemple avec quoted_printable_encode
  • Example#4938 - Exemple avec quotemeta
  • Example#4939 - Exemple avec rtrim
  • Example#4940 - Exemple avec setlocale
  • Example#4941 - Exemple avec setlocale sous Windows
  • Example#4942 - Exemple avec sha1_file
  • Example#4943 - Exemple avec sha1
  • Example#4944 - Exemple de similar_text en inversant les arguments
  • Example#4945 - Exemples Soundex
  • Example#4946 - Échange d'arguments
  • Example#4947 - Spécification du caractère de remplissage
  • Example#4948 - Spécificateur de position avec d'autres spécificateurs
  • Example#4949 - sprintf : entier sans espace
  • Example#4950 - sprintf : formatage de devises
  • Example#4951 - sprintf : notation scientifique
  • Example#4952 - Exemple avec sscanf
  • Example#4953 - sscanf - utilisation des paramètres optionnels
  • Example#4954 - Avec une chaîne vide ''
  • Example#4955 - Démonstration de la sensibilité à la casse
  • Example#4956 - Exemple basique de la fonction str_decrement
  • Example#4957 - Exemple de la fonction str_decrement avec une retenue
  • Example#4958 - Avec une chaîne vide ''
  • Example#4959 - Démonstration de la sensibilité à la casse
  • Example#4960 - Exemple avec str_getcsv
  • Example#4961 - Exemple de str_getcsv avec une chaîne vide
  • Example#4962 - Exemple basique de la fonction str_increment
  • Example#4963 - Exemple de str_increment avec une retenue
  • Example#4964 - Exemple avec str_ireplace
  • Example#4965 - Exemple avec str_pad
  • Example#4966 - Exemple avec str_repeat
  • Example#4967 - Exemple 1 avec str_replace
  • Example#4968 - Exemple 2 avec str_replace
  • Example#4969 - Exemple avec str_rot13
  • Example#4970 - Exemple avec str_shuffle
  • Example#4971 - Exemple avec str_split
  • Example#4972 - Avec une chaîne vide ''
  • Example#4973 - Démonstration de la sensibilité à la casse
  • Example#4974 - Exemple avec str_word_count
  • Example#4975 - Exemple avec strcasecmp
  • Example#4976 - Exemple d'utilisation de strcmp
  • Example#4977 - Exemple avec strcspn
  • Example#4978 - Exemple avec strip_tags
  • Example#4979 - Exemple avec stripcslashes
  • Example#4980 - Exemple avec stripos
  • Example#4981 - Exemple avec stripslashes
  • Example#4982 - Utilisation de stripslashes sur un tableau
  • Example#4983 - Exemple avec stristr
  • Example#4984 - Teste si une chaîne de caractères est trouvée ou pas
  • Example#4985 - Utilisation d'une "chaîne de caractères" en chiffre
  • Example#4986 - Exemple avec strlen
  • Example#4987 - Exemple avec strnatcasecmp
  • Example#4988 - Exemple avec strncasecmp
  • Example#4989 - Exemple avec strncmp
  • Example#4990 - Exemple avec strpbrk
  • Example#4991 - Avec ===
  • Example#4992 - Avec !==
  • Example#4993 - Utiliser un offset
  • Example#4994 - Exemple avec strrchr
  • Example#4995 - Inverser une chaîne avec strrev
  • Example#4996 - Exemple avec strripos
  • Example#4997 - Vérifie si une occurrence est trouvée dans une chaîne
  • Example#4998 - Recherche avec des positions
  • Example#4999 - Exemple avec strspn
  • Example#5000 - Exemple avec strstr
  • Example#5001 - Exemple avec strtok
  • Example#5002 - Comportement de strtok sur une partie vide trouvée
  • Example#5003 - La différence entre strtok et explode
  • Example#5004 - Exemple avec strtolower
  • Example#5005 - Exemple avec strtoupper
  • Example#5006 - Exemple avec strtr
  • Example#5007 - Exemple avec strtr et 2 arguments
  • Example#5008 - Comparaison de comportement de strtr
  • Example#5009 - Exemple avec substr_compare
  • Example#5010 - Exemple avec substr_count
  • Example#5011 - Exemple avec substr_replace
  • Example#5012 - Utilisation de substr_replace pour remplacer plusieurs chaînes en une seule fois
  • Example#5013 - Exemple de offset négatif
  • Example#5014 - Utilisation d'une valeur négative pour length
  • Example#5015 - Exemple avec substr
  • Example#5016 - Comportement du cast avec substr
  • Example#5017 -
  • Example#5018 - Intervalle de Caractères Invalide
  • Example#5019 - Exemple avec trim
  • Example#5020 - Suppression de caractères dans un tableau avec trim
  • Example#5021 - Exemple avec ucfirst
  • Example#5022 - Exemple avec ucwords
  • Example#5023 - Exemple avec ucwords et un séparation personnalisé
  • Example#5024 - Exemple de ucwords des séparateurs supplémentaires
  • Example#5025 - Exemple d'utilisation
  • Example#5026 - Exemple d'utilisation
  • Example#5027 - vfprintf : zéro comme caractères d'espacements
  • Example#5028 - Exemple avec vprintf : entiers complétés avec des zéros
  • Example#5029 - Exemple avec vsprintf : entiers avec zéro initiaux
  • Example#5030 - Exemple avec wordwrap
  • Example#5031 - Exemple avec wordwrap
  • Example#5032 - Exemple avec wordwrap
  • Example#5033 - Exemple avec array_change_key_case
  • Example#5034 - Exemple avec array_chunk
  • Example#5035 - Récupère la colonne des prénoms
  • Example#5036 - Récupère la colonne des noms, indexé par la colonne "id"
  • Example#5037 - Récupère la colonne des username depuis la propriété publique "username" d'un objet
  • Example#5038 - Récupère la colonne nom depuis la propriété privée "name" d'un objet en utilisant la méthode magique __get.
  • Example#5039 - Exemple avec array_combine
  • Example#5040 - Exemple avec array_count_values
  • Example#5041 - Exemple avec array_diff_assoc
  • Example#5042 - Exemple avec array_diff_assoc
  • Example#5043 - Exemple avec array_diff_key
  • Example#5044 - Exemple avec array_diff_uassoc
  • Example#5045 - Exemple avec array_diff_ukey
  • Example#5046 - Exemple avec array_diff
  • Example#5047 - Exemple avec la fonction array_diff avec des types qui ne correspondent pas
  • Example#5048 - Exemple avec array_fill_keys
  • Example#5049 - Exemple avec array_fill
  • Example#5050 - Exemple de array_fill avec un indice de départ négatif
  • Example#5051 - Exemple avec array_filter
  • Example#5052 - Exemple avec array_filter callback
  • Example#5053 - Exemple avec array_filter et mode
  • Example#5054 - Exemple avec array_flip
  • Example#5055 - Exemple avec array_flip : collision
  • Example#5056 - Exemple avec array_intersect_assoc
  • Example#5057 - Exemple avec array_intersect_key
  • Example#5058 - Exemple avec array_intersect_uassoc
  • Example#5059 - Exemple avec array_intersect_ukey
  • Example#5060 - Exemple avec array_intersect
  • Example#5061 - Exemple de array_is_list
  • Example#5062 - Exemple avec array_key_exists
  • Example#5063 - array_key_exists et isset
  • Example#5064 - Usage simple de array_key_first
  • Example#5065 - Exemple avec array_keys
  • Example#5066 - Exemple avec array_map
  • Example#5067 - array_map utilisant une fonction quelconque
  • Example#5068 - array_map : utilisation de plusieurs tableaux
  • Example#5069 - Exécution d'une opération zip de tableaux
  • Example#5070 - null callback avec seulement array
  • Example#5071 - array_map - avec des clés sous la forme de chaîne de caractères
  • Example#5072 - array_map - tableaux associatifs
  • Example#5073 - Exemple avec array_merge_recursive
  • Example#5074 - Exemple avec array_merge
  • Example#5075 - Exemple simple avec array_merge
  • Example#5076 - Exemple avec array_merge avec des types non-tableaux
  • Example#5077 - Trier plusieurs tableaux
  • Example#5078 - Trier un tableau multidimensionnel
  • Example#5079 - Classer les résultats d'une base de données
  • Example#5080 - Tri non sensible à la casse
  • Example#5081 - Exemple avec array_pad
  • Example#5082 - Exemple avec array_pop
  • Example#5083 - Exemple avec array_product
  • Example#5084 - Exemple avec array_push
  • Example#5085 - Exemple avec array_rand
  • Example#5086 - Exemple avec array_reduce
  • Example#5087 - Exemple avec array_replace_recursive
  • Example#5088 - Exemple avec array_replace_recursive et la récursivité
  • Example#5089 - Exemple avec array_replace
  • Example#5090 - Exemple avec array_reverse
  • Example#5091 - Exemple avec array_search
  • Example#5092 - Exemple avec array_shift
  • Example#5093 - Exemple avec array_slice
  • Example#5094 - array_slice et basé sur un tableau
  • Example#5095 - array_slice et tableau avec des clés mixtes
  • Example#5096 - Exemples avec array_splice
  • Example#5097 - Déclaration équivalentes à des exemples de array_splice divers
  • Example#5098 - Exemple avec array_sum
  • Example#5099 - Exemple avec array_udiff_assoc
  • Example#5100 - Exemple avec array_udiff_uassoc
  • Example#5101 - Exemple avec array_udiff en utilisant les objets stdClass
  • Example#5102 - Exemple avec array_udiff en utilisant des objets DateTime
  • Example#5103 - Exemple avec array_uintersect_assoc
  • Example#5104 - Exemple avec array_uintersect_uassoc
  • Example#5105 - Exemple avec array_uintersect
  • Example#5106 - Exemple avec array_unique
  • Example#5107 - Exemple avec array_unique et les types
  • Example#5108 - Exemple avec array_unshift
  • Example#5109 - Utilisation avec des tableaux associatifs
  • Example#5110 - Exemple avec array_values
  • Example#5111 - Exemple avec array_walk_recursive
  • Example#5112 - Exemple avec array_walk
  • Example#5113 - Exemple de array_walk avec l'utilisation d'une fonction anonyme
  • Example#5114 - Exemple avec array
  • Example#5115 - Index automatique avec array
  • Example#5116 - Index commençant à 1 avec array
  • Example#5117 - Accéder à un tableau dans des doubles guillemets
  • Example#5118 - Exemple avec arsort
  • Example#5119 - Exemple avec asort
  • Example#5120 - Exemple avec compact
  • Example#5121 - Exemple avec count
  • Example#5122 - Exemple de count avec un argument non Countable|array (contre-exemple - ne pas faire ceci)
  • Example#5123 - Exemple de récursivité avec count
  • Example#5124 - Objet Countable
  • Example#5125 - Exemple d'utilisation de current
  • Example#5126 - Exemple avec each
  • Example#5127 - Passer en revue un tableau avec each
  • Example#5128 - Exemple avec end
  • Example#5129 - Exemple avec extract
  • Example#5130 - Exemple avec in_array
  • Example#5131 - Exemple avec in_array et le mode strict
  • Example#5132 - Exemple avec in_array et un tableau en paramètre
  • Example#5133 - Exemple avec key
  • Example#5134 - Exemple avec krsort
  • Example#5135 - Exemple avec ksort
  • Example#5136 - ksort avec des clés int
  • Example#5137 - Exemple avec list
  • Example#5138 - Exemple d'utilisation de list
  • Example#5139 - Utilisation d'un sous-list
  • Example#5140 - list et l'ordre de définition des index
  • Example#5141 - list avec des clés
  • Example#5142 - Exemple avec natcasesort
  • Example#5143 - Exemple d'utilisation de base avec natsort
  • Example#5144 - Exemples montrant les pièges de natsort
  • Example#5145 - Exemple avec next
  • Example#5146 - Exemple avec prev
  • Example#5147 - Exemple avec range
  • Example#5148 - Exemple avec reset
  • Example#5149 - Exemple avec rsort
  • Example#5150 - Exemple avec shuffle
  • Example#5151 - Exemple avec sort
  • Example#5152 - Exemple avec sort en utilisant l'ordre naturel sans tenir compte de la casse
  • Example#5153 - Exemple avec uasort
  • Example#5154 - Exemple avec uksort
  • Example#5155 - Exemple avec usort
  • Example#5156 - Tri avec usort sur un tableau multidimensionnel
  • Example#5157 - Tri avec usort sur un objet
  • Example#5158 - Exemple avec usort en utilisant une closure pour trier un tableau multidimensionnel
  • Example#5159 - Exemple d'utilisation de l'opérateur combiné avec usort.
  • Example#5160 - Définitions des Classes
  • Example#5161 - test_script.php
  • Example#5162 - Exemple avec class_alias
  • Example#5163 - Exemple avec class_exists
  • Example#5164 - Exemple avec le paramètre autoload
  • Example#5165 - Exemple de enum_exists
  • Example#5166 - Exemple avec get_called_class
  • Example#5167 - Exemple avec get_class_methods
  • Example#5168 - Exemple avec get_class_vars
  • Example#5169 - Exemple avec get_class_vars et les contextes
  • Example#5170 - Exemple avec get_class
  • Example#5171 - Utilisation de get_class dans une superclasse
  • Example#5172 - Utilisation get_class avec des namespace de classe
  • Example#5173 - Exemple avec get_declared_classes
  • Example#5174 - Exemple avec get_declared_interfaces
  • Example#5175 - Exemple de get_mangled_object_vars
  • Example#5176 - Exemple avec get_object_vars
  • Example#5177 - Exemple avec get_parent_class
  • Example#5178 - Exemple avec interface_exists
  • Example#5179 - Exemple avec is_a
  • Example#5180 - Utilisation de l'opérateur instanceof
  • Example#5181 - Exemple avec is_subclass_of
  • Example#5182 - Exemple avec is_subclass_of en utilisant une interface
  • Example#5183 - Exemple avec method_exists
  • Example#5184 - Exemple avec method_exists en appel statique
  • Example#5185 - Exemple avec property_exists
  • Example#5186 - Exemple avec ctype_alnum (en utilisant les locales par défaut)
  • Example#5187 - Exemple avec ctype_alpha (en utilisant les locales courantes)
  • Example#5188 - Exemple avec ctype_cntrl
  • Example#5189 - Exemple avec ctype_digit
  • Example#5190 - Exemple avec ctype_digit pour comparer des chaînes et des nombres
  • Example#5191 - Exemple avec ctype_graph
  • Example#5192 - Exemple avec ctype_lower (en utilisant les locales courantes)
  • Example#5193 - Exemple avec ctype_print
  • Example#5194 - Exemple avec ctype_punct
  • Example#5195 - Exemple avec ctype_space
  • Example#5196 - Exemple avec ctype_upper (en utilisant la locale courante)
  • Example#5197 - Exemple avec ctype_xdigit
  • Example#5198 - Configurer le filtre par défaut pour qu'il agisse comme htmlspecialchars
  • Example#5199 - Configurer le filtre par défaut pour agir comme htmlspecialchars
  • Example#5200 - Validation d'adresses email avec filter_var
  • Example#5201 - Validation d'adresses IP avec filter_var
  • Example#5202 - Passage d'options à la fonction filter_var
  • Example#5203 - Nettoyage et validation d'adresses email
  • Example#5204 - Configurer le filtre par défaut
  • Example#5205 - Exemple avec filter_input_array
  • Example#5206 - Exemple avec filter_input
  • Example#5207 - Exemple avec filter_list
  • Example#5208 - Exemple avec filter_var_array
  • Example#5209 - Exemple avec filter_var
  • Example#5210 - Exemple de filtrage d'un tableau
  • Example#5211 - Exemple avec call_user_func_array
  • Example#5212 - Exemple avec call_user_func_array en utilisant un espace de nom
  • Example#5213 - Utilisation d'une fonction lambda
  • Example#5214 - En passant une valeur par référence
  • Example#5215 - call_user_func_array en utilisant des arguments nommés
  • Example#5216 - Exemple avec call_user_func par référence
  • Example#5217 - Exemple avec call_user_func
  • Example#5218 - Exemple avec call_user_func en utilisant un espace de noms
  • Example#5219 - Utilisation d'une méthode de classe avec call_user_func
  • Example#5220 - Utilisation d'une fonction lambda avec call_user_func
  • Example#5221 - Création d'une fonction anonyme avec create_function
  • Example#5222 - Traitement générique par fonction avec create_function
  • Example#5223 - Utilisation de fonctions anonymes comme fonction de rappel
  • Example#5224 - Exemple avec forward_static_call_array
  • Example#5225 - Exemple avec forward_static_call
  • Example#5226 - Exemple avec func_get_arg
  • Example#5227 - Exemple func_get_arg avec des arguments par référence et par valeur
  • Example#5228 - Exemple avec func_get_args
  • Example#5229 - Exemple func_get_args avec des arguments par référence et par valeur
  • Example#5230 - Exemple avec func_num_args
  • Example#5231 - Exemple avec function_exists
  • Example#5232 - Exemple avec get_defined_functions
  • Example#5233 - Exemple avec register_shutdown_function
  • Example#5234 - Exemple avec register_tick_function
  • Example#5235 - Quickhash Example
  • Example#5236 - Quickhash ArrayAccess Example
  • Example#5237 - Quickhash Iterator Example
  • Example#5238 - Quickhash String Values Example
  • Example#5239 - QuickHashIntSet::add example
  • Example#5240 - QuickHashIntSet::__construct example
  • Example#5241 - QuickHashIntSet::delete example
  • Example#5242 - QuickHashIntSet::exists example
  • Example#5243 - QuickHashIntSet::getSize example
  • Example#5244 - QuickHashIntSet::loadFromFile example
  • Example#5245 - QuickHashIntSet::loadFromString example
  • Example#5246 - QuickHashIntSet::saveToFile example
  • Example#5247 - QuickHashIntSet::saveToString example
  • Example#5248 - QuickHashIntHash::add example
  • Example#5249 - QuickHashIntHash::__construct example
  • Example#5250 - QuickHashIntHash::delete example
  • Example#5251 - QuickHashIntHash::exists example
  • Example#5252 - QuickHashIntHash::get example
  • Example#5253 - QuickHashIntHash::getSize example
  • Example#5254 - QuickHash IntHash file format
  • Example#5255 - QuickHash IntHash file format
  • Example#5256 - QuickHashIntHash::loadFromFile example
  • Example#5257 - QuickHashIntHash::loadFromString example
  • Example#5258 - QuickHashIntHash::saveToFile example
  • Example#5259 - QuickHashIntHash::saveToString example
  • Example#5260 - QuickHashIntHash::set example
  • Example#5261 - QuickHashIntHash::update example
  • Example#5262 - QuickHashStringIntHash::add example
  • Example#5263 - QuickHashStringIntHash::__construct example
  • Example#5264 - QuickHashStringIntHash::delete example
  • Example#5265 - QuickHashStringIntHash::get example
  • Example#5266 - QuickHashStringIntHash::getSize example
  • Example#5267 - QuickHash StringIntHash file format
  • Example#5268 - QuickHash IntHash file format
  • Example#5269 - QuickHashStringIntHash::loadFromFile example
  • Example#5270 - QuickHashStringIntHash::loadFromString example
  • Example#5271 - QuickHashStringIntHash::saveToFile example
  • Example#5272 - QuickHashStringIntHash::saveToString example
  • Example#5273 - QuickHashStringIntHash::set example
  • Example#5274 - QuickHashStringIntHash::update example
  • Example#5275 - QuickHashIntStringHash::add example
  • Example#5276 - QuickHashIntStringHash::__construct example
  • Example#5277 - QuickHashIntStringHash::delete example
  • Example#5278 - QuickHashIntStringHash::get example
  • Example#5279 - QuickHashIntStringHash::getSize example
  • Example#5280 - QuickHash IntString file format
  • Example#5281 - QuickHash IntString file format
  • Example#5282 - QuickHashIntStringHash::loadFromFile example
  • Example#5283 - QuickHashIntStringHash::loadFromString example
  • Example#5284 - QuickHashIntStringHash::saveToFile example
  • Example#5285 - QuickHashIntStringHash::saveToString example
  • Example#5286 - QuickHashIntStringHash::set example
  • Example#5287 - QuickHashIntStringHash::update example
  • Example#5288 - Exemple avec Reflection depuis un Shell (un Terminal)
  • Example#5289 - Étendre les classes internes
  • Example#5290 - Exemple Reflection::getModifierNames
  • Example#5291 - Utilisation simple de ReflectionClass
  • Example#5292 - Utilisation basique de ReflectionClass::export
  • Example#5293 - Basic usage
  • Example#5294 - Filtering results by class name
  • Example#5295 - Filtering results by class name, with inheritance
  • Example#5296 - Utilisation de ReflectionClass::getConstant
  • Example#5297 - Utilisation simple de ReflectionClass::getConstructor
  • Example#5298 - Exemple avec ReflectionClass::getDefaultProperties
  • Example#5299 - Exemple avec ReflectionClass::getDocComment
  • Example#5300 - Exemple avec ReflectionClass::getEndLine
  • Example#5301 - Utilisation simple de ReflectionClass::getExtension
  • Example#5302 - Utilisation simple de ReflectionClass::getExtensionName
  • Example#5303 - Exemple avec ReflectionClass::getInterfaceNames
  • Example#5304 - >Exemple avec ReflectionClass::getInterfaces
  • Example#5305 - Utilisation simple de ReflectionClass::getMethod
  • Example#5306 - Utilisation simple de ReflectionClass::getMethods
  • Example#5307 - Filtrage des résultats depuis ReflectionClass::getMethods
  • Example#5308 - Exemple avec ReflectionClass::getName
  • Example#5309 - Exemple avec ReflectionClass::getNamespaceName
  • Example#5310 - Exemple avec ReflectionClass::getProperties
  • Example#5311 - Exemple avec ReflectionClass::getProperty
  • Example#5312 - Exemple basique de ReflectionClass::getReflectionConstants
  • Example#5313 - Exemple avec ReflectionClass::getShortName
  • Example#5314 - Exemple avec ReflectionClass::getStaticPropertyValue
  • Example#5315 - Exemple avec ReflectionClass::hasConstant
  • Example#5316 - Exemple avec ReflectionClass::hasMethod
  • Example#5317 - Exemple avec ReflectionClass::hasProperty
  • Example#5318 - Exemple avec ReflectionClass::inNamespace
  • Example#5319 - Exemple avec ReflectionClass::isAbstract
  • Example#5320 - Exemple avec ReflectionClass::isAnonymous
  • Example#5321 - Utilisation basique de ReflectionClass::isCloneable
  • Example#5322 - Exemple avec ReflectionClass::isFinal
  • Example#5323 - Exemple avec ReflectionClass::isInstance
  • Example#5324 - Exemple avec ReflectionClass::isInstantiable
  • Example#5325 - Exemple avec ReflectionClass::isInterface
  • Example#5326 - Exemple avec ReflectionClass::isInternal
  • Example#5327 - Utilisation simple de ReflectionClass::isIterable
  • Example#5328 - ReflectionClass::isReadOnly example
  • Example#5329 - Utilisation basique de ReflectionClass::newInstanceArgs
  • Example#5330 - Exemple pour ReflectionClass::__toString
  • Example#5331 - Basic usage
  • Example#5332 - Filtering results by class name
  • Example#5333 - Filtering results by class name, with inheritance
  • Example#5334 - ReflectionClassConstant::isEnumCase example
  • Example#5335 - ReflectionEnum::getBackingType example
  • Example#5336 - ReflectionEnum::getCase example
  • Example#5337 - ReflectionEnum::getCases example
  • Example#5338 - ReflectionEnum::hasCase example
  • Example#5339 - ReflectionEnum::isBacked example
  • Example#5340 - ReflectionEnum::getValue example
  • Example#5341 - ReflectionEnum::getBackingValue example
  • Example#5342 - Exemple avec ReflectionExtension
  • Example#5343 - Exemple avec ReflectionExtension::getClasses
  • Example#5344 - Exemple avec ReflectionExtension::getClassNames
  • Example#5345 - Exemple avec ReflectionExtension::getConstants
  • Example#5346 - Exemple avec ReflectionExtension::getDependencies
  • Example#5347 - Exemple avec ReflectionExtension::getFunctions
  • Example#5348 - Exemple avec ReflectionExtension::getINIEntries
  • Example#5349 - Exemple avec ReflectionExtension::getName
  • Example#5350 - Exemple avec ReflectionExtension::getVersion
  • Example#5351 - Exemple avec ReflectionExtension::info
  • Example#5352 - Exemple avec ReflectionFunction::__construct
  • Example#5353 - Exemple avec ReflectionFunction::invoke
  • Example#5354 - Exemple avec ReflectionFunction::invokeArgs
  • Example#5355 - Exemple pour ReflectionFunction::invokeArgs avec des références
  • Example#5356 - ReflectionFunction::isAnonymous example
  • Example#5357 - Exemple pour ReflectionFunction::__toString
  • Example#5358 - Basic usage with a class method
  • Example#5359 - Basic usage with a function
  • Example#5360 - Filtering results by class name
  • Example#5361 - Filtering results by class name, with inheritance
  • Example#5362 - ReflectionFunctionAbstract::getClosureUsedVariables example
  • Example#5363 - Exemple avec ReflectionFunctionAbstract::getReturnType
  • Example#5364 - Utilisation sur les fonctions intégrés
  • Example#5365 - ReflectionFunctionAbstract::getTentativeReturnType example
  • Example#5366 - Exemple avec ReflectionFunctionAbstract::hasReturnType
  • Example#5367 - Utilisation sur les fonctions intégrés
  • Example#5368 - ReflectionFunctionAbstract::hasTentativeReturnType example
  • Example#5369 - Exemple de ReflectionFunctionAbstract::isClosure
  • Example#5370 - Exemple avec ReflectionFunctionAbstract::isDeprecated
  • Example#5371 - Exemple avec ReflectionMethod::__construct
  • Example#5372 - ReflectionMethod::createFromMethodName example
  • Example#5373 - Exemple pour ReflectionMethod::getDeclaringClass
  • Example#5374 - Exemple avec ReflectionMethod::getModifiers
  • Example#5375 - Exemple avec ReflectionMethod::getPrototype
  • Example#5376 - ReflectionMethod::hasPrototype example
  • Example#5377 - Exemple avec ReflectionMethod::invoke
  • Example#5378 - Exemple pour ReflectionMethod::invokeArgs
  • Example#5379 - Définition d'une classe simple
  • Example#5380 - ReflectionMethod::__toString example
  • Example#5381 - Exemple avec ReflectionNamedType::isBuiltin
  • Example#5382 - Exemple avec ReflectionParameter
  • Example#5383 - Basic usage
  • Example#5384 - Filtering results by class name
  • Example#5385 - Filtering results by class name, with inheritance
  • Example#5386 - Exemple d'utilisation de la classe ReflectionParameter
  • Example#5387 - Récupération de la classe qui a déclarée la méthode
  • Example#5388 - Récupérer les valeurs par défaut des paramètres de la fonction
  • Example#5389 - Récupérer les noms des constantes qui servent de valeurs par défaut aux paramètres d'une fonction
  • Example#5390 - Utilisation de ReflectionParameter::getType à partir de PHP 7.1.0
  • Example#5391 - Utilisation de ReflectionParameter::getType antérieur à PHP 7.1.0
  • Example#5392 - Utilisation de ReflectionParameter::getType en PHP 8.0.0 et ultérieur
  • Example#5393 - Exemple avec ReflectionParameter::hasType
  • Example#5394 - Équivalent PHP 8.0.0
  • Example#5395 - Équivalent PHP 8.0.0
  • Example#5396 - Exemple de ReflectionParameter::__toString
  • Example#5397 - Exemple avec ReflectionProperty::__construct
  • Example#5398 - Récupération d'une valeur depuis une propriété privée ou protégée en utilisant la classe ReflectionProperty
  • Example#5399 - Basic usage
  • Example#5400 - Filtering results by class name
  • Example#5401 - Filtering results by class name, with inheritance
  • Example#5402 - ReflectionProperty::getDefaultValue example
  • Example#5403 - ReflectionProperty::getDocComment example
  • Example#5404 - Multiple property declarations
  • Example#5405 - Exemple de ReflectionProperty::getType
  • Example#5406 - Exemple avec ReflectionProperty::getValue
  • Example#5407 - ReflectionProperty::hasDefaultValue example
  • Example#5408 - Exemple de ReflectionProperty::hasType
  • Example#5409 - Exemple avec ReflectionClass::isDefault
  • Example#5410 - Exemple de ReflectionProperty::isInitialized
  • Example#5411 - ReflectionProperty::isPromoted example
  • Example#5412 - Définition d'une classe simple
  • Example#5413 - Exemple avec ReflectionProperty::setValue
  • Example#5414 - Exemple avec ReflectionType::allowsNull
  • Example#5415 - Exemple avec ReflectionType::__toString
  • Example#5416 - ReflectionUnionType::getTypes example
  • Example#5417 - Exemple avec ReflectionGenerator::__construct
  • Example#5418 - Exemple avec ReflectionGenerator::getExecutingFile
  • Example#5419 - Exemple avec ReflectionGenerator::getExecutingGenerator
  • Example#5420 - Exemple avec ReflectionGenerator::getExecutingLine
  • Example#5421 - Exemple avec ReflectionGenerator::getFunction
  • Example#5422 - Exemple avec ReflectionGenerator::getThis
  • Example#5423 - Exemple avec ReflectionGenerator::getTrace
  • Example#5424 - ReflectionIntersectionType::getTypes example
  • Example#5425 - Basic ReflectionReference::getId usage
  • Example#5426 - Exemple avec boolval
  • Example#5427 - Exemple avec debug_zval_dump
  • Example#5428 -
  • Example#5429 - Une comparaison simple empty / isset.
  • Example#5430 - empty sur des positions dans une chaîne
  • Example#5431 - Exemple avec floatval
  • Example#5432 - Exemple avec floatval avec des caractères à gauche non numériques
  • Example#5433 - get_debug_type example
  • Example#5434 - Exemple avec get_defined_vars
  • Example#5435 - get_resource_id produit le même résultat qu'un cast int
  • Example#5436 - Exemple avec get_resource_type
  • Example#5437 - Exemple avec gettype
  • Example#5438 - Exemples avec intval
  • Example#5439 - Exemple avec is_array
  • Example#5440 - Exemple avec is_bool
  • Example#5441 - Exemple avec is_callable
  • Example#5442 - is_callable et les constructeurs
  • Example#5443 - Exemples avec is_countable
  • Example#5444 - Exemple avec is_float
  • Example#5445 - Exemple avec is_int
  • Example#5446 - Exemples avec is_iterable
  • Example#5447 - Exemple avec is_null
  • Example#5448 - Exemple avec is_numeric
  • Example#5449 - is_numeric avec des caractères d'espacement blanc
  • Example#5450 - Exemple avec is_object
  • Example#5451 - Exemple avec is_resource
  • Example#5452 - Exemple avec is_scalar
  • Example#5453 - Exemple avec is_string
  • Example#5454 - Exemple avec isset
  • Example#5455 - isset sur des positions dans une chaîne
  • Example#5456 - Exemple avec print_r
  • Example#5457 - Exemple avec le paramètre return
  • Example#5458 - Exemple avec serialize
  • Example#5459 - Exemple avec settype
  • Example#5460 - Exemple pour strval utilisant la méthode magique PHP __toString().
  • Example#5461 - Exemple avec unserialize
  • Example#5462 - Exemple avec la directive unserialize_callback_func
  • Example#5463 - Exemple avec unset
  • Example#5464 - Exemple avec un transtypage (unset)
  • Example#5465 - Exemple avec var_dump
  • Example#5466 - Exemple avec var_export
  • Example#5467 - Exporter stdClass (à partir de PHP 7.3.0)
  • Example#5468 - Exporter des classes
  • Example#5469 - Utilisation de __set_state
  • Example#5470 -
  • Example#5471 - Exemple avec OAuth::fetch
  • Example#5472 - Exemple avec OAuth::getAccessToken
  • Example#5473 - Exemple avec OAuth::getRequestToken
  • Example#5474 - Exemple avec OAuth::setRequestEngine
  • Example#5475 - Exemple avec OAuth::setRsaCertificate
  • Example#5476 - L'exemple OAuth::setToken
  • Example#5477 - Exemple avec OAuthProvider::__construct
  • Example#5478 - Exemple avec OAuthProvider::consumerHandler
  • Example#5479 - Exemple avec OAuthProvider::generateToken
  • Example#5480 - Exemple avec OAuthProvider::is2LeggedEndpoint
  • Example#5481 - Exemple avec OAuthProvider::timestampNonceHandler
  • Example#5482 - Exemple avec OAuthProvider::tokenHandler
  • Example#5483 - Exemple avec is_soap_fault
  • Example#5484 - Gestion des erreurs par exception avec SOAP
  • Example#5485 - Spécifier l'utilisation de TLS 1.3 uniquement
  • Example#5486 - Example SoapClient::__construct
  • Example#5487 - Utilisant la fonctionnalité SOAP_SINGLE_ELEMENT_ARRAYS
  • Example#5488 - Exemple avec SoapClient::__doRequest
  • Example#5489 - Exemple avec SoapClient::__getFunctions
  • Example#5490 - Exemple avec SoapClient::__getLastRequest
  • Example#5491 - SoapClient::__getLastRequestHeaders() example
  • Example#5492 - Exemple avec SoapClient::__getLastResponse
  • Example#5493 - Exemple avec SoapClient::__getLastResponseHeaders
  • Example#5494 - Exemple avec SoapClient::__getTypes
  • Example#5495 - Exemple avec SoapClient::__setLocation
  • Example#5496 - Exemple avec SoapClient::__setSoapHeaders
  • Example#5497 - Configuration d'en-têtes multiples pour SOAP
  • Example#5498 - Exemple avec SoapClient::__soapCall
  • Example#5499 - Exemple avec SoapServer::addFunction
  • Example#5500 - Exemples avec SoapServer::__construct
  • Example#5501 - Exemple avec SoapServer::getFunctions
  • Example#5502 - Exemple avec SoapServer::handle
  • Example#5503 - Exemple SoapServer::setPersistence
  • Example#5504 - Quelques exemples avec SoapFault
  • Example#5505 - Emission d'exceptions SoapFault
  • Example#5506 - Exemple avec SoapHeader::__construct
  • Example#5507 - Exemple avec SoapParam::__construct
  • Example#5508 - Exemple avec SoapVar::__construct
  • Example#5509 - Exemple de serveur Yar
  • Example#5510 - Accès au serveur depuis un navigateur (requête GET)
  • Example#5511 - Exemple de client Yar
  • Example#5512 - Exemple de client Yar concurrent
  • Example#5513 - Exemple avec Yar_Server::__construct
  • Example#5514 - Exemple avec Yar_Server::handle
  • Example#5515 - Exemple avec Yar_Client::__call
  • Example#5516 - Exemple avec Yar_Client::__construct
  • Example#5517 - Exemple avec Yar_Client::setOpt
  • Example#5518 - Exemple avec Yar_Concurrent_Client::call
  • Example#5519 - Exemple avec Yar_Concurrent_Client::loop
  • Example#5520 - Exemple avec Yar_Concurrent_Client::reset
  • Example#5521 - Exemple avec Yar_Server_Exception::getType
  • Example#5522 - Exemple avec Yar_Client_Exception::getType
  • Example#5523 - Exemple avec XMLRPC
  • Example#5524 - Exemple de type XML-RPC
  • Example#5525 - Exemple avec xmlrpc_set_type
  • Example#5526 - For Each en ASP
  • Example#5527 - Foreach en PHP
  • Example#5528 - Exemple com (1)
  • Example#5529 - Exemple com (2)
  • Example#5530 - Exemple dotnet
  • Example#5531 - Exemple variant
  • Example#5532 - Basic COMPersistHelper::saveToFile Usage
  • Example#5533 - Exemple de connexions d'événements COM
  • Example#5534 - Enregistre un script PHP pour exécuter en tant que service
  • Example#5535 - Efface un service
  • Example#5536 - Exécution d'un service
  • Example#5537 - Exemple avec win32_create_service
  • Example#5538 - Un exemple win32_create_service avec les dépendances
  • Example#5539 - Exemple de win32_create_service avec les options de récupération
  • Example#5540 - Exemple avec win32_delete_service
  • Example#5541 - Exemple avec win32_start_service_ctrl_dispatcher
  • Example#5542 - book.xml
  • Example#5543 - Création d'un nouvel objet DOMAttr
  • Example#5544 - Exemple avec DOMAttr::isId()
  • Example#5545 - Création d'un nouvel objet DOMCdataSection
  • Example#5546 - DOMCharacterData::after example
  • Example#5547 - DOMCharacterData::before example
  • Example#5548 - DOMCharacterData::remove example
  • Example#5549 - DOMCharacterData::replaceWith example
  • Example#5550 - Création d'un nouveau DOMComment
  • Example#5551 - DOMDocument::adoptNode example
  • Example#5552 - DOMDocument::append example
  • Example#5553 - Création d'un nouveau DOMDocument
  • Example#5554 - Création d'un nouvel élément et insertion en tant que racine
  • Example#5555 - Passer comme value du texte contenant & non échappé
  • Example#5556 - Création d'un nouvel élément et insertion en tant que racine
  • Example#5557 - Un exemple avec un espace de noms en préfixe
  • Example#5558 - Exemple avec DOMDocument::getElementById()
  • Example#5559 - Exemple de base
  • Example#5560 - Récupération de tous les éléments XInclude
  • Example#5561 - Exemple avec DOMDocument::importNode
  • Example#5562 - Création d'un Document
  • Example#5563 - Création d'un document
  • Example#5564 - Création d'un document
  • Example#5565 - Création d'un Document
  • Example#5566 - DOMDocument::prepend example
  • Example#5567 - Ajout d'un nouvelle méthode à DOMElement
  • Example#5568 - Récupération d'éléments sous la forme d'une classe personnalisée
  • Example#5569 - Récupération du propriétaire du document
  • Example#5570 - Les objets personalisé sont éphémère
  • Example#5571 - DOMDocument::replaceChildren example
  • Example#5572 - Sauvegarde d'un arbre DOM dans un fichier
  • Example#5573 - Sauvegarde d'un arbre HTML dans une chaîne de caractères
  • Example#5574 - Sauvegarde d'un arbre HTML dans un fichier
  • Example#5575 - Sauvegarde de l'arbre DOM dans une chaîne de caractères
  • Example#5576 - Exemple de validation DTD
  • Example#5577 - Exemple avec DOMDocument::xinclude()
  • Example#5578 - DOMDocumentFragment::append example
  • Example#5579 - Ajout de données XML à votre document
  • Example#5580 - DOMDocumentFragment::prepend example
  • Example#5581 - DOMDocumentFragment::replaceChildren example
  • Example#5582 - DOMElement::after example
  • Example#5583 - DOMElement::append example
  • Example#5584 - DOMElement::before example
  • Example#5585 - Création d'un nouveau DOMElement
  • Example#5586 - DOMElement::getAttributeNames example
  • Example#5587 - DOMElement::insertAdjacentElement example
  • Example#5588 - DOMElement::insertAdjacentText example
  • Example#5589 - DOMElement::prepend example
  • Example#5590 - DOMElement::remove example
  • Example#5591 - DOMElement::replaceChildren example
  • Example#5592 - DOMElement::replaceWith example
  • Example#5593 - Ajout d'un attribut
  • Example#5594 - DOMElement::toggleAttribute example
  • Example#5595 - Création d'un nouveau DOMEntityReference
  • Example#5596 - Création d'un document avec une DTD attachée
  • Example#5597 - Test votre implémentation DOM
  • Example#5598 - Ajout d'un fils
  • Example#5599 - Enfant imbriqué
  • Example#5600 - DOMNode::contains example
  • Example#5601 - Exemple avec DOMNode::getLineNo
  • Example#5602 - Exemple avec DOMNode::getNodePath
  • Example#5603 - DOMNode::getRootNode example
  • Example#5604 - DOMNode::isEqualNode example
  • Example#5605 - Effacement d'un fils
  • Example#5606 - Parcours de toutes les entrées de la table
  • Example#5607 - DOMParentNode::replaceChildren example
  • Example#5608 - Création d'un nouveau DOMProcessingInstruction
  • Example#5609 - Création d'un nouveau DOMText
  • Example#5610 - Récupération du nombre total de livres anglais
  • Example#5611 - Récupération de tous les livres anglais
  • Example#5612 - book.xml
  • Example#5613 - Exemple avec DOMXPath::registerPHPFunctions et php:functionString
  • Example#5614 - Exemple avec DOMXPath::registerPHPFunctions et php:function
  • Example#5615 - Importation d'un objet SimpleXML dans DOM avec dom_import_simplexml
  • Example#5616 - Exemple avec libxml_get_errors
  • Example#5617 - Exemple avec libxml_set_external_entity_loader
  • Example#5618 - Exemple avec libxml_set_streams_context
  • Example#5619 - Exemple avec libxml_use_internal_errors
  • Example#5620 - Fichier avec une chaîne XML qui sera inclus partout
  • Example#5621 - Lecture de <plot>
  • Example#5622 - Récupération de <line>
  • Example#5623 - Accéder à un élément non-unique avec SimpleXML
  • Example#5624 - Utilisation des attributs
  • Example#5625 - Comparaison des éléments et des attributs avec du texte
  • Example#5626 - Comparaison de 2 éléments
  • Example#5627 - Utilisation de XPath
  • Example#5628 - Attribuer des valeurs
  • Example#5629 - Ajout d'éléments et d'attributs
  • Example#5630 - Interopérabilité DOM
  • Example#5631 - Chargement de chaînes XML cassées
  • Example#5632 - Ajoute des attributs et enfants à un élément SimpleXML
  • Example#5633 - Ajoute des attributs et des enfants à un élément SimpleXML
  • Example#5634 - Obtenir du XML avec SimpleXML
  • Example#5635 - Utilisation de SimpleXMLElement::asXML avec les résultats de SimpleXMLElement::xpath
  • Example#5636 - Interprétation d'une chaîne XML
  • Example#5637 - Parcours d'un pseudo-tableau children()
  • Example#5638 - Utilisation des espaces de noms
  • Example#5639 - Crée un objet SimpleXMLElement
  • Example#5640 - Crée un objet SimpleXMLElement à partir d'un URL
  • Example#5641 - Comptage du nombre de fils
  • Example#5642 - Retourne l'élément courant
  • Example#5643 - Récupère les espaces de noms du document
  • Example#5644 - Travail avec plusieurs espaces de noms
  • Example#5645 - Récupère les noms des éléments XML
  • Example#5646 - Récupère les espaces de noms utilisés dans un document
  • Example#5647 - Lecture des sous-éléments de l'objet courant
  • Example#5648 - Vérifie si un élément a des sous-éléments
  • Example#5649 - Le nom de la balise XML courante
  • Example#5650 - Passe au prochain élément
  • Example#5651 - Fixe un préfixe d'espace de nom pour utiliser dans une requête XPath
  • Example#5652 - Retour au premier élément
  • Example#5653 - Récupérer le contenu chaine
  • Example#5654 - Vérifie si un élément est valide
  • Example#5655 - Xpath
  • Example#5656 - Import DOM
  • Example#5657 - Interprétation d'un document XML
  • Example#5658 - Convertir une chaîne XML
  • Example#5659 - Sérialisation d'une valeur simple avec WDDX
  • Example#5660 - Utilisation de paquets incrémentaux avec WDDX
  • Example#5661 - Exemple avec wddx_serialize_vars
  • Example#5662 - Afficher une structure XML
  • Example#5663 - Transtypage XML -> HTML
  • Example#5664 - Entité externe
  • Example#5665 - xmltest.xml
  • Example#5666 - xmltest2.xml
  • Example#5667 - Exemple avec xml_parse_into_struct
  • Example#5668 - moldb.xml - Petite base de données moléculaires
  • Example#5669 - parsemoldb.php : Analyse moldb.xml et crée un tableau d'objets moléculaires
  • Example#5670 - Analyse de gros documents XML par morceaux
  • Example#5671 - Exemple avec xml_set_object
  • Example#5672 - Validation XML
  • Example#5673 - Créer un document XML basique
  • Example#5674 - Travailler avec les espaces de noms XML
  • Example#5675 - Travailler avec l'API OO
  • Example#5676 - Écrire directement de l'XML
  • Example#5677 - XMLWriter::setIndent et divers contenus
  • Example#5678 - Utilisation Basique de XMLWriter::startAttribute
  • Example#5679 - Mélanger des Sous-éléments et Attributs
  • Example#5680 - Utilisation Basique de xmlwriter_write_cdata
  • Example#5681 - collection.xml
  • Example#5682 - collection.xsl
  • Example#5683 - fruits.xml
  • Example#5684 - fruits.xsl
  • Example#5685 - Collating and printing errors
  • Example#5686 - Exemple avec XSLTProcessor
  • Example#5687 - Test du support EXSLT
  • Example#5688 - Appel d'une fonction PHP depuis une feuille de style
  • Example#5689 - Modification du propriétaire avant la transformation
  • Example#5690 - Exemple d'utilisation du profilage
  • Example#5691 - Transformation en un document DOM
  • Example#5692 - Transformation en un fichier HTML
  • Example#5693 - Transformation en une chaîne
  • Example#5694 - Un élément de formulaire HTML caché
  • Example#5695 - Données éditables par l'utilisateur
  • Example#5696 - Dans une URL
  • Example#5697 - Génération de Javascript avec PHP
  • Example#5698 - Exemple de code PHP/FI
  • Example#5699 - Active la sortie d'erreur à l'écran pour dev.site.com
  • Example#5700 - Ajoute un script de sécurité pour les zones protégées
  • Example#5701 - include_path sous Unix
  • Example#5702 - include_path sous Windows
  • Example#5703 - include_path sous Unix en utilisant la variable d'environnement ${USER}
  • Example#5704 - string.rot13
  • Example#5705 - string.toupper
  • Example#5706 - string.tolower
  • Example#5707 - string.strip_tags
  • Example#5708 - convert.base64-encode & convert.base64-decode
  • Example#5709 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5710 - convert.iconv.*
  • Example#5711 - zlib.deflate and zlib.inflate
  • Example#5712 - zlib.deflate simple
  • Example#5713 - bzip2.compress et bzip2.decompress
  • Example#5714 - Chiffrement / Déchiffrement avec Blowfish
  • Example#5715 - Chiffrer un fichier en utilisant AES-128 CBC avec SHA256 HMAC

User Contributed Notes

There are no user contributed notes for this page.


Historique des modifications

Les modifications suivantes ont été apportées aux fonctions des extensions embarquées.

Version Function Description

User Contributed Notes

There are no user contributed notes for this page.


Version d'aide HTML

  • About This Edition
  • 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.


About This Edition

The Windows HTML Help Edition of the PHP Manual is aimed at developers, who want the manual at hand every time, and would like to read manual pages and user notes without waiting for a remote web page to download. This edition gives you the full content of the manual plus the user notes, with some great features provided by the viewer application by the scripts we use to generate this format and by other contributors in the form of skins.

This distribution of the PHP Manual contains many files, including the main manual file php_manual_en.chm. You can view the manual by double clicking on this file (as you already guessed). You may also see a php_manual_en.chw file in the directory, it's generated the first time you use the index tab, and it contains an index with the manual's pages.

For those interested in technical details about Microsoft HTML Help, » http://www.helpware.net/ is a great resource. For more information and positioning of Windows HTML Help in the Microsoft help formats and services history, see this » WinWriters article.

User Contributed Notes

There are no user contributed notes for this page.


Using PHP Manual CHM Edition

Sommaire

  • 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

Sommaire

  • 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.